<?php
ini_set('display_errors', 0);
ini_set('display_startup_errors', 0);
error_reporting(0);

require 'db.php';

// 2. Handle Delete Action
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['delete'])) {
    try {
        // v2.2 - Delete synced time entries first to prevent ghost hours
        $stmtTime = $pdo->prepare("DELETE FROM time_entries WHERE job_id = ?");
        $stmtTime->execute([$_POST['delete']]);

        // Then delete the job
        $stmt = $pdo->prepare("DELETE FROM jobs WHERE id = ?");
        $stmt->execute([$_POST['delete']]);

        $queryString = http_build_query($_GET);
        header("Location: reports.php" . ($queryString ? '?' . $queryString : ''));
        exit;
    } catch (Exception $e) {
        $error_msg = "Delete Error: " . $e->getMessage();
    }
}

// 3. Filter Logic
$where = ["1=1"];
$params = [];

$start_date = $_GET['start_date'] ?? '';
$end_date = $_GET['end_date'] ?? '';
$top_complainers = $_GET['top_complainers'] ?? '0';
$customer_id_filter = $_GET['customer_id'] ?? '';

// --- TOP COMPLAINERS EXCLUSIONS ---
// Hide specific automated/utility accounts from the complainer report
if ($top_complainers === '1') {
    $where[] = "c.name NOT LIKE '%BWTelcom%'";
    $where[] = "c.name NOT LIKE '%811%'";
    $where[] = "c.name NOT LIKE '%locates%'";
}
// -----------------------

if ($start_date) { 
    $where[] = "j.job_date >= ?"; 
    $params[] = $start_date; 
}
if ($end_date) { 
    $where[] = "j.job_date <= ?"; 
    $params[] = $end_date; 
}
if ($customer_id_filter) {
    $where[] = "j.customer_id = ?";
    $params[] = $customer_id_filter;
}

$search = $_GET['search'] ?? '';
if ($search) { 
    $where[] = "(c.name LIKE ? OR j.notes LIKE ? OR j.calix_position LIKE ? OR j.splitter_position LIKE ?)"; 
    $params[] = "%$search%"; 
    $params[] = "%$search%"; 
    $params[] = "%$search%"; 
    $params[] = "%$search%"; 
}

// 4. Fetch Data
$jobs = [];
if (!isset($error_msg)) $error_msg = "";

try {
    $whereSQL = implode(" AND ", $where);
    
    // Mode 1: Grouped Summary for Top Complainers
    if ($top_complainers === '1') {
        $sql = "SELECT c.id as customer_id, c.name as customer_name, 
                COUNT(j.id) as job_count, MAX(j.job_date) as last_job_date
                FROM jobs j 
                JOIN customers c ON j.customer_id = c.id 
                WHERE $whereSQL 
                GROUP BY c.id, c.name
                HAVING job_count > 1
                ORDER BY job_count DESC, last_job_date DESC";
    } 
    // Mode 2: Standard Individual Ticket List
    else {
        $sql = "SELECT j.*, c.name as customer_name 
                FROM jobs j 
                JOIN customers c ON j.customer_id = c.id 
                WHERE $whereSQL 
                ORDER BY j.job_date DESC, j.id DESC";
    }
            
    $stmt = $pdo->prepare($sql);
    $stmt->execute($params);
    $jobs = $stmt->fetchAll();

} catch (Exception $e) {
    $error_msg = "Database Error: " . $e->getMessage();
}
?>

<!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>Job History</title>
    

    <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 rel="stylesheet" href="/assets/css/tailwind.min.css">
    
    <link href="/assets/css/font-awesome.min.css" rel="stylesheet">
    
    <style>
        .dense-table th { padding: 8px 12px; font-size: 11px; text-transform: uppercase; letter-spacing: 0.05em; border-bottom: 2px solid #e5e7eb; }
        .dense-table td { padding: 8px 12px; font-size: 13px; border-bottom: 1px solid #f3f4f6; vertical-align: top; }
        
        .dark .dense-table th { border-color: #4b5563; background: #374151; color: #d1d5db; }
        .dark .dense-table td { border-color: #374151; color: #e5e7eb; }
        .dark .dense-table tr:hover td { background-color: #4b5563; }
        
        input, select, button { box-sizing: border-box; }
    </style>
</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 z-10 border-b dark:border-gray-700">
            <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">Job History</h2>
            
            <div class="flex gap-2">
                <?php if ($top_complainers !== '1'): ?>
                    <button onclick="emailLog()" class="bg-purple-600 hover:bg-purple-500 text-white px-4 py-2 rounded shadow font-bold uppercase text-[10px] tracking-wider transition h-[34px] flex items-center">
                        <i class="fas fa-envelope mr-2"></i> Email Log
                    </button>
                    <button onclick="copyLog()" class="bg-gray-500 hover:bg-gray-400 text-white px-4 py-2 rounded shadow font-bold uppercase text-[10px] tracking-wider transition h-[34px] flex items-center">
                        <i class="fas fa-copy mr-2"></i> Copy Log
                    </button>
                    <button onclick="printSmxSheet()" class="bg-indigo-600 hover:bg-indigo-500 text-white px-4 py-2 rounded shadow font-bold uppercase text-[10px] tracking-wider transition h-[34px] flex items-center">
                        <i class="fas fa-file-invoice mr-2"></i> SMx Sheet
                    </button>
                    <button onclick="printBillSheet()" class="bg-blue-600 hover:bg-blue-500 text-white px-4 py-2 rounded shadow font-bold uppercase text-[10px] tracking-wider transition h-[34px] flex items-center">
                        <i class="fas fa-print mr-2"></i> Bill Sheet
                    </button>
                <?php endif; ?>
                <a href="export_csv.php?<?= http_build_query($_GET) ?>" class="bg-emerald-600 hover:bg-emerald-500 text-white px-4 py-2 rounded shadow font-bold uppercase text-[10px] tracking-wider transition h-[34px] flex items-center">
                    <i class="fas fa-file-csv mr-2"></i> Export
                </a>
            </div>
        </header>

        <div class="px-6 py-4 bg-white dark:bg-gray-800 border-b border-gray-200 dark:border-gray-700 shrink-0">
            <form id="reportForm" method="GET" class="flex flex-wrap items-end gap-3">
                
                <input type="hidden" name="auto_select" id="auto_select_input" value="0">
                <input type="hidden" name="top_complainers" id="top_complainers_input" value="<?= htmlspecialchars($top_complainers) ?>">
                <input type="hidden" name="customer_id" value="<?= htmlspecialchars($customer_id_filter) ?>">
                
                <div>
                    <label class="block text-[10px] font-bold text-gray-400 uppercase mb-1">Quick Filters</label>
                    <div class="flex bg-gray-100 dark:bg-gray-700 rounded p-1 h-[34px] items-center border dark:border-gray-600 gap-1">
                        <button type="button" onclick="setDates('today')" class="px-3 py-1 text-[10px] font-bold uppercase hover:bg-white dark:hover:bg-gray-600 rounded transition text-gray-600 dark:text-gray-300 h-full flex items-center">Today</button>
                        <button type="button" onclick="setDates('week')" class="px-3 py-1 text-[10px] font-bold uppercase hover:bg-white dark:hover:bg-gray-600 rounded transition text-gray-600 dark:text-gray-300 h-full flex items-center">Week</button>
                        <button type="button" onclick="setDates('all')" class="px-3 py-1 text-[10px] font-bold uppercase hover:bg-white dark:hover:bg-gray-600 rounded transition text-gray-600 dark:text-gray-300 h-full flex items-center">All</button>
                        
                        <div class="w-px h-4 bg-gray-300 dark:bg-gray-500 mx-1"></div>
                        
                        <button type="button" onclick="toggleTopComplainers()" class="px-3 py-1 text-[10px] font-bold uppercase rounded transition h-full flex items-center <?= ($top_complainers === '1') ? 'bg-red-100 text-red-700 dark:bg-red-900/50 dark:text-red-300 shadow-sm' : 'hover:bg-white dark:hover:bg-gray-600 text-gray-600 dark:text-gray-300' ?>" title="Sort by customers with the most tickets">
                            <i class="fas fa-fire <?= ($top_complainers === '1') ? 'text-red-600 dark:text-red-400' : 'text-gray-400' ?> mr-1.5"></i> Top Complainers
                        </button>
                    </div>
                </div>

                <?php if ($customer_id_filter): ?>
                    <div class="flex items-center gap-2 bg-blue-50 dark:bg-blue-900/20 text-blue-700 dark:text-blue-300 px-3 h-[34px] rounded border border-blue-200 dark:border-blue-800">
                        <span class="text-[10px] font-bold uppercase tracking-wider"><i class="fas fa-user-circle mr-1"></i> Customer Filter Active</span>
                        <button type="button" onclick="window.location.href='reports.php'" class="ml-1 text-blue-400 hover:text-blue-600 transition"><i class="fas fa-times-circle"></i></button>
                    </div>
                <?php endif; ?>

                <div>
                    <label class="block text-[10px] font-bold text-gray-400 uppercase mb-1">Start</label>
                    <input type="date" id="start" name="start_date" value="<?= htmlspecialchars($start_date) ?>" class="bg-gray-50 dark:bg-gray-700 border border-gray-300 dark:border-gray-600 rounded px-2 h-[34px] text-xs focus:outline-none focus:border-blue-500">
                </div>
                <div>
                    <label class="block text-[10px] font-bold text-gray-400 uppercase mb-1">End</label>
                    <input type="date" id="end" name="end_date" value="<?= htmlspecialchars($end_date) ?>" class="bg-gray-50 dark:bg-gray-700 border border-gray-300 dark:border-gray-600 rounded px-2 h-[34px] text-xs focus:outline-none focus:border-blue-500">
                </div>

                <div class="flex-1 min-w-[150px]">
                    <label class="block text-[10px] font-bold text-gray-400 uppercase mb-1">Search</label>
                    <input type="text" name="search" value="<?= htmlspecialchars($search) ?>" placeholder="Search..." class="w-full bg-gray-50 dark:bg-gray-700 border border-gray-300 dark:border-gray-600 rounded px-2 h-[34px] text-xs focus:outline-none focus:border-blue-500">
                </div>
                
                <button type="submit" class="bg-gray-600 hover:bg-gray-500 text-white px-5 rounded shadow text-[10px] font-bold uppercase transition h-[34px] flex items-center">
                    Filter
                </button>
            </form>
        </div>

        <div class="flex-1 overflow-auto bg-white dark:bg-gray-800 relative">
            
            <?php if ($error_msg): ?>
                <div class="p-8 text-center">
                    <div class="bg-red-100 border border-red-400 text-red-700 px-4 py-3 rounded relative inline-block text-left">
                        <strong class="font-bold">System Error!</strong>
                        <span class="block sm:inline"><?= htmlspecialchars($error_msg) ?></span>
                    </div>
                </div>
            <?php else: ?>

            <form id="batchForm" method="POST" target="_blank" class="h-full">
                <table class="w-full text-left border-collapse dense-table">
                    
                    <?php if ($top_complainers === '1'): ?>
                        <thead class="sticky top-0 z-10 bg-gray-50 dark:bg-gray-700 shadow-sm">
                            <tr>
                                <th class="w-16 text-center">Rank</th>
                                <th>Customer Name</th>
                                <th class="w-40 text-center">Total Tickets</th>
                                <th class="w-40 text-center">Latest Ticket</th>
                                <th class="w-24 text-right">Actions</th>
                            </tr>
                        </thead>
                        <tbody class="divide-y divide-gray-100 dark:divide-gray-700">
                            <?php if (count($jobs) > 0): $rank = 1; ?>
                                <?php foreach ($jobs as $job): ?>
                                <tr class="group transition-colors hover:bg-red-50 dark:hover:bg-red-900/20">
                                    <td class="text-center font-bold text-gray-400 py-4">#<?= $rank++ ?></td>
                                    <td class="font-bold text-lg text-gray-900 dark:text-gray-100 py-4"><?= htmlspecialchars($job['customer_name']) ?></td>
                                    <td class="text-center py-4">
                                        <a href="reports.php?customer_id=<?= $job['customer_id'] ?>&start_date=<?= urlencode($start_date) ?>&end_date=<?= urlencode($end_date) ?>" 
                                           class="inline-flex items-center justify-center px-3 py-1.5 rounded text-xs font-bold uppercase tracking-wider bg-red-100 text-red-700 border border-red-200 hover:bg-red-200 dark:bg-red-900/40 dark:text-red-400 dark:border-red-800 dark:hover:bg-red-900/60 transition shadow-sm" 
                                           title="Click to view individual tickets">
                                            <i class="fas fa-search mr-2"></i> <?= $job['job_count'] ?> Tickets
                                        </a>
                                    </td>
                                    <td class="text-center font-mono text-gray-500 dark:text-gray-400 py-4"><?= date('M d, Y', strtotime($job['last_job_date'])) ?></td>
                                    <td class="text-right py-4 pr-6">
                                         <a href="reports.php?customer_id=<?= $job['customer_id'] ?>&start_date=<?= urlencode($start_date) ?>&end_date=<?= urlencode($end_date) ?>" class="text-blue-500 hover:text-blue-600 text-[10px] font-bold uppercase tracking-wider">View Log &rarr;</a>
                                    </td>
                                </tr>
                                <?php endforeach; ?>
                            <?php else: ?>
                                <tr><td colspan="5" class="p-12 text-center text-gray-400 italic">No complainers found for this date range.</td></tr>
                            <?php endif; ?>
                        </tbody>

                    <?php else: ?>
                        <thead class="sticky top-0 z-10 bg-gray-50 dark:bg-gray-700 shadow-sm">
                            <tr>
                                <th class="w-10 text-center"><input type="checkbox" onclick="toggleAll(this)" id="master-checkbox" class="rounded text-blue-600 focus:ring-0 cursor-pointer"></th>
                                <th class="w-24">Date</th>
                                <th class="w-48">Customer</th>
                                <th>Notes</th>
                                <th class="w-16 text-center">Bill?</th>
                                <th class="w-24 text-right">Actions</th>
                            </tr>
                        </thead>
                        <tbody class="divide-y divide-gray-100 dark:divide-gray-700">
                            <?php if (count($jobs) > 0): ?>
                                <?php foreach ($jobs as $job): 
                                    $is_billable = $job['is_billable'] ?? 1;
                                    $is_bwtelcom = stripos($job['customer_name'], 'BWTelcom') !== false;
                                    
                                    // UI display for time
                                    $time_display = "";
                                    if (!empty($job['time_spent'])) {
                                        $h = floor($job['time_spent'] / 60);
                                        $m = $job['time_spent'] % 60;
                                        if ($h > 0) $time_display .= "{$h}h ";
                                        if ($m > 0) $time_display .= "{$m}m";
                                    }

                                    // Build Email/Copy Data Format
                                    if ($is_bwtelcom) {
                                        $email_text = trim(preg_replace('/\s+/', ' ', $job['notes']));
                                    } else {
                                        $email_desc = "";
                                        if (!empty($job['is_smx'])) $email_desc .= "SMx Conversion";
                                        elseif (!empty($job['is_cobalt'])) $email_desc .= "Cobalt";
                                        elseif ($job['job_type'] === 'Fiber Burial') $email_desc .= "Fiber Burial";

                                        $notes_clean = trim(preg_replace('/\s+/', ' ', $job['notes']));
                                        if (!empty($notes_clean)) $email_desc .= ($email_desc !== "") ? ". " . $notes_clean : $notes_clean;

                                        $email_text = $job['customer_name'];
                                        if ($email_desc !== "") $email_text .= ". " . $email_desc; // Uses period instead of colon
                                    }
                                ?>
                                <tr class="group transition-colors hover:bg-blue-50 dark:hover:bg-gray-700">
                                    <td class="text-center align-top py-3">
                                        <input type="checkbox" name="job_ids[]" value="<?= $job['id'] ?>" 
                                               class="job-check rounded text-blue-600 focus:ring-0 cursor-pointer" 
                                               data-billable="<?= $is_billable ?>"
                                               data-smx="<?= !empty($job['is_smx']) ? 1 : 0 ?>"
                                               data-date="<?= $job['job_date'] ?>"
                                               data-email="<?= htmlspecialchars($email_text) ?>">
                                    </td>
                                    <td class="font-mono text-gray-500 dark:text-gray-400 align-top py-3"><?= date('m/d/y', strtotime($job['job_date'])) ?></td>
                                    
                                    <td class="font-bold text-gray-900 dark:text-gray-100 align-top py-3">
                                        <?= htmlspecialchars($job['customer_name']) ?>
                                    </td>
                                    
                                    <td class="align-top py-3">
                                        <?php if(!$is_bwtelcom): ?>
                                            <?php if(!empty($job['is_smx'])): ?><span class="inline-flex px-1.5 py-0.5 mb-1 rounded text-[9px] font-bold uppercase bg-purple-100 text-purple-700 border border-purple-200">SMx</span><?php endif; ?>
                                            <?php if(!empty($job['is_cobalt'])): ?><span class="inline-flex px-1.5 py-0.5 mb-1 rounded text-[9px] font-bold uppercase bg-blue-100 text-blue-700 border border-blue-200">Cobalt</span><?php endif; ?>
                                            <?php if($job['job_type'] === 'Fiber Burial'): ?>
                                                <span class="inline-flex px-1.5 py-0.5 mb-1 rounded text-[9px] font-bold uppercase bg-orange-100 text-orange-700 border border-orange-200">Fiber Burial</span>
                                                <?php if(!empty($job['location'])): ?><div class="text-[10px] text-gray-500 dark:text-gray-400 mb-1"><i class="fas fa-map-marker-alt"></i> <?= htmlspecialchars($job['location']) ?></div><?php endif; ?>
                                            <?php endif; ?>
                                        <?php endif; ?>

                                        <div class="text-gray-600 dark:text-gray-300 line-clamp-2"><?= htmlspecialchars($job['notes']) ?></div>
                                        
                                        <?php if(!$is_bwtelcom && $time_display): ?>
                                            <div class="text-[10px] text-blue-600 dark:text-blue-400 font-bold mt-1">
                                                <i class="fas fa-clock mr-1"></i> <?= $time_display ?>
                                            </div>
                                        <?php endif; ?>
                                    </td>
                                    <td class="text-center align-top py-3">
                                        <?php if($is_billable): ?><i class="fas fa-check text-emerald-500 text-xs" title="Billable"></i>
                                        <?php else: ?><i class="fas fa-times text-gray-400 text-xs" title="Not Billable"></i><?php endif; ?>
                                    </td>
                                    <td class="text-right align-top py-3">
                                        <div class="flex justify-end gap-3 opacity-0 group-hover:opacity-100 transition-opacity">
                                            <a href="job_edit.php?id=<?= $job['id'] ?>" class="text-gray-400 hover:text-blue-500" title="Edit"><i class="fas fa-pen"></i></a>
                                            <a href="job_entry.php?clone_id=<?= $job['id'] ?>" class="text-gray-400 hover:text-purple-500" title="Clone"><i class="fas fa-copy"></i></a>
                                            <form method="POST" class="inline" onsubmit="return confirm('Are you sure you want to delete this job record?');">
                                                <input type="hidden" name="delete" value="<?= $job['id'] ?>">
                                                <button type="submit" class="text-gray-400 hover:text-red-500" title="Delete"><i class="fas fa-trash-alt"></i></button>
                                            </form>
                                        </div>
                                    </td>
                                </tr>
                                <?php endforeach; ?>
                            <?php else: ?>
                                <tr>
                                    <td colspan="6" class="p-12 text-center text-gray-400 italic">No job records found.</td>
                                </tr>
                            <?php endif; ?>
                        </tbody>
                    <?php endif; ?>

                </table>
            </form>
            <?php endif; ?>
        </div>
    </main>

    <script>
        function toggleAll(source) {
            document.querySelectorAll('.job-check').forEach(cb => cb.checked = source.checked);
        }

        // Toggles the Top Complainers filter on and off
        function toggleTopComplainers() {
            const tcInput = document.getElementById('top_complainers_input');
            tcInput.value = (tcInput.value === '1') ? '0' : '1';
            
            // Clear specific customer filter when toggling
            document.querySelector('input[name="customer_id"]').value = ''; 
            
            document.getElementById('reportForm').submit();
        }

        // HELPER: Get strictly sorted elements (Oldest to Newest)
        function getSortedSelected() {
            const nodes = document.querySelectorAll('.job-check:checked');
            return Array.from(nodes).sort((a, b) => {
                const dateA = new Date(a.getAttribute('data-date')).getTime();
                const dateB = new Date(b.getAttribute('data-date')).getTime();
                
                if (dateA !== dateB) return dateA - dateB; // Sort Oldest Date First
                return parseInt(a.value) - parseInt(b.value); // Sort Lowest ID First (fallback)
            });
        }

        function emailLog() {
            const selected = getSortedSelected();
            if(selected.length === 0) { alert("Please select at least one job to email."); return; }
            let body = "";
            selected.forEach((chk, i) => { body += `${i+1}. ${chk.getAttribute('data-email')}\n`; });
            const subject = new Date().toLocaleDateString();
            window.location.href = `mailto:?subject=${encodeURIComponent(subject)}&body=${encodeURIComponent(body)}`;
        }

        function copyLog() {
            const selected = getSortedSelected();
            if(selected.length === 0) { alert("Please select at least one job to copy."); return; }
            let body = "";
            selected.forEach((chk, i) => { body += `${i+1}. ${chk.getAttribute('data-email')}\n`; });
            if (navigator.clipboard) {
                navigator.clipboard.writeText(body).then(() => { alert("✅ Log copied to clipboard!"); })
                .catch(err => { alert("Failed to copy text: " + err); });
            } else {
                const textArea = document.createElement("textarea");
                textArea.value = body; document.body.appendChild(textArea); textArea.select();
                try { document.execCommand('copy'); alert("✅ Log copied to clipboard!"); } 
                catch (err) { alert("Failed to copy text: " + err); }
                document.body.removeChild(textArea);
            }
        }

        function printSmxSheet() {
            const selected = document.querySelectorAll('.job-check:checked'); // Print order depends on SQL
            if(selected.length === 0) { alert("Please select jobs to print."); return; }
            let nonSmxCount = 0;
            selected.forEach(chk => {
                if (chk.getAttribute('data-smx') != "1") { chk.checked = false; nonSmxCount++; }
            });
            if (nonSmxCount > 0) {
                if(!confirm(`${nonSmxCount} of the selected jobs are not SMx conversions and were deselected.\n\nContinue printing only the SMx jobs?`)) return; 
                if(document.querySelectorAll('.job-check:checked').length === 0) { alert("No SMx jobs remaining to print."); return; }
            }
            const form = document.getElementById('batchForm');
            form.action = 'print_smx.php'; form.submit();
        }

        function printBillSheet() {
            const selected = document.querySelectorAll('.job-check:checked'); // Print order depends on SQL
            if(selected.length === 0) { alert("Please select jobs to print."); return; }
            let nonBillableCount = 0;
            selected.forEach(chk => {
                if (chk.getAttribute('data-billable') != "1") { chk.checked = false; nonBillableCount++; }
            });
            if (nonBillableCount > 0) {
                if(!confirm(`${nonBillableCount} of the selected jobs are marked 'Non-Billable' and were deselected.\n\nContinue printing only the billable jobs?`)) return; 
                if(document.querySelectorAll('.job-check:checked').length === 0) { alert("No billable jobs remaining to print."); return; }
            }
            const form = document.getElementById('batchForm');
            form.action = 'print_summary.php'; form.submit();
        }

        function setDates(range) {
            const s = document.getElementById('start'), e = document.getElementById('end');
            const d = new Date();
            
            if(range === 'today') { 
                const str = d.toLocaleDateString('en-CA');
                s.value = str; e.value = str; 
            }
            else if(range === 'week') {
                const day = d.getDay(), diff = d.getDate() - day + (day == 0 ? -6 : 1); 
                s.value = new Date(d.setDate(diff)).toLocaleDateString('en-CA');
                e.value = new Date(d.setDate(diff+6)).toLocaleDateString('en-CA');
            }
            else { s.value = ''; e.value = ''; }

            // Tell the form to auto-select all checkboxes after it reloads
            document.getElementById('auto_select_input').value = '1';
            document.getElementById('reportForm').submit();
        }

        // Auto-select checkboxes on page load if a quick filter was used
        window.addEventListener('DOMContentLoaded', () => {
            const urlParams = new URLSearchParams(window.location.search);
            if (urlParams.get('auto_select') === '1' && document.getElementById('master-checkbox')) {
                document.querySelectorAll('.job-check').forEach(cb => cb.checked = true);
                document.getElementById('master-checkbox').checked = true;
            }
        });

    </script>
</body>
</html>