<?php
declare(strict_types=1);

namespace App\Controllers;

use App\Core\Controller;
use App\Core\Response;
use App\Models\AuditLogModel;
use App\Config\Database;

class CategoryController extends Controller
{
    private AuditLogModel $auditLogger;

    public function __construct()
    {
        $this->auditLogger = new AuditLogModel();
    }

    public function index(): void
    {
        $tenantId = (int) $_REQUEST['tenant_id'];
        $db = Database::getInstance();
        $stmt = $db->prepare("SELECT * FROM categories WHERE tenant_id = ? ORDER BY name ASC");
        $stmt->execute([$tenantId]);
        Response::success($stmt->fetchAll());
    }

    public function store(): void
    {
        $tenantId = (int) $_REQUEST['tenant_id'];
        $userId = (int) $_REQUEST['user']['sub'];
        $data = $this->getJsonBody();

        $this->validate($data, ['name' => 'required']);

        $db = Database::getInstance();
        $stmt = $db->prepare("INSERT INTO categories (tenant_id, name, parent_id, description) VALUES (?, ?, ?, ?)");
        $stmt->execute([$tenantId, $data['name'], $data['parent_id'] ?? null, $data['description'] ?? null]);

        $id = $db->lastInsertId();
        $this->auditLogger->log($tenantId, $userId, 'create', 'categories', (int) $id, null, $data);
        Response::success(['id' => $id], 'Category created', 201);
    }
}
