<?php

namespace App\Http\Controllers;

use App\Models\Category;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;

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']]);
    }

    /**
     * GET /categories
     */
    public function index()
    {
        $categories = Category::with('creator')
            ->latest()
            ->get();

        // audit
        audit_log(
            'categories',
            null,
            'listed',
            'Categories list viewed',
            ['count' => $categories->count()]
        );

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

    /**
     * GET /categories/create
     */
    public function create()
    {
        audit_log(
            'categories',
            null,
            'create_form',
            'Category create form opened',
            []
        );

        return view('categories.create');
    }

    /**
     * POST /categories
     */
    public function store(Request $request)
    {
        $validated = $request->validate([
            'name' => ['required', 'string', 'max:255'],
        ]);

        $category = Category::create([
            'name' => $validated['name'],
            'created_by' => Auth::id(),
        ]);

        audit_log(
            'categories',
            $category->id,
            'created',
            'Category created successfully',
            $category->toArray()
        );

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

    /**
     * GET /categories/{category}
     */
    public function show(Category $category)
    {
        $category->load('creator');

        audit_log(
            'categories',
            $category->id,
            'viewed',
            'Category viewed successfully',
            $category->toArray()
        );

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

    /**
     * GET /categories/{category}/edit
     */
    public function edit(Category $category)
    {
        audit_log(
            'categories',
            $category->id,
            'edit_form',
            'Category edit form opened',
            $category->toArray()
        );

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

    /**
     * PUT/PATCH /categories/{category}
     */
    public function update(Request $request, Category $category)
    {
        $validated = $request->validate([
            'name' => ['required', 'string', 'max:255'],
        ]);

        $before = $category->toArray();

        $category->update([
            'name' => $validated['name'],
        ]);

        audit_log(
            'categories',
            $category->id,
            'updated',
            'Category updated successfully',
            [
                'before' => $before,
                'after'  => $category->fresh()->toArray(),
            ]
        );

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

    /**
     * DELETE /categories/{category}
     */
    public function destroy(Category $category)
    {
        $data = $category->toArray();
        $id = $category->id;

        $category->delete();

        audit_log(
            'categories',
            $id,
            'deleted',
            'Category deleted successfully',
            $data
        );

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