<?php

namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Controller;
use App\Models\Banner;
use Illuminate\Http\Request;

class BannerController extends Controller
{
    public function index()
    {
        $banners = Banner::orderBy('order')->orderBy('created_at', 'desc')->paginate(20);

        return view('admin.banners.index', compact('banners'));
    }

    public function create()
    {
        return view('admin.banners.form', ['banner' => null]);
    }

    public function store(Request $request)
    {
        $validated = $this->validateBanner($request);
        $validated['is_active'] = $request->boolean('is_active');
        Banner::create($validated);

        return redirect()->route('admin.banners.index')->with('success', 'Bannière créée.');
    }

    public function edit(Banner $banner)
    {
        return view('admin.banners.form', ['banner' => $banner]);
    }

    public function update(Request $request, Banner $banner)
    {
        $validated = $this->validateBanner($request);
        $validated['is_active'] = $request->boolean('is_active');
        $banner->update($validated);

        return redirect()->route('admin.banners.index')->with('success', 'Bannière mise à jour.');
    }

    public function destroy(Banner $banner)
    {
        $banner->delete();

        return redirect()->route('admin.banners.index')->with('success', 'Bannière supprimée.');
    }

    protected function validateBanner(Request $request): array
    {
        return $request->validate([
            'name' => 'required|string|max:255',
            'type' => 'required|in:bar,popup,alert',
            'content' => 'nullable|string|max:2000',
            'link_url' => 'nullable|string|max:500',
            'link_text' => 'nullable|string|max:120',
            'position' => 'required|in:top,bottom,floating',
            'background_color' => 'nullable|string|max:20',
            'text_color' => 'nullable|string|max:20',
            'image' => 'nullable|string|max:500',
            'starts_at' => 'nullable|date',
            'ends_at' => 'nullable|date',
            'order' => 'nullable|integer|min:0',
        ], [], [
            'name' => 'nom',
            'type' => 'type',
            'content' => 'contenu',
            'position' => 'position',
        ]);
    }
}
