<?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
$whatsapp_contact = $wa['display'] ?? ''; 
$whatsapp_url_link = $wa['link'] ?? ''; 

// FIX: Validación para evitar el error "Cannot redeclare"
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);

// --- FETCH DATA ---
$raw_token = $_GET['token'] ?? '';
$token = trim(preg_replace('/[^a-zA-Z0-9.\-_]/', '', $raw_token)); 
$estimate = null;
$items = [];
$wa_message_quote = "Hi! I'm interested in getting a quote.";

if (!empty($token) && isset($pdo)) {
    try {
        $stmt = $pdo->prepare("
            SELECT q.*, 
                   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
            FROM quotes q
            LEFT JOIN clients c ON q.client_id = c.id
            LEFT JOIN leads l ON q.lead_id = l.id
            WHERE q.external_id = :token LIMIT 1
        ");
        $stmt->execute(['token' => $token]);
        $estimate = $stmt->fetch(PDO::FETCH_ASSOC);

        if ($estimate) {
            $stmtItems = $pdo->prepare("SELECT * FROM quotes_items WHERE quote_id = ?");
            $stmtItems->execute([$estimate['id']]);
            $items = $stmtItems->fetchAll(PDO::FETCH_ASSOC);
            
            $wa_message_quote = "Hi! I have a question about Quote #{$estimate['id']}.";
        }
    } catch (Exception $e) {
        error_log("DB Error: " . $e->getMessage());
    }
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Quote #<?php echo htmlspecialchars($estimate['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, #feedback-form-container, .whatsapp-btn, #vip-modal, .no-print { display: none !important; }
            body { background: white; }
            .shadow-md, .shadow-xl { box-shadow: none !important; }
            .border { border: 1px solid #ddd !important; }
            #quote-container { margin: 0; padding: 0; border: none; }
        }
        .fade-in { animation: fadeIn 0.5s ease-in-out; }
        .scale-in { animation: scaleIn 0.4s cubic-bezier(0.175, 0.885, 0.32, 1.275); }
        
        @keyframes fadeIn { from { opacity: 0; } to { opacity: 1; } }
        @keyframes scaleIn { from { transform: scale(0.9); opacity: 0; } to { transform: scale(1); opacity: 1; } }
    </style>
</head>
<body class="max-w-full mx-auto bg-[var(--color-background)]">
    <div id="toast-container" class="toast-container"></div>
    
    <div id="vip-modal" class="fixed inset-0 z-50 hidden flex items-center justify-center bg-slate-900/95 backdrop-blur-sm fade-in p-4 no-print">
        <div class="bg-white max-w-lg w-full rounded-2xl shadow-2xl overflow-hidden scale-in relative">
            <div class="absolute top-0 left-0 w-full h-2 bg-gradient-to-r from-yellow-500 via-yellow-200 to-yellow-600"></div>
            
            <div class="p-8 text-center">
                <div class="mx-auto flex items-center justify-center h-20 w-20 rounded-full bg-green-100 mb-6">
                    <i data-lucide="check" class="h-10 w-10 text-green-600"></i>
                </div>
                
                <h2 class="text-3xl font-black text-slate-800 uppercase mb-2">Thank You!</h2>
                <p class="text-sm font-bold text-yellow-600 uppercase tracking-widest mb-6">Quote Approved Successfully</p>
                
                <p class="text-gray-600 text-lg mb-8 leading-relaxed">
                    We have received your approval. You are now a priority for us. 
                    <br><br>
                    Our team will contact you shortly to 
                    <span class="font-bold text-slate-800">finalize the details</span> and schedule your service.
                </p>
                
                <button onclick="window.location.reload()" 
                    class="w-full py-4 px-6 bg-slate-900 hover:bg-slate-800 text-white font-bold rounded-xl shadow-lg transform transition hover:-translate-y-1 uppercase tracking-wider flex items-center justify-center gap-2">
                    <i data-lucide="check-circle" class="w-5 h-5"></i>
                    Close & Download Quote
                </button>
            </div>
            
            <div class="bg-gray-50 px-6 py-3 border-t border-gray-100 flex justify-center items-center gap-2">
                 <i data-lucide="shield-check" class="w-4 h-4 text-gray-400"></i>
                 <span class="text-xs text-gray-400 font-medium uppercase">Secured by <?php echo htmlspecialchars($client_info['business_name'] ?? ''); ?> System</span>
            </div>
        </div>
    </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_quote); ?>" 
               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="calendar-check" class="w-5 h-5"></i>
                <p class="text-sm font-black uppercase tracking-wide">Estimate Follow Up System</p>
            </div>
        </div>
        
    </div>
</header>

    <main class="max-w-3xl mx-auto px-4 py-8">
        
        <?php if ($estimate): ?>
            <?php 
                $dbStatus = strtolower($estimate['status']);
                $headerBg = 'bg-orange-500'; 
                $headerIcon = 'clock'; 
                $headerTitle = 'REVIEW REQUIRED'; 
                $headerSub = 'Please review the proposal below';
                $showActions = true;
                $isApproved = false;

                // Mapeo de estados
                if (in_array($dbStatus, ['converted', 'approved', 'ganada', 'aceptada', 'convertida'])) {
                    $headerBg = 'bg-green-600'; 
                    $headerIcon = 'check-circle'; 
                    $headerTitle = 'QUOTE APPROVED'; 
                    $headerSub = 'Everything is set! Thank you.';
                    $showActions = false;
                    $isApproved = true;
                } elseif ($dbStatus === 'revision_requested') {
                    $headerBg = 'bg-blue-500'; 
                    $headerIcon = 'refresh-cw'; 
                    $headerTitle = 'CHANGES REQUESTED'; 
                    $headerSub = 'We are updating your quote based on your feedback.';
                    $showActions = false;
                } elseif (in_array($dbStatus, ['rejected', 'rechazada', 'perdida'])) {
                    $headerBg = 'bg-red-500'; 
                    $headerIcon = 'x-circle'; 
                    $headerTitle = 'QUOTE DECLINED'; 
                    $headerSub = 'This quote has been closed.';
                    $showActions = false;
                }
            ?>
            
            <section id="quote-container" class="bg-white p-0 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-white print:text-black print:border-b print:p-4">
                    <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-3xl font-black uppercase"><?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 mb-8 border-b border-gray-100 pb-8">
                        <div>
                            <p class="text-xs font-bold text-gray-400 uppercase tracking-widest mb-1">PREPARED FOR</p>
                            <p class="text-2xl font-black text-gray-800 uppercase"><?php echo htmlspecialchars($estimate['first_name'] . ' ' . $estimate['last_name']); ?></p>
                            <?php if(!empty($estimate['company'])): ?><p class="text-gray-500 font-medium"><?php echo htmlspecialchars($estimate['company']); ?></p><?php endif; ?>
                            <p class="text-gray-400 text-sm mt-1"><?php echo htmlspecialchars($estimate['email']); ?></p>
                        </div>
                        <div class="mt-4 md:mt-0 md:text-right">
                            <p class="text-xs font-bold text-gray-400 uppercase tracking-widest mb-1">DETAILS</p>
                            <p class="font-bold text-gray-700">Date: <span class="font-normal"><?php echo date('M d, Y', strtotime($estimate['estimate_date'])); ?></span></p>
                            <p class="font-bold text-gray-700">Quote ID: <span class="text-[var(--color-primary)]">#<?php echo htmlspecialchars($estimate['id']); ?></span></p>
                        </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-500 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 hover:bg-gray-50 transition">
                                    <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-8">
                        <div class="w-full md:w-1/2 space-y-2">
                            <div class="flex justify-between text-gray-600">
                                <span>Subtotal</span>
                                <span class="font-bold">$<?php echo number_format($estimate['subtotal'], 2); ?></span>
                            </div>
                             <?php if ($estimate['tax_rate'] > 0): $taxAmount = $estimate['subtotal'] * ($estimate['tax_rate'] / 100); ?>
                            <div class="flex justify-between text-gray-600">
                                <span>Tax (<?php echo floatval($estimate['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-2 border-[var(--color-primary)] text-[var(--color-primary)] mt-2">
                                <span class="text-xl font-black uppercase">Total</span>
                                <span class="text-3xl font-black">$<?php echo number_format($estimate['total_amount'], 2); ?></span>
                            </div>
                        </div>
                    </div>

                    <div id="action-panel" class="no-print">
                        <?php if ($showActions): ?>
                            <div id="main-buttons" class="grid grid-cols-1 md:grid-cols-2 gap-4">
                                <button onclick="handleApprove()" class="bg-green-600 hover:bg-green-700 text-white font-black py-4 px-6 rounded-lg uppercase shadow-lg flex items-center justify-center gap-2 text-lg transition transform hover:-translate-y-1">
                                    <i data-lucide="check" class="w-6 h-6"></i> APPROVE & SCHEDULE
                                </button>
                                <button onclick="toggleFeedback()" class="bg-white border-2 border-gray-300 text-gray-600 hover:border-gray-800 hover:text-gray-800 font-bold py-4 px-6 rounded-lg uppercase shadow-sm flex items-center justify-center gap-2 text-lg transition">
                                    <i data-lucide="edit-3" class="w-5 h-5"></i> REQUEST CHANGES
                                </button>
                            </div>

                            <div id="feedback-form-container" class="hidden mt-6 fade-in bg-gray-50 p-6 rounded-lg border border-gray-200">
                                <h5 class="text-lg font-black text-gray-800 mb-2 flex items-center gap-2">
                                    <i data-lucide="message-square-plus" class="w-5 h-5 text-[var(--color-primary)]"></i> Tell us what needs to change
                                </h5>
                                <p class="text-sm text-gray-500 mb-4">We will review your request, update the quote, and you can use this same link to see the new price.</p>
                                <textarea id="feedback-text" rows="3" class="w-full p-3 border border-gray-300 rounded-lg focus:ring-2 focus:ring-[var(--color-primary)] focus:outline-none mb-4" placeholder="Example: Please remove the carpet cleaning service..."></textarea>
                                <div class="flex gap-3">
                                    <button onclick="submitFeedback()" class="bg-[var(--color-primary)] hover:opacity-90 text-white font-bold py-3 px-6 rounded-lg flex-1">SEND REQUEST</button>
                                    <button onclick="toggleFeedback()" class="bg-gray-200 hover:bg-gray-300 text-gray-700 font-bold py-3 px-6 rounded-lg">CANCEL</button>
                                </div>
                            </div>
                        <?php elseif ($dbStatus === 'revision_requested'): ?>
                            <div class="bg-blue-50 border border-blue-200 rounded-lg p-4 text-center">
                                <p class="text-blue-800 font-bold">Feedback Sent</p>
                                <p class="text-sm text-blue-600">Please wait for us to update this link with the new details.</p>
                            </div>
                        
                        <?php elseif ($isApproved): ?>
                            <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 Quote PDF
                                </button>
                            </div>
                        <?php endif; ?>
                    </div>
                </div>
            </section>

        <?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="clipboard-list" class="w-20 h-20 text-white"></i>
            </div>
            <h3 class="text-3xl font-black text-[var(--color-primary)] uppercase mb-2">QUOTE 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>

    <?php @include 'brand/page-footer.php'; ?>

    <script>
        lucide.createIcons();
        window.jsPDF = window.jspdf.jsPDF; 
        const token = "<?php echo $token; ?>";

        function toggleFeedback() {
            const form = document.getElementById('feedback-form-container');
            const mainBtns = document.getElementById('main-buttons');
            form.classList.toggle('hidden');
            mainBtns.classList.toggle('hidden');
        }

        async function handleApprove() {
            if(!confirm("Are you sure you want to approve this quote?")) return;
            sendAction('approve');
        }

        async function submitFeedback() {
            const text = document.getElementById('feedback-text').value;
            if(!text.trim()) { alert("Please write your request before sending."); return; }
            sendAction('request_changes', text);
        }

        async function sendAction(action, feedback = '') {
            let btn;
            if (action === 'approve') {
                btn = document.querySelector('button[onclick="handleApprove()"]');
            } else {
                btn = document.querySelector('button[onclick="submitFeedback()"]');
            }
            
            const originalContent = btn.innerHTML;
            btn.disabled = true;
            btn.innerHTML = '<i data-lucide="loader" class="w-5 h-5 animate-spin"></i> Processing...';
            lucide.createIcons();

            try {
                const response = await fetch('db/quote-action-handler.php', {
                    method: 'POST',
                    headers: {'Content-Type': 'application/json'},
                    body: JSON.stringify({ token, action, feedback })
                });
                const data = await response.json();
                
                if(data.status === 'success') { 
                    if(action === 'approve') {
                        document.getElementById('vip-modal').classList.remove('hidden');
                        lucide.createIcons();
                    } else {
                        window.location.reload(); 
                    }
                } 
                else { 
                    alert('Error: ' + data.message); 
                    btn.disabled = false; 
                    btn.innerHTML = originalContent; 
                    lucide.createIcons(); 
                }
            } catch (e) {
                alert('Connection Error'); 
                btn.disabled = false; 
                btn.innerHTML = originalContent; 
                lucide.createIcons();
            }
        }

        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('quote-container');
            const clone = element.cloneNode(true);
            
            // Ajustes para el PDF
            clone.style.width = '800px'; 
            clone.style.position = 'absolute';
            clone.style.top = '-9999px';
            clone.style.left = '-9999px';
            clone.style.background = 'white'; 
            clone.style.padding = '0';
            
            // Remover botones del clon si existen
            const actions = clone.querySelector('#action-panel');
            if(actions) actions.remove();

            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();
                // Calcular altura proporcional
                const imgProps = pdf.getImageProperties(imgData);
                const imgHeight = (imgProps.height * pdfWidth) / imgProps.width;

                pdf.addImage(imgData, 'JPEG', 0, 0, pdfWidth, imgHeight);
                pdf.save('Quote_<?php echo $estimate['id'] ?? "Doc"; ?>.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>