<?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('trip.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 'active': handleActive($pdo); break;
        case 'end': handleEnd($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, 'trip', $recordId ?? 0, $description, null, null);
}

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

    if (!empty($_GET['vehicle_id'])) {
        $where[] = 't.vehicle_id = :vehicle_id';
        $params['vehicle_id'] = (int)$_GET['vehicle_id'];
    }
    if (!empty($_GET['driver_id'])) {
        $where[] = 't.driver_id = :driver_id';
        $params['driver_id'] = (int)$_GET['driver_id'];
    }
    if (!empty($_GET['status'])) {
        $where[] = 't.status = :status';
        $params['status'] = $_GET['status'];
    }
    if (!empty($_GET['date_from'])) {
        $where[] = 't.start_date >= :date_from';
        $params['date_from'] = $_GET['date_from'];
    }
    if (!empty($_GET['date_to'])) {
        $where[] = 't.start_date <= :date_to';
        $params['date_to'] = $_GET['date_to'];
    }
    if (!empty($_GET['search'])) {
        $q = '%' . $_GET['search'] . '%';
        $where[] = '(v.plate_number LIKE :q1 OR d.name LIKE :q2 OR t.purpose LIKE :q3 OR t.start_location LIKE :q4 OR t.end_location LIKE :q5)';
        $params['q1'] = $q; $params['q2'] = $q; $params['q3'] = $q; $params['q4'] = $q; $params['q5'] = $q;
    }

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

function handleSave(PDO $pdo): void
{
    if (!isAdmin() && !can('trip.create') && !can('trip.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,
        'start_date' => $_POST['start_date'] ?? '',
        'end_date' => !empty($_POST['end_date']) ? $_POST['end_date'] : null,
        'start_odometer' => !empty($_POST['start_odometer']) ? (int)$_POST['start_odometer'] : null,
        'end_odometer' => !empty($_POST['end_odometer']) ? (int)$_POST['end_odometer'] : null,
        'start_location' => trim($_POST['start_location'] ?? ''),
        'end_location' => trim($_POST['end_location'] ?? ''),
        'purpose' => trim($_POST['purpose'] ?? ''),
        'route_description' => trim($_POST['route_description'] ?? ''),
        'status' => $_POST['status'] ?? 'active',
        'notes' => trim($_POST['notes'] ?? ''),
    ];

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

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

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

function handleActive(PDO $pdo): void
{
    $stmt = $pdo->prepare("
        SELECT t.*, v.plate_number, d.full_name AS driver_name
        FROM trips t
        LEFT JOIN vehicles v ON v.id = t.vehicle_id
        LEFT JOIN drivers d ON d.id = t.driver_id
        WHERE t.status = 'active' AND t.deleted_at IS NULL
        ORDER BY t.start_date DESC
    ");
    $stmt->execute();
    respond(['status' => 'success', 'data' => $stmt->fetchAll()]);
}

function handleEnd(PDO $pdo): void
{
    if (!isAdmin() && !can('trip.edit')) {
        respond(['status' => 'error', 'message' => 'Unauthorized']);
    }
    $id = (int)($_POST['id'] ?? 0);
    $endOdometer = !empty($_POST['end_odometer']) ? (int)$_POST['end_odometer'] : null;
    $endLocation = trim($_POST['end_location'] ?? '');

    if ($id <= 0) respond(['status' => 'error', 'message' => 'Invalid ID']);

    $pdo->prepare("UPDATE trips SET end_date = NOW(), end_odometer = :odometer, end_location = :location, status = 'completed', updated_at = NOW() WHERE id = :id")
        ->execute(['odometer' => $endOdometer, 'location' => $endLocation, 'id' => $id]);
    doAudit($pdo, 'end', "Trip #{$id} ended", $id);
    respond(['status' => 'success', 'message' => 'Trip ended']);
}
