<?php
require 'db.php';

// 1. Safety Check
if (!isset($_POST['job_ids']) || empty($_POST['job_ids'])) {
    die("No jobs selected.");
}

// 2. Fetch Data
$job_ids = $_POST['job_ids'];
$placeholders = str_repeat('?,', count($job_ids) - 1) . '?';

// Sort by Date (Oldest to Newest), then by Customer Name
$stmt = $pdo->prepare("
    SELECT j.*, c.name as customer_name
    FROM jobs j 
    JOIN customers c ON j.customer_id = c.id 
    WHERE j.id IN ($placeholders)
    ORDER BY j.job_date ASC, c.name ASC
");
$stmt->execute($job_ids);
$all_jobs = $stmt->fetchAll();

// 3. Filter & Clean Data
$billed_jobs = [];
$total_minutes = 0;
$total_mileage = 0.0;
$unique_dates = []; // Track dates to see if we span multiple days

foreach($all_jobs as $job) {
    // Include job if it is billable (regardless of time/mileage entered)
    if ($job['is_billable'] == 1) {

        // Deep clean DB whitespace
        $job['customer_name'] = preg_replace('/^[\s\r\n]+/', '', $job['customer_name']);
        $job['notes'] = preg_replace('/^[\s\r\n]+/', '', $job['notes']);

        $billed_jobs[] = $job;
        $unique_dates[] = $job['job_date']; // Log the date for this job

        $total_minutes += (int)$job['time_spent'];
        $total_mileage += (float)$job['mileage'];
    }
}

// ---------------------------------------------------------
// SMART DATE RANGES
// ---------------------------------------------------------
$unique_dates_clean = array_unique($unique_dates);
$show_dates = count($unique_dates_clean) > 1;

if ($show_dates) {
    // Find the absolute oldest and newest jobs in this print batch
    $min_ts = strtotime(min($unique_dates_clean));
    $max_ts = strtotime(max($unique_dates_clean));
    
    // Determine the exact Monday-Sunday calendar week for the newest job
    $day_of_week = date('N', $max_ts); // 1 (Mon) to 7 (Sun)
    $monday_ts = strtotime('-' . ($day_of_week - 1) . ' days', $max_ts);
    $sunday_ts = strtotime('+' . (7 - $day_of_week) . ' days', $max_ts);
    
    // If the oldest job also safely fits inside this exact same week, format it!
    if ($min_ts >= $monday_ts && $max_ts <= $sunday_ts) {
        if (date('Y', $monday_ts) === date('Y', $sunday_ts)) {
            $date_subtitle = date('M j', $monday_ts) . ' - ' . date('M j, Y', $sunday_ts);
        } else {
            $date_subtitle = date('M j, Y', $monday_ts) . ' - ' . date('M j, Y', $sunday_ts);
        }
    } else {
        // If the jobs cross into past or future weeks (e.g. the "All" filter), default back
        $date_subtitle = "Multiple Dates";
    }
} else {
    // Single Day Mode
    $date_subtitle = count($unique_dates_clean) === 1 ? date('F d, Y', strtotime(reset($unique_dates_clean))) : date('F d, Y');
}
// ---------------------------------------------------------

$total_h = floor($total_minutes / 60);
$total_m = $total_minutes % 60;

// 4. Generate Auto-Filename
$filename_date = date('M-d-Y');
$clean_filename = "Bill_Sheet_{$filename_date}";
?>

<!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><?= $clean_filename ?></title>
    
    <script>
        if (localStorage.theme === 'dark' || (!('theme' in localStorage) && window.matchMedia('(prefers-color-scheme: dark)').matches)) {
            document.documentElement.classList.add('dark');
        } else {
            document.documentElement.classList.remove('dark');
        }
    </script>
    
    <style>
        /* Force dark background immediately for dark mode users */
        html.dark body { background-color: #111827 !important; color: #e5e7eb !important; }
        /* Force light background immediately for light mode users */
        html:not(.dark) body { background-color: #f3f4f6 !important; }
    </style>

    <link rel="stylesheet" href="/assets/css/tailwind.min.css">
    
    <link href="/assets/css/font-awesome.min.css" rel="stylesheet">
    
    <style>
        /* CSS GRID: Dynamically change columns based on Multi-Day Mode */
        .bill-row {
            display: grid;
            grid-template-columns: <?= $show_dates ? '3fr 6fr 1.5fr' : '3fr 5fr 1fr 1fr' ?>; 
            gap: 1rem;
            align-items: start;
            padding: 0.5rem 0.5rem;
            border-bottom: 1px solid #e5e7eb;
            page-break-inside: avoid;
        }

        .bill-row:nth-child(even) {
            background-color: #f9fafb; 
        }

        @media print {
            @page { margin: 0.5in; size: letter; }
            
            .no-print, aside, header, #theme-toggle-container { display: none !important; }
            
            html, body, main, #print-wrapper { 
                background-color: white !important; 
                background: white !important;
                margin: 0 !important; 
                padding: 0 !important;
                display: block !important;
                height: auto !important;
                min-height: auto !important;
                width: 100% !important;
                overflow: visible !important;
                -webkit-print-color-adjust: exact !important;
                print-color-adjust: exact !important;
                color-adjust: exact !important;
                color: black !important;
            }

            * {
                -webkit-print-color-adjust: exact !important;
                print-color-adjust: exact !important;
                color-adjust: exact !important;
            }

            #sheet-container {
                box-shadow: none !important;
                border: none !important;
                width: 100% !important;
                max-width: 100% !important;
                margin: 0 !important;
                padding: 0 !important;
            }
            
            .bill-row:nth-child(even) {
                background-color: #f9fafb !important;
                -webkit-print-color-adjust: exact !important; 
                print-color-adjust: exact !important;
                color-adjust: exact !important;
            }
        }
    </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="no-print h-14 bg-white dark:bg-gray-800 shadow flex items-center px-6 justify-between shrink-0 z-10">
            <div class="flex items-center gap-4">
                <a href="reports.php" class="text-gray-500 hover:text-blue-600 font-bold uppercase text-xs flex items-center gap-2 transition">
                    <i class="fas fa-arrow-left"></i> Back to Reports
                </a>
                <h2 class="font-bold text-lg text-gray-700 dark:text-gray-200">Bill Sheet Preview</h2>
            </div>
            
            <div class="flex gap-2">
                <button onclick="downloadAndEmail()" class="bg-purple-600 hover:bg-purple-500 text-white px-4 py-2 rounded shadow font-bold uppercase text-[10px] tracking-wider transition flex items-center">
                    <i class="fas fa-file-pdf mr-2"></i> Get PDF & Email
                </button>
                <button onclick="printWithFilename()" class="bg-blue-600 hover:bg-blue-500 text-white px-4 py-2 rounded shadow font-bold uppercase text-[10px] tracking-wider transition flex items-center">
                    <i class="fas fa-print mr-2"></i> Print
                </button>
            </div>
        </header>

        <div id="print-wrapper" class="flex-1 overflow-auto p-8 flex justify-center bg-gray-100 dark:bg-gray-900 transition-colors duration-0">
            
            <div id="sheet-container" class="bg-white w-full max-w-[8.5in] shadow-lg border border-gray-200 p-8 h-fit text-gray-900">
                
                <div class="flex justify-between items-end border-b-2 border-gray-800 pb-3 mb-1">
                    <div>
                        <h1 class="text-2xl font-bold uppercase tracking-widest text-gray-900 leading-none">Bill Sheet</h1>
                        <div class="text-xs font-bold text-gray-500 mt-1 uppercase tracking-wide">
                            <?= $date_subtitle ?>
                        </div>
                    </div>
                    <div class="text-right">
                        <div class="text-xs font-bold text-gray-400 uppercase tracking-wide">Tech: Chris</div>
                    </div>
                </div>

                <div class="bill-row border-b border-gray-300 text-[10px] font-bold uppercase text-gray-400 pb-1 pt-2">
                    <div>Customer</div>
                    <div>Notes</div>
                    <?php if (!$show_dates): ?>
                        <div class="text-right">Miles</div>
                    <?php endif; ?>
                    <div class="text-right">Time</div>
                </div>

                <div class="flex flex-col">
                    <?php if (count($billed_jobs) > 0): ?>
                        <?php foreach ($billed_jobs as $job): ?>
                        
                        <div class="bill-row">
                            
                            <div class="font-semibold text-gray-700 text-xs uppercase leading-tight break-words">
                                <?= htmlspecialchars($job['customer_name']) ?>
                                <?php if ($show_dates): ?>
                                    <div class="text-[9px] text-gray-400 font-bold tracking-wider mt-0.5">
                                        <?= date('M d, Y', strtotime($job['job_date'])) ?>
                                    </div>
                                <?php endif; ?>
                            </div>
                            
                            <div class="text-xs text-gray-600 whitespace-pre-wrap leading-tight"><?= !empty($job['notes']) ? htmlspecialchars($job['notes']) : '<span class="italic text-gray-300">No notes.</span>' ?></div>
                            
                            <?php if (!$show_dates): ?>
                                <div class="text-right font-bold font-mono text-sm text-gray-600">
                                    <?= !empty($job['mileage']) ? number_format($job['mileage'], 1) : '-' ?>
                                </div>
                            <?php endif; ?>

                            <div class="text-right font-bold font-mono text-sm text-gray-900">
                                <?php 
                                    $h = floor((int)$job['time_spent']/60);
                                    $m = (int)$job['time_spent']%60;
                                    echo ($h > 0 ? "{$h}h " : "") . ($m > 0 ? "{$m}m" : "");
                                    if ($h == 0 && $m == 0) echo '-';
                                ?>
                            </div>

                        </div>
                        <?php endforeach; ?>

                        <div class="mt-6 pt-4 flex justify-end items-center gap-6 border-t-2 border-gray-800">
                            <?php if (!$show_dates): ?>
                                <div class="flex items-center gap-3">
                                    <div class="text-xs font-bold uppercase text-gray-400 tracking-wide">Total Miles</div>
                                    <div class="text-lg font-bold text-gray-600"><?= number_format($total_mileage, 1) ?></div>
                                </div>
                            <?php endif; ?>
                            
                            <div class="flex items-center gap-3 <?= !$show_dates ? 'border-l border-gray-300 pl-6' : '' ?>">
                                <div class="text-xs font-bold uppercase text-gray-400 tracking-wide">Total Billed Time</div>
                                <div class="text-lg font-bold text-gray-800"><?= $total_h ?><span class="text-sm text-gray-400 font-normal ml-0.5 mr-2">h</span><?= $total_m ?><span class="text-sm text-gray-400 font-normal ml-0.5">m</span></div>
                            </div>
                        </div>

                    <?php else: ?>
                        <div class="py-12 text-center text-gray-400 italic text-sm">
                            No billable time or mileage found in selected records.
                        </div>
                    <?php endif; ?>
                </div>

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

    <script>
        const totalTime    = <?= json_encode($total_h . 'h ' . $total_m . 'm') ?>;
        const totalMiles   = <?= json_encode(number_format($total_mileage, 1)) ?>;
        const dateStr      = <?= json_encode($date_subtitle) ?>;
        const autoFilename = <?= json_encode($clean_filename) ?>;

        function printWithFilename() {
            document.title = autoFilename;
            window.print();
        }

        function downloadAndEmail() {
            // Build email body
            let body = `Hello,\n\nPlease see the attached Bill Sheet for ${dateStr}.\n\n`;
            body += `Total Billed Time: ${totalTime}\n`;
            <?php if (!$show_dates): ?>
            body += `Total Billed Miles: ${totalMiles}\n\n`;
            <?php else: ?>
            body += `\n`;
            <?php endif; ?>
            body += `Thanks,\nChris`;

            const subject = encodeURIComponent(autoFilename);
            const bodyEnc = encodeURIComponent(body);
            const mailtoLink = `mailto:?subject=${subject}&body=${bodyEnc}`;

            // After print dialog closes, open email client
            window.addEventListener('afterprint', () => {
                const link = document.createElement('a');
                link.href = mailtoLink;
                document.body.appendChild(link);
                link.click();
                document.body.removeChild(link);
            }, { once: true });

            document.title = autoFilename;
            window.print();
        }


        // FIREFOX FIX: Temporarily strip layout classes that cause 1-page cutoff
        window.addEventListener('beforeprint', () => {
            document.documentElement.classList.remove('h-full');
            document.body.classList.remove('h-full', 'overflow-hidden', 'flex');
        });
        window.addEventListener('afterprint', () => {
            document.documentElement.classList.add('h-full');
            document.body.classList.add('h-full', 'overflow-hidden', 'flex');
        });
    </script>
</body>
</html>