<?php
declare(strict_types=1);
require_once '../config/database.php';
require_once '../app/helpers/rbac.php';
require_once '../app/helpers/audit.php';
require_once '../app/helpers/api_security.php';
require_once '../app/helpers/soft_delete.php';

header('Content-Type: application/json');

requireApiLogin();
enforceCsrfForUnsafeRequest();

$action = $_GET['action'] ?? '';

if (!isAdmin() && !can('tyre_brand.view')) {
    respond(['status' => 'error', 'message' => 'Unauthorized']);
}

try {
    switch ($action) {
        case 'list': handleList($pdo); break;
        case 'save': handleSave($pdo); break;
        case 'delete': handleDelete($pdo); break;
        default: respond(['status' => 'error', 'message' => 'Unknown action']);
    }
} catch (Exception $e) {
    respond(['status' => 'error', 'message' => $e->getMessage()]);
}

function respond(array $payload): void { apiRespond($payload); }

function doAudit(PDO $pdo, string $action, string $description, ?int $recordId = null): void {
    audit($pdo, (int)($_SESSION['user_id'] ?? 0), $action, 'tyre_brand', $recordId ?? 0, $description, null, null);
}

function handleList(PDO $pdo): void
{
    $where = ['deleted_at IS NULL'];
    $params = [];
    if (!empty($_GET['search'])) {
        $q = '%' . $_GET['search'] . '%';
        $where[] = '(name LIKE :q1 OR description LIKE :q2)';
        $params['q1'] = $q; $params['q2'] = $q;
    }
    if (isset($_GET['active_only'])) $where[] = 'is_active = 1';

    $stmt = $pdo->prepare("SELECT * FROM tyre_brands WHERE " . implode(' AND ', $where) . " ORDER BY name ASC");
    $stmt->execute($params);
    respond(['status' => 'success', 'data' => $stmt->fetchAll()]);
}

function handleSave(PDO $pdo): void
{
    if (!isAdmin() && !can('tyre_brand.create') && !can('tyre_brand.edit')) {
        respond(['status' => 'error', 'message' => 'Unauthorized']);
    }
    $id = (int)($_POST['id'] ?? 0);
    $name = trim($_POST['name'] ?? '');
    if (!$name) respond(['status' => 'error', 'message' => 'Brand name is required']);
    $data = ['name' => $name, 'description' => trim($_POST['description'] ?? '')];

    if ($id > 0) {
        $data['id'] = $id;
        $sets = implode(', ', array_map(function ($c) { return "{$c} = :{$c}"; }, array_keys($data)));
        $pdo->prepare("UPDATE tyre_brands SET {$sets} WHERE id = :id")->execute($data);
        doAudit($pdo, 'update', "Brand #{$id} updated", $id);
        respond(['status' => 'success', 'message' => 'Brand updated']);
    } else {
        $cols = implode(', ', array_keys($data));
        $vals = ':' . implode(', :', array_keys($data));
        $pdo->prepare("INSERT INTO tyre_brands ({$cols}) VALUES ({$vals})")->execute($data);
        $newId = (int)$pdo->lastInsertId();
        doAudit($pdo, 'create', "Brand #{$newId} created", $newId);
        respond(['status' => 'success', 'message' => 'Brand created', 'id' => $newId]);
    }
}

function handleDelete(PDO $pdo): void
{
    if (!isAdmin() && !can('tyre_brand.delete')) {
        respond(['status' => 'error', 'message' => 'Unauthorized']);
    }
    $id = (int)($_POST['id'] ?? 0);
    if ($id <= 0) respond(['status' => 'error', 'message' => 'Invalid ID']);
    softDelete($pdo, 'tyre_brands', $id);
    doAudit($pdo, 'delete', "Brand #{$id} deleted", $id);
    respond(['status' => 'success', 'message' => 'Brand deleted']);
}
