<?php
require 'db.php';
require_once 'helpers.php';

// Assuming user_id 1 is the default for 'chris' based on the SQL dump
$user_id = 1;

// -----------------------------------------
// 1. JOB TRACKER STATS
// -----------------------------------------
$startOfMonth = date('Y-m-01');
$startOfWeek  = date('Y-m-d', strtotime('monday this week'));

$stmt = $pdo->prepare("SELECT COUNT(*) FROM jobs WHERE job_date >= ?");
$stmt->execute([$startOfMonth]);
$jobsThisMonth = $stmt->fetchColumn();

$stmt = $pdo->prepare("SELECT COUNT(*) FROM jobs WHERE job_date >= ?");
$stmt->execute([$startOfWeek]);
$jobsThisWeek = $stmt->fetchColumn();

$stmt = $pdo->prepare("SELECT COUNT(*) FROM jobs WHERE job_date >= ? AND is_smx = 1");
$stmt->execute([$startOfMonth]);
$smxThisMonth = $stmt->fetchColumn();

$stmt = $pdo->prepare("SELECT SUM(time_spent) FROM jobs WHERE job_date >= ?");
$stmt->execute([$startOfMonth]);
$minutesThisMonth = (int)$stmt->fetchColumn();
$hoursThisMonth   = floor($minutesThisMonth / 60);
$minsRemainder    = $minutesThisMonth % 60;

$stmt = $pdo->prepare("SELECT SUM(mileage) FROM jobs WHERE job_date >= ?");
$stmt->execute([$startOfMonth]);
$mileageThisMonth = (float)$stmt->fetchColumn();

$totalCustomers = $pdo->query("SELECT COUNT(*) FROM customers")->fetchColumn();

$today = date('Y-m-d');
$stmtToday = $pdo->prepare("
    SELECT j.*, c.name as customer_name
    FROM jobs j
    JOIN customers c ON j.customer_id = c.id
    WHERE j.job_date = ?
    ORDER BY j.id DESC
");
$stmtToday->execute([$today]);
$todaysJobs = $stmtToday->fetchAll();

$stmtJobs = $pdo->query("
    SELECT j.*, c.name as customer_name
    FROM jobs j
    JOIN customers c ON j.customer_id = c.id
    ORDER BY j.job_date DESC, j.id DESC
    LIMIT 5
");
$recentJobs = $stmtJobs->fetchAll();

// -----------------------------------------
// 2. TIMESHEET STATS
// -----------------------------------------
$stmtTs = $pdo->prepare("SELECT * FROM timesheets WHERE user_id = ? ORDER BY week_ending_date DESC LIMIT 1");
$stmtTs->execute([$user_id]);
$latestTimesheet = $stmtTs->fetch();

$tsHours = 0;
$tsStatus = 'No Draft';
$logTimeLink = 'timesheet_edit.php'; // Default to a blank new week

if ($latestTimesheet) {
    $stmtHours = $pdo->prepare("SELECT SUM(hours) FROM time_entries WHERE timesheet_id = ?");
    $stmtHours->execute([$latestTimesheet['id']]);
    $tsHours = $stmtHours->fetchColumn() ?: 0;
    $tsStatus = ucfirst($latestTimesheet['status']);

    // If the latest timesheet is still a draft, link directly to it
    if ($latestTimesheet['status'] === 'draft') {
        $logTimeLink = 'timesheet_edit.php?id=' . $latestTimesheet['id'];
    }
}

// -----------------------------------------
// 3. DAILY JOBS CHART DATA
// -----------------------------------------
$chartLabels = [];
$chartData   = [];
$daysElapsed = (int)date('j');
for ($d = 1; $d <= $daysElapsed; $d++) {
    $dateStr = date('Y-m-') . str_pad($d, 2, '0', STR_PAD_LEFT);
    $dow     = (int)date('N', strtotime($dateStr)); // 6=Sat, 7=Sun
    if ($dow >= 6) continue;
    $chartLabels[]       = date('M j', strtotime($dateStr));
    $chartData[$dateStr] = 0;
}
$stmtDaily = $pdo->prepare("SELECT job_date, COUNT(*) as cnt FROM jobs WHERE job_date >= ? AND job_date <= ? GROUP BY job_date");
$stmtDaily->execute([$startOfMonth, $today]);
foreach ($stmtDaily->fetchAll() as $row) {
    if (isset($chartData[$row['job_date']])) $chartData[$row['job_date']] = (int)$row['cnt'];
}
$chartCounts = array_values($chartData);

// -----------------------------------------
// 4. FIBER TRACKER STATS
// -----------------------------------------
$totalProjects = $pdo->query("SELECT COUNT(*) FROM projects")->fetchColumn();

$stmtProjects = $pdo->query("SELECT * FROM projects ORDER BY updated_at DESC LIMIT 5");
$recentProjects = $stmtProjects->fetchAll();

// -----------------------------------------
// 5. PTO BALANCE
// -----------------------------------------
$pto = getPtoBalance($pdo, $user_id, (int)date('Y'));
?>

<!DOCTYPE html>
<html lang="en" class="h-full">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>ChrisOS v3.0</title>
    <link rel="stylesheet" href="/assets/css/tailwind.min.css">
    
    <script>
        if (localStorage.theme === 'dark' || (!('theme' in localStorage) && window.matchMedia('(prefers-color-scheme: dark)').matches)) {
            document.documentElement.classList.add('dark');
            document.documentElement.style.backgroundColor = '#111827'; 
        } else {
            document.documentElement.classList.remove('dark');
            document.documentElement.style.backgroundColor = '#f3f4f6'; 
        }
    </script>
    <link href="/assets/css/font-awesome.min.css" rel="stylesheet">
    <script src="/assets/js/chart.min.js"></script>
</head>
<body class="bg-gray-100 dark:bg-gray-900 text-gray-800 dark:text-gray-200 h-full flex overflow-hidden text-sm">

    <?php include 'sidebar.php'; ?>

    <main class="flex-1 flex flex-col h-full overflow-hidden">
        <header class="h-14 bg-white dark:bg-gray-800 shadow flex items-center px-6 justify-between shrink-0">
        <button class="open-sidebar-btn md:hidden mr-3 text-gray-500 hover:text-blue-600 transition">
    <i class="fas fa-bars text-xl"></i>
</button>    
        <h2 class="font-bold text-lg text-gray-700 dark:text-gray-200 flex items-center">
                Dashboard 
                <span class="ml-3 px-2 py-0.5 bg-gray-200 dark:bg-gray-700 text-gray-500 dark:text-gray-400 rounded text-[10px] font-mono tracking-wider uppercase border border-gray-300 dark:border-gray-600">v3.0</span>
            </h2>
            <div class="text-xs font-bold text-gray-500 dark:text-gray-400 uppercase tracking-wide"><?= date('l, F j, Y') ?></div>
        </header>

        <div class="flex-1 overflow-auto p-6">
            
            <div class="flex flex-wrap gap-3 mb-6">
                <a href="job_entry.php" class="bg-blue-600 hover:bg-blue-500 text-white rounded shadow px-4 py-2 flex items-center font-bold uppercase text-xs transition">
                    <i class="fas fa-plus-circle mr-2"></i> New Job
                </a>
                <a href="<?= $logTimeLink ?>" class="bg-indigo-600 hover:bg-indigo-500 text-white rounded shadow px-4 py-2 flex items-center font-bold uppercase text-xs transition">
                    <i class="fas fa-clock mr-2"></i> Log Time
                </a>
                <a href="projects.php" class="bg-orange-600 hover:bg-orange-500 text-white rounded shadow px-4 py-2 flex items-center font-bold uppercase text-xs transition">
                    <i class="fas fa-project-diagram mr-2"></i> Fiber Projects
                </a>
            </div>

            <div class="grid grid-cols-2 md:grid-cols-4 gap-4 mb-3">
                <a href="reports.php" class="bg-white dark:bg-gray-800 rounded shadow border dark:border-gray-700 p-4 flex items-center justify-between group">
                    <div>
                        <div class="text-gray-500 dark:text-gray-400 text-[10px] font-bold uppercase tracking-wider">Jobs This Week</div>
                        <div class="font-bold text-3xl text-gray-800 dark:text-gray-100 mt-1"><?= $jobsThisWeek ?></div>
                    </div>
                    <div class="h-10 w-10 rounded-full bg-blue-100 dark:bg-blue-900/40 flex items-center justify-center text-blue-600 dark:text-blue-400 transition-transform group-hover:scale-110">
                        <i class="fas fa-calendar-week text-lg"></i>
                    </div>
                </a>

                <a href="reports.php" class="bg-white dark:bg-gray-800 rounded shadow border dark:border-gray-700 p-4 flex items-center justify-between group">
                    <div>
                        <div class="text-gray-500 dark:text-gray-400 text-[10px] font-bold uppercase tracking-wider">Jobs This Month</div>
                        <div class="font-bold text-3xl text-gray-800 dark:text-gray-100 mt-1"><?= $jobsThisMonth ?></div>
                    </div>
                    <div class="h-10 w-10 rounded-full bg-sky-100 dark:bg-sky-900/40 flex items-center justify-center text-sky-600 dark:text-sky-400 transition-transform group-hover:scale-110">
                        <i class="fas fa-calendar-check text-lg"></i>
                    </div>
                </a>

                <a href="reports.php" class="bg-white dark:bg-gray-800 rounded shadow border dark:border-gray-700 p-4 flex items-center justify-between group">
                    <div>
                        <div class="text-gray-500 dark:text-gray-400 text-[10px] font-bold uppercase tracking-wider">SMx This Month</div>
                        <div class="font-bold text-3xl text-gray-800 dark:text-gray-100 mt-1"><?= $smxThisMonth ?></div>
                    </div>
                    <div class="h-10 w-10 rounded-full bg-purple-100 dark:bg-purple-900/40 flex items-center justify-center text-purple-600 dark:text-purple-400 transition-transform group-hover:scale-110">
                        <i class="fas fa-exchange-alt text-lg"></i>
                    </div>
                </a>

                <a href="customers.php" class="bg-white dark:bg-gray-800 rounded shadow border dark:border-gray-700 p-4 flex items-center justify-between group">
                    <div>
                        <div class="text-gray-500 dark:text-gray-400 text-[10px] font-bold uppercase tracking-wider">Active Customers</div>
                        <div class="font-bold text-3xl text-gray-800 dark:text-gray-100 mt-1"><?= $totalCustomers ?></div>
                    </div>
                    <div class="h-10 w-10 rounded-full bg-emerald-100 dark:bg-emerald-900/40 flex items-center justify-center text-emerald-600 dark:text-emerald-400 transition-transform group-hover:scale-110">
                        <i class="fas fa-users text-lg"></i>
                    </div>
                </a>
            </div>

            <div class="grid grid-cols-2 md:grid-cols-3 lg:grid-cols-5 gap-4 mb-6">
                <a href="<?= $logTimeLink ?>" class="bg-white dark:bg-gray-800 rounded shadow border dark:border-gray-700 p-4 flex items-center justify-between group">
                    <div>
                        <div class="text-gray-500 dark:text-gray-400 text-[10px] font-bold uppercase tracking-wider">Hours This Month</div>
                        <div class="font-bold text-3xl text-gray-800 dark:text-gray-100 mt-1">
                            <?= $hoursThisMonth ?><span class="text-base font-normal text-gray-400 ml-0.5">h</span><?= $minsRemainder > 0 ? ' ' . $minsRemainder . '<span class="text-base font-normal text-gray-400 ml-0.5">m</span>' : '' ?>
                        </div>
                    </div>
                    <div class="h-10 w-10 rounded-full bg-indigo-100 dark:bg-indigo-900/40 flex items-center justify-center text-indigo-600 dark:text-indigo-400 transition-transform group-hover:scale-110">
                        <i class="fas fa-user-clock text-lg"></i>
                    </div>
                </a>

                <?php
                    $weekGoal = 40;
                    $weekPct  = $weekGoal > 0 ? min(100, round(($tsHours / $weekGoal) * 100)) : 0;
                    $barColor = $weekPct >= 100 ? 'bg-emerald-500' : ($weekPct >= 75 ? 'bg-blue-500' : ($weekPct >= 40 ? 'bg-yellow-400' : 'bg-gray-300 dark:bg-gray-600'));
                ?>
                <a href="<?= $logTimeLink ?>" class="bg-white dark:bg-gray-800 rounded shadow border dark:border-gray-700 p-4 flex flex-col justify-between group min-h-[88px]">
                    <div class="flex items-center justify-between">
                        <div>
                            <div class="text-gray-500 dark:text-gray-400 text-[10px] font-bold uppercase tracking-wider">Timesheet (<?= $tsStatus ?>)</div>
                            <div class="font-bold text-3xl text-gray-800 dark:text-gray-100 mt-1">
                                <?= number_format($tsHours, 2) ?><span class="text-base font-normal text-gray-400 ml-1">/ <?= $weekGoal ?>h</span>
                            </div>
                        </div>
                        <div class="h-10 w-10 rounded-full bg-teal-100 dark:bg-teal-900/40 flex items-center justify-center text-teal-600 dark:text-teal-400 transition-transform group-hover:scale-110 shrink-0">
                            <i class="fas fa-clock text-lg"></i>
                        </div>
                    </div>
                    <div class="mt-3">
                        <div class="w-full bg-gray-100 dark:bg-gray-700 rounded-full h-1.5">
                            <div class="<?= $barColor ?> h-1.5 rounded-full transition-all" style="width: <?= $weekPct ?>%"></div>
                        </div>
                        <div class="text-[9px] text-gray-400 font-bold uppercase tracking-wide mt-1"><?= $weekPct ?>% of week</div>
                    </div>
                </a>

                <div class="bg-white dark:bg-gray-800 rounded shadow border dark:border-gray-700 p-4 flex items-center justify-between group cursor-default">
                    <div>
                        <div class="text-gray-500 dark:text-gray-400 text-[10px] font-bold uppercase tracking-wider">Mileage This Month</div>
                        <div class="font-bold text-3xl text-gray-800 dark:text-gray-100 mt-1">
                            <?= $mileageThisMonth > 0 ? number_format($mileageThisMonth, 1) : '—' ?>
                        </div>
                    </div>
                    <div class="h-10 w-10 rounded-full bg-yellow-100 dark:bg-yellow-900/40 flex items-center justify-center text-yellow-600 dark:text-yellow-400 transition-transform group-hover:scale-110">
                        <i class="fas fa-car text-lg"></i>
                    </div>
                </div>

                <a href="projects.php" class="bg-white dark:bg-gray-800 rounded shadow border dark:border-gray-700 p-4 flex items-center justify-between group">
                    <div>
                        <div class="text-gray-500 dark:text-gray-400 text-[10px] font-bold uppercase tracking-wider">Fiber Projects</div>
                        <div class="font-bold text-3xl text-gray-800 dark:text-gray-100 mt-1"><?= $totalProjects ?></div>
                    </div>
                    <div class="h-10 w-10 rounded-full bg-orange-100 dark:bg-orange-900/40 flex items-center justify-center text-orange-600 dark:text-orange-400 transition-transform group-hover:scale-110">
                        <i class="fas fa-network-wired text-lg"></i>
                    </div>
                </a>

                <?php
                    $ptoRemainClass = $pto['remaining'] <= 0
                        ? 'text-red-600 dark:text-red-400'
                        : ($pto['remaining'] <= 8 ? 'text-amber-600 dark:text-amber-400' : 'text-emerald-600 dark:text-emerald-400');
                    $ptoBgClass = $pto['remaining'] <= 0
                        ? 'bg-red-100 dark:bg-red-900/40 text-red-600 dark:text-red-400'
                        : 'bg-emerald-100 dark:bg-emerald-900/40 text-emerald-600 dark:text-emerald-400';
                ?>
                <a href="timesheet.php" class="bg-white dark:bg-gray-800 rounded shadow border dark:border-gray-700 p-4 flex items-center justify-between group">
                    <div>
                        <div class="text-gray-500 dark:text-gray-400 text-[10px] font-bold uppercase tracking-wider">PTO Remaining</div>
                        <div class="font-bold text-3xl mt-1 <?= $ptoRemainClass ?>">
                            <?= number_format($pto['remaining'], 1) ?><span class="text-base font-normal text-gray-400 ml-0.5">h</span>
                        </div>
                        <div class="text-[9px] text-gray-400 uppercase tracking-wide mt-0.5"><?= number_format($pto['used'], 1) ?>h used of <?= number_format($pto['allotted'], 1) ?>h</div>
                    </div>
                    <div class="h-10 w-10 rounded-full <?= $ptoBgClass ?> flex items-center justify-center transition-transform group-hover:scale-110 shrink-0">
                        <i class="fas fa-umbrella-beach text-lg"></i>
                    </div>
                </a>
            </div>

            <!-- Jobs Activity Chart -->
            <div class="bg-white dark:bg-gray-800 rounded shadow border dark:border-gray-700 mb-6 p-5">
                <div class="flex justify-between items-center mb-4">
                    <h3 class="font-bold text-gray-700 dark:text-gray-200 text-xs uppercase tracking-wide">
                        <i class="fas fa-chart-bar mr-2 text-gray-400"></i> Jobs — <?= date('F Y') ?>
                    </h3>
                    <span class="text-[10px] font-bold text-gray-400 uppercase tracking-wide"><?= $jobsThisMonth ?> total</span>
                </div>
                <div class="relative" style="height:140px">
                    <canvas id="jobsChart"></canvas>
                </div>
            </div>

            <?php if (!empty($todaysJobs)): ?>
            <div class="bg-white dark:bg-gray-800 rounded shadow border border-blue-200 dark:border-blue-800 mb-6">
                <div class="px-5 py-3 border-b border-blue-100 dark:border-blue-800 flex justify-between items-center bg-blue-50 dark:bg-blue-900/20">
                    <h3 class="font-bold text-blue-700 dark:text-blue-300 text-xs uppercase tracking-wide">
                        <i class="fas fa-sun mr-2"></i> Today's Jobs — <?= date('F j') ?>
                    </h3>
                    <span class="text-[10px] font-bold text-blue-500 uppercase"><?= count($todaysJobs) ?> job<?= count($todaysJobs) !== 1 ? 's' : '' ?></span>
                </div>
                <div class="divide-y divide-gray-100 dark:divide-gray-700">
                    <?php foreach ($todaysJobs as $job):
                        $jh = floor((int)$job['time_spent'] / 60);
                        $jm = (int)$job['time_spent'] % 60;
                        $timeLabel = $job['time_spent'] > 0
                            ? ($jh > 0 ? "{$jh}h " : '') . ($jm > 0 ? "{$jm}m" : '')
                            : '—';
                    ?>
                    <div class="px-5 py-2.5 flex items-center justify-between hover:bg-gray-50 dark:hover:bg-gray-700/30 transition text-xs">
                        <div class="flex items-center gap-3 min-w-0">
                            <span class="font-medium truncate" title="<?= htmlspecialchars($job['customer_name']) ?>"><?= htmlspecialchars($job['customer_name']) ?></span>
                            <div class="flex gap-1 shrink-0">
                                <?php if (!empty($job['is_billable'])): ?>
                                    <span class="px-1 py-0 rounded text-[9px] font-bold bg-emerald-100 dark:bg-emerald-900/40 text-emerald-700 dark:text-emerald-400 border border-emerald-200 dark:border-emerald-800">Bill</span>
                                <?php endif; ?>
                                <?php if (!empty($job['is_smx'])): ?>
                                    <span class="px-1 py-0 rounded text-[9px] font-bold bg-purple-100 dark:bg-purple-900/40 text-purple-700 dark:text-purple-400 border border-purple-200 dark:border-purple-800">SMx</span>
                                <?php endif; ?>
                                <?php if (!empty($job['is_cobalt'])): ?>
                                    <span class="px-1 py-0 rounded text-[9px] font-bold bg-blue-100 dark:bg-blue-900/40 text-blue-700 dark:text-blue-400 border border-blue-200 dark:border-blue-800">Cobalt</span>
                                <?php endif; ?>
                            </div>
                        </div>
                        <div class="flex items-center gap-4 shrink-0 ml-4">
                            <span class="font-mono text-gray-500"><?= $timeLabel ?></span>
                            <a href="job_edit.php?id=<?= $job['id'] ?>" class="text-gray-400 hover:text-blue-500 text-[10px] font-bold uppercase transition">Edit</a>
                            <a href="job_view.php?id=<?= $job['id'] ?>" class="text-blue-600 hover:text-blue-500 text-[10px] font-bold uppercase">View</a>
                        </div>
                    </div>
                    <?php endforeach; ?>
                </div>
            </div>
            <?php endif; ?>

            <div class="grid grid-cols-1 lg:grid-cols-2 gap-6">
                
                <div class="bg-white dark:bg-gray-800 rounded shadow border dark:border-gray-700 flex flex-col h-full">
                    <div class="px-5 py-3 border-b border-gray-100 dark:border-gray-700 flex justify-between items-center bg-gray-50/50 dark:bg-gray-800">
                        <h3 class="font-bold text-gray-700 dark:text-gray-200 text-xs uppercase tracking-wide"><i class="fas fa-tools mr-2 text-gray-400"></i> Recent Jobs</h3>
                        <a href="reports.php" class="text-[10px] text-blue-500 hover:text-blue-400 font-bold uppercase">View All</a>
                    </div>
                    <div class="overflow-x-auto flex-1">
                        <table class="w-full text-left border-collapse">
                            <thead>
                                <tr class="bg-gray-50 dark:bg-gray-700/50 text-[10px] uppercase tracking-wider text-gray-500 dark:text-gray-400 border-b dark:border-gray-700">
                                    <th class="px-5 py-2 font-bold w-20">Date</th>
                                    <th class="px-5 py-2 font-bold">Customer</th>
                                    <th class="px-5 py-2 font-bold text-right">Time</th>
                                    <th class="px-5 py-2 text-right font-bold">Action</th>
                                </tr>
                            </thead>
                            <tbody class="divide-y divide-gray-100 dark:divide-gray-700 text-xs">
                                <?php if(empty($recentJobs)): ?>
                                    <tr><td colspan="4" class="px-5 py-6 text-center text-gray-400 italic">No recent jobs found.</td></tr>
                                <?php else: ?>
                                    <?php foreach ($recentJobs as $job):
                                        $jh = floor((int)$job['time_spent'] / 60);
                                        $jm = (int)$job['time_spent'] % 60;
                                        $timeLabel = $job['time_spent'] > 0
                                            ? ($jh > 0 ? "{$jh}h " : '') . ($jm > 0 ? "{$jm}m" : '')
                                            : '—';
                                    ?>
                                    <tr class="hover:bg-gray-50 dark:hover:bg-gray-700/30 transition">
                                        <td class="px-5 py-2.5 whitespace-nowrap text-gray-500"><?= date('M d', strtotime($job['job_date'])) ?></td>
                                        <td class="px-5 py-2.5 font-medium truncate max-w-[130px]" title="<?= htmlspecialchars($job['customer_name']) ?>">
                                            <?= htmlspecialchars($job['customer_name']) ?>
                                            <div class="flex gap-1 mt-0.5">
                                                <?php if (!empty($job['is_billable'])): ?>
                                                    <span class="px-1 py-0 rounded text-[9px] font-bold bg-emerald-100 dark:bg-emerald-900/40 text-emerald-700 dark:text-emerald-400 border border-emerald-200 dark:border-emerald-800">Bill</span>
                                                <?php endif; ?>
                                                <?php if (!empty($job['is_smx'])): ?>
                                                    <span class="px-1 py-0 rounded text-[9px] font-bold bg-purple-100 dark:bg-purple-900/40 text-purple-700 dark:text-purple-400 border border-purple-200 dark:border-purple-800">SMx</span>
                                                <?php endif; ?>
                                                <?php if (!empty($job['is_cobalt'])): ?>
                                                    <span class="px-1 py-0 rounded text-[9px] font-bold bg-blue-100 dark:bg-blue-900/40 text-blue-700 dark:text-blue-400 border border-blue-200 dark:border-blue-800">Cobalt</span>
                                                <?php endif; ?>
                                            </div>
                                        </td>
                                        <td class="px-5 py-2.5 text-right font-mono text-gray-500 whitespace-nowrap"><?= $timeLabel ?></td>
                                        <td class="px-5 py-2.5 text-right">
                                            <a href="job_view.php?id=<?= $job['id'] ?>" class="text-blue-600 hover:text-blue-500 font-bold text-[10px] uppercase">View</a>
                                        </td>
                                    </tr>
                                    <?php endforeach; ?>
                                <?php endif; ?>
                            </tbody>
                        </table>
                    </div>
                </div>

                <div class="bg-white dark:bg-gray-800 rounded shadow border dark:border-gray-700 flex flex-col h-full">
                    <div class="px-5 py-3 border-b border-gray-100 dark:border-gray-700 flex justify-between items-center bg-gray-50/50 dark:bg-gray-800">
                        <h3 class="font-bold text-gray-700 dark:text-gray-200 text-xs uppercase tracking-wide"><i class="fas fa-project-diagram mr-2 text-gray-400"></i> Recent Fiber Projects</h3>
                        <a href="projects.php" class="text-[10px] text-blue-500 hover:text-blue-400 font-bold uppercase">View All</a>
                    </div>
                    <div class="overflow-x-auto flex-1">
                        <table class="w-full text-left border-collapse">
                            <thead>
                                <tr class="bg-gray-50 dark:bg-gray-700/50 text-[10px] uppercase tracking-wider text-gray-500 dark:text-gray-400 border-b dark:border-gray-700">
                                    <th class="px-5 py-2 font-bold w-16">ID</th>
                                    <th class="px-5 py-2 font-bold">Project Name</th>
                                    <th class="px-5 py-2 font-bold">Last Updated</th>
                                    <th class="px-5 py-2 text-right font-bold">Action</th>
                                </tr>
                            </thead>
                            <tbody class="divide-y divide-gray-100 dark:divide-gray-700 text-xs">
                                <?php if(empty($recentProjects)): ?>
                                    <tr><td colspan="4" class="px-5 py-6 text-center text-gray-400 italic">No recent projects found.</td></tr>
                                <?php else: ?>
                                    <?php foreach ($recentProjects as $proj): ?>
                                    <tr class="hover:bg-gray-50 dark:hover:bg-gray-700/30 transition">
                                        <td class="px-5 py-2.5 text-gray-500 font-mono text-[10px]">#<?= $proj['id'] ?></td>
                                        <td class="px-5 py-2.5 font-medium truncate max-w-[150px]"><?= htmlspecialchars($proj['project_name']) ?></td>
                                        <td class="px-5 py-2.5 text-gray-500 whitespace-nowrap"><?= date('M d, g:ia', strtotime($proj['updated_at'])) ?></td>
                                        <td class="px-5 py-2.5 text-right">
                                            <a href="cable_map.php?id=<?= $proj['id'] ?>" class="text-blue-600 hover:text-blue-500 font-bold text-[10px] uppercase">Map</a>
                                        </td>
                                    </tr>
                                    <?php endforeach; ?>
                                <?php endif; ?>
                            </tbody>
                        </table>
                    </div>
                </div>

            </div>
        </div>
    </main>

    <script>
    (function() {
        const isDark    = document.documentElement.classList.contains('dark');
        const gridColor = isDark ? 'rgba(255,255,255,0.07)' : 'rgba(0,0,0,0.06)';
        const textColor = isDark ? '#9ca3af' : '#6b7280';
        const barBlue   = isDark ? '#3b82f6' : '#93c5fd';
        const barToday  = '#f97316';

        const labels = <?= json_encode($chartLabels) ?>;
        const counts = <?= json_encode($chartCounts) ?>;
        const colors = counts.map((_, i) => i === counts.length - 1 ? barToday : barBlue);

        new Chart(document.getElementById('jobsChart'), {
            type: 'bar',
            data: {
                labels,
                datasets: [{
                    data: counts,
                    backgroundColor: colors,
                    borderRadius: 4,
                    borderSkipped: false,
                }]
            },
            options: {
                responsive: true,
                maintainAspectRatio: false,
                plugins: {
                    legend: { display: false },
                    tooltip: {
                        callbacks: {
                            title: ctx => ctx[0].label,
                            label: ctx => ` ${ctx.parsed.y} job${ctx.parsed.y !== 1 ? 's' : ''}`
                        }
                    }
                },
                scales: {
                    x: {
                        grid: { display: false },
                        ticks: {
                            color: textColor,
                            font: { size: 10 },
                            maxRotation: 0,
                            autoSkip: true,
                            maxTicksLimit: 10
                        }
                    },
                    y: {
                        beginAtZero: true,
                        ticks: {
                            color: textColor,
                            font: { size: 10 },
                            stepSize: 1,
                            precision: 0
                        },
                        grid: { color: gridColor }
                    }
                }
            }
        });
    })();
    </script>
</body>
</html>