<?php

namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Controller;
use App\Http\Requests\Admin\StoreRouletteCategoryRequest;
use App\Http\Requests\Admin\StoreRouletteItemRequest;
use App\Models\AuditLog;
use App\Models\RouletteCategory;
use App\Models\RouletteItem;
use Illuminate\Http\RedirectResponse;
use Illuminate\Support\Facades\Storage;
use Inertia\Inertia;
use Inertia\Response;

class RouletteAdminController extends Controller
{
    public function index(): Response
    {
        return Inertia::render('Admin/Roulette/Index', [
            'categories' => RouletteCategory::query()->orderBy('name')->get(),
            'items' => RouletteItem::query()->with('category:id,name')->orderBy('name')->get(),
        ]);
    }

    public function storeCategory(StoreRouletteCategoryRequest $request): RedirectResponse
    {
        $category = RouletteCategory::create([
            'name' => $request->validated('name'),
            'slug' => $request->slug(),
        ]);

        AuditLog::record('roulette_category.created', $category);

        return back()->with('success', 'Category created.');
    }

    public function destroyCategory(RouletteCategory $category): RedirectResponse
    {
        AuditLog::record('roulette_category.deleted', $category);
        $category->delete();

        return back()->with('success', 'Category deleted.');
    }

    public function storeItem(StoreRouletteItemRequest $request): RedirectResponse
    {
        $data = $request->safe()->except('image');
        $data['image_path'] = Storage::disk('public')->put('roulette', $request->file('image'));

        $item = RouletteItem::create($data);

        AuditLog::record('roulette_item.created', $item, $data);

        return back()->with('success', 'Item created.');
    }

    public function updateItem(StoreRouletteItemRequest $request, RouletteItem $item): RedirectResponse
    {
        $data = $request->safe()->except('image');

        if ($request->hasFile('image')) {
            Storage::disk('public')->delete($item->image_path);
            $data['image_path'] = Storage::disk('public')->put('roulette', $request->file('image'));
        }

        $item->update($data);

        AuditLog::record('roulette_item.updated', $item, $data);

        return back()->with('success', 'Item updated.');
    }

    public function destroyItem(RouletteItem $item): RedirectResponse
    {
        AuditLog::record('roulette_item.deleted', $item);
        Storage::disk('public')->delete($item->image_path);
        $item->delete();

        return back()->with('success', 'Item deleted.');
    }
}
