<?php

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

use App\Http\Controllers\Controller;
use App\Http\Requests\Menyus\MenyuStoreRequest;
use App\Http\Requests\Menyus\MenyuUpdateRequest;
use App\Models\MenuCategory;
use App\Models\Menyu;
use App\Models\MenyuGallery;
use App\Traits\Description;
use App\Traits\FileUploader;
use App\Traits\ImageCompressor;
use App\Traits\Slug;
use App\Traits\Title;
use DataTables;
use Exception;
use Illuminate\Http\JsonResponse;
use Illuminate\Support\Facades\File;
use Illuminate\Http\Request;



class MenyuController extends Controller
{

    use ImageCompressor ,FileUploader,Slug ,Title,Description;

    public function __construct()
    {
        $this->middleware('permission:view menyus')->only('index', 'ajax');
        $this->middleware('permission:create menyu')->only('create');
        $this->middleware('permission:store menyu')->only('store');
        $this->middleware('permission:edit menyu')->only('edit');
        $this->middleware('permission:update menyu')->only('update');
        $this->middleware('permission:destroy menyu')->only('destroy');
    }
    /**
     * Display a listing of the resource.
     */
    public function index(Request $request)
    {
        $categoryId = $request->input('category_id'); 
        $menuCategories = MenuCategory::where('position', 1)->get();

        if ($categoryId) {
            $menyus = Menyu::where('category_id', $categoryId)->get();
        } else {
            $menyus = Menyu::all();
        }

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

    /**
     * Show the form for creating a new resource.
     */
    public function create()
    {
        $menuCategories = MenuCategory::pluck('menu_category_az', 'id');
        return view('app.admin.pages.menus.create-menu', compact('menuCategories'));
    }


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

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

            if ($request->hasFile('video')) {
                $videoPath = $request->file('video')->store('videos', 'public');
                $validatedData['video'] = $videoPath; 
            }

            $category_id = $request->input('category_id');

            $validatedData['category_id'] = $category_id;

            $menyu=Menyu::create($validatedData);

            if ($request->hasFile('partners')) {
                foreach ($request->file('partners') as $image) {
                    MenyuGallery::create([
                        'menyu_id' => $menyu->id,
                        'partners' => self::compressImage($image, 'MenyuGallery')
                    ]);
                }
            }

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



    /**
     * Display the specified resource.
     */
    public function show(Menyu $menyu)
    {
        //
    }

    /**
     * Show the form for editing the specified resource.
     */
    public function edit(Menyu $menyu)
    {
        $menuCategories = MenuCategory::pluck('menu_category_az', 'id');
        return view('app.admin.pages.menus.edit-menu', compact(
            'menuCategories',
            'menyu',
        ));
    }

    /**
     * Update the specified resource in storage.
     */
    public function update(MenyuUpdateRequest $request, $id)
    {
        $validatedData = $request->safe();
        $menyu=Menyu::findOrFail($id);
        try {

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

            if ($request->hasFile('video')) {
                $videoPath = $request->file('video')->store('videos', 'public');
                $validatedData['video'] = $videoPath; 
            } else {
                $validatedData['video'] = $menyu->getAttribute('video');
            }




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

            if ($request->hasFile('partners')) {
                foreach ($request->file('partners') as $image) {
                    MenyuGallery::create([
                        'menyu_id' => $menyu->id,
                        'partners' => self::compressImage($image, 'MenyuGallery')
                    ]);
                }
            }

            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 {
            $menyu=Menyu::find($id);
            $menyu->delete();
            return back()->with('success', __('Data successfully deleted!'));
        } catch (Exception $e) {
            return back()->with('error', $e->getMessage());
        }
    }

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