<?php
/**
 * Enhanced Dashboard
 * Dozar & Tripper Management System
 * Features: Charts, Auto-refresh, Alerts, Automation
 */

require_once __DIR__ . '/config/config.php';
require_once __DIR__ . '/config/db.php';
require_once __DIR__ . '/includes/auth.php';

// Load auto alerts if available
if (file_exists(__DIR__ . '/includes/auto_alerts.php')) {
    require_once __DIR__ . '/includes/auto_alerts.php';
}
if (file_exists(__DIR__ . '/includes/activity_log.php')) {
    require_once __DIR__ . '/includes/activity_log.php';
}

$user = getCurrentUser();
$pdo = getPDO();

// Today & date ranges
$today = date('Y-m-d');
$weekAgo = date('Y-m-d', strtotime('-7 days'));
$monthStart = date('Y-m-01');

// ============================================
// STATS
// ============================================
$stats = [];

// Dozar
$stats['dozar_today'] = (int)$pdo->query("SELECT COUNT(*) FROM dozar_records WHERE created_date = '$today'")->fetchColumn();
$stats['dozar_week'] = (int)$pdo->query("SELECT COUNT(*) FROM dozar_records WHERE created_date >= '$weekAgo'")->fetchColumn();
$stats['dozar_month'] = (int)$pdo->query("SELECT COUNT(*) FROM dozar_records WHERE created_date >= '$monthStart'")->fetchColumn();
$stats['hours_today'] = round((float)$pdo->query("SELECT COALESCE(SUM(work_length_hours),0) FROM dozar_records WHERE created_date = '$today'")->fetchColumn(), 2);
$stats['hours_month'] = round((float)$pdo->query("SELECT COALESCE(SUM(work_length_hours),0) FROM dozar_records WHERE created_date >= '$monthStart'")->fetchColumn(), 2);

// Tripper
$stats['tripper_today'] = (int)$pdo->query("SELECT COUNT(*) FROM tripper_records WHERE created_date = '$today'")->fetchColumn();
$stats['tripper_week'] = (int)$pdo->query("SELECT COUNT(*) FROM tripper_records WHERE created_date >= '$weekAgo'")->fetchColumn();
$stats['tripper_month'] = (int)$pdo->query("SELECT COUNT(*) FROM tripper_records WHERE created_date >= '$monthStart'")->fetchColumn();
$stats['pending'] = (int)$pdo->query("SELECT COUNT(*) FROM tripper_records WHERE status = 'pending_unloading'")->fetchColumn();
$stats['completed_today'] = (int)$pdo->query("SELECT COUNT(*) FROM tripper_records WHERE status = 'completed' AND created_date = '$today'")->fetchColumn();
$stats['completed_month'] = (int)$pdo->query("SELECT COUNT(*) FROM tripper_records WHERE status = 'completed' AND created_date >= '$monthStart'")->fetchColumn();
$stats['km_today'] = round((float)$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(), 2);
$stats['km_month'] = round((float)$pdo->query("SELECT COALESCE(SUM(unloading_end_odometer - loading_start_odometer),0) FROM tripper_records WHERE status='completed' AND created_date >= '$monthStart' AND unloading_end_odometer > loading_start_odometer")->fetchColumn(), 2);

// Active resources today
$stats['active_vehicles'] = (int)$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') c")->fetchColumn();
$stats['active_drivers'] = (int)$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') c")->fetchColumn();

// Admin totals
if (hasRole('admin')) {
    $stats['total_vehicles'] = (int)$pdo->query("SELECT COUNT(*) FROM vehicles WHERE is_active=1")->fetchColumn();
    $stats['total_drivers'] = (int)$pdo->query("SELECT COUNT(*) FROM drivers WHERE is_active=1")->fetchColumn();
    $stats['total_projects'] = (int)$pdo->query("SELECT COUNT(*) FROM projects WHERE is_active=1")->fetchColumn();
    $stats['total_users'] = (int)$pdo->query("SELECT COUNT(*) FROM users WHERE is_active=1")->fetchColumn();
}

// ============================================
// CHART DATA: Weekly trend (last 7 days)
// ============================================
$weekly_data = [];
for ($i = 6; $i >= 0; $i--) {
    $d = date('Y-m-d', strtotime("-$i days"));
    $label = date('D d', strtotime($d));
    $dz = (int)$pdo->query("SELECT COUNT(*) FROM dozar_records WHERE created_date='$d'")->fetchColumn();
    $tr = (int)$pdo->query("SELECT COUNT(*) FROM tripper_records WHERE created_date='$d'")->fetchColumn();
    $weekly_data[] = ['label' => $label, 'dozar' => $dz, 'tripper' => $tr];
}

// CHART DATA: Top vehicles this month
$top_vehicles = $pdo->query("SELECT v.vehicle_number, COUNT(*) as 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 km
    FROM tripper_records t LEFT JOIN vehicles v ON t.vehicle_id=v.id
    WHERE t.created_date >= '$monthStart' GROUP BY t.vehicle_id ORDER BY trips DESC LIMIT 8")->fetchAll();

// CHART DATA: Project distribution
$project_dist = $pdo->query("SELECT p.project_name,
    (SELECT COUNT(*) FROM dozar_records d WHERE d.project_id=p.id AND d.created_date >= '$monthStart') as dozar,
    (SELECT COUNT(*) FROM tripper_records t WHERE t.project_id=p.id AND t.created_date >= '$monthStart') as tripper
    FROM projects p WHERE p.is_active=1")->fetchAll();

// ============================================
// PENDING TRIPS (overdue alerts)
// ============================================
$pending_trips = $pdo->query("SELECT t.id, t.created_date, t.loading_location, t.loading_time, t.created_at,
    v.vehicle_number, dr.full_name as driver_name
    FROM tripper_records t
    LEFT JOIN vehicles v ON t.vehicle_id=v.id
    LEFT JOIN drivers dr ON t.driver_id=dr.id
    WHERE t.status='pending_unloading' ORDER BY t.created_at ASC")->fetchAll();

// ============================================
// RECENT ACTIVITY
// ============================================
$recentActivity = [];
$stmt = $pdo->query("(SELECT 'dozar' as type, d.id, d.created_date, d.work_location as location,
    v.vehicle_number, d.collector_name as user_name, d.created_at, 'completed' as status
    FROM dozar_records d LEFT JOIN vehicles v ON d.vehicle_id=v.id ORDER BY d.created_at DESC LIMIT 8)
    UNION ALL
    (SELECT 'tripper' as type, t.id, t.created_date, t.loading_location as location,
    v.vehicle_number, u.full_name as user_name, t.created_at, t.status
    FROM tripper_records t LEFT JOIN vehicles v ON t.vehicle_id=v.id LEFT JOIN users u ON t.loading_collector_id=u.id ORDER BY t.created_at DESC LIMIT 8)
    ORDER BY created_at DESC LIMIT 12");
$recentActivity = $stmt->fetchAll();

// ============================================
// DUPLICATE WARNINGS (fixed SQL injection)
// ============================================
$duplicateWarnings = [];
$stmt = $pdo->prepare("SELECT d.vehicle_id, v.vehicle_number, COUNT(*) as cnt
    FROM dozar_records d LEFT JOIN vehicles v ON d.vehicle_id=v.id
    WHERE d.created_date = ? GROUP BY d.vehicle_id, v.vehicle_number HAVING cnt > 1");
$stmt->execute([$today]);
foreach ($stmt->fetchAll() as $row) {
    $duplicateWarnings[] = ['type' => 'dozar', 'vehicle' => $row['vehicle_number'], 'count' => $row['cnt']];
}
$stmt = $pdo->prepare("SELECT t.vehicle_id, v.vehicle_number, COUNT(*) as cnt
    FROM tripper_records t LEFT JOIN vehicles v ON t.vehicle_id=v.id
    WHERE t.created_date = ? AND t.status='pending_unloading' GROUP BY t.vehicle_id, v.vehicle_number HAVING cnt > 1");
$stmt->execute([$today]);
foreach ($stmt->fetchAll() as $row) {
    $duplicateWarnings[] = ['type' => 'tripper', 'vehicle' => $row['vehicle_number'], 'count' => $row['cnt']];
}

?>
<?php include __DIR__ . '/includes/header.php'; ?>

<!-- Chart.js CDN -->
<script src="https://cdn.jsdelivr.net/npm/chart.js@4.4.0/dist/chart.umd.min.js"></script>

<style>
.stat-card { transition: transform 0.2s; cursor: pointer; }
.stat-card:hover { transform: translateY(-3px); }
.pulse { animation: pulse 2s infinite; }
@keyframes pulse { 0%,100%{opacity:1} 50%{opacity:0.6} }
.auto-refresh-badge { font-size: 0.7rem; }
.chart-container { position: relative; height: 280px; }
.pending-row:hover { background: #fff3cd !important; }
.activity-timeline { border-left: 3px solid #dee2e6; padding-left: 15px; }
.activity-dot { width: 12px; height: 12px; border-radius: 50%; position: absolute; left: -22px; top: 5px; }
</style>

<!-- Alerts Row -->
<?php if (!empty($duplicateWarnings) || !empty($pending_trips)): ?>
<div class="row mb-3">
    <?php if (!empty($duplicateWarnings)): ?>
    <div class="col-12 mb-2">
        <div class="alert alert-warning alert-dismissible fade show mb-0" role="alert">
            <strong><i class="fas fa-exclamation-triangle"></i> Duplicate Warnings:</strong>
            <?php foreach ($duplicateWarnings as $w): ?>
                <span class="badge bg-warning text-dark me-1"><?php echo ucfirst($w['type']); ?>: <?php echo htmlspecialchars($w['vehicle']); ?> (<?php echo $w['count']; ?>x)</span>
            <?php endforeach; ?>
            <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
        </div>
    </div>
    <?php endif; ?>
    <?php if (count($pending_trips) > 0): ?>
    <div class="col-12">
        <div class="alert alert-danger alert-dismissible fade show mb-0" role="alert">
            <strong><i class="fas fa-bell pulse"></i> <?php echo count($pending_trips); ?> Pending Unloading</strong> &mdash;
            <?php
            $overdue_count = 0;
            foreach ($pending_trips as $pt) {
                $hrs = (time() - strtotime($pt['created_at'])) / 3600;
                if ($hrs > 8) $overdue_count++;
            }
            if ($overdue_count > 0): ?>
            <span class="badge bg-danger"><?php echo $overdue_count; ?> overdue (>8hrs)</span>
            <?php endif; ?>
            <a href="#pendingSection" class="text-danger fw-bold ms-2">View Details <i class="fas fa-arrow-down"></i></a>
            <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
        </div>
    </div>
    <?php endif; ?>
</div>
<?php endif; ?>

<!-- Welcome & Live Clock -->
<div class="card bg-primary text-white mb-4">
    <div class="card-body py-3">
        <div class="row align-items-center">
            <div class="col-md-6">
                <h3 class="mb-1"><i class="fas fa-tachometer-alt"></i> Dashboard</h3>
                <h5 class="mb-0">Welcome, <?php echo htmlspecialchars($user['full_name']); ?>!
                    <span class="badge bg-light text-primary ms-1"><?php echo ucfirst($user['role']); ?></span>
                </h5>
            </div>
            <div class="col-md-3 text-md-end">
                <h5 class="mb-0"><i class="fas fa-calendar"></i> <?php echo getCurrentDateFormatted(); ?></h5>
                <small class="opacity-75"><?php echo CURRENT_LANGUAGE === 'ne' ? 'बिक्रम सम्वत' : 'Bikram Sambat'; ?></small>
            </div>
            <div class="col-md-3 text-md-end">
                <h5 class="mb-0"><i class="fas fa-clock"></i> <span id="liveClock"></span></h5>
                <small class="opacity-75 auto-refresh-badge"><i class="fas fa-sync-alt" id="refreshIcon"></i> Auto-refresh: <span id="refreshTimer">30</span>s</small>
            </div>
        </div>
    </div>
</div>

<!-- ============================================ -->
<!-- LIVE STATS ROW 1: Today's Numbers -->
<!-- ============================================ -->
<div class="row mb-3">
    <div class="col-md-3 mb-3">
        <a href="dozar/index.php" class="text-decoration-none">
            <div class="card stat-card bg-primary text-white h-100">
                <div class="card-body">
                    <div class="d-flex justify-content-between">
                        <div>
                            <small class="opacity-75">Today's Dozar</small>
                            <h2 class="mb-0" id="stat_dozar_today"><?php echo $stats['dozar_today']; ?></h2>
                            <small class="opacity-75"><i class="fas fa-calendar-week"></i> Week: <?php echo $stats['dozar_week']; ?> | Month: <?php echo $stats['dozar_month']; ?></small>
                        </div>
                        <i class="fas fa-truck-monster fa-2x opacity-50 mt-2"></i>
                    </div>
                </div>
            </div>
        </a>
    </div>
    <div class="col-md-3 mb-3">
        <a href="tripper/index.php" class="text-decoration-none">
            <div class="card stat-card bg-success text-white h-100">
                <div class="card-body">
                    <div class="d-flex justify-content-between">
                        <div>
                            <small class="opacity-75">Today's Tripper</small>
                            <h2 class="mb-0" id="stat_tripper_today"><?php echo $stats['tripper_today']; ?></h2>
                            <small class="opacity-75"><i class="fas fa-calendar-week"></i> Week: <?php echo $stats['tripper_week']; ?> | Month: <?php echo $stats['tripper_month']; ?></small>
                        </div>
                        <i class="fas fa-truck-loading fa-2x opacity-50 mt-2"></i>
                    </div>
                </div>
            </div>
        </a>
    </div>
    <div class="col-md-3 mb-3">
        <a href="tripper/index.php?status=pending" class="text-decoration-none">
            <div class="card stat-card bg-warning text-dark h-100">
                <div class="card-body">
                    <div class="d-flex justify-content-between">
                        <div>
                            <small>Pending Unloading</small>
                            <h2 class="mb-0 <?php echo $stats['pending'] > 0 ? 'pulse' : ''; ?>" id="stat_pending"><?php echo $stats['pending']; ?></h2>
                            <small><i class="fas fa-check-circle text-success"></i> Completed today: <?php echo $stats['completed_today']; ?></small>
                        </div>
                        <i class="fas fa-clock fa-2x opacity-50 mt-2"></i>
                    </div>
                </div>
            </div>
        </a>
    </div>
    <div class="col-md-3 mb-3">
        <a href="reports/index.php" class="text-decoration-none">
            <div class="card stat-card bg-info text-white h-100">
                <div class="card-body">
                    <div class="d-flex justify-content-between">
                        <div>
                            <small class="opacity-75">Today's Output</small>
                            <h2 class="mb-0"><?php echo $stats['hours_today']; ?> <small>hrs</small></h2>
                            <small class="opacity-75"><i class="fas fa-road"></i> <?php echo number_format($stats['km_today'], 1); ?> KM driven</small>
                        </div>
                        <i class="fas fa-chart-line fa-2x opacity-50 mt-2"></i>
                    </div>
                </div>
            </div>
        </a>
    </div>
</div>

<!-- ============================================ -->
<!-- LIVE STATS ROW 2: Resources & Monthly -->
<!-- ============================================ -->
<div class="row mb-4">
    <div class="col-md-3 mb-3">
        <div class="card h-100 border-start border-4 border-primary">
            <div class="card-body">
                <small class="text-muted">Active Vehicles Today</small>
                <h3 class="mb-0"><?php echo $stats['active_vehicles']; ?> <small class="text-muted fs-6">/ <?php echo $stats['total_vehicles'] ?? '-'; ?></small></h3>
                <div class="progress mt-2" style="height:5px">
                    <div class="progress-bar bg-primary" style="width:<?php echo ($stats['total_vehicles'] ?? 1) > 0 ? round($stats['active_vehicles']/($stats['total_vehicles'] ?? 1)*100) : 0; ?>%"></div>
                </div>
            </div>
        </div>
    </div>
    <div class="col-md-3 mb-3">
        <div class="card h-100 border-start border-4 border-success">
            <div class="card-body">
                <small class="text-muted">Active Drivers Today</small>
                <h3 class="mb-0"><?php echo $stats['active_drivers']; ?> <small class="text-muted fs-6">/ <?php echo $stats['total_drivers'] ?? '-'; ?></small></h3>
                <div class="progress mt-2" style="height:5px">
                    <div class="progress-bar bg-success" style="width:<?php echo ($stats['total_drivers'] ?? 1) > 0 ? round($stats['active_drivers']/($stats['total_drivers'] ?? 1)*100) : 0; ?>%"></div>
                </div>
            </div>
        </div>
    </div>
    <div class="col-md-3 mb-3">
        <div class="card h-100 border-start border-4 border-warning">
            <div class="card-body">
                <small class="text-muted">This Month - Dozar</small>
                <h3 class="mb-0"><?php echo $stats['dozar_month']; ?> <small class="text-muted fs-6">entries</small></h3>
                <small class="text-success"><i class="fas fa-clock"></i> <?php echo $stats['hours_month']; ?> total hours</small>
            </div>
        </div>
    </div>
    <div class="col-md-3 mb-3">
        <div class="card h-100 border-start border-4 border-info">
            <div class="card-body">
                <small class="text-muted">This Month - Tripper</small>
                <h3 class="mb-0"><?php echo $stats['completed_month']; ?> <small class="text-muted fs-6">completed</small></h3>
                <small class="text-primary"><i class="fas fa-road"></i> <?php echo number_format($stats['km_month'], 1); ?> KM total</small>
            </div>
        </div>
    </div>
</div>

<!-- ============================================ -->
<!-- CHARTS ROW -->
<!-- ============================================ -->
<div class="row mb-4">
    <!-- Weekly Trend -->
    <div class="col-md-8 mb-3">
        <div class="card h-100">
            <div class="card-header d-flex justify-content-between align-items-center">
                <h6 class="mb-0"><i class="fas fa-chart-bar"></i> Weekly Activity Trend</h6>
                <small class="text-muted">Last 7 days</small>
            </div>
            <div class="card-body">
                <div class="chart-container">
                    <canvas id="weeklyChart"></canvas>
                </div>
            </div>
        </div>
    </div>
    <!-- Project Distribution -->
    <div class="col-md-4 mb-3">
        <div class="card h-100">
            <div class="card-header">
                <h6 class="mb-0"><i class="fas fa-chart-pie"></i> Project Distribution</h6>
            </div>
            <div class="card-body">
                <div class="chart-container">
                    <canvas id="projectChart"></canvas>
                </div>
            </div>
        </div>
    </div>
</div>

<!-- Vehicle Usage Chart + Quick Actions -->
<div class="row mb-4">
    <div class="col-md-8 mb-3">
        <div class="card h-100">
            <div class="card-header">
                <h6 class="mb-0"><i class="fas fa-truck"></i> Top Vehicles This Month (by trips)</h6>
            </div>
            <div class="card-body">
                <div class="chart-container">
                    <canvas id="vehicleChart"></canvas>
                </div>
            </div>
        </div>
    </div>
    <div class="col-md-4 mb-3">
        <div class="card h-100">
            <div class="card-header">
                <h6 class="mb-0"><i class="fas fa-bolt"></i> Quick Actions</h6>
            </div>
            <div class="card-body d-flex flex-column gap-2">
                <?php if (hasRole('admin') || hasAccess('dozar_only') || hasAccess('all_modules')): ?>
                <a href="dozar/add.php" class="btn btn-primary"><i class="fas fa-plus-circle"></i> New Dozar Record</a>
                <?php endif; ?>
                <?php if (hasRole('admin') || hasAccess('tripper_loading_only') || hasAccess('all_modules')): ?>
                <a href="tripper/add_loading.php" class="btn btn-success"><i class="fas fa-plus-circle"></i> New Loading Entry</a>
                <?php endif; ?>
                <?php if (hasRole('admin') || hasAccess('tripper_unloading_only') || hasAccess('all_modules')): ?>
                <a href="tripper/add_unloading.php" class="btn btn-warning"><i class="fas fa-truck"></i> Complete Unloading</a>
                <?php endif; ?>
                <?php if (hasRole('admin') || hasRole('viewer')): ?>
                <a href="reports/index.php" class="btn btn-info text-white"><i class="fas fa-chart-bar"></i> View Reports</a>
                <?php endif; ?>
                <?php if (hasRole('admin')): ?>
                <hr class="my-1">
                <a href="vehicles/index.php" class="btn btn-outline-secondary btn-sm"><i class="fas fa-car"></i> Manage Vehicles</a>
                <a href="drivers/index.php" class="btn btn-outline-secondary btn-sm"><i class="fas fa-id-card"></i> Manage Drivers</a>
                <a href="users/index.php" class="btn btn-outline-secondary btn-sm"><i class="fas fa-users-cog"></i> Manage Users</a>
                <?php endif; ?>
            </div>
        </div>
    </div>
</div>

<!-- ============================================ -->
<!-- PENDING UNLOADING TABLE (with urgency colors) -->
<!-- ============================================ -->
<?php if (!empty($pending_trips)): ?>
<div class="row mb-4" id="pendingSection">
    <div class="col-12">
        <div class="card border-warning">
            <div class="card-header bg-warning text-dark d-flex justify-content-between align-items-center">
                <h6 class="mb-0"><i class="fas fa-exclamation-triangle"></i> Pending Unloading - Requires Action (<?php echo count($pending_trips); ?>)</h6>
                <span class="badge bg-dark"><?php echo count($pending_trips); ?> trips waiting</span>
            </div>
            <div class="card-body p-0">
                <div class="table-responsive">
                    <table class="table table-sm table-hover mb-0">
                        <thead class="table-dark">
                            <tr>
                                <th>Urgency</th>
                                <th>Vehicle</th>
                                <th>Driver</th>
                                <th>Loading Location</th>
                                <th>Date</th>
                                <th>Time</th>
                                <th>Waiting</th>
                                <th>Action</th>
                            </tr>
                        </thead>
                        <tbody>
                            <?php foreach ($pending_trips as $pt):
                                $hrs = (time() - strtotime($pt['created_at'])) / 3600;
                                if ($hrs > 24) { $urgency = 'danger'; $label = 'Critical'; }
                                elseif ($hrs > 8) { $urgency = 'warning'; $label = 'Overdue'; }
                                else { $urgency = 'info'; $label = 'Normal'; }
                            ?>
                            <tr class="pending-row">
                                <td><span class="badge bg-<?php echo $urgency; ?>"><?php echo $label; ?></span></td>
                                <td><strong><?php echo htmlspecialchars($pt['vehicle_number'] ?? '-'); ?></strong></td>
                                <td><?php echo htmlspecialchars($pt['driver_name'] ?? '-'); ?></td>
                                <td><?php echo htmlspecialchars($pt['loading_location'] ?? '-'); ?></td>
                                <td><?php echo $pt['created_date']; ?></td>
                                <td><?php echo $pt['loading_time'] ? date('H:i', strtotime($pt['loading_time'])) : '-'; ?></td>
                                <td><strong><?php echo round($hrs, 1); ?> hrs</strong></td>
                                <td>
                                    <a href="tripper/add_unloading.php?id=<?php echo $pt['id']; ?>" class="btn btn-sm btn-success">
                                        <i class="fas fa-check"></i> Complete
                                    </a>
                                </td>
                            </tr>
                            <?php endforeach; ?>
                        </tbody>
                    </table>
                </div>
            </div>
        </div>
    </div>
</div>
<?php endif; ?>

<!-- ============================================ -->
<!-- RECENT ACTIVITY FEED -->
<!-- ============================================ -->
<div class="row mb-4">
    <div class="col-12">
        <div class="card">
            <div class="card-header bg-dark text-white d-flex justify-content-between align-items-center">
                <h6 class="mb-0"><i class="fas fa-stream"></i> Recent Activity</h6>
                <small class="opacity-75" id="lastUpdate">Updated: <?php echo date('H:i:s'); ?></small>
            </div>
            <div class="card-body" id="activityFeed">
                <?php if (empty($recentActivity)): ?>
                <p class="text-muted text-center py-3">No recent activity.</p>
                <?php else: ?>
                <?php foreach ($recentActivity as $a): ?>
                <div class="d-flex align-items-start mb-3 pb-2 border-bottom">
                    <div class="me-3">
                        <?php if ($a['type'] === 'dozar'): ?>
                        <span class="badge bg-primary rounded-circle p-2"><i class="fas fa-truck-monster"></i></span>
                        <?php else: ?>
                        <span class="badge bg-<?php echo $a['status'] === 'completed' ? 'success' : ($a['status'] === 'pending_unloading' ? 'warning' : 'secondary'); ?> rounded-circle p-2"><i class="fas fa-truck-loading"></i></span>
                        <?php endif; ?>
                    </div>
                    <div class="flex-grow-1">
                        <div class="d-flex justify-content-between">
                            <div>
                                <strong><?php echo ucfirst($a['type']); ?></strong>
                                <?php if ($a['status'] === 'pending_unloading'): ?>
                                    <span class="badge bg-warning text-dark">Pending</span>
                                <?php elseif ($a['status'] === 'completed'): ?>
                                    <span class="badge bg-success">Completed</span>
                                <?php endif; ?>
                                <span class="text-muted">at</span>
                                <?php echo htmlspecialchars($a['location'] ?? '-'); ?>
                            </div>
                            <small class="text-muted"><?php echo date('H:i', strtotime($a['created_at'])); ?></small>
                        </div>
                        <div class="mt-1">
                            <span class="badge bg-secondary"><i class="fas fa-car"></i> <?php echo htmlspecialchars($a['vehicle_number'] ?? '-'); ?></span>
                            <span class="badge bg-light text-dark"><i class="fas fa-user"></i> <?php echo htmlspecialchars($a['user_name'] ?? '-'); ?></span>
                            <span class="badge bg-info"><i class="fas fa-calendar"></i> <?php echo $a['created_date']; ?></span>
                        </div>
                    </div>
                    <a href="<?php echo $a['type']; ?>/view.php?id=<?php echo $a['id']; ?>" class="btn btn-sm btn-outline-primary ms-2"><i class="fas fa-eye"></i></a>
                </div>
                <?php endforeach; ?>
                <?php endif; ?>
            </div>
        </div>
    </div>
</div>

<!-- ============================================ -->
<!-- JAVASCRIPT: Charts + Auto-refresh + Live Clock -->
<!-- ============================================ -->
<script>
// ---- Live Clock ----
function updateClock() {
    var now = new Date();
    document.getElementById('liveClock').textContent =
        now.getHours().toString().padStart(2,'0') + ':' +
        now.getMinutes().toString().padStart(2,'0') + ':' +
        now.getSeconds().toString().padStart(2,'0');
}
setInterval(updateClock, 1000);
updateClock();

// ---- Auto Refresh Timer ----
var refreshInterval = 30;
var refreshCounter = refreshInterval;
function refreshCountdown() {
    refreshCounter--;
    var el = document.getElementById('refreshTimer');
    if (el) el.textContent = refreshCounter;
    if (refreshCounter <= 0) {
        refreshCounter = refreshInterval;
        autoRefreshStats();
    }
}
setInterval(refreshCountdown, 1000);

function autoRefreshStats() {
    var icon = document.getElementById('refreshIcon');
    if (icon) icon.classList.add('fa-spin');

    fetch('api_dashboard.php?action=stats')
        .then(r => r.json())
        .then(data => {
            if (data.success) {
                animateNumber('stat_dozar_today', data.dozar_today);
                animateNumber('stat_tripper_today', data.tripper_today);
                animateNumber('stat_pending', data.pending);
                document.getElementById('lastUpdate').textContent = 'Updated: ' + data.timestamp;
            }
            if (icon) setTimeout(() => icon.classList.remove('fa-spin'), 500);
        })
        .catch(() => { if (icon) icon.classList.remove('fa-spin'); });
}

function animateNumber(id, newVal) {
    var el = document.getElementById(id);
    if (!el) return;
    var old = parseInt(el.textContent) || 0;
    if (old !== newVal) {
        el.textContent = newVal;
        el.style.transform = 'scale(1.3)';
        el.style.transition = 'transform 0.3s';
        setTimeout(() => { el.style.transform = 'scale(1)'; }, 300);
    }
}

// ---- Charts ----
// Weekly Trend Bar Chart
var weeklyCtx = document.getElementById('weeklyChart').getContext('2d');
new Chart(weeklyCtx, {
    type: 'bar',
    data: {
        labels: <?php echo json_encode(array_column($weekly_data, 'label')); ?>,
        datasets: [
            { label: 'Dozar', data: <?php echo json_encode(array_column($weekly_data, 'dozar')); ?>, backgroundColor: 'rgba(46,125,50,0.8)', borderRadius: 4 },
            { label: 'Tripper', data: <?php echo json_encode(array_column($weekly_data, 'tripper')); ?>, backgroundColor: 'rgba(21,101,192,0.8)', borderRadius: 4 }
        ]
    },
    options: {
        responsive: true, maintainAspectRatio: false,
        plugins: { legend: { position: 'top' } },
        scales: { y: { beginAtZero: true, ticks: { stepSize: 1 } } }
    }
});

// Project Distribution Doughnut
var projCtx = document.getElementById('projectChart').getContext('2d');
var projLabels = <?php echo json_encode(array_column($project_dist, 'project_name')); ?>;
var projDozar = <?php echo json_encode(array_map('intval', array_column($project_dist, 'dozar'))); ?>;
var projTripper = <?php echo json_encode(array_map('intval', array_column($project_dist, 'tripper'))); ?>;
var projTotals = projDozar.map((d, i) => d + projTripper[i]);
new Chart(projCtx, {
    type: 'doughnut',
    data: {
        labels: projLabels,
        datasets: [{
            data: projTotals,
            backgroundColor: ['#2E7D32','#1565C0','#FF6F00','#8E24AA','#D32F2F','#00838F','#6D4C41','#546E7A'],
            borderWidth: 2
        }]
    },
    options: {
        responsive: true, maintainAspectRatio: false,
        plugins: { legend: { position: 'bottom', labels: { boxWidth: 12, padding: 8, font: { size: 11 } } } }
    }
});

// Vehicle Usage Horizontal Bar
var vehCtx = document.getElementById('vehicleChart').getContext('2d');
new Chart(vehCtx, {
    type: 'bar',
    data: {
        labels: <?php echo json_encode(array_column($top_vehicles, 'vehicle_number')); ?>,
        datasets: [
            { label: 'Trips', data: <?php echo json_encode(array_map('intval', array_column($top_vehicles, 'trips'))); ?>, backgroundColor: 'rgba(255,111,0,0.8)', borderRadius: 4 },
            { label: 'KM', data: <?php echo json_encode(array_map('floatval', array_column($top_vehicles, 'km'))); ?>, backgroundColor: 'rgba(21,101,192,0.5)', borderRadius: 4 }
        ]
    },
    options: {
        indexAxis: 'y',
        responsive: true, maintainAspectRatio: false,
        plugins: { legend: { position: 'top' } },
        scales: { x: { beginAtZero: true } }
    }
});
</script>

<?php include __DIR__ . '/includes/footer.php'; ?>
