<?php

namespace App\Http\Controllers\Client;

use App\Http\Controllers\Controller;
use App\Http\Requests\testimonialRequest;
use App\Models\testimonial;
use Illuminate\Http\Request;
use Inertia\Inertia;
use Spatie\LaravelImageOptimizer\Facades\ImageOptimizer;
use Storage;

class TestimonialController extends Controller
{
    public function index()
    {
        $testimonial = Testimonial::all();
        $testimonialResponse = $testimonial->map(function ($item) {
            return [
                "name" => $item->name,
                "description" => $item->description,
                "location" => $item->location,
                "image" => $item->image ? asset(Storage::url($item->image)) : null,
            ];
        });

        return Inertia::render('dashboard/testimonial', ["testimonial" => $testimonialResponse]);
    }

    public function store(testimonialRequest $request)
    {
        $request->validated();

        if ($request->hasFile('image')) {
            $path = $request->file('image')->store('testimonial', 'public');
            $fullPath = storage_path('app/public/' . $path);
            ImageOptimizer::optimize($fullPath);

            $testimonial = Testimonial::create([
                "name" => $request->name,
                "location" => $request->location,
                "description" => $request->description,
                "image" => $path
            ]);

            $testimonialResponse = [
                "name" => $testimonial->name,
                "location" => $testimonial->location,
                "description" => $testimonial->description,
                "image" => $testimonial->image ? asset(Storage::url($testimonial->image)) : null
            ];

            return to_route('home', $testimonialResponse);
        }
        return response()->json([
            'status' => 'error',
            'message' => 'File upload failed',
        ], 400);
    }
}
