<?php

namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Controller;
use App\Models\HomeSlider;
use Illuminate\Http\RedirectResponse;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Storage;
use Illuminate\View\View;

class HomeSliderController extends Controller
{
    public function index(): View
    {
        return view('admin.home-sliders.index', [
            'sliders' => HomeSlider::query()->orderBy('sort_order')->latest()->paginate(12),
        ]);
    }

    public function create(): View
    {
        return view('admin.home-sliders.create', [
            'slider' => new HomeSlider(['is_active' => true, 'sort_order' => 0]),
        ]);
    }

    public function store(Request $request): RedirectResponse
    {
        $data = $this->validated($request);
        $data['image_path'] = $data['image']->store('sliders', 'public');
        unset($data['image']);

        HomeSlider::query()->create($data);

        return redirect()->route('admin.home-sliders.index')->with('status', 'Slider created.');
    }

    public function edit(HomeSlider $homeSlider): View
    {
        return view('admin.home-sliders.edit', [
            'slider' => $homeSlider,
        ]);
    }

    public function update(Request $request, HomeSlider $homeSlider): RedirectResponse
    {
        $data = $this->validated($request, updating: true);

        if (isset($data['image'])) {
            Storage::disk('public')->delete($homeSlider->image_path);
            $data['image_path'] = $data['image']->store('sliders', 'public');
            unset($data['image']);
        }

        $homeSlider->update($data);

        return redirect()->route('admin.home-sliders.index')->with('status', 'Slider updated.');
    }

    public function toggle(HomeSlider $homeSlider): RedirectResponse
    {
        $homeSlider->update(['is_active' => ! $homeSlider->is_active]);

        return back()->with('status', 'Slider status updated.');
    }

    public function destroy(HomeSlider $homeSlider): RedirectResponse
    {
        Storage::disk('public')->delete($homeSlider->image_path);
        $homeSlider->delete();

        return back()->with('status', 'Slider deleted.');
    }

    /**
     * @return array<string, mixed>
     */
    private function validated(Request $request, bool $updating = false): array
    {
        $data = $request->validate([
            'title' => ['required', 'string', 'max:255'],
            'subtitle' => ['nullable', 'string', 'max:255'],
            'button_text' => ['nullable', 'string', 'max:80'],
            'button_url' => ['nullable', 'url', 'max:2048'],
            'image' => [$updating ? 'nullable' : 'required', 'image', 'mimes:jpg,jpeg,png,webp', 'max:4096'],
            'sort_order' => ['required', 'integer', 'min:0', 'max:9999'],
            'is_active' => ['nullable', 'boolean'],
        ]);

        $data['is_active'] = $request->boolean('is_active');

        return $data;
    }
}
