<?php

namespace App\Http\Controllers\Admin;

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

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

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

    public function store(Request $request)
    {
        $data = $request->validate([
            'titulo'       => 'required|string|max:255',
            'subtitulo'    => 'nullable|string|max:255',
            'descripcion'  => 'nullable|string',
            'imagen'       => 'nullable|image|max:2048',
            'boton_texto'  => 'nullable|string|max:100',
            'boton_url'    => 'nullable|string|max:255',
            'boton2_texto' => 'nullable|string|max:100',
            'boton2_url'   => 'nullable|string|max:255',
            'orden'        => 'nullable|integer',
            'activo'       => 'nullable|boolean',
        ]);

        if ($request->hasFile('imagen')) {
            $data['imagen'] = $request->file('imagen')->store('sliders', 'public');
        }
        $data['activo'] = $request->has('activo') ? 1 : 0;

        Slider::create($data);
        return redirect()->route('admin.sliders.index')->with('success', 'Slider creado correctamente.');
    }

    public function edit(Slider $slider)
    {
        return view('admin.sliders.edit', compact('slider'));
    }

    public function update(Request $request, Slider $slider)
    {
        $data = $request->validate([
            'titulo'       => 'required|string|max:255',
            'subtitulo'    => 'nullable|string|max:255',
            'descripcion'  => 'nullable|string',
            'imagen'       => 'nullable|image|max:2048',
            'boton_texto'  => 'nullable|string|max:100',
            'boton_url'    => 'nullable|string|max:255',
            'boton2_texto' => 'nullable|string|max:100',
            'boton2_url'   => 'nullable|string|max:255',
            'orden'        => 'nullable|integer',
            'activo'       => 'nullable|boolean',
        ]);

        if ($request->hasFile('imagen')) {
            if ($slider->imagen) Storage::disk('public')->delete($slider->imagen);
            $data['imagen'] = $request->file('imagen')->store('sliders', 'public');
        }
        $data['activo'] = $request->has('activo') ? 1 : 0;

        $slider->update($data);
        return redirect()->route('admin.sliders.index')->with('success', 'Slider actualizado correctamente.');
    }

    public function destroy(Slider $slider)
    {
        if ($slider->imagen) Storage::disk('public')->delete($slider->imagen);
        $slider->delete();
        return redirect()->route('admin.sliders.index')->with('success', 'Slider eliminado correctamente.');
    }
}
