<?php

namespace App\Http\Controllers\Admin;

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

class CategoryController extends Controller
{
    public function __construct()
    {
        $this->middleware('permission:view categories', ['only' => ['index', 'show']]);
        $this->middleware('permission:create categories', ['only' => ['create', 'store']]);
        $this->middleware('permission:update categories', ['only' => ['edit', 'update']]);
        $this->middleware('permission:delete categories', ['only' => ['destroy']]);
    }

    public function index()
    {
        $user = auth()->user();
        $isAdminOrSuper = $user->hasAnyRole(['admin', 'super admin']);

        $categories = Category::query()
            ->when(! $isAdminOrSuper, fn ($q) => $q->where('created_by', $user->id))
            ->latest()
            ->paginate(15);

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

    public function create()
    {
        $isAdminOrSuper = auth()->user()->hasAnyRole(['admin', 'super admin']);

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

    public function store(StoreCategoryRequest $request)
    {
        $user = $request->user();
        $isAdminOrSuper = $user->hasAnyRole(['admin', 'super admin']);

        $data = $request->validated();
        $data['created_by'] = $user->id;
        $data['slug'] = $data['slug'] ?? Str::slug($data['name']);
        $data['is_active'] = $isAdminOrSuper
            ? (bool) ($data['is_active'] ?? true)
            : false;

        Category::create($data);

        $message = $isAdminOrSuper
            ? 'Category created successfully.'
            : 'Category created in pending status.';

        return redirect()->route('admin.categories.index')->with('status', $message);
    }

    public function show(Category $category)
    {
        $this->authorizeCategoryAccess($category);

        return redirect()->route('admin.categories.edit', $category);
    }

    public function edit(Category $category)
    {
        $this->authorizeCategoryAccess($category);
        $isAdminOrSuper = auth()->user()->hasAnyRole(['admin', 'super admin']);

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

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

        $isAdminOrSuper = $request->user()->hasAnyRole(['admin', 'super admin']);
        $data = $request->validated();
        $data['slug'] = $data['slug'] ?? Str::slug($data['name']);

        if ($isAdminOrSuper) {
            $data['is_active'] = (bool) ($data['is_active'] ?? false);
        } else {
            unset($data['is_active']);
        }

        $category->update($data);

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

    public function destroy(Category $category)
    {
        $this->authorizeCategoryAccess($category);

        $category->delete();

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

    private function authorizeCategoryAccess(Category $category): void
    {
        $user = auth()->user();

        if ($user->hasAnyRole(['admin', 'super admin'])) {
            return;
        }

        abort_if((int) $category->created_by !== (int) $user->id, 403);
    }
}
