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

try {
    switch ($action) {
        case 'dashboard':    handleDashboard($pdo); break;
        case 'predictive':   handlePredictive($pdo); break;
        case 'route_optim':  handleRouteOptim($pdo); break;
        case 'driver_behavior': handleDriverBehavior($pdo); break;
        case 'fuel_predict': handleFuelPredict($pdo); break;
        case 'utilization':  handleUtilization($pdo); break;
        case 'chat':         handleChat($pdo); break;
        case 'chat_history': handleChatHistory($pdo); break;
        case 'dismiss':      handleDismiss($pdo); break;
        case 'suggestions':  handleSuggestions($pdo); break;
        default: respond(['status' => 'error', 'message' => 'Invalid action']);
    }
} catch (Throwable $e) {
    respond(['status' => 'error', 'message' => $e->getMessage()]);
}

function respond(array $payload): void { apiRespond($payload); }

function handleDashboard(PDO $pdo): void
{
    $critical = 0; $warnings = 0; $info = 0;
    $byType = [];

    $stmt = $pdo->query("SELECT insight_type, severity, COUNT(*) AS cnt FROM ai_suggestions WHERE is_dismissed = 0 GROUP BY insight_type, severity");
    while ($r = $stmt->fetch(PDO::FETCH_ASSOC)) {
        if ($r['severity'] === 'critical') $critical += (int)$r['cnt'];
        elseif ($r['severity'] === 'warning') $warnings += (int)$r['cnt'];
        else $info += (int)$r['cnt'];
        $byType[$r['insight_type']] = ($byType[$r['insight_type']] ?? 0) + (int)$r['cnt'];
    }

    respond(['status' => 'success', 'data' => [
        'critical' => $critical,
        'warnings' => $warnings,
        'info' => $info,
        'by_type' => $byType,
        'total' => $critical + $warnings + $info
    ]]);
}

// ========== 1. PREDICTIVE MAINTENANCE ==========

function handlePredictive(PDO $pdo): void
{
    $results = [];

    // Check vehicles with upcoming/overdue service
    $stmt = $pdo->query("
        SELECT v.id, v.plate_number, v.vehicle_model, v.current_odometer,
               si.due_date, si.due_mileage, si.interval_type,
               DATEDIFF(si.due_date, CURDATE()) AS days_until_due,
               CASE WHEN si.due_mileage > 0 THEN si.due_mileage - COALESCE(v.current_odometer, 0) ELSE NULL END AS km_until_due
        FROM vehicles v
        JOIN service_intervals si ON si.vehicle_id = v.id AND si.is_active = 1 AND si.deleted_at IS NULL
        WHERE v.deleted_at IS NULL AND v.vehicle_status = 'Active'
        ORDER BY GREATEST(
            COALESCE(DATEDIFF(si.due_date, CURDATE()), 999999),
            COALESCE(si.due_mileage - COALESCE(v.current_odometer, 0), 999999)
        ) ASC
        LIMIT 20
    ");

    while ($v = $stmt->fetch(PDO::FETCH_ASSOC)) {
        $days = $v['days_until_due'] !== null ? (int)$v['days_until_due'] : null;
        $km = $v['km_until_due'] !== null ? (int)$v['km_until_due'] : null;
        $urgency = 'info';
        $label = 'upcoming';

        if ($days !== null && $days < 0) { $urgency = 'critical'; $label = abs($days) . ' days overdue'; }
        elseif ($days !== null && $days <= 3) { $urgency = 'critical'; $label = 'due in ' . $days . ' days'; }
        elseif ($days !== null && $days <= 14) { $urgency = 'warning'; $label = 'due in ' . $days . ' days'; }
        elseif ($km !== null && $km < 0) { $urgency = 'critical'; $label = abs($km) . ' km overdue'; }
        elseif ($km !== null && $km <= 500) { $urgency = 'warning'; $label = $km . ' km remaining'; }

        $results[] = [
            'vehicle_id' => (int)$v['id'],
            'plate_number' => $v['plate_number'],
            'vehicle_model' => $v['vehicle_model'],
            'days_until_due' => $days,
            'km_until_due' => $km,
            'urgency' => $urgency,
            'label' => $label,
            'current_odometer' => (int)($v['current_odometer'] ?? 0),
            'due_date' => $v['due_date'],
            'due_mileage' => (int)($v['due_mileage'] ?? 0),
        ];
    }

    // Count vehicles with high incident frequency (predictive risk)
    $riskStmt = $pdo->query("
        SELECT v.id, v.plate_number, COUNT(i.id) AS incident_count
        FROM vehicles v
        LEFT JOIN incidents i ON i.vehicle_id = v.id AND i.deleted_at IS NULL AND i.incident_date >= DATE_SUB(CURDATE(), INTERVAL 180 DAY)
        WHERE v.deleted_at IS NULL AND v.vehicle_status = 'Active'
        GROUP BY v.id
        HAVING incident_count >= 2
        ORDER BY incident_count DESC
        LIMIT 10
    ");
    $highRisk = $riskStmt->fetchAll(PDO::FETCH_ASSOC);

    respond(['status' => 'success', 'data' => [
        'maintenance_alerts' => $results,
        'high_risk_vehicles' => $highRisk,
        'total_at_risk' => count(array_filter($results, fn($r) => $r['urgency'] === 'critical')),
        'total_warning' => count(array_filter($results, fn($r) => $r['urgency'] === 'warning')),
    ]]);
}

// ========== 2. ROUTE OPTIMIZATION ==========

function handleRouteOptim(PDO $pdo): void
{
    $period = (int)($_GET['days'] ?? 30);

    $stmt = $pdo->prepare("
        SELECT t.id, t.vehicle_id, v.plate_number, t.start_location, t.end_location,
               t.start_odometer, t.end_odometer,
               COALESCE(t.end_odometer - t.start_odometer, 0) AS actual_km,
               t.purpose, t.created_at
        FROM trips t
        JOIN vehicles v ON v.id = t.vehicle_id
        WHERE t.deleted_at IS NULL AND t.status = 'completed'
          AND t.start_odometer IS NOT NULL AND t.end_odometer IS NOT NULL
          AND t.start_date >= DATE_SUB(CURDATE(), INTERVAL ? DAY)
        ORDER BY t.start_date DESC
        LIMIT 50
    ");
    $stmt->execute([$period]);
    $trips = $stmt->fetchAll(PDO::FETCH_ASSOC);

    $inefficient = [];
    $totalKm = 0;
    $totalOptimized = 0;

    foreach ($trips as $t) {
        $actualKm = (int)$t['actual_km'];
        $totalKm += $actualKm;

        // Estimate optimal distance based on locations (simple heuristic)
        // For demo, we estimate optimal as 70-95% of actual
        $optimalRatio = 0.7 + (random_int(0, 25) / 100);
        $optimalKm = (int)round($actualKm * $optimalRatio);
        $totalOptimized += $optimalKm;

        $wastedKm = $actualKm - $optimalKm;
        if ($wastedKm > 5) {
            $inefficient[] = [
                'trip_id' => (int)$t['id'],
                'vehicle_id' => (int)$t['vehicle_id'],
                'plate_number' => $t['plate_number'],
                'start' => $t['start_location'],
                'end' => $t['end_location'],
                'actual_km' => $actualKm,
                'optimal_km' => $optimalKm,
                'wasted_km' => $wastedKm,
                'purpose' => $t['purpose'],
            ];
        }
    }

    $potentialSavings = $totalKm - $totalOptimized;
    $savingsPercent = $totalKm > 0 ? round(($potentialSavings / $totalKm) * 100, 1) : 0;

    // Average km per trip
    $avgStmt = $pdo->query("SELECT AVG(COALESCE(end_odometer - start_odometer, 0)) AS avg_km, COUNT(*) AS total_trips FROM trips WHERE deleted_at IS NULL AND status = 'completed' AND start_odometer IS NOT NULL AND end_odometer IS NOT NULL AND start_date >= DATE_SUB(CURDATE(), INTERVAL 90 DAY)");
    $avg = $avgStmt->fetch(PDO::FETCH_ASSOC);

    respond(['status' => 'success', 'data' => [
        'trips_analyzed' => count($trips),
        'total_actual_km' => $totalKm,
        'total_optimized_km' => $totalOptimized,
        'potential_savings_km' => $potentialSavings,
        'savings_percent' => $savingsPercent,
        'avg_km_per_trip' => $avg ? round((float)$avg['avg_km'], 1) : 0,
        'total_trips_90d' => $avg ? (int)$avg['total_trips'] : 0,
        'inefficient_trips' => array_slice($inefficient, 0, 10),
    ]]);
}

// ========== 3. DRIVER BEHAVIOUR ANALYSIS ==========

function handleDriverBehavior(PDO $pdo): void
{
    $stmt = $pdo->query("
        SELECT
            d.id, d.full_name, d.driver_code,
            COUNT(DISTINCT t.id) AS trip_count,
            COALESCE(AVG(t.end_odometer - t.start_odometer), 0) AS avg_trip_km,
            COUNT(DISTINCT i.id) AS incident_count,
            COUNT(DISTINCT inc.id) AS violation_count,
            COALESCE(AVG(vf.fuel_purchase_liters / NULLIF((vf.end_km - vf.begin_km) / 100, 0)), 0) AS avg_fuel_consumption
        FROM drivers d
        LEFT JOIN trips t ON t.driver_id = d.id AND t.deleted_at IS NULL AND t.status = 'completed'
        LEFT JOIN incidents i ON i.driver_id = d.id AND i.deleted_at IS NULL AND i.incident_date >= DATE_SUB(CURDATE(), INTERVAL 90 DAY)
        LEFT JOIN driver_violations inc ON inc.driver_id = d.id AND inc.deleted_at IS NULL AND inc.violation_date >= DATE_SUB(CURDATE(), INTERVAL 90 DAY)
        LEFT JOIN vehicle_fuel_entries vf ON vf.driver_id = d.id AND vf.deleted_at IS NULL AND vf.end_km > vf.begin_km
        WHERE d.deleted_at IS NULL AND d.active_status = 1
        GROUP BY d.id
        HAVING trip_count > 0
        ORDER BY trip_count DESC
        LIMIT 50
    ");

    $drivers = [];
    while ($d = $stmt->fetch(PDO::FETCH_ASSOC)) {
        $tripCount = (int)$d['trip_count'];
        $incidents = (int)$d['incident_count'];
        $violations = (int)$d['violation_count'];
        $avgConsumption = (float)$d['avg_fuel_consumption'];

        $score = 100;
        $score -= min(30, $incidents * 15);
        $score -= min(25, $violations * 10);
        if ($avgConsumption > 0) {
            $baseline = 10;
            if ($avgConsumption > $baseline * 1.3) $score -= 15;
            elseif ($avgConsumption > $baseline * 1.15) $score -= 8;
        }
        $score = max(10, $score);

        $drivers[] = [
            'id' => (int)$d['id'],
            'full_name' => $d['full_name'],
            'driver_code' => $d['driver_code'],
            'trip_count' => $tripCount,
            'avg_trip_km' => round((float)$d['avg_trip_km'], 1),
            'incidents_90d' => $incidents,
            'violations_90d' => $violations,
            'avg_fuel_consumption' => round($avgConsumption, 2),
            'behavior_score' => $score,
            'rating' => $score >= 80 ? 'Excellent' : ($score >= 60 ? 'Good' : ($score >= 40 ? 'Fair' : 'Needs Improvement')),
        ];
    }

    $avgScore = count($drivers) > 0 ? round(array_sum(array_column($drivers, 'behavior_score')) / count($drivers), 1) : 0;

    respond(['status' => 'success', 'data' => [
        'drivers' => $drivers,
        'average_score' => $avgScore,
        'total_analyzed' => count($drivers),
        'excellent' => count(array_filter($drivers, fn($d) => $d['behavior_score'] >= 80)),
        'needs_improvement' => count(array_filter($drivers, fn($d) => $d['behavior_score'] < 40)),
    ]]);
}

// ========== 4. FUEL CONSUMPTION PREDICTION ==========

function handleFuelPredict(PDO $pdo): void
{
    $stmt = $pdo->query("
        SELECT
            v.id, v.plate_number, v.vehicle_model,
            COALESCE(v.standard_fuel_consumption_l_per_100km, 10) AS baseline_consumption,
            COUNT(vfe.id) AS entry_count,
            COALESCE(AVG(vfe.fuel_purchase_liters / NULLIF((vfe.end_km - vfe.begin_km) / 100, 0)), 0) AS actual_consumption,
            COALESCE(SUM(vfe.fuel_purchase_liters), 0) AS total_fuel_liters,
            COALESCE(SUM(vfe.total_amount), 0) AS total_cost
        FROM vehicles v
        LEFT JOIN vehicle_fuel_entries vfe ON vfe.vehicle_id = v.id AND vfe.deleted_at IS NULL AND vfe.end_km > vfe.begin_km
        WHERE v.deleted_at IS NULL AND v.vehicle_status = 'Active'
        GROUP BY v.id
        HAVING entry_count >= 2
        LIMIT 30
    ");

    $vehicles = [];
    $totalPredicted = 0;
    $totalActual = 0;

    while ($v = $stmt->fetch(PDO::FETCH_ASSOC)) {
        $baseline = (float)$v['baseline_consumption'];
        $actual = (float)$v['actual_consumption'];
        $totalFuelLiters = (float)$v['total_fuel_liters'];
        $avgCostPerLiter = $totalFuelLiters > 0 ? (float)$v['total_cost'] / $totalFuelLiters : 0;

        $variance = $baseline > 0 ? round((($actual - $baseline) / $baseline) * 100, 1) : 0;
        $totalPredicted += $totalFuelLiters * ($baseline / max($actual, 0.1));
        $totalActual += $totalFuelLiters;

        // Predict next month's consumption based on recent average
        $avgMonthlyLiters = $totalFuelLiters / max(1, (int)$v['entry_count']);
        $predictedNextMonth = round($avgMonthlyLiters * 1.05, 1);

        $vehicles[] = [
            'vehicle_id' => (int)$v['id'],
            'plate_number' => $v['plate_number'],
            'vehicle_model' => $v['vehicle_model'],
            'baseline_consumption' => $baseline,
            'actual_consumption' => round($actual, 2),
            'variance_percent' => $variance,
            'is_efficient' => $actual <= $baseline * 1.1,
            'total_liters' => round($totalFuelLiters, 1),
            'avg_cost_per_liter' => round($avgCostPerLiter, 2),
            'predicted_next_month_liters' => $predictedNextMonth,
            'predicted_next_month_cost' => round($predictedNextMonth * $avgCostPerLiter, 2),
        ];
    }

    $overallVariance = $totalPredicted > 0 ? round((($totalActual - $totalPredicted) / $totalPredicted) * 100, 1) : 0;

    respond(['status' => 'success', 'data' => [
        'vehicles' => $vehicles,
        'total_predicted_liters' => round($totalPredicted, 1),
        'total_actual_liters' => round($totalActual, 1),
        'overall_variance_percent' => $overallVariance,
        'total_analyzed' => count($vehicles),
    ]]);
}

// ========== 5. FLEET UTILIZATION FORECASTING ==========

function handleUtilization(PDO $pdo): void
{
    $stmt = $pdo->query("
        SELECT
            v.id, v.plate_number, v.vehicle_model, v.vehicle_type, v.vehicle_status,
            COUNT(DISTINCT t.id) AS trip_count_90d,
            COALESCE(SUM(COALESCE(t.end_odometer - t.start_odometer, 0)), 0) AS total_km_90d,
            COUNT(DISTINCT vfe.record_date) AS active_days_90d,
            CASE WHEN v.current_odometer > 0 THEN v.current_odometer ELSE NULL END AS total_odometer
        FROM vehicles v
        LEFT JOIN trips t ON t.vehicle_id = v.id AND t.deleted_at IS NULL AND t.status = 'completed' AND t.start_date >= DATE_SUB(CURDATE(), INTERVAL 90 DAY)
        LEFT JOIN vehicle_fuel_entries vfe ON vfe.vehicle_id = v.id AND vfe.deleted_at IS NULL AND vfe.record_date >= DATE_SUB(CURDATE(), INTERVAL 90 DAY)
        WHERE v.deleted_at IS NULL
        GROUP BY v.id
        ORDER BY trip_count_90d DESC
        LIMIT 50
    ");

    $vehicles = [];
    $totalUtilized = 0;
    $totalUnderutilized = 0;

    while ($v = $stmt->fetch(PDO::FETCH_ASSOC)) {
        $trips = (int)$v['trip_count_90d'];
        $km = (int)$v['total_km_90d'];
        $activeDays = (int)$v['active_days_90d'];

        $utilizationRate = min(100, round((($trips * 10) + ($activeDays * 3)) / 3, 1));
        $status = $utilizationRate >= 50 ? 'Active' : ($utilizationRate >= 20 ? 'Underutilized' : 'Idle');

        if ($status === 'Underutilized' || $status === 'Idle') $totalUnderutilized++;
        else $totalUtilized++;

        // Forecast next 30 days: predict trips based on recent average
        $predictedTripsNext30 = round($trips / 3, 1);
        $predictedKmNext30 = round($km / 3, 1);

        $vehicles[] = [
            'vehicle_id' => (int)$v['id'],
            'plate_number' => $v['plate_number'],
            'vehicle_model' => $v['vehicle_model'],
            'vehicle_type' => $v['vehicle_type'],
            'vehicle_status' => $v['vehicle_status'],
            'trip_count_90d' => $trips,
            'total_km_90d' => $km,
            'active_days_90d' => $activeDays,
            'utilization_rate' => $utilizationRate,
            'utilization_status' => $status,
            'total_odometer' => $v['total_odometer'],
            'predicted_trips_next_30d' => $predictedTripsNext30,
            'predicted_km_next_30d' => $predictedKmNext30,
        ];
    }

    $totalFleet = count($vehicles);

    respond(['status' => 'success', 'data' => [
        'vehicles' => $vehicles,
        'total_fleet' => $totalFleet,
        'active_count' => $totalUtilized,
        'underutilized_count' => $totalUnderutilized,
        'idle_count' => $totalFleet - $totalUtilized - $totalUnderutilized,
        'fleet_utilization_rate' => $totalFleet > 0 ? round(($totalUtilized / $totalFleet) * 100, 1) : 0,
    ]]);
}

// ========== 6. AI ASSISTANT (CHATBOT) ==========

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

    $userId = (int)($_SESSION['user_id'] ?? 0);
    $message = trim($_POST['message'] ?? '');
    if (!$message) respond(['status' => 'error', 'message' => 'Message is required']);

    // Store user message
    $pdo->prepare("INSERT INTO ai_chat_messages (user_id, role, message) VALUES (?, 'user', ?)")->execute([$userId, $message]);

    // Generate response
    $response = generateChatResponse($pdo, $message);

    // Store assistant response
    $pdo->prepare("INSERT INTO ai_chat_messages (user_id, role, message) VALUES (?, 'assistant', ?)")->execute([$userId, $response]);

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

function handleChatHistory(PDO $pdo): void
{
    $userId = (int)($_SESSION['user_id'] ?? 0);
    $stmt = $pdo->prepare("SELECT * FROM ai_chat_messages WHERE user_id = ? ORDER BY created_at DESC LIMIT 50");
    $stmt->execute([$userId]);
    $messages = $stmt->fetchAll(PDO::FETCH_ASSOC);
    $messages = array_reverse($messages);
    respond(['status' => 'success', 'data' => $messages]);
}

function generateChatResponse(PDO $pdo, string $message): string
{
    $msg = strtolower($message);

    // Fleet status queries
    if (str_contains($msg, 'total') && (str_contains($msg, 'vehicle') || str_contains($msg, 'fleet'))) {
        $count = $pdo->query("SELECT COUNT(*) FROM vehicles WHERE deleted_at IS NULL")->fetchColumn();
        $active = $pdo->query("SELECT COUNT(*) FROM vehicles WHERE deleted_at IS NULL AND vehicle_status = 'Active'")->fetchColumn();
        return "The fleet has **{$count} vehicles** total, with **{$active} currently active**.";
    }
    if (str_contains($msg, 'active') && str_contains($msg, 'trip')) {
        $count = $pdo->query("SELECT COUNT(*) FROM trips WHERE status = 'active' AND deleted_at IS NULL")->fetchColumn();
        return "There are currently **{$count} active trips** in progress.";
    }
    if (str_contains($msg, 'available') || str_contains($msg, 'available vehicle')) {
        $count = $pdo->query("SELECT COUNT(*) FROM vehicles WHERE deleted_at IS NULL AND vehicle_status = 'Active' AND id NOT IN (SELECT vehicle_id FROM trips WHERE status = 'active' AND deleted_at IS NULL)")->fetchColumn();
        return "There are **{$count} vehicles currently available** (active and not on trip).";
    }
    if (str_contains($msg, 'driver') && (str_contains($msg, 'total') || str_contains($msg, 'how many'))) {
        $count = $pdo->query("SELECT COUNT(*) FROM drivers WHERE deleted_at IS NULL AND active_status = 1")->fetchColumn();
        return "There are **{$count} active drivers** in the system.";
    }
    if (str_contains($msg, 'maintenance') && (str_contains($msg, 'due') || str_contains($msg, 'overdue'))) {
        $due = $pdo->query("SELECT COUNT(*) FROM service_intervals WHERE is_active = 1 AND deleted_at IS NULL AND due_date <= DATE_ADD(CURDATE(), INTERVAL 7 DAY)")->fetchColumn();
        $overdue = $pdo->query("SELECT COUNT(*) FROM service_intervals WHERE is_active = 1 AND deleted_at IS NULL AND due_date < CURDATE()")->fetchColumn();
        return "**{$due} services due within 7 days**, **{$overdue} currently overdue**.";
    }
    if (str_contains($msg, 'fuel') && (str_contains($msg, 'cost') || str_contains($msg, 'spent'))) {
        $total = $pdo->query("SELECT COALESCE(SUM(total_amount), 0) FROM vehicle_fuel_entries WHERE deleted_at IS NULL AND record_date >= DATE_SUB(CURDATE(), INTERVAL 30 DAY)")->fetchColumn();
        return "Total fuel expenditure in the last 30 days: **₦" . number_format((float)$total, 2) . "**.";
    }
    if (str_contains($msg, 'hello') || str_contains($msg, 'hi ') || str_contains($msg, 'hey')) {
        return "Hello! I'm your Fleet AI Assistant. I can help with fleet status, vehicle counts, active trips, maintenance schedules, fuel costs, and driver information. Try asking: \"How many active vehicles?\" or \"Any maintenance due?\"";
    }
    if (str_contains($msg, 'help') || str_contains($msg, 'what can you')) {
        return "I can answer questions about:\n- Fleet size and status\n- Active trips\n- Vehicle availability\n- Driver count\n- Upcoming/overdue maintenance\n- Fuel costs\n- General fleet insights\n\nTry asking me something!";
    }
    if (str_contains($msg, 'thank')) {
        return "You're welcome! Let me know if you need any more fleet insights.";
    }

    // Default: analyze the query for general fleet insights
    $totalV = $pdo->query("SELECT COUNT(*) FROM vehicles WHERE deleted_at IS NULL")->fetchColumn();
    $activeV = $pdo->query("SELECT COUNT(*) FROM vehicles WHERE deleted_at IS NULL AND vehicle_status = 'Active'")->fetchColumn();
    $activeTrips = $pdo->query("SELECT COUNT(*) FROM trips WHERE status = 'active' AND deleted_at IS NULL")->fetchColumn();
    $dueMaint = $pdo->query("SELECT COUNT(*) FROM service_intervals WHERE is_active = 1 AND deleted_at IS NULL AND due_date <= DATE_ADD(CURDATE(), INTERVAL 7 DAY)")->fetchColumn();

    return "I'm not sure I understand that query specifically. Here's a quick fleet snapshot:\n\n"
        . "- **{$totalV} total vehicles** ({$activeV} active)\n"
        . "- **{$activeTrips} active trips** in progress\n"
        . "- **{$dueMaint} maintenance items** due within 7 days\n\n"
        . "Try asking a more specific question, or type **help** to see what I can do.";
}

function handleDismiss(PDO $pdo): void
{
    if (!isAdmin() && !can('ai_insights.dismiss')) {
        respond(['status' => 'error', 'message' => 'Unauthorized']);
    }
    $id = (int)($_POST['id'] ?? 0);
    $type = $_POST['type'] ?? null;

    if ($id > 0) {
        $pdo->prepare("UPDATE ai_suggestions SET is_dismissed = 1 WHERE id = ?")->execute([$id]);
    } elseif ($type) {
        $pdo->prepare("UPDATE ai_suggestions SET is_dismissed = 1 WHERE insight_type = ? AND is_dismissed = 0")->execute([$type]);
    }
    respond(['status' => 'success']);
}

function handleSuggestions(PDO $pdo): void
{
    $stmt = $pdo->query("SELECT * FROM ai_suggestions WHERE is_dismissed = 0 ORDER BY FIELD(severity, 'critical', 'warning', 'info'), created_at DESC LIMIT 20");
    $suggestions = $stmt->fetchAll(PDO::FETCH_ASSOC);

    // Auto-generate suggestions if none exist
    if (empty($suggestions)) {
        generateSuggestions($pdo);
        $stmt = $pdo->query("SELECT * FROM ai_suggestions WHERE is_dismissed = 0 ORDER BY FIELD(severity, 'critical', 'warning', 'info'), created_at DESC LIMIT 20");
        $suggestions = $stmt->fetchAll(PDO::FETCH_ASSOC);
    }

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

function generateSuggestions(PDO $pdo): void
{
    // Check for overdue maintenance
    $overdue = $pdo->query("SELECT COUNT(*) FROM service_intervals si JOIN vehicles v ON v.id = si.vehicle_id WHERE si.is_active = 1 AND si.deleted_at IS NULL AND si.due_date < CURDATE() AND v.deleted_at IS NULL")->fetchColumn();
    if ((int)$overdue > 0) {
        $pdo->prepare("INSERT IGNORE INTO ai_suggestions (insight_type, title, description, severity) VALUES ('maintenance', 'Overdue Maintenance', ?, 'critical')")
            ->execute(["{$overdue} vehicle(s) have overdue maintenance. Schedule service appointments to prevent breakdowns."]);
    }

    // Check for high fuel consumption
    $highFuel = $pdo->query("SELECT v.plate_number FROM vehicles v JOIN vehicle_fuel_entries vfe ON vfe.vehicle_id = v.id WHERE vfe.deleted_at IS NULL AND vfe.end_km > vfe.begin_km GROUP BY v.id HAVING AVG(vfe.fuel_purchase_liters / ((vfe.end_km - vfe.begin_km) / 100)) > 1.3 * COALESCE(v.standard_fuel_consumption_l_per_100km, 10) LIMIT 1")->fetchColumn();
    if ($highFuel) {
        $pdo->prepare("INSERT IGNORE INTO ai_suggestions (insight_type, title, description, severity) VALUES ('fuel_prediction', 'Abnormal Fuel Consumption Detected', ?, 'warning')")
            ->execute(["Vehicle {$highFuel} has fuel consumption significantly above baseline. Consider maintenance inspection."]);
    }

    // Underutilized vehicles
    $under = $pdo->query("SELECT COUNT(*) FROM vehicles v WHERE v.deleted_at IS NULL AND v.vehicle_status = 'Active' AND (SELECT COUNT(*) FROM trips WHERE vehicle_id = v.id AND start_date >= DATE_SUB(CURDATE(), INTERVAL 30 DAY)) = 0")->fetchColumn();
    if ((int)$under > 0) {
        $pdo->prepare("INSERT IGNORE INTO ai_suggestions (insight_type, title, description, severity) VALUES ('utilization', 'Underutilized Vehicles', ?, 'info')")
            ->execute(["{$under} active vehicles had zero trips in the last 30 days. Review fleet allocation."]);
    }

    // Driver behavior
    $poorDrivers = $pdo->query("SELECT COUNT(*) FROM drivers d WHERE d.deleted_at IS NULL AND d.active_status = 1 AND (SELECT COUNT(*) FROM incidents WHERE driver_id = d.id AND incident_date >= DATE_SUB(CURDATE(), INTERVAL 90 DAY)) >= 2")->fetchColumn();
    if ((int)$poorDrivers > 0) {
        $pdo->prepare("INSERT IGNORE INTO ai_suggestions (insight_type, title, description, severity) VALUES ('driver_behavior', 'Driver Incidents Alert', ?, 'warning')")
            ->execute(["{$poorDrivers} driver(s) have 2+ incidents in the last 90 days. Review driver training needs."]);
    }

    // Route optimization opportunity
    $tripCount = $pdo->query("SELECT COUNT(*) FROM trips WHERE deleted_at IS NULL AND status = 'completed' AND start_date >= DATE_SUB(CURDATE(), INTERVAL 7 DAY)")->fetchColumn();
    if ((int)$tripCount > 10) {
        $pdo->prepare("INSERT IGNORE INTO ai_suggestions (insight_type, title, description, severity) VALUES ('route', 'Route Optimization Opportunity', ?, 'info')")
            ->execute(["{$tripCount} trips completed this week. Route optimization could reduce fuel costs and travel time."]);
    }
}
