<?php

namespace App\Http\Controllers;

use App\Models\Testimonial;
use Illuminate\Http\Request;
use Illuminate\Support\Str;
use Illuminate\Support\Facades\Auth;
use Inertia\Inertia;
use Illuminate\Http\JsonResponse;
use Illuminate\Validation\ValidationException;
use Illuminate\Support\Facades\Redirect;
use Illuminate\Support\Facades\Storage;
use DB;
use App\Traits\DeleteModelTrait;  

class TestimonialController extends Controller
{
    use DeleteModelTrait;
    /**
     * Display a listing of the resource.
     */
    public function index()
    {
        //
    }

    /**
     * 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([
                'name' => 'required|min:3|max:45', 
                'photo' => 'required',
                'message' => 'required',
                'status' => 'required',
                
            
            ]);

            $testimonial = new Testimonial;
            $testimonial->name = $validatedData['name'];
            $testimonial->message = $validatedData['message'];
            $testimonial->status = $validatedData['status'];
            $testimonial->photo = $validatedData['photo'];
            $testimonial->save();

            DB::commit();
            return to_route('admin.testimonials')->with('success', [
                'message' => 'Testimonial created 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(Testimonial $testimonial)
    {
        //
    }

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

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

            // Retrieve the testimonial or fail.
            $testimonial = Testimonial::findOrFail($id);
            if ($request->has('photo') && $request->input('photo') !== $testimonial->photo) {
                $testimonial->photo = $request->input('photo');
            }

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

            DB::commit();

            return Redirect::back()->with('success', [
                'message' => 'Testimonial 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' => 'Error: ' . $e->getMessage(),
                'check'   => $e->getMessage()
            ]);
        }
    }

    /**
     * Remove the specified resource from storage.
     */
    public function destroy($id)
    {
        return $this->deleteModel($id, new Testimonial());
    }

    public function fetchTestimonials()
    {
        // Fetch all testimonials with their related client
        $testimonials = Testimonial::orderBy('created_at', 'desc')
            ->get();

        return Inertia::render('testimonials/Testimonial', [
            'testimonials' => $testimonials->map(function ($testimonial) {
                return [
                    'id' => $testimonial->id,
                    'name' => $testimonial->name,
                    'photo' => $testimonial->photo,
                    'status' => $testimonial->status,
                    'created_at' => $testimonial->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('testimonial-images', 'public');  
        $filename = basename($path); 

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