<?php

namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Controller;
use App\Models\Testimonio;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Storage;

class TestimonioController extends Controller
{
    public function index()
    {
        $testimonios = Testimonio::orderBy('orden')->get();
        return view('admin.testimonios.index', compact('testimonios'));
    }

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

    public function store(Request $request)
    {
        $data = $request->validate([
            'nombre'   => 'required|string|max:255',
            'cargo'    => 'nullable|string|max:150',
            'empresa'  => 'nullable|string|max:255',
            'avatar'   => 'nullable|image|max:1024',
            'mensaje'  => 'required|string',
            'estrellas'=> 'required|integer|min:1|max:5',
            'orden'    => 'nullable|integer',
        ]);
        $data['activo'] = $request->has('activo') ? 1 : 0;
        if ($request->hasFile('avatar')) {
            $data['avatar'] = $request->file('avatar')->store('testimonios', 'public');
        }
        Testimonio::create($data);
        return redirect()->route('admin.testimonios.index')->with('success', 'Testimonio creado correctamente.');
    }

    public function edit(Testimonio $testimonio)
    {
        return view('admin.testimonios.edit', compact('testimonio'));
    }

    public function update(Request $request, Testimonio $testimonio)
    {
        $data = $request->validate([
            'nombre'   => 'required|string|max:255',
            'cargo'    => 'nullable|string|max:150',
            'empresa'  => 'nullable|string|max:255',
            'avatar'   => 'nullable|image|max:1024',
            'mensaje'  => 'required|string',
            'estrellas'=> 'required|integer|min:1|max:5',
            'orden'    => 'nullable|integer',
        ]);
        $data['activo'] = $request->has('activo') ? 1 : 0;
        if ($request->hasFile('avatar')) {
            if ($testimonio->avatar) Storage::disk('public')->delete($testimonio->avatar);
            $data['avatar'] = $request->file('avatar')->store('testimonios', 'public');
        }
        $testimonio->update($data);
        return redirect()->route('admin.testimonios.index')->with('success', 'Testimonio actualizado correctamente.');
    }

    public function destroy(Testimonio $testimonio)
    {
        if ($testimonio->avatar) Storage::disk('public')->delete($testimonio->avatar);
        $testimonio->delete();
        return redirect()->route('admin.testimonios.index')->with('success', 'Testimonio eliminado correctamente.');
    }
}
