<?php

namespace App\Http\Controllers;

use App\Models\Gallary;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Redirect;
use Illuminate\Validation\ValidationException;
use Illuminate\Support\Facades\Storage;
use Inertia\Inertia;
use DB;
use App\Traits\DeleteModelTrait; 

class GallaryController extends Controller
{
    use DeleteModelTrait;

    /**
     * Display a listing of the resource.
     */
    public function index()
    {
        //
        $gallery = Gallary::where('status', true)
                ->select('photo','title','caption')
                ->get();
        return Inertia::render('Gallery', [
            'gallery' => $gallery ?? [],
        ]);
    }

    /**
     * Show the form for creating a new resource.
     */
    public function create()
    {
        //
    }

    /**
     * Store a newly created resource in storage.
     */
    public function store(Request $request)
    {
        //
        try{
            DB::beginTransaction();
            //validating form data
            $validatedData = $request->validate([
                'title' => 'required|min:3|max:500', 
                'photo' => 'required',
                'caption' => 'nullable|max:255',
                'status' => 'required|boolean',
                
                
            
            ]);

            $gallery = new Gallary;
            $gallery->title = $validatedData['title'];
            $gallery->status = $validatedData['status'];
            $gallery->photo = $validatedData['photo'];
            if ($request->has('caption') && $request->input('caption') !== $gallery->caption) {
                $gallery->caption = $request->input('caption');
            }
            $gallery->save();

            DB::commit();
            return to_route('admin.gallerys')->with('success', [
                'message' => 'Image added successfully',
                'check' => false
            ]);
        } catch (ValidationException $e){
            DB::rollBack();
            return redirect()->back()
                ->withErrors($e->errors()) 
                ->withInput(); 
                
        } catch(\Exception $e) {
            DB::rollBack();
            return Redirect::back()->with('error', [
                'message' => 'Error: '.$e->getMessage(),
                'check' => $e->getMessage()
            ]);
        }

    }

    /**
     * Display the specified resource.
     */
    public function show(Gallary $gallary)
    {
        //
    }

    /**
     * Show the form for editing the specified resource.
     */
    public function edit($id)
    {
        //
        $gallary = Gallary::findOrFail($id);
        return response()->json($gallary);
    }

    /**
     * Update the specified resource in storage.
     */
    public function update(Request $request, $id)
    {
        //
        try {
            DB::beginTransaction();
            $validatedData = $request->validate([
                'title' => 'required|min:3|max:500', 
                'photo' => 'required',
                'caption' => 'nullable|max:255',
                'status' => 'required|boolean',
                
            ]);

            // Retrieve the gallery or fail.
            $gallery = Gallary::findOrFail($id);

            if ($request->has('photo') && $request->input('photo') !== $gallery->photo) {
                $gallery->photo = $request->input('photo');
            }

            if ($request->has('caption') && $request->input('caption') !== $gallery->caption) {
                $gallery->caption = $request->input('caption');
            }

            $gallery->fill($validatedData);
            if ($gallery->isDirty()){
                $gallery->save();
            } 

            DB::commit();

            return Redirect::back()->with('success', [
                'message' => 'Photo updated successfully',
                'check'   => false
            ]);
        } catch (ValidationException $e) {
            DB::rollBack();
            return redirect()->back()
                ->withErrors($e->errors()) 
                ->withInput(); 
        } catch (\Exception $e) {
            DB::rollBack();
            return redirect()->back()->with('error', [
                'message' => 'An error occurred:' . $e->getMessage(),
                'check'   => false
            ]);
        }
    }

    /**
     * Remove the specified resource from storage.
     */
    public function destroy($id)
    {
        //
        return $this->deleteModel($id, new Gallary());
    }
    public function fetchGallary(){
        // Fetch all gallary
        $gallery = Gallary::orderBy('created_at', 'desc')->get();
        return Inertia::render('galleries/Gallery', [
            'gallery' => $gallery->map(function ($gallery_item) {
                return [
                    'id'          => $gallery_item->id,
                    'title'        => $gallery_item->title,
                    'photo'=> $gallery_item->photo, 
                    'status'      => $gallery_item->status,
                    'created_at'  => $gallery_item->created_at,
                    
                ];
            }),
        ]);
    }

    public function uploadImage(Request $request)
    {
        // Validate the image upload
        $request->validate([
            'file' => 'required|image|mimes:jpeg,png,jpg,gif,svg|max:5048',
        ]);

         
        $path = $request->file('file')->store('gallery/images', 'public');  
        $filename = basename($path); 

        return response()->json(['filename' => 'gallery/images/' . $filename]); 
    }
}
