<?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('incident.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 'damages': handleDamages($pdo); break;
        case 'save_damage': handleSaveDamage($pdo); break;
        case 'delete_damage': handleDeleteDamage($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 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['type'])) {
        $where[] = 'i.incident_type = :type';
        $params['type'] = $_GET['type'];
    }
    if (!empty($_GET['severity'])) {
        $where[] = 'i.severity = :severity';
        $params['severity'] = $_GET['severity'];
    }
    if (!empty($_GET['status'])) {
        $where[] = 'i.status = :status';
        $params['status'] = $_GET['status'];
    }

    $whereSql = implode(' AND ', $where);
    $stmt = $pdo->prepare("
        SELECT i.*, v.plate_number, v.vehicle_model,
               d.full_name AS driver_name
        FROM incidents i
        LEFT JOIN vehicles v ON v.id = i.vehicle_id
        LEFT JOIN drivers d ON d.id = i.driver_id
        WHERE {$whereSql}
        ORDER BY i.incident_date DESC, i.id DESC
    ");
    $stmt->execute($params);
    respond(['status' => 'success', 'data' => $stmt->fetchAll()]);
}

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

    $id = (int)($_POST['id'] ?? 0);
    $data = [
        'vehicle_id' => (int)($_POST['vehicle_id'] ?? 0),
        'driver_id' => !empty($_POST['driver_id']) ? (int)$_POST['driver_id'] : null,
        'incident_date' => $_POST['incident_date'] ?? '',
        'incident_time' => !empty($_POST['incident_time']) ? $_POST['incident_time'] : null,
        'incident_type' => $_POST['incident_type'] ?? 'collision',
        'severity' => $_POST['severity'] ?? 'minor',
        'description' => trim($_POST['description'] ?? ''),
        'location' => trim($_POST['location'] ?? ''),
        'police_report_number' => trim($_POST['police_report_number'] ?? ''),
        'police_station' => trim($_POST['police_station'] ?? ''),
        'third_party_details' => trim($_POST['third_party_details'] ?? ''),
        'is_fleet_fault' => (int)($_POST['is_fleet_fault'] ?? 0),
        'damage_cost_estimate' => !empty($_POST['damage_cost_estimate']) ? (float)$_POST['damage_cost_estimate'] : null,
        'status' => $_POST['status'] ?? 'reported',
    ];

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

    if ($id > 0) {
        $data['updated_at'] = date('Y-m-d H:i:s');
        $data['id'] = $id;
        $sets = [];
        foreach ($data as $col => $val) {
            $sets[] = "{$col} = :{$col}";
        }
        $pdo->prepare("UPDATE incidents SET " . implode(', ', $sets) . " WHERE id = :id")->execute($data);
        respond(['status' => 'success', 'message' => 'Incident updated']);
    } else {
        $data['created_by'] = (int)($_SESSION['user_id'] ?? 0);
        $cols = implode(', ', array_keys($data));
        $vals = ':' . implode(', :', array_keys($data));
        $pdo->prepare("INSERT INTO incidents ({$cols}) VALUES ({$vals})")->execute($data);
        respond(['status' => 'success', 'message' => 'Incident created', 'id' => (int)$pdo->lastInsertId()]);
    }
}

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

function handleDamages(PDO $pdo): void
{
    $stmt = $pdo->prepare("
        SELECT * FROM incident_damages WHERE incident_id = :incident_id ORDER BY id ASC
    ");
    $stmt->execute(['incident_id' => (int)($_GET['incident_id'] ?? 0)]);
    respond(['status' => 'success', 'data' => $stmt->fetchAll()]);
}

function handleSaveDamage(PDO $pdo): void
{
    if (!isAdmin() && !can('incident.edit')) {
        respond(['status' => 'error', 'message' => 'Unauthorized']);
    }
    $id = (int)($_POST['id'] ?? 0);
    $data = [
        'incident_id' => (int)($_POST['incident_id'] ?? 0),
        'damage_area' => trim($_POST['damage_area'] ?? ''),
        'damage_description' => trim($_POST['damage_description'] ?? ''),
        'estimated_cost' => !empty($_POST['estimated_cost']) ? (float)$_POST['estimated_cost'] : null,
        'actual_cost' => !empty($_POST['actual_cost']) ? (float)$_POST['actual_cost'] : null,
    ];

    if (!$data['incident_id']) {
        respond(['status' => 'error', 'message' => 'Incident is required']);
    }

    if ($id > 0) {
        $data['id'] = $id;
        $pdo->prepare("UPDATE incident_damages SET damage_area=:damage_area, damage_description=:damage_description, estimated_cost=:estimated_cost, actual_cost=:actual_cost WHERE id=:id")->execute($data);
        respond(['status' => 'success', 'message' => 'Damage updated']);
    } else {
        $pdo->prepare("INSERT INTO incident_damages (incident_id, damage_area, damage_description, estimated_cost, actual_cost) VALUES (:incident_id, :damage_area, :damage_description, :estimated_cost, :actual_cost)")->execute($data);
        respond(['status' => 'success', 'message' => 'Damage added', 'id' => (int)$pdo->lastInsertId()]);
    }
}

function handleDeleteDamage(PDO $pdo): void
{
    if (!isAdmin() && !can('incident.delete')) {
        respond(['status' => 'error', 'message' => 'Unauthorized']);
    }
    $id = (int)($_POST['id'] ?? 0);
    if ($id <= 0) respond(['status' => 'error', 'message' => 'Invalid ID']);
    $pdo->prepare("DELETE FROM incident_damages WHERE id = :id")->execute(['id' => $id]);
    respond(['status' => 'success', 'message' => 'Damage deleted']);
}
