<?php

namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Controller;
use App\Models\Item;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Gate;

class ItemsAdminController extends Controller
{
    public function index()
    {

        if (Gate::denies('is-admin')) {
            return redirect()->route('home')->with(['errors' => 'У вас не достаточно полномочий']);
        }

        $items = DB::table('items')
            ->join('categories', 'items.category_id', '=', 'categories.id')
            ->join('subcategories', 'items.subcategory_id', '=', 'subcategories.id')
            ->select('items.id',
                'items.user_id as user',
                'items.caption',
                'items.description',
                'categories.title as category',
                'subcategories.title as subcategory',
                'items.created_at'
            )
            ->paginate(15);
        if ($items->total() > 0) {
            $colNames = [];
            foreach ($items->first() as $key => $value) {
                $colNames[] = $key;
            }
            $items->title = 'Список предметов';

            $items->colNames = $colNames;
        }
        return view('admin.items', ['items' => $items ?? collect()]);
    }

    public function ajaxRequest(Request $request)
    {

        $content = json_decode($request->getContent());

        if ($content->item) {

            $data = collect([]);
            $data->item = Item::find((int)$content->item);
            $data->item->colNames = $data->item->getAttributes();
            $data->categories = DB::table('categories')->get();
            $data->subcategories = DB::table('subcategories')->get();
            $route = route('item.delete', $data->item);
            $data->pictures = $data->item->getPictures();
//            $data->item->picturesPath = $data->item->getPicturesOnlyPath();

            return view('templates.modal_form', ['route' => $route, 'data' => $data]);
        }

    }
}
