<?php

namespace App\Http\Controllers\Admin\Pages\MenuCategories;

use App\Http\Controllers\Controller;
use App\Http\Requests\MenuCategories\MenuCategoryStoreRequest;
use App\Http\Requests\MenuCategories\MenuCategoryUpdateRequest;
use App\Models\MenuCategory;
use App\Traits\ImageCompressor;
use DataTables;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\File;
use PHPUnit\TextUI\XmlConfiguration\Exception;

class MenuCategoryController extends Controller
{


    use ImageCompressor;

    public function __construct()
    {
        $this->middleware('permission:view menuCategories')->only('index', 'ajax');
        $this->middleware('permission:create menuCategory')->only('create');
        $this->middleware('permission:store menuCategory')->only('store');
        $this->middleware('permission:edit menuCategory')->only('edit');
        $this->middleware('permission:update menuCategory')->only('update');
        $this->middleware('permission:destroy menuCategory')->only('destroy');
    }


    /**
     * Display a listing of the resource.
     */
    public function index()
    {
        $menuCategories =MenuCategory::all();
        return view('app.admin.pages.menuCategories.all-menuCategories',compact([
            'menuCategories'
        ]));
    }

    public function search(Request $request)
    {
        $query = $request->input('query');

        $menuCategories = MenuCategory::where('menu_category_az', 'LIKE', "%{$query}%")
                            ->orWhere('menu_category_ru', 'LIKE', "%{$query}%")
                            ->orWhere('menu_category_en', 'LIKE', "%{$query}%")
                            ->get();

        return view('app.admin.pages.menuCategories.all-menuCategories',compact([
            'menuCategories'
        ]));
    }

    /**
     * Show the form for creating a new resource.
     */
    public function create()
    {
        $menuCategories =MenuCategory::all();
        return view('app.admin.pages.menuCategories.create-menuCategory',compact([
            'menuCategories'
        ]));
    }

    /**
     * Store a newly created resource in storage.
     */
    public function store(MenuCategoryStoreRequest $request)
    {
        $validatedData = $request->safe();

        try {

            if ($request->hasFile('image')) {
                $validatedData['image'] = self::compressImage($request->file('image'), 'MenuCategoryImage');
            }

            $menuCategory = MenuCategory::create($validatedData->except('partners'));



            return back()->with('success', __('Data successfully created!'));
        } catch (Exception $e) {
            return back()->withErrors([$e->getMessage()]);
        }
    }

    /**
     * Display the specified resource.
     */
    public function show(MenuCategory $menuCategory)
    {
        //
    }

    /**
     * Show the form for editing the specified resource.
     */
    public function edit(MenuCategory $menuCategory)
    {
        $menuCategories =MenuCategory::all();
        return view('app.admin.pages.menuCategories.edit-menuCategory',compact([
            'menuCategory',
            'menuCategories'
        ]));
    }

    /**
     * Update the specified resource in storage.
     */
    public function update(MenuCategoryUpdateRequest $request, MenuCategory $menuCategory)
    {
        $validatedData = $request->safe();
        try {

            if ($request->hasFile('image')) {
                File::delete('/storage/images/' . $menuCategory->getAttribute('image'));
                $validatedData['image'] = self::compressImage($request->file('image'), 'MenuCategoryImage');
            } else {
                $validatedData['image'] = $menuCategory->getAttribute('image');
            }


            $menuCategory->update($validatedData->except('partners'));


            if ($request->hasFile('partners')) {
                foreach ($request->file('partners') as $image) {
                    MenuCategoryGallery::create([
                        'category_id' => $menuCategory->id,
                        'image' => self::compressImage($image, 'CategoryGallery')
                    ]);
                }
            }

            return back()->with('success', __('Data successfully updated!'));
        } catch (Exception $e) {
            return back()->withErrors([$e->getMessage()]);
        }
    }

    /**
     * Remove the specified resource from storage.
     */
    public function destroy($id)
    {

        try {

            $menuCategory =MenuCategory::find($id);
            $menuCategory->delete();

            return back()->with('success', __('Data successfully deleted!'));
        } catch (Exception $e) {
            return back()->with('error', $e->getMessage());
        }
    }

    /**
     * @return JsonResponse
     * @throws Exception
     */
    public function ajax()
    {
        $menuCategories = MenuCategory::query();
        return DataTables::of($menuCategories)->editColumn('image', function (MenuCategory $menuCategory) {
            return view('app.admin.includes.table-elements.image', [
                'image' => $menuCategory->image()
            ]);
        })->addColumn('options', function (MenuCategory $menuCategory) {
            return view('app.admin.includes.table-elements.action-buttons', [
                'modelName' => 'menuCategory',
                'editUrl' => route('admin:menuCategories.edit', $menuCategory->getAttribute('id')),
                'deleteUrl' => route('admin:menuCategories.destroy', $menuCategory->getAttribute('id'))
            ]);
        })->toJson();
    }
}
