<?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_model.view')) {
    respond(['status' => 'error', 'message' => 'Unauthorized']);
}

try {
    switch ($action) {
        case 'list': handleList($pdo); break;
        case 'save': handleSave($pdo); break;
        case 'delete': handleDelete($pdo); break;
        case 'brands': handleBrands($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_model', $recordId ?? 0, $description, null, null);
}

function handleList(PDO $pdo): void
{
    $where = ['m.deleted_at IS NULL'];
    $params = [];

    if (!empty($_GET['brand_id'])) {
        $where[] = 'm.brand_id = :brand_id';
        $params['brand_id'] = (int)$_GET['brand_id'];
    }
    if (!empty($_GET['search'])) {
        $q = '%' . $_GET['search'] . '%';
        $where[] = '(m.name LIKE :q1 OR m.description LIKE :q2 OR b.name LIKE :q3)';
        $params['q1'] = $q; $params['q2'] = $q; $params['q3'] = $q;
    }
    if (isset($_GET['active_only'])) $where[] = 'm.is_active = 1';

    $stmt = $pdo->prepare("
        SELECT m.*, b.name AS brand_name
        FROM tyre_models m
        LEFT JOIN tyre_brands b ON b.id = m.brand_id AND b.deleted_at IS NULL
        WHERE " . implode(' AND ', $where) . "
        ORDER BY b.name ASC, m.name ASC
    ");
    $stmt->execute($params);
    respond(['status' => 'success', 'data' => $stmt->fetchAll()]);
}

function handleBrands(PDO $pdo): void
{
    $stmt = $pdo->query("SELECT id, name FROM tyre_brands WHERE deleted_at IS NULL AND is_active = 1 ORDER BY name ASC");
    respond(['status' => 'success', 'data' => $stmt->fetchAll()]);
}

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

    $data = ['name' => $name, 'brand_id' => $brandId, '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_models SET {$sets} WHERE id = :id")->execute($data);
        doAudit($pdo, 'update', "Model #{$id} updated", $id);
        respond(['status' => 'success', 'message' => 'Model updated']);
    } else {
        $cols = implode(', ', array_keys($data));
        $vals = ':' . implode(', :', array_keys($data));
        $pdo->prepare("INSERT INTO tyre_models ({$cols}) VALUES ({$vals})")->execute($data);
        $newId = (int)$pdo->lastInsertId();
        doAudit($pdo, 'create', "Model #{$newId} created", $newId);
        respond(['status' => 'success', 'message' => 'Model created', 'id' => $newId]);
    }
}

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