<?php

namespace App\Http\Controllers\Portal;

use App\Http\Controllers\Controller;
use App\Http\Requests\Portal\StoreCategoryRequest;
use App\Http\Requests\Portal\UpdateCategoryRequest;
use App\Models\Category;
use Illuminate\Http\RedirectResponse;
use Illuminate\Support\Str;
use Illuminate\View\View;

class CategoryController extends Controller
{
    public function index(): View
    {
        $branchId = auth()->user()->active_branch_id;

        $categories = Category::forBranch($branchId)
            ->with(['parent', 'children'])
            ->orderBy('sort_order')
            ->get();

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

    public function create(): View
    {
        $branchId = auth()->user()->active_branch_id;
        $categories = Category::forBranch($branchId)->whereNull('parent_id')->get();

        return view('portal.categories.create', compact('categories'));
    }

    public function store(StoreCategoryRequest $request): RedirectResponse
    {
        $branchId = auth()->user()->active_branch_id;

        $validated = $request->validated();
        $validated['branch_id'] = $branchId;
        $validated['slug'] = Str::slug($validated['slug']);

        Category::create($validated);

        return redirect()->route('portal.categories.create')->with('success', 'Category created successfully.');
    }

    public function edit(Category $category): View
    {
        $this->authorizeAccess($category);

        $branchId = auth()->user()->active_branch_id;
        $categories = Category::forBranch($branchId)
            ->whereNull('parent_id')
            ->where('id', '!=', $category->id)
            ->get();

        return view('portal.categories.edit', compact('category', 'categories'));
    }

    public function update(UpdateCategoryRequest $request, Category $category): RedirectResponse
    {
        $this->authorizeAccess($category);

        $validated = $request->validated();
        $validated['slug'] = Str::slug($validated['slug']);

        $category->update($validated);

        return redirect()->route('portal.categories.index')->with('success', 'Category updated successfully.');
    }

    public function destroy(Category $category): RedirectResponse
    {
        $this->authorizeAccess($category);

        $category->delete();

        return redirect()->route('portal.categories.index')->with('success', 'Category deleted successfully.');
    }

    /**
     * Ensure the user has access to the category.
     */
    protected function authorizeAccess(Category $category): void
    {
        if ($category->branch_id !== auth()->user()->active_branch_id) {
            abort(403, 'Unauthorized access to this category.');
        }
    }
}
