<?php
// CARGA MAESTRA DE CONFIGURACIÓN Y BRANDING
require_once(__DIR__ . '/core/init-pages.php');

$user_id_to_query = $ci['user_id'] ?? 1; 

// Configuración por defecto
$db_schedule_config = ['slot_duration' => 60, 'capacity' => 1, 'start_time' => '09:00:00', 'end_time' => '17:00:00', 'work_days' => ['1', '2', '3', '4', '5']];
$db_weekly_hours = [];
$db_blocked_dates = [];
$occupied_slots = [];

// Configuración WhatsApp Global
$whatsapp_contact = $wa['display'] ?? ''; 
$whatsapp_url_link = $wa['link'] ?? ''; 

// Evitar redeclaración de función si se usa en otros includes
if (!function_exists('formatUSPhoneNumber')) {
    function formatUSPhoneNumber($number) {
        $number = preg_replace('/[^0-9]/', '', $number);
        if (strlen($number) === 10) {
            return '(' . substr($number, 0, 3) . ') ' . substr($number, 3, 3) . '-' . substr($number, 6, 4);
        }
        return $number;
    }
}

$whatsapp_display_formatted = formatUSPhoneNumber($whatsapp_contact);

// --- OBTENER DATOS DE LA FACTURA ---
$raw_token = $_GET['token'] ?? '';
// Limpieza estricta del token (external_id)
$token = trim(preg_replace('/[^a-zA-Z0-9.\-_]/', '', $raw_token)); 
$invoice = null;
$items = [];
$isOverdue = false;
$wa_message_direct = "Hi! I have a question about an invoice."; // Default fallback

if (!empty($token) && isset($pdo)) {
    try {
        // Consulta segura a la tabla 'invoices' con los joins necesarios
        $stmt = $pdo->prepare("
            SELECT i.*, 
                   COALESCE(c.first_name, l.first_name) as first_name,
                   COALESCE(c.last_name, l.last_name) as last_name,
                   COALESCE(c.email, l.email) as email,
                   COALESCE(c.phone, l.phone) as phone,
                   COALESCE(c.company, l.company) as company,
                   COALESCE(c.street_address, l.street_address) as address,
                   COALESCE(c.city, l.city) as city,
                   COALESCE(c.state_province, l.state_province) as state,
                   COALESCE(c.zip_code, l.zip_code) as zip
            FROM invoices i
            LEFT JOIN clients c ON i.client_id = c.id
            LEFT JOIN leads l ON i.lead_id = l.id
            WHERE i.external_id = :token LIMIT 1
        ");
        $stmt->execute(['token' => $token]);
        $invoice = $stmt->fetch(PDO::FETCH_ASSOC);

        if ($invoice) {
            $status = strtolower($invoice['status'] ?? ''); 
            $dueDate = !empty($invoice['due_date']) ? strtotime($invoice['due_date']) : time();
            $now = time();
            
            // Lógica de atraso
            $isOverdue = (in_array($status, ['atrasada', 'atrasado', 'overdue']) || ($status !== 'pagada' && $dueDate < strtotime('today')));

            // Items de la factura
            $stmtItems = $pdo->prepare("SELECT * FROM invoice_items WHERE invoice_id = ?");
            $stmtItems->execute([$invoice['id']]);
            $items = $stmtItems->fetchAll(PDO::FETCH_ASSOC);

            // CORRECCIÓN: Mensaje directo y específico con el ID de la factura
            $wa_message_direct = "Hello, I received Invoice #{$invoice['id']} and would like to pay.";
            if ($isOverdue) {
                $wa_message_direct = "Hello, I am contacting you regarding Overdue Invoice #{$invoice['id']} to resolve payment.";
            }
        }
    } catch (Exception $e) {
        die("Error DB: " . $e->getMessage());
    }
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Invoice #<?php echo htmlspecialchars($invoice['id'] ?? ''); ?> - <?php echo htmlspecialchars($client_info['business_name'] ?? 'FlowCRM'); ?></title>
    <meta name="robots" content="noindex, nofollow">
    
    <link rel="icon" type="image/png" href="<?php echo htmlspecialchars($branding['favicon'] ?? '/core/img/favicon.png'); ?>">
    <link rel="apple-touch-icon" href="<?php echo htmlspecialchars($branding['favicon'] ?? '/core/img/favicon.png'); ?>">
    
    <script src="https://cdn.tailwindcss.com"></script>
    <link rel="stylesheet" href="<?php echo htmlspecialchars($google_font_url ?? ''); ?>">
    
    <script src="https://unpkg.com/lucide@latest"></script>
    <script src="https://unpkg.com/imask"></script>
    <link rel="stylesheet" href="style.css">

    <script src="https://cdnjs.cloudflare.com/ajax/libs/jspdf/2.5.1/jspdf.umd.min.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/html2canvas/1.4.1/html2canvas.min.js"></script>

    <style>
        @media print {
            header, #action-panel, .no-print { display: none !important; }
            body { background: white; -webkit-print-color-adjust: exact; }
            .shadow-xl { box-shadow: none !important; }
            #invoice-container { border: none !important; box-shadow: none !important; }
        }
    </style>
</head>
<body class="max-w-full mx-auto bg-[var(--color-background)]">
    <div id="toast-container" class="toast-container"></div>
    
    <header class="bg-white shadow-sm top-0 z-20 border-b-4 border-[var(--color-highlight)]">
        <div class="max-w-6xl mx-auto px-4 py-4 flex flex-col md:flex-row justify-between items-center space-y-3 md:space-y-0">
            
            <div class="flex-shrink-0 flex items-center justify-center">
                <?php if (!empty($biz['logo_url'])): ?>
                    <img src="<?php echo htmlspecialchars($biz['logo_url']); ?>" alt="Logo <?php echo htmlspecialchars($biz['company_name'] ?? ''); ?>" class="h-20 md:h-12 object-contain">
                <?php else: ?>
                    <h2 class="text-2xl font-black text-[var(--color-primary)] uppercase">
                        <?php echo htmlspecialchars($biz['company_name'] ?? ''); ?>
                    </h2>
                <?php endif; ?>
            </div>

            <?php 
            $wa_clean = preg_replace('/[^0-9]/', '', $biz['whatsapp'] ?? '');
            if (!empty($biz['whatsapp'])): 
            ?>
                <a href="https://wa.me/<?php echo $wa_clean; ?>?text=<?php echo rawurlencode($wa_message_direct); ?>" 
                   target="_blank" 
                   class="flex items-center justify-center space-x-2 bg-green-500 hover:bg-green-600 text-white font-black px-4 py-2 rounded-lg transition-colors shadow-md w-full md:w-auto order-3 md:order-none">
                    <i data-lucide="message-circle" class="w-5 h-5"></i>
                    <span class="text-lg">WHATSAPP: <?php echo formatUSPhoneNumber($biz['whatsapp']); ?></span>
                </a>
            <?php endif; ?>

            <div class="hidden md:block flex-shrink-0 text-right">
                <h1 class="text-2xl md:text-3xl font-black text-[var(--color-primary)] leading-none">
                    <?php echo htmlspecialchars($biz['company_name'] ?? ''); ?>
                </h1>
                <div class="flex items-center justify-end gap-2 text-[var(--color-secondary)]">
                    <i data-lucide="file-text" class="w-5 h-5"></i>
                    <p class="text-sm font-black uppercase tracking-wide">Invoicing Follow Up System</p>
                </div>
            </div>
            
        </div>
    </header>

    <main class="max-w-3xl mx-auto px-4 py-8">
        
        <?php if ($invoice): ?>
            <?php 
                $headerBg = 'bg-blue-600'; 
                $headerIcon = 'credit-card'; 
                $headerTitle = 'PAYMENT DUE'; 
                $headerSub = 'Please review details below.';
                
                if ($status === 'pagada') {
                    $headerBg = 'bg-green-600'; 
                    $headerIcon = 'check-circle'; 
                    $headerTitle = 'PAID IN FULL'; 
                    $headerSub = 'Thank you for your business!';
                } elseif ($isOverdue) {
                    $headerBg = 'bg-orange-600'; 
                    $headerIcon = 'alert-triangle'; 
                    $headerTitle = 'INVOICE OVERDUE'; 
                    $headerSub = 'Payment is required immediately.';
                }
            ?>
            
            <div id="invoice-container" class="bg-white rounded-xl shadow-xl border border-gray-200 overflow-hidden mb-8">
                
                <div class="<?php echo $headerBg; ?> p-8 text-center text-white print:bg-gray-100 print:text-black print:border-b">
                    <div class="inline-flex items-center justify-center w-16 h-16 bg-white bg-opacity-20 rounded-full mb-3 print:hidden">
                        <i data-lucide="<?php echo $headerIcon; ?>" class="w-8 h-8"></i>
                    </div>
                    <h3 class="text-4xl font-black uppercase tracking-wider"><?php echo $headerTitle; ?></h3>
                    <p class="text-white text-opacity-90 font-medium text-lg print:text-gray-600"><?php echo $headerSub; ?></p>
                </div>
                
                <div class="p-8">
                    <div class="flex flex-col md:flex-row justify-between items-start mb-8 border-b border-gray-100 pb-8 gap-4">
                        <div>
                            <?php if (!empty($ci['logo_url'])): ?>
                                <img src="<?php echo htmlspecialchars($ci['logo_url']); ?>" alt="Logo" class="h-20 mb-2">
                            <?php endif; ?>
                            <p class="font-bold text-gray-800 text-xl"><?php echo htmlspecialchars($ci['business_name'] ?? ''); ?></p>
                            <p class="text-sm text-gray-500">Invoicing Follow Up System</p>
                        </div>
                        <div class="md:text-right">
                             <h2 class="text-3xl font-black text-gray-300 uppercase">INVOICE #<?php echo htmlspecialchars($invoice['id']); ?></h2>
                        </div>
                    </div>

                    <div class="flex flex-col md:flex-row justify-between mb-8 border-b border-gray-100 pb-8 gap-6">
                        <div class="w-full md:w-1/2">
                            <p class="text-xs font-bold text-gray-400 uppercase tracking-widest mb-2">BILL TO</p>
                            <p class="text-xl font-black text-gray-800 uppercase"><?php echo htmlspecialchars(($invoice['first_name'] ?? '') . ' ' . ($invoice['last_name'] ?? '')); ?></p>
                            <?php if(!empty($invoice['company'])): ?>
                                <p class="text-gray-600 font-bold uppercase text-sm mb-1"><?php echo htmlspecialchars($invoice['company']); ?></p>
                            <?php endif; ?>
                            <p class="text-gray-500 text-sm mt-2"><?php echo htmlspecialchars($invoice['email'] ?? ''); ?></p>
                        </div>

                        <div class="w-full md:w-1/2 md:text-right">
                            <p class="text-xs font-bold text-gray-400 uppercase tracking-widest mb-2">DETAILS</p>
                            <div class="flex justify-between md:justify-end gap-4 mb-1">
                                <span class="text-gray-600 font-medium">Date Issued:</span>
                                <span class="font-bold text-gray-800"><?php echo date('M d, Y', strtotime($invoice['invoice_date'])); ?></span>
                            </div>
                            <?php if(!empty($invoice['due_date'])): ?>
                            <div class="flex justify-between md:justify-end gap-4">
                                <span class="text-gray-600 font-medium">Due Date:</span>
                                <span class="font-bold <?php echo $isOverdue ? 'text-red-600' : 'text-gray-800'; ?>">
                                    <?php echo date('M d, Y', strtotime($invoice['due_date'])); ?>
                                </span>
                            </div>
                            <?php endif; ?>
                        </div>
                    </div>

                    <div class="overflow-x-auto rounded-lg border border-gray-200 mb-6">
                        <table class="w-full text-left min-w-[500px]">
                            <thead class="bg-gray-100 text-gray-600 uppercase text-xs font-bold">
                                <tr>
                                    <th class="p-4">Description</th>
                                    <th class="p-4 text-center w-20">Qty</th>
                                    <th class="p-4 text-right w-32">Price</th>
                                    <th class="p-4 text-right w-32">Total</th>
                                </tr>
                            </thead>
                            <tbody class="divide-y divide-gray-100">
                                <?php foreach ($items as $item): 
                                    $rowTotal = $item['quantity'] * $item['unit_price'];
                                ?>
                                <tr class="text-sm">
                                    <td class="p-4 font-bold text-gray-700"><?php echo htmlspecialchars($item['description']); ?></td>
                                    <td class="p-4 text-center text-gray-500"><?php echo $item['quantity']; ?></td>
                                    <td class="p-4 text-right text-gray-500">$<?php echo number_format($item['unit_price'], 2); ?></td>
                                    <td class="p-4 text-right font-black text-gray-800">$<?php echo number_format($rowTotal, 2); ?></td>
                                </tr>
                                <?php endforeach; ?>
                            </tbody>
                        </table>
                    </div>
                    
                    <div class="flex flex-col items-end mb-4">
                        <div class="w-full md:w-1/2 bg-[var(--color-highlight)] bg-opacity-5 p-4 rounded-lg border border-gray-100">
                            <div class="flex justify-between text-gray-600 mb-2">
                                <span>Subtotal</span>
                                <span class="font-bold">$<?php echo number_format($invoice['subtotal'], 2); ?></span>
                            </div>
                             <?php if ($invoice['tax_rate'] > 0): $taxAmount = $invoice['subtotal'] * ($invoice['tax_rate'] / 100); ?>
                            <div class="flex justify-between text-gray-600 mb-2">
                                <span>Tax (<?php echo floatval($invoice['tax_rate']); ?>%)</span>
                                <span class="font-bold">$<?php echo number_format($taxAmount, 2); ?></span>
                            </div>
                            <?php endif; ?>
                            <div class="flex justify-between pt-3 border-t border-gray-300 text-[var(--color-primary)]">
                                <span class="text-xl font-black uppercase">Total</span>
                                <span class="text-3xl font-black">$<?php echo number_format($invoice['total_amount'], 2); ?></span>
                            </div>
                        </div>
                    </div>
                    
                    <?php if ($status === 'pagada'): ?>
                        <div class="text-center mt-6">
                             <div class="inline-block border-2 border-green-600 text-green-600 font-black text-4xl px-4 py-2 uppercase transform -rotate-6 opacity-80">
                                 PAID IN FULL
                             </div>
                             <p class="text-xs text-gray-400 mt-2">Paid on <?php echo date('M d, Y', strtotime($invoice['updated_at'])); ?></p>
                        </div>
                    <?php endif; ?>
                </div>
            </div>

            <div id="action-panel" class="max-w-4xl mx-auto mb-10 no-print">
                <?php if ($status === 'pagada'): ?>
                    <div class="text-center">
                        <button onclick="downloadPDF()" id="download-btn" class="w-full md:w-auto bg-slate-800 hover:bg-slate-900 text-white font-bold py-4 px-8 rounded-lg uppercase shadow-lg flex items-center justify-center gap-2 mx-auto transition">
                            <i data-lucide="download" class="w-5 h-5"></i>
                            Download PDF Receipt
                        </button>
                    </div>
                <?php else: ?>
                    <div class="text-center">
                         <div class="bg-white p-6 rounded-xl shadow-md border border-gray-200">
                            <p class="text-gray-500 font-bold uppercase text-sm mb-4">How would you like to pay?</p>
                            <a href="<?php echo htmlspecialchars($whatsapp_url_link); ?>?text=<?php echo urlencode($wa_message_direct); ?>" target="_blank"
                               class="w-full md:w-auto inline-flex items-center justify-center gap-2 bg-[#25D366] hover:bg-[#128C7E] text-white font-black py-4 px-8 rounded-lg uppercase shadow-lg transition text-lg">
                                <i data-lucide="message-circle" class="w-6 h-6"></i>
                                <?php echo $isOverdue ? 'CONTACT TO RESOLVE PAYMENT' : 'ASK HOW TO PAY'; ?>
                            </a>
                        </div>
                    </div>
                <?php endif; ?>
            </div>

        <?php else: ?>
        <section class="w-full bg-white rounded-2xl shadow-2xl overflow-hidden border-t-8 border-[var(--color-secondary)] text-center p-8">
            <div class="w-32 h-32 bg-[var(--color-secondary)] rounded-full flex items-center justify-center mx-auto mb-4 border-4 border-red-200">
                <i data-lucide="file-x" class="w-20 h-20 text-white"></i>
            </div>
            <h3 class="text-3xl font-black text-[var(--color-primary)] uppercase mb-2">INVOICE NOT FOUND</h3>
            <p class="text-gray-500 text-lg mb-6">The page you just accessed does not exist or the link has expired</p>
            
            <a href="booking.php" 
                class="w-full bg-[var(--color-secondary)] hover:opacity-90 text-white font-black py-2.5 px-4 rounded-lg uppercase sm:w-auto flex items-center justify-center gap-2">
                <i data-lucide="calendar-plus" class="w-4 h-4"></i> 
                BOOK AN APPOINTMENT
            </a>
            
            <?php if (!empty($client_info['phone_primary'])): ?>
            <a href="tel:<?php echo htmlspecialchars($client_info['phone_primary']); ?>" class="w-full bg-[var(--color-primary)] hover:opacity-90 text-white font-black mt-4 py-2.5 px-4 rounded-lg uppercase sm:w-auto flex items-center justify-center gap-2">
                <i data-lucide="phone-call" class="w-4 h-4"></i> CALL OFFICE TO HELP
            </a>
            <?php endif; ?>
            
            <p class="text-md text-gray-400 mt-4">If you believe this is an error, please contact the office.</p>
            <p class="text-lg font-black text-gray-400 mt-4 items-center justify-center"><?php echo htmlspecialchars($client_info['business_name'] ?? ''); ?></p>
        </section>
    <?php endif; ?>

    </main>
    
    <div class="no-print">   <?php @include 'brand/page-footer.php'; ?></div>

    <script>
        lucide.createIcons();
        window.jsPDF = window.jspdf.jsPDF; 

        async function downloadPDF() {
            const btn = document.getElementById('download-btn');
            const originalText = btn.innerHTML;
            
            btn.disabled = true;
            btn.innerHTML = '<i data-lucide="loader" class="w-5 h-5 animate-spin"></i> GENERATING PDF...';
            lucide.createIcons();

            const element = document.getElementById('invoice-container');
            const clone = element.cloneNode(true);
            
            clone.style.width = '800px'; 
            clone.style.position = 'absolute';
            clone.style.top = '-9999px';
            clone.style.left = '-9999px';
            clone.style.background = 'white'; 
            clone.style.padding = '0';
            
            document.body.appendChild(clone);

            try {
                const canvas = await html2canvas(clone, {
                    scale: 2, 
                    useCORS: true, 
                    logging: false,
                    backgroundColor: '#ffffff'
                });

                const imgData = canvas.toDataURL('image/jpeg', 0.95);
                const pdf = new jsPDF('p', 'mm', 'a4');
                const pdfWidth = pdf.internal.pageSize.getWidth();
                const pdfHeight = pdf.internal.pageSize.getHeight();
                const imgProps = pdf.getImageProperties(imgData);
                const imgHeight = (imgProps.height * pdfWidth) / imgProps.width;

                pdf.addImage(imgData, 'JPEG', 0, 0, pdfWidth, imgHeight);
                pdf.save('Invoice_<?php echo $invoice['id'] ?? "Receipt"; ?>.pdf');

            } catch (err) {
                console.error("PDF Error:", err);
                alert("Error generating PDF. Please try again.");
            } finally {
                document.body.removeChild(clone);
                btn.disabled = false;
                btn.innerHTML = originalText;
                lucide.createIcons();
            }
        }
    </script>
</body>
</html>