<?php
/**
 * Dashboard API - Returns live stats as JSON
 * Used for auto-refresh and real-time updates
 */
require_once __DIR__ . '/config/config.php';

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

if (!isLoggedIn()) {
    echo json_encode(['error' => 'Unauthorized']);
    exit;
}

$pdo = getPDO();
$action = $_GET['action'] ?? 'stats';

if ($action === 'stats') {
    // Today's stats
    $today = date('Y-m-d');

    $dozar_today = $pdo->query("SELECT COUNT(*) FROM dozar_records WHERE created_date = '$today'")->fetchColumn();
    $tripper_today = $pdo->query("SELECT COUNT(*) FROM tripper_records WHERE created_date = '$today'")->fetchColumn();
    $pending = $pdo->query("SELECT COUNT(*) FROM tripper_records WHERE status = 'pending_unloading'")->fetchColumn();
    $completed_today = $pdo->query("SELECT COUNT(*) FROM tripper_records WHERE status = 'completed' AND created_date = '$today'")->fetchColumn();

    // This week
    $week_start = date('Y-m-d', strtotime('monday this week'));
    $dozar_week = $pdo->query("SELECT COUNT(*) FROM dozar_records WHERE created_date >= '$week_start'")->fetchColumn();
    $tripper_week = $pdo->query("SELECT COUNT(*) FROM tripper_records WHERE created_date >= '$week_start'")->fetchColumn();

    // This month
    $month_start = date('Y-m-01');
    $dozar_month = $pdo->query("SELECT COUNT(*) FROM dozar_records WHERE created_date >= '$month_start'")->fetchColumn();
    $tripper_month = $pdo->query("SELECT COUNT(*) FROM tripper_records WHERE created_date >= '$month_start'")->fetchColumn();

    // Total hours today (dozar)
    $hours_today = $pdo->query("SELECT COALESCE(SUM(work_length_hours), 0) FROM dozar_records WHERE created_date = '$today'")->fetchColumn();

    // Total KM today (tripper completed)
    $km_today = $pdo->query("SELECT COALESCE(SUM(unloading_end_odometer - loading_start_odometer), 0)
                             FROM tripper_records
                             WHERE status = 'completed' AND created_date = '$today'
                             AND unloading_end_odometer > loading_start_odometer")->fetchColumn();

    // Active vehicles today
    $active_vehicles = $pdo->query("SELECT COUNT(DISTINCT vehicle_id) FROM (
                                        SELECT vehicle_id FROM dozar_records WHERE created_date = '$today'
                                        UNION
                                        SELECT vehicle_id FROM tripper_records WHERE created_date = '$today'
                                    ) combined")->fetchColumn();

    // Active drivers today
    $active_drivers = $pdo->query("SELECT COUNT(DISTINCT driver_id) FROM (
                                        SELECT driver_id FROM dozar_records WHERE created_date = '$today'
                                        UNION
                                        SELECT driver_id FROM tripper_records WHERE created_date = '$today'
                                    ) combined")->fetchColumn();

    echo json_encode([
        'success' => true,
        'timestamp' => date('H:i:s'),
        'dozar_today' => (int)$dozar_today,
        'tripper_today' => (int)$tripper_today,
        'pending' => (int)$pending,
        'completed_today' => (int)$completed_today,
        'dozar_week' => (int)$dozar_week,
        'tripper_week' => (int)$tripper_week,
        'dozar_month' => (int)$dozar_month,
        'tripper_month' => (int)$tripper_month,
        'hours_today' => round((float)$hours_today, 2),
        'km_today' => round((float)$km_today, 2),
        'active_vehicles' => (int)$active_vehicles,
        'active_drivers' => (int)$active_drivers
    ]);

} elseif ($action === 'chart_weekly') {
    // Last 7 days data for charts
    $data = [];
    for ($i = 6; $i >= 0; $i--) {
        $date = date('Y-m-d', strtotime("-$i days"));
        $label = date('D', strtotime($date));

        $dozar = $pdo->query("SELECT COUNT(*) FROM dozar_records WHERE created_date = '$date'")->fetchColumn();
        $tripper = $pdo->query("SELECT COUNT(*) FROM tripper_records WHERE created_date = '$date'")->fetchColumn();
        $completed = $pdo->query("SELECT COUNT(*) FROM tripper_records WHERE status = 'completed' AND created_date = '$date'")->fetchColumn();

        $data[] = [
            'date' => $date,
            'label' => $label,
            'dozar' => (int)$dozar,
            'tripper' => (int)$tripper,
            'completed' => (int)$completed
        ];
    }
    echo json_encode(['success' => true, 'data' => $data]);

} elseif ($action === 'chart_vehicle_usage') {
    // Top 10 vehicles by usage this month
    $month_start = date('Y-m-01');
    $stmt = $pdo->query("SELECT v.vehicle_number,
                                COUNT(*) as total_trips,
                                COALESCE(SUM(CASE WHEN t.unloading_end_odometer > t.loading_start_odometer
                                    THEN t.unloading_end_odometer - t.loading_start_odometer ELSE 0 END), 0) as total_km
                         FROM tripper_records t
                         LEFT JOIN vehicles v ON t.vehicle_id = v.id
                         WHERE t.created_date >= '$month_start'
                         GROUP BY t.vehicle_id, v.vehicle_number
                         ORDER BY total_trips DESC LIMIT 10");
    echo json_encode(['success' => true, 'data' => $stmt->fetchAll()]);

} elseif ($action === 'chart_project_distribution') {
    // Records by project this month
    $month_start = date('Y-m-01');
    $stmt = $pdo->query("SELECT p.project_name,
                                COUNT(DISTINCT d.id) as dozar_count,
                                COUNT(DISTINCT t.id) as tripper_count
                         FROM projects p
                         LEFT JOIN dozar_records d ON d.project_id = p.id AND d.created_date >= '$month_start'
                         LEFT JOIN tripper_records t ON t.project_id = p.id AND t.created_date >= '$month_start'
                         WHERE p.is_active = 1
                         GROUP BY p.id, p.project_name
                         ORDER BY (COUNT(DISTINCT d.id) + COUNT(DISTINCT t.id)) DESC");
    echo json_encode(['success' => true, 'data' => $stmt->fetchAll()]);

} elseif ($action === 'recent_activity') {
    // Last 15 activities (combined dozar + tripper)
    $activities = [];

    // Recent dozar
    $stmt = $pdo->query("SELECT 'dozar' as type, d.id, d.created_date, d.work_location as location,
                                v.vehicle_number, dr.full_name as driver_name, d.work_length_hours,
                                d.created_at, 'completed' as status
                         FROM dozar_records d
                         LEFT JOIN vehicles v ON d.vehicle_id = v.id
                         LEFT JOIN drivers dr ON d.driver_id = dr.id
                         ORDER BY d.created_at DESC LIMIT 10");
    foreach ($stmt->fetchAll() as $r) { $r['sort_time'] = $r['created_at']; $activities[] = $r; }

    // Recent tripper
    $stmt = $pdo->query("SELECT 'tripper' as type, t.id, t.created_date, t.loading_location as location,
                                v.vehicle_number, dr.full_name as driver_name, NULL as work_length_hours,
                                t.created_at, t.status
                         FROM tripper_records t
                         LEFT JOIN vehicles v ON t.vehicle_id = v.id
                         LEFT JOIN drivers dr ON t.driver_id = dr.id
                         ORDER BY t.created_at DESC LIMIT 10");
    foreach ($stmt->fetchAll() as $r) { $r['sort_time'] = $r['created_at']; $activities[] = $r; }

    // Sort by time desc
    usort($activities, function($a, $b) { return strtotime($b['sort_time']) - strtotime($a['sort_time']); });
    $activities = array_slice($activities, 0, 15);

    echo json_encode(['success' => true, 'data' => $activities]);
}
