<?php

namespace App\Http\Controllers;

use App\Http\Requests\CategoryRequest;
use App\Models\Category;
use Illuminate\Http\RedirectResponse;
use Illuminate\Support\Facades\Cache;
use Illuminate\View\View;

class CategoryController extends Controller
{
    public function index(): View
    {
        $categories = Category::query()
            ->where('outlet_id', auth()->user()->outlet_id)
            ->orderBy('sort_order')
            ->paginate(20);

        return view('master.categories.index', compact('categories'));
    }

    public function store(CategoryRequest $request): RedirectResponse
    {
        Category::query()->create([
            'outlet_id' => $request->user()->outlet_id,
            'name' => $request->validated('name'),
            'sort_order' => (int) ($request->validated('sort_order') ?? 0),
        ]);
        Cache::forget("pos.catalog.{$request->user()->outlet_id}");

        return back()->with('success', 'Kategori ditambahkan.');
    }

    public function update(CategoryRequest $request, Category $category): RedirectResponse
    {
        abort_if((int) $category->outlet_id !== (int) $request->user()->outlet_id, 403);
        $category->update([
            'name' => $request->validated('name'),
            'sort_order' => (int) ($request->validated('sort_order') ?? 0),
        ]);
        Cache::forget("pos.catalog.{$request->user()->outlet_id}");

        return back()->with('success', 'Kategori diperbarui.');
    }

    public function destroy(Category $category): RedirectResponse
    {
        abort_if((int) $category->outlet_id !== (int) auth()->user()->outlet_id, 403);
        Cache::forget("pos.catalog.".auth()->user()->outlet_id);
        $category->delete();

        return back()->with('success', 'Kategori dihapus.');
    }
}
