<?php

namespace App\Http\Controllers;

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

class SliderController extends Controller
{
    /**
     * Display the active slides for the public hero slider.
     */
    public function index()
    {
        return Slider::where('is_active', true)->orderBy('sort_order')->get();
    }

    /**
     * Display all slides for the admin dashboard.
     */
    public function adminIndex()
    {
        return Slider::orderBy('sort_order')->get();
    }

    /**
     * Display the specified resource for the admin dashboard.
     */
    public function adminShow(Slider $slider)
    {
        return $slider;
    }

    /**
     * Store a newly created resource in storage.
     */
    public function store(Request $request)
    {
        $data = $request->validate([
            'title' => ['nullable', 'string', 'max:255'],
            'subtitle' => ['nullable', 'string'],
            'link_url' => ['nullable', 'url', 'max:255'],
            'sort_order' => ['nullable', 'integer'],
            'is_active' => ['boolean'],
            'image' => ['required', 'image', 'max:5120'],
        ]);

        $data['image_path'] = $request->file('image')->store('sliders', 'public');
        unset($data['image']);

        return response()->json(Slider::create($data), 201);
    }

    /**
     * Update the specified resource in storage.
     */
    public function update(Request $request, Slider $slider)
    {
        $data = $request->validate([
            'title' => ['nullable', 'string', 'max:255'],
            'subtitle' => ['nullable', 'string'],
            'link_url' => ['nullable', 'url', 'max:255'],
            'sort_order' => ['nullable', 'integer'],
            'is_active' => ['boolean'],
            'image' => ['nullable', 'image', 'max:5120'],
        ]);

        if ($request->hasFile('image')) {
            if ($slider->image_path && ! str_starts_with($slider->image_path, 'http')) {
                Storage::disk('public')->delete($slider->image_path);
            }

            $data['image_path'] = $request->file('image')->store('sliders', 'public');
        }
        unset($data['image']);

        $slider->update($data);

        return $slider;
    }

    /**
     * Remove the specified resource from storage.
     */
    public function destroy(Slider $slider)
    {
        if ($slider->image_path && ! str_starts_with($slider->image_path, 'http')) {
            Storage::disk('public')->delete($slider->image_path);
        }

        $slider->delete();

        return response()->noContent();
    }
}
