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

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

requireApiLogin();
enforceCsrfForUnsafeRequest();

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

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

try {
    switch ($action) {
        case 'list': handleList($pdo); break;
        case 'show': handleShow($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 handleShow(PDO $pdo): void
{
    $driverId = (int)($_GET['driver_id'] ?? 0);
    if ($driverId <= 0) respond(['status' => 'error', 'message' => 'Invalid driver']);

    $driver = $pdo->prepare("SELECT * FROM drivers WHERE id = :id AND deleted_at IS NULL");
    $driver->execute(['id' => $driverId]);
    $driverData = $driver->fetch();
    if (!$driverData) respond(['status' => 'error', 'message' => 'Driver not found']);

    $tripStats = $pdo->prepare("
        SELECT COUNT(*) AS total_trips, COALESCE(SUM(end_odometer - start_odometer), 0) AS total_km,
               COALESCE(AVG(end_odometer - start_odometer), 0) AS avg_km_per_trip
        FROM trips WHERE driver_id = :did AND deleted_at IS NULL AND status = 'completed'
    ");
    $tripStats->execute(['did' => $driverId]);
    $tripStats = $tripStats->fetch();

    $fuelStats = $pdo->prepare("
        SELECT COUNT(*) AS fuel_entries, COALESCE(SUM(quantity_litres), 0) AS total_litres,
               COALESCE(SUM(total_amount), 0) AS total_fuel_cost,
               COALESCE(AVG(naira_per_liter), 0) AS avg_cost_per_litre
        FROM vehicle_fuel_entries WHERE driver_id = :did AND deleted_at IS NULL AND approval_status = 'Approved'
    ");
    $fuelStats->execute(['did' => $driverId]);
    $fuelStats = $fuelStats->fetch();

    $kmPerLitre = 0;
    if ((float)($fuelStats['total_litres'] ?? 0) > 0 && (float)($tripStats['total_km'] ?? 0) > 0) {
        $kmPerLitre = (float)$tripStats['total_km'] / (float)$fuelStats['total_litres'];
    }

    $incidentStats = $pdo->prepare("
        SELECT COUNT(*) AS total_incidents,
               COALESCE(SUM(CASE WHEN severity = 'major' THEN 1 ELSE 0 END), 0) AS major_incidents,
               COALESCE(SUM(CASE WHEN is_fleet_fault = 1 THEN 1 ELSE 0 END), 0) AS at_fault
        FROM incidents WHERE driver_id = :did AND deleted_at IS NULL
    ");
    $incidentStats->execute(['did' => $driverId]);
    $incidentStats = $incidentStats->fetch();

    $license = $pdo->prepare("SELECT valid_until, license_no, driving_license_no FROM driver_licenses WHERE driver_id = :did AND deleted_at IS NULL AND status_yn = 1 ORDER BY valid_until DESC LIMIT 1");
    $license->execute(['did' => $driverId]);
    $licenseData = $license->fetch();

    $licenseStatus = 'valid';
    $daysToExpiry = null;
    $licenseDisplay = $licenseData['license_no'] ?? $licenseData['driving_license_no'] ?? '-';
    $licenseExpiryDate = $licenseData['valid_until'] ?? null;
    if ($licenseExpiryDate) {
        $daysToExpiry = (int)ceil((strtotime($licenseExpiryDate) - time()) / 86400);
        if ($daysToExpiry < 0) {
            $licenseStatus = 'expired';
            $daysToExpiry = abs($daysToExpiry);
        } elseif ($daysToExpiry <= 30) {
            $daysToExpiry = abs($daysToExpiry);
            $licenseStatus = 'expiring_soon';
        }
    }

    $assignments = $pdo->prepare("
        SELECT va.*, v.plate_number
        FROM vehicle_assignments va
        LEFT JOIN vehicles v ON v.id = va.vehicle_id
        WHERE va.driver_id = :did AND va.deleted_at IS NULL
        ORDER BY va.created_at DESC
    ");
    $assignments->execute(['did' => $driverId]);

    respond(['status' => 'success', 'data' => [
        'driver' => $driverData,
        'trip_stats' => $tripStats,
        'fuel_stats' => $fuelStats,
        'km_per_litre' => round($kmPerLitre, 2),
        'incident_stats' => $incidentStats,
        'license_status' => $licenseStatus,
        'license_number' => $licenseDisplay,
        'license_expiry' => $licenseExpiryDate,
        'days_to_expiry' => $daysToExpiry,
        'recent_assignments' => $assignments->fetchAll(),
    ]]);
}

function handleList(PDO $pdo): void
{
    $stmt = $pdo->query("
        SELECT d.id, d.full_name AS name, d.phone, d.driver_status AS status,
               (SELECT COUNT(*) FROM trips WHERE driver_id = d.id AND deleted_at IS NULL) AS trip_count,
               (SELECT COUNT(*) FROM vehicle_fuel_entries WHERE driver_id = d.id AND deleted_at IS NULL) AS fuel_count,
               (SELECT COUNT(*) FROM incidents WHERE driver_id = d.id AND deleted_at IS NULL) AS incident_count,
               (SELECT v.plate_number FROM vehicle_assignments va LEFT JOIN vehicles v ON v.id = va.vehicle_id WHERE va.driver_id = d.id AND va.deleted_at IS NULL ORDER BY va.created_at DESC LIMIT 1) AS current_vehicle
        FROM drivers d
        WHERE d.deleted_at IS NULL
        ORDER BY d.full_name ASC
    ");
    respond(['status' => 'success', 'data' => $stmt->fetchAll()]);
}
