<?php

namespace App\Http\Controllers;

use App\Http\Controllers\Controller;
use App\Models\Testimonial;
use Illuminate\Http\Request;

class AdminTestimonialController extends Controller
{
    public function index()
    {
        $testimonials = Testimonial::latest()->paginate(15);
        return view('admin.testimonials.index', compact('testimonials'));
    }

    public function create()
    {
        return view('admin.testimonials.create');
    }

    public function store(Request $request)
    {
        $data = $request->validate([
            'client_name'       => 'required|max:255',
            'client_profession' => 'required|max:255',
            'review'            => 'required|string',
            'stars'             => 'required|integer|between:1,5',
            'image'             => 'nullable|image|max:4048',
            'is_active'         => 'boolean'
        ]);

        // ✅ Save image directly into /public/testimonials folder
        if ($request->hasFile('image')) {
            $image = $request->file('image');
            $filename = time() . '-' . uniqid() . '.' . $image->getClientOriginalExtension();
            $image->move(public_path('testimonials'), $filename);
            $data['image'] = 'testimonials/' . $filename;
        }

        Testimonial::create($data);
        return redirect()->route('admin.testimonials.index')->with('success', 'Testimonial added.');
    }

    public function edit(Testimonial $review)
    {
        return view('admin.testimonials.edit', compact('review'));
    }

    public function update(Request $request, Testimonial $review)
    {
        $data = $request->validate([
            'client_name'       => 'required|max:255',
            'client_profession' => 'required|max:255',
            'review'            => 'required|string',
            'stars'             => 'required|integer|between:1,5',
            'image'             => 'nullable|image|max:4048',
            'is_active'         => 'boolean'
        ]);

        // ✅ Replace old image if a new one is uploaded
        if ($request->hasFile('image')) {
            if ($review->image && file_exists(public_path($review->image))) {
                unlink(public_path($review->image));
            }

            $image = $request->file('image');
            $filename = time() . '-' . uniqid() . '.' . $image->getClientOriginalExtension();
            $image->move(public_path('testimonials'), $filename);
            $data['image'] = 'testimonials/' . $filename;
        }

        $review->update($data);
        return redirect()->route('admin.testimonials.index')->with('success', 'Testimonial updated.');
    }

    public function destroy(Testimonial $review)
    {
        if ($review->image && file_exists(public_path($review->image))) {
            unlink(public_path($review->image));
        }

        $review->delete();
        return redirect()->route('admin.testimonials.index')->with('success', 'Testimonial deleted.');
    }
}
