<?php

namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Controller;
use App\Models\CarouselItem;
use App\Services\ImageOptimizer;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\File;

class CarouselItemController extends Controller
{
    private function checkGeneralAdmin(Request $request): void
    {
        if (!session('admin_logged_in') || !in_array(session('admin_role'), [1, 2])) {
            abort(403, 'Acceso denegado');
        }
    }

    public function index(Request $request)
    {
        $this->checkGeneralAdmin($request);
        $items = CarouselItem::orderBy('orden', 'asc')->latest()->get();
        return view('admin.carousel.index', compact('items'));
    }

    public function create(Request $request)
    {
        $this->checkGeneralAdmin($request);
        return view('admin.carousel.create');
    }

    public function store(Request $request)
    {
        $this->checkGeneralAdmin($request);
        $request->validate([
            'titulo' => 'nullable|string|max:255',
            'subtitulo' => 'nullable|string|max:255',
            'boton_texto' => 'nullable|string|max:255',
            'boton_enlace' => 'nullable|string|max:255',
            'imagen' => 'required|image|mimes:jpeg,png,jpg,webp|max:5120',
            'orden' => 'nullable|integer',
            'activo' => 'nullable|boolean',
        ]);

        $data = $request->except('imagen');
        $data['activo'] = $request->has('activo');

        if ($request->hasFile('imagen')) {
            $path = app(ImageOptimizer::class)->storeAndOptimize($request->file('imagen'), 'carousel');
            $data['imagen'] = 'storage/' . $path;
        }

        CarouselItem::create($data);

        return redirect()->route('admin.carousel.index')->with('admin_msg', 'Slide creado exitosamente.');
    }

    public function edit(Request $request, CarouselItem $carouselItem)
    {
        $this->checkGeneralAdmin($request);
        return view('admin.carousel.edit', compact('carouselItem'));
    }

    public function update(Request $request, CarouselItem $carouselItem)
    {
        $this->checkGeneralAdmin($request);
        $request->validate([
            'titulo' => 'nullable|string|max:255',
            'subtitulo' => 'nullable|string|max:255',
            'boton_texto' => 'nullable|string|max:255',
            'boton_enlace' => 'nullable|string|max:255',
            'imagen' => 'nullable|image|mimes:jpeg,png,jpg,webp|max:5120',
            'orden' => 'nullable|integer',
            'activo' => 'nullable|boolean',
        ]);

        $data = $request->except('imagen');
        $data['activo'] = $request->has('activo');

        if ($request->hasFile('imagen')) {
            // Eliminar imagen anterior si existe
            if ($carouselItem->imagen) {
                $oldPath = public_path($carouselItem->imagen);
                if (File::exists($oldPath)) {
                    File::delete($oldPath);
                }
            }

            $path = app(ImageOptimizer::class)->storeAndOptimize($request->file('imagen'), 'carousel');
            $data['imagen'] = 'storage/' . $path;
        }

        $carouselItem->update($data);

        return redirect()->route('admin.carousel.index')->with('admin_msg', 'Slide actualizado exitosamente.');
    }

    public function destroy(Request $request, CarouselItem $carouselItem)
    {
        $this->checkGeneralAdmin($request);
        if ($carouselItem->imagen) {
            $imagePath = public_path($carouselItem->imagen);
            if (File::exists($imagePath)) {
                File::delete($imagePath);
            }
        }

        $carouselItem->delete();

        return redirect()->route('admin.carousel.index')->with('admin_msg', 'Slide eliminado exitosamente.');
    }
}
