<?php
require 'db.php';

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

// 2. Fetch Jobs (Updated to include Network Name)
$job_ids = $_POST['job_ids'];
$placeholders = str_repeat('?,', count($job_ids) - 1) . '?';

$stmt = $pdo->prepare("
    SELECT j.*, c.name as customer_name, n.name as network_name
    FROM jobs j 
    JOIN customers c ON j.customer_id = c.id 
    LEFT JOIN networks n ON j.network_id = n.id
    WHERE j.id IN ($placeholders)
    ORDER BY j.job_date ASC, c.name ASC
");
$stmt->execute($job_ids);
$all_jobs = $stmt->fetchAll();

// 3. Fetch Materials for these jobs
$stmtMat = $pdo->prepare("
    SELECT jm.job_id, jm.quantity, jm.serial_number, jm.cxnk_number, m.name
    FROM job_materials jm
    JOIN materials m ON jm.material_id = m.id
    WHERE jm.job_id IN ($placeholders)
");
$stmtMat->execute($job_ids);
// Group materials by job_id for easy access
$all_materials = $stmtMat->fetchAll(PDO::FETCH_GROUP | PDO::FETCH_ASSOC);

// 4. Filter & Clean Data
$smx_jobs = [];

foreach($all_jobs as $job) {
    // Include job ONLY if it is flagged as an SMx job
    if (isset($job['is_smx']) && $job['is_smx'] == 1) {
        
        // Deep clean DB whitespace
        $job['customer_name'] = preg_replace('/^[\s\r\n]+/', '', $job['customer_name']);
        
        // Attach materials
        $job['materials'] = $all_materials[$job['id']] ?? [];
        
        $smx_jobs[] = $job;
    }
}

$total_smx = count($smx_jobs);

// 5. Generate Auto-Filename
$filename_date = date('M-d-Y');
$clean_filename = "SMx_Conversions_{$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>
        @media print {
            /* Force Standard 8.5x11 Letter Size */
            @page { size: letter portrait; margin: 0.5in; }
            
            /* Hide UI Elements */
            .no-print, aside, header, #theme-toggle-container { display: none !important; }
            
            /* Strip web scrolling and flexbox to behave like normal paper */
            html, body, main, #print-wrapper { 
                background-color: white !important; 
                margin: 0 !important; 
                padding: 0 !important;
                display: block !important;
                height: auto !important;
                width: 100% !important;
                overflow: visible !important;
                color: black !important;
            }
            
            /* Remove the shadow and extra padding from the container for native print */
            #sheet-container {
                box-shadow: none !important; 
                border: none !important; 
                width: 100% !important; 
                max-width: 100% !important; 
                margin: 0 !important; 
                padding: 0 !important;
            }
            
            /* Force browsers to print the gray background */
            .customer-header {
                background-color: #f3f4f6 !important;
                -webkit-print-color-adjust: exact !important;
                print-color-adjust: exact !important;
            }
        }
    </style>
</head>
<body class="bg-gray-100 dark:bg-gray-900 text-gray-900 dark:text-gray-200 h-full flex overflow-hidden font-sans">

    <?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">SMx 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-4 md:p-8 flex justify-center bg-gray-200 dark:bg-gray-900 transition-colors duration-0">
            
            <div id="sheet-container" class="bg-white w-[8.5in] shrink-0 shadow-2xl border border-gray-300 p-[0.5in] h-max text-gray-900">
                
                <div class="border-b-2 border-black pb-4 mb-6 flex justify-between items-end">
                    <div>
                        <h1 class="text-xl font-bold">SMx Conversions</h1>
                        <div class="text-sm mt-1"><?= date('F d, Y') ?></div>
                    </div>
                    <div class="text-sm font-semibold text-gray-600">
                        Tech: Chris
                    </div>
                </div>

                <div class="flex flex-col gap-6">
                    <?php if (count($smx_jobs) > 0): ?>
                        <?php foreach ($smx_jobs as $job): ?>
                        
                        <div class="break-inside-avoid">
                            
                            <div class="customer-header bg-gray-100 font-bold text-base px-3 py-1.5 rounded border-b border-gray-200 mb-2">
                                <?= htmlspecialchars($job['customer_name']) ?>
                            </div>
                            
                            <div class="grid grid-cols-2 gap-8 text-xs px-3 text-gray-800">
                                <div>
                                    <div class="font-semibold text-sm text-gray-900 mb-1 underline decoration-gray-400 underline-offset-2">Plant Information</div>
                                    <?php if (!empty($job['network_name']) || !empty($job['calix_position']) || !empty($job['splitter_position'])): ?>
                                        <?php if (!empty($job['network_name'])): ?><div class="mb-0.5">Network: <?= htmlspecialchars($job['network_name']) ?></div><?php endif; ?>
                                        <div class="mb-0.5">Calix: <?= htmlspecialchars($job['calix_position'] ?: '-') ?></div>
                                        <div>Splitter: <?= htmlspecialchars($job['splitter_position'] ?: '-') ?></div>
                                    <?php else: ?>
                                        <div class="italic text-gray-500">N/A</div>
                                    <?php endif; ?>
                                </div>

                                <div>
                                    <div class="font-semibold text-sm text-gray-900 mb-1 underline decoration-gray-400 underline-offset-2">Equipment Used</div>
                                    <?php if (!empty($job['materials'])): ?>
                                        <ul class="list-disc pl-4 space-y-1.5">
                                        <?php foreach ($job['materials'] as $mat): ?>
                                            <li>
                                                <?= (int)$mat['quantity'] ?>x <?= htmlspecialchars($mat['name']) ?>
                                                <?php if (!empty($mat['serial_number'])): ?>
                                                    <div class="text-gray-500 text-[11px] mt-0.5">SN: <?= htmlspecialchars($mat['serial_number']) ?></div>
                                                <?php endif; ?>
                                                <?php if (!empty($mat['cxnk_number'])): ?>
                                                    <div class="text-gray-500 text-[11px] mt-0.5">CXNK: <?= htmlspecialchars($mat['cxnk_number']) ?></div>
                                                <?php endif; ?>
                                            </li>
                                        <?php endforeach; ?>
                                        </ul>
                                    <?php else: ?>
                                        <div class="italic text-gray-500">None</div>
                                    <?php endif; ?>
                                </div>
                            </div>

                        </div>
                        <?php endforeach; ?>

                        <div class="mt-4 pt-4 border-t-2 border-black font-bold text-base flex justify-between">
                            <span>Total SMx Conversions:</span>
                            <span><?= $total_smx ?></span>
                        </div>

                    <?php else: ?>
                        <div class="py-12 text-center text-gray-500 italic">
                            No SMx jobs found in selected records.
                        </div>
                    <?php endif; ?>
                </div>

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

    <script>
        const totalConversions = <?= json_encode((string)$total_smx) ?>;
        const dateStr          = <?= json_encode(date('M d, Y')) ?>;
        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 SMx Conversions Sheet for ${dateStr}.\n\n`;
            body += `Total SMx Conversions: ${totalConversions}\n\n`;
            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>