<?php

namespace App\Http\Controllers;

use App\Http\Requests\StoreItemRequest;
use App\Models\Category;
use App\Models\Item;
use App\Models\Picture;
use App\Models\Subcategory;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Input;
use Illuminate\Support\Facades\Storage;

class ItemController extends Controller
{
    /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function index()
    {
        return view('items.index');
    }

    /**
     * Show the form for creating a new resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function create()
    {
        $categories = Category::all();
        $subcategories = Subcategory::all();

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

    /**
     * Store a newly created resource in storage.
     *
     * @param  \Illuminate\Http\Request $request
     * @return \Illuminate\Http\Response
     */
    public function store(StoreItemRequest $request)
    {
        if ($request->isMethod('POST')) {
            $item = new Item($request->all());
            $item->pictures = !empty(Input::file());
            $item->save();

            Picture::fromRequest($item);

            return redirect()->back()->with(['message' => 'Новый объект создан']);
        }

        return redirect()->back()->with(['message' => 'Объект не создан!']);
    }

    /**
     * Display the specified resource.
     *
     * @param  \App\Item $item
     * @return \Illuminate\Http\Response
     */
    public function show(Item $item)
    {
        $item->load('category');
        return view('items.info_page', ['item' => $item]);
    }

    /**
     * Show the form for editing the specified resource.
     *
     * @param  \App\Item $item
     * @return \Illuminate\Http\Response
     */
    public function edit(Item $item)
    {
        //
    }

    /**
     * Update the specified resource in storage.
     *
     * @param  \Illuminate\Http\Request $request
     * @param  \App\Item $item
     * @return \Illuminate\Http\Response
     */
    public function update(Request $request, Item $item)
    {
        if ($request->isMethod('PUT')) {
            $item = $item ?? Item::find(Input::get('id'));
            if (!is_object($item)) {
                abort(404);
            }

            $item->pictures = !empty(Input::file());
            $item->update($request->all());

            $pictures = $item->getPictures();

            $deletedFiles = $request->all()['files'] ?? [];
            foreach ($deletedFiles as $key => $file) {
                if ($file) {
                    $picture = $pictures[explode('_', $key)[1]] ?? null;
                    if ($picture){
                        Storage::disk('images')->delete($picture->path);
                        $picture->delete();
                    }
                }
            }

            $files = $request->allFiles()['files'] ?? [];
            foreach ($files as $file) {
                Picture::store($item, $file);
            }

            return redirect()->back()->with(['message' => 'Информация обновлена']);
        }
        return redirect()->back()->with(['message' => 'Информация не обновлена']);
    }

    /**
     * Remove the specified resource from storage.
     *
     * @param  \App\Item $item
     * @return \Illuminate\Http\Response
     */
    public function destroy(Item $item)
    {
        $user = Auth::user();

        if ($user->can('destroy', $item)) {
            $item->delete();
            return redirect()->back();
        }
        return redirect()->back()->with('errors','У Вас нет прав');
    }

//    public function userItemsAJAX(Request $request)
//    {
//        $itemListResponse = '';
//        $items = Item::where('user_id',Auth::id())->where('archive','0')->get();
//        foreach ($items as $item) {
//            $itemListResponse .= view('templates.info_card', ['item' => $item]);
//        }
//        return $itemListResponse;
//    }
}
