<?php

namespace App\Http\Controllers;

use App\Models\Category;
use App\Models\Item;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Storage;

class DashboardController extends Controller
{
    /**
     * @return \Illuminate\Contracts\View\Factory|\Illuminate\View\View
     */
    public function index(Request $request)
    {
        $itemsList = Item::with(['category', 'subcategory', 'picture'])->where('items.archive','0')->get();
        $categories = Category::with('subcategory')->get();

        return view('items.dashboard', ['itemsList' => $itemsList, 'categories' => $categories]);
    }

    public function category(int $categoryId)
    {
        $itemsList = Item::with(['category', 'subcategory', 'picture'])->where('category_id', $categoryId)->get();
        $categories = Category::with('subcategory')->get();
        return view('items.dashboard', ['itemsList' => $itemsList, 'categories' => $categories]);
    }

    public function fromCategories(Request $request)
    {
        $jsonRequest = $request->json()->all();

        if (isset($jsonRequest['categories'])) {
            $categories = $jsonRequest['categories'];
            if (count($categories) < 1) {
                $itemsList = Item::with(['category', 'subcategory', 'picture'])->get();
            } else {
                $itemsList = Item::with(['category', 'subcategory', 'picture'])->whereIn('category_id', $categories)->get();
            }
            $itemsView = '';
            foreach ($itemsList as $item) {
                $itemsView .= view('templates.fine_card', ['item' => $item]) . PHP_EOL;
            }
            if ($itemsView === '') {
                return view('templates.no_items');
            }
            return $itemsView;
        }
        return null;
    }

}

