<?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'] ?? '';

$input = $_POST;
if (empty($input)) {
    $raw = file_get_contents('php://input');
    if ($raw) {
        $decoded = json_decode($raw, true);
        if (is_array($decoded)) $input = $decoded;
    }
}

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

try {
    switch ($action) {
        case 'checklist':    handleChecklist($pdo); break;
        case 'list':         handleList($pdo); break;
        case 'get':          handleGet($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, 'vehicle_inspection', $recordId ?? 0, $description, null, null);
}

function handleChecklist(PDO $pdo): void
{
    $stmt = $pdo->query("SELECT id, category, item_name, sort_order FROM inspection_checklist_items WHERE is_active = 1 ORDER BY category, sort_order");
    $items = $stmt->fetchAll();
    $grouped = ['body_interior' => [], 'devices_routing' => []];
    foreach ($items as $item) {
        $grouped[$item['category']][] = $item;
    }
    respond(['status' => 'success', 'data' => $grouped]);
}

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

    if (!empty($_GET['vehicle_id'])) {
        $where[] = 'i.vehicle_id = :vehicle_id';
        $params['vehicle_id'] = (int)$_GET['vehicle_id'];
    }
    if (!empty($_GET['date_from'])) {
        $where[] = 'i.inspection_date >= :date_from';
        $params['date_from'] = $_GET['date_from'];
    }
    if (!empty($_GET['date_to'])) {
        $where[] = 'i.inspection_date <= :date_to';
        $params['date_to'] = $_GET['date_to'];
    }

    $whereSql = implode(' AND ', $where);
    $stmt = $pdo->prepare("
        SELECT i.*, v.plate_number,
               (SELECT COUNT(*) FROM inspection_results r WHERE r.inspection_id = i.id AND r.result = 'fail') AS fail_count,
               (SELECT COUNT(*) FROM inspection_results r WHERE r.inspection_id = i.id) AS total_items
        FROM vehicle_inspections i
        LEFT JOIN vehicles v ON v.id = i.vehicle_id
        WHERE {$whereSql}
        ORDER BY i.inspection_date DESC, i.id DESC
    ");
    $stmt->execute($params);
    respond(['status' => 'success', 'data' => $stmt->fetchAll()]);
}

function handleGet(PDO $pdo): void
{
    $id = (int)($_GET['id'] ?? 0);
    if ($id <= 0) respond(['status' => 'error', 'message' => 'Invalid ID']);

    $stmt = $pdo->prepare("SELECT i.*, v.plate_number FROM vehicle_inspections i LEFT JOIN vehicles v ON v.id = i.vehicle_id WHERE i.id = :id");
    $stmt->execute(['id' => $id]);
    $inspection = $stmt->fetch();
    if (!$inspection) respond(['status' => 'error', 'message' => 'Not found']);

    $stmt = $pdo->prepare("SELECT r.id, r.checklist_item_id, r.result, r.remarks FROM inspection_results r WHERE r.inspection_id = :inspection_id");
    $stmt->execute(['inspection_id' => $id]);
    $inspection['results'] = $stmt->fetchAll();

    respond(['status' => 'success', 'data' => $inspection]);
}

function handleSave(PDO $pdo): void
{
    if (!isAdmin() && !can('vehicle_inspection.create') && !can('vehicle_inspection.edit')) {
        respond(['status' => 'error', 'message' => 'Unauthorized']);
    }

    $raw = file_get_contents('php://input');
    $input = $raw ? (json_decode($raw, true) ?? []) : [];

    $id = (int)($input['id'] ?? 0);
    $inspection = [
        'vehicle_id' => (int)($input['vehicle_id'] ?? 0),
        'inspection_date' => $input['inspection_date'] ?? '',
        'inspector_name' => trim($input['inspector_name'] ?? ''),
        'overall_result' => $input['overall_result'] ?? 'pass',
        'notes' => trim($input['notes'] ?? ''),
    ];

    if (!$inspection['vehicle_id'] || !$inspection['inspection_date']) {
        respond(['status' => 'error', 'message' => 'Vehicle and inspection date are required']);
    }

    $results = $input['results'] ?? [];
    if (!is_array($results)) $results = [];

    if ($id > 0) {
        $inspection['updated_at'] = date('Y-m-d H:i:s');
        $inspection['id'] = $id;
        $sets = [];
        foreach ($inspection as $col => $val) {
            $sets[] = "{$col} = :{$col}";
        }
        $pdo->prepare("UPDATE vehicle_inspections SET " . implode(', ', $sets) . " WHERE id = :id")->execute($inspection);
        doAudit($pdo, 'update', "Inspection #{$id} updated", $id);
    } else {
        $inspection['created_by'] = (int)($_SESSION['user_id'] ?? 0);
        $cols = implode(', ', array_keys($inspection));
        $vals = ':' . implode(', :', array_keys($inspection));
        $pdo->prepare("INSERT INTO vehicle_inspections ({$cols}) VALUES ({$vals})")->execute($inspection);
        $id = (int)$pdo->lastInsertId();
        doAudit($pdo, 'create', "Inspection created for vehicle #{$inspection['vehicle_id']}", $id);
    }

    $pdo->prepare("DELETE FROM inspection_results WHERE inspection_id = :id")->execute(['id' => $id]);
    $insertStmt = $pdo->prepare("INSERT INTO inspection_results (inspection_id, checklist_item_id, result, remarks) VALUES (:inspection_id, :checklist_item_id, :result, :remarks)");
    foreach ($results as $item) {
        if (empty($item['checklist_item_id'])) continue;
        $insertStmt->execute([
            'inspection_id' => $id,
            'checklist_item_id' => (int)$item['checklist_item_id'],
            'result' => $item['result'] ?? 'na',
            'remarks' => trim($item['remarks'] ?? ''),
        ]);
    }

    respond(['status' => 'success', 'message' => $id > 0 ? 'Inspection updated' : 'Inspection created', 'id' => $id]);
}

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