<?php

namespace App\Http\Controllers\Dashboard\UsefulInfoItemController;

use App\Http\Controllers\Controller as ExController;

use App\Http\Requests\Dashboard\UsefulInfoItemRequest\Update as UpdateRequest;
use App\Http\Requests\Dashboard\UsefulInfoItemRequest\Store as StoreRequest;

use App\Jobs\Dashboard\UsefulInfoItemJob\Store as StoreJob;
use App\Jobs\Dashboard\UsefulInfoItemJob\Update as UpdateJob;
use App\Models\UsefulInfo;
use App\Models\UsefulInfoItem;
use Illuminate\Support\Facades\File;

class Controller extends ExController
{
    public function index($usefulinfo_id)
    {
        $this->authorize('view', 'usefulinfoitems');

        $items = UsefulInfoItem::where('useful_info_id', $usefulinfo_id)
            ->latest('id')->paginate(20);

        return view('dashboard.usefulinfos.usefulinfos_item.index', compact('items', 'usefulinfo_id'));
    }

    public function create($usefulinfo_id)
    {
        $this->authorize('create', 'usefulinfoitem');
        return view('dashboard.usefulinfos.usefulinfos_item.create', compact('usefulinfo_id'));
    }

    public function store(StoreRequest $request, $usefulinfo_id)
    {
        $file_path = null;
        if ($request->hasFile('file')) {
            $file_path = $request->file('file')->store('uploads/usefulinfoitems');
        }

        $this->dispatchSync(StoreJob::fromRequest($request, $file_path, $usefulinfo_id));

        $this->info(trans('admin.messages.created'));
        return redirect()->route('dashboard.usefulinfoitems.index', $usefulinfo_id);
    }

    public function edit($usefulinfo_id, UsefulInfoItem $usefulinfoitem)
    {
        $this->authorize('update', 'usefulinfoitems');
        return view('dashboard.usefulinfos.usefulinfos_item.edit', compact('usefulinfoitem', 'usefulinfo_id'));
    }

    public function update(UpdateRequest $request, $usefulinfo_id, UsefulInfoItem $usefulinfoitem)
    {
        $file_path = null;
        if ($request->hasFile('file')) {
            $filePath = public_path($usefulinfoitem->file_url);

            if (File::exists($filePath)) {
                File::delete($filePath);
            }

            $file_path =  $request->file('file')->store('uploads/usefulinfoitems');
        } else {
            $file_path = $usefulinfoitem->file_url;
        }

        $this->dispatchSync(UpdateJob::fromRequest($usefulinfoitem, $request, $file_path));

        $this->info(trans('admin.messages.updated'));
        return redirect()->route('dashboard.usefulinfoitems.index', $usefulinfo_id);
    }

    public function destroy($usefulinfo_id, UsefulInfoItem $usefulinfoitem)
    {
        $this->authorize('delete', 'usefulinfoitems');

        $filePath = public_path($usefulinfoitem->file_url);

        if (File::exists($filePath)) {
            File::delete($filePath);
        }

        $usefulinfoitem->delete();

        $this->info(trans('admin.messages.deleted'));
        return redirect()->back();
    }
}
