<?php

namespace App\Http\Controllers;

use App\Models\Testimonial;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;

class TestimonialController extends Controller
{
    public function index()
    {
        $user = Auth::user();

        if ($user->role === 'admin') {
            // If the user is an admin, return all testimonials
            $testimonials = Testimonial::all();
        } else {
            // If the user is not an admin, return only their testimonials
            $testimonials = Testimonial::where('user_id', $user->id)->get();
        }

        return response()->json($testimonials);
    }

    public function getTestimonials()
    {
        $testimonials = Testimonial::where('status','!=','pending')->get();
        return response()->json($testimonials);
    }

    public function store(Request $request)
    {
        $request->validate([
            'name' => 'required|string|max:255',
            'message' => 'required|string',
            'photo' => 'nullable|image|mimes:jpeg,png,jpg,gif|max:2048',
        ]);

        $testimonial = new Testimonial();
        $testimonial->name = $request->name;
        $testimonial->message = $request->message;

        if ($request->hasFile('photo')) {
            // Manually move the file to the public/testimonials directory
            $photo = $request->file('photo');
            $fileName = time() . '_' . $photo->getClientOriginalName();
            $destinationPath = public_path('/testimonials');
            $photo->move($destinationPath, $fileName);

            // Construct the URL to the stored file
            $url = asset('testimonials/' . $fileName);

            $testimonial->photo = $url;
        }

        $user = Auth::user();
        if ($user->role === 'admin') {
            $testimonial->status = 'approved';
        } else {
            $testimonial->status = 'pending';
        }
        $testimonial->user_id = Auth::id();
        $testimonial->save();

        return response()->json(['message' => 'Testimonial submitted successfully'], 201);
    }

    public function update(Request $request, $id)
    {
        $testimonial = Testimonial::findOrFail($id);

        $request->validate([
            'status' => 'required|in:pending,approved',
        ]);

        $testimonial->status = $request->status;
        $testimonial->save();

        return response()->json(['message' => 'Testimonial status updated successfully']);
    }

    public function destroy($id)
    {
        $testimonial = Testimonial::findOrFail($id);
        $testimonial->delete();

        return response()->json(['message' => 'Testimonial deleted successfully']);
    }

    public function approve($id)
    {
        $testimonial = Testimonial::findOrFail($id);
        $testimonial->status = 'approved';
        $testimonial->save();

        return response()->json(['message' => 'Testimonial approved successfully']);
    }
}
