<?php

namespace App\Http\Controllers;

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

class BannerController extends Controller
{
    /**
     * Get list of all banners (sorted).
     */
    public function index()
    {
        return response()->json(
            Banner::orderBy('sort_order')->orderBy('id')->get()
        );
    }

    /**
     * Upload a new banner image.
     */
    public function store(Request $request)
    {
        $validated = $request->validate([
            'image' => ['required', 'image', 'mimes:jpg,jpeg,png,webp', 'max:2048'], // 2MB
            'title' => ['nullable', 'string', 'max:120'],
            'caption' => ['nullable', 'string', 'max:255'],
            'sort_order' => ['nullable', 'integer', 'min:0', 'max:9999'],
        ]);

        $path = $request->file('image')->store('banners', 'public');

        Banner::create([
            'image_path' => $path,
            'title' => $validated['title'] ?? null,
            'caption' => $validated['caption'] ?? null,
            'sort_order' => $validated['sort_order'] ?? 0,
        ]);

        return $this->index();
    }

    /**
     * Delete a banner (file + record).
     */
    public function destroy($id)
    {
        $banner = Banner::findOrFail($id);
        if ($banner->image_path && Storage::disk('public')->exists($banner->image_path)) {
            Storage::disk('public')->delete($banner->image_path);
        }
        $banner->delete();

        return $this->index();
    }

    /**
     * Public endpoint untuk halaman tracking (tanpa auth).
     */
    public function publicIndex()
    {
        return $this->index();
    }
}
