<?php include 'files/guardiankey.php'; ?>
<?php
// =================================================================
//        DATA BLOCK FOR FORM PRE-FILLING (Best Practice)
// =================================================================

// 1. Include the central business information file.
//    This creates the $client_info variable with all the data.
include __DIR__ . '/client-information.php';

// 2. Assign info to easy-to-use variables for this form.
//    Using English names for consistency with the database and array keys.
$client_name       = $client_info['name'] ?? '';
$business_name     = $client_info['business_name'] ?? '';
$phone             = $client_info['phone'] ?? '';
$whatsapp          = $client_info['whatsapp'] ?? '';
$email             = $client_info['email'] ?? '';
$website           = $client_info['website'] ?? '';
$operating_cities  = $client_info['operating_cities'] ?? '';
$value_proposition = $client_info['value_proposition'] ?? '';
$logo_url          = $client_info['logo_url'] ?? '';

// Social links come as an array, hence the '?? []' fallback.
$social_links      = $client_info['social_links'] ?? [];

// =================================================================
?>
<!DOCTYPE html>
<html lang="es">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Generador De Facturas Digitales Con IAMarketing™ Powered By OrozCO</title>
    <meta name="description" content="Genera Facturas Profesionales Para Tus Servicios Fácilmente">
    <meta name="robots" content="noindex, nofollow">

    <link rel="icon" type="image/png" href="img/favicon.png">
    <link rel="apple-touch-icon" href="img/apple-touch-icon.png">

    <?php include 'files/gtm-head.php'; ?>
    
    <script src="https://cdn.tailwindcss.com"></script>
    <link rel="preconnect" href="https://fonts.googleapis.com">
    <link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
    <link href="https://fonts.googleapis.com/css2?family=Barlow:wght@300;400;500;600;700;800;900&display=swap" rel="stylesheet">
    
    <script src="https://unpkg.com/lucide@latest"></script>
    <script src="https://unpkg.com/imask"></script>

    <link rel="stylesheet" href="style.css">
    <link rel="stylesheet" href="tools.css">
    <script src="files/header-manager.js"></script>
    
    <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>
        #pdf-preview-content { font-family: 'Barlow', sans-serif; color: #3d3d3d; position: relative; }
        [contenteditable]:focus { outline: 2px solid var(--color-highlight); background-color: #fffbeb; border-radius: 4px; padding: 2px; }
        .delete-item-btn { background: none; border: none; color: #ef4444; font-size: 1.5rem; line-height: 1; cursor: pointer; transition: color 0.2s; }
        .delete-item-btn:hover { color: #b91c1c; }
        .payment-stamp { 
            position: absolute; 
            top: 50%; 
            left: 50%; 
            transform: translate(-50%, -50%) rotate(-25deg); 
            font-size: 4rem; 
            font-weight: bold; 
            padding: 0.5rem 2rem; 
            border-radius: 5px; 
            z-index: 100; 
            pointer-events: none; 
            text-transform: uppercase;
            white-space: nowrap;
        }
        .unpaid-stamp { color: rgba(220, 38, 38, 0.5); border: 4px solid rgba(220, 38, 38, 0.5); }
        .paid-stamp { color: rgba(4, 120, 87, 0.5); border: 4px solid rgba(4, 120, 87, 0.5); }
    </style>
</head>
<body data-page-title="Generador De Facturas Digitales"
      data-page-subtitle="Genera Facturas Profesionales Para Tus Servicios Fácilmente"
      data-page-icon="brain">

    <div id="toast-container" class="toast-container"></div>

    <?php include 'files/gtm-body.php'; ?>

<div class="relative min-h-screen md:flex">

    <div id="sidebar-overlay" class="fixed inset-0 bg-black bg-opacity-50 z-30 hidden md:hidden"></div>
    <div id="task-panel-overlay" class="off-canvas-overlay"></div> 
    
    <?php include 'ia-menu.php'; ?>

    <main class="flex-1 overflow-y-auto">
        <header class="bg-white shadow-sm p-4 flex justify-between items-center sticky top-0 z-20">
            <button id="mobile-menu-button" class="md:hidden text-gray-600 hover:text-gray-800">
                <i data-lucide="menu" class="w-6 h-6"></i>
            </button>
            <div class="page-header-container">
                <h2 id="page-title"></h2>
                <p id="page-subtitle"></p>
            </div>
        </header>

        <div id="content-area" class="p-4 md:p-8">
            <section id="estimator-section" class="dashboard-section">
                <div class="grid grid-cols-1 lg:grid-cols-5 gap-8">

                    <div class="lg:col-span-2">
                        <div class="bg-white p-6 md:p-8 rounded-xl shadow-md">
                            <form id="invoice-form" class="space-y-8">
                                <div class="step-header">
                                    <h2 class="text-2xl font-black pb-0 mb-0 flex items-center uppercase">
                                        <i data-lucide="file-text" class="w-6 h-6 mr-3 text-[var(--color-secondary)]"></i>
                                        <span class="text-[var(--color-secondary)] mr-2">PASO 1:</span> Ingresa los Datos
                                    </h2>
                                    <p class="step-subtitle uppercase">Completa la información para generar la factura</p>
                                </div>
                                <div class="space-y-4">
                                    <h3 class="font-bold text-lg capitalize text-gray-700">Datos De Tu Negocio</h3>
                                    <input type="text" id="companyName" name="companyName" placeholder="Nombre De Tu Empresa" class="w-full p-3 bg-gray-50 border border-gray-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-[var(--color-highlight)]" value="<?php echo htmlspecialchars($business_name); ?>">
                                    <input type="text" id="yourName" name="yourName" placeholder="Tu Nombre" class="w-full p-3 bg-gray-50 border border-gray-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-[var(--color-highlight)]" value="<?php echo htmlspecialchars($client_name); ?>">
                                    <input type="email" id="yourEmail" name="yourEmail" placeholder="Tu Email" class="w-full p-3 bg-gray-50 border border-gray-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-[var(--color-highlight)]" value="<?php echo htmlspecialchars($email); ?>">
                                    <input type="tel" id="yourPhone" name="yourPhone" placeholder="(555) 123-4567" class="w-full p-3 bg-gray-50 border border-gray-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-[var(--color-highlight)]" value="<?php echo htmlspecialchars($phone); ?>">
                                    <div>
                                        <label for="logoUpload" class="block font-bold capitalize text-gray-700 mb-2 text-lg">Sube El Logo De Tu Negocio</label>
                                        <input type="file" id="logoUpload" name="logoUpload" accept="image/*" class="w-full text-sm text-gray-500 file:mr-4 file:py-2 file:px-4 file:rounded-full file:border-0 file:text-sm file:font-semibold file:bg-gray-100 hover:file:bg-gray-200 transition">
                                    </div>
                                </div>
                                <div class="space-y-4">
                                    <h3 class="font-bold text-lg capitalize text-gray-700">Datos Del Cliente</h3>
                                    <input type="text" id="clientName" name="clientName" placeholder="Nombre Del Cliente" class="w-full p-3 bg-gray-50 border border-gray-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-[var(--color-highlight)]">
                                    <input type="text" id="clientAddress" name="clientAddress" placeholder="Dirección Del Cliente" class="w-full p-3 bg-gray-50 border border-gray-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-[var(--color-highlight)]">
                                </div>
                                <div class="space-y-4">
                                    <h3 class="font-bold text-lg capitalize text-gray-700">Detalles De Los Servicios</h3>
                                    
                                    <div id="service-items-container" class="space-y-4"></div>
                                    
                                    <button id="add-item-btn" type="button" class="w-full mt-6 bg-gray-800 text-white font-bold py-3 px-6 rounded-lg hover:bg-gray-700 transition-all shadow-lg text-md flex items-center justify-center uppercase">
                                        <i data-lucide="plus" class="w-5 h-5 mr-2"></i> Agregar Servicio
                                    </button>
                                    
                                    <div>
                                        <label for="tax-rate" class="block font-bold capitalize text-gray-700 mb-2 text-lg">Impuesto (%)</label>
                                        <input type="number" id="tax-rate" name="tax-rate" placeholder="Ej: 7" step="0.1" min="0" class="w-full p-3 bg-gray-50 border border-gray-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-[var(--color-highlight)]">
                                    </div>
                                </div>
                            </form>
                        </div>
                    </div>

                    <div class="lg:col-span-3">
                        <div class="bg-white p-6 md:p-8 rounded-xl shadow-md">
                            <div class="step-header">
                                <h2 class="text-2xl font-black pb-0 mb-0 flex items-center uppercase">
                                    <i data-lucide="eye" class="w-6 h-6 mr-3 text-[var(--color-secondary)]"></i>
                                    <span class="text-[var(--color-secondary)] mr-2">PASO 2:</span> Revisa y Descarga
                                </h2>
                                <p class="step-subtitle uppercase">Verifica la información y descarga tu factura en PDF</p>
                            </div>
                            <div class="border-b border-gray-200 pb-4 mb-6"></div>
                            
                            <div class="mb-4">
                                <label for="payment-status" class="block font-bold capitalize text-gray-700 mb-2 text-lg">Estado De La Factura</label>
                                <select id="payment-status" class="w-full p-3 bg-gray-50 border border-gray-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-[var(--color-highlight)]">
                                    <option value="none" selected>Sin Etiqueta</option>
                                    <option value="unpaid">Unpaid (No Pagada)</option>
                                    <option value="paid">Paid in Full (Pagada)</option>
                                </select>
                            </div>

                            <div id="pdf-preview" class="bg-white p-4 sm:p-6 md:p-8 rounded-lg shadow-inner border border-gray-200">
                                <div id="pdf-preview-content" class="pb-4">
                                    <div class="flex justify-between items-start mb-8">
                                        <div>
                                            <img id="logoPreview" src="<?php echo !empty($logo_url) ? htmlspecialchars($logo_url) : 'https://via.placeholder.com/200x80/cccccc/ffffff?text=Your+Logo'; ?>" alt="Company Logo" class="h-16 mb-4 object-contain">
                                            <h2 id="previewCompanyName" class="text-xl font-black text-gray-800" contenteditable="true">Nombre De Tu Empresa</h2>
                                            <p id="previewYourName" class="text-sm text-gray-600" contenteditable="true">Tu Nombre</p>
                                            <p id="previewYourEmail" class="text-sm text-gray-600" contenteditable="true">tu.email@ejemplo.com</p>
                                            <p id="previewYourPhone" class="text-sm text-gray-600" contenteditable="true">(555) 123-4567</p>
                                        </div>
                                        <div class="text-right">
                                            <h1 class="text-4xl font-black text-gray-300 tracking-wider">INVOICE</h1>
                                            <p class="text-xs text-gray-600"><strong>Date:</strong> <span id="previewDate" contenteditable="true">--/--/----</span></p>
                                            <p class="text-xs text-gray-600"><strong>Invoice #:</strong> <span id="previewInvoiceId" contenteditable="true">0001</span></p>
                                        </div>
                                    </div>
                                    <div class="bg-gray-50 p-4 rounded-lg mb-6">
                                        <h3 class="font-bold text-gray-500 text-xs tracking-wider uppercase">BILLED TO:</h3>
                                        <p id="previewClientName" class="text-gray-800 font-semibold" contenteditable="true">Nombre Del Cliente</p>
                                        <p id="previewClientAddress" class="text-gray-700 text-sm" contenteditable="true">Dirección Del Cliente</p>
                                    </div>
                                    <table class="w-full mb-6 text-sm">
                                        <thead>
                                            <tr class="bg-[var(--color-primary)] text-white">
                                                <th class="text-left p-2 font-bold tracking-wider">DESCRIPTION</th>
                                                <th class="text-right p-2 font-bold tracking-wider">PRICE</th>
                                                <th class="w-10 no-print"></th>
                                            </tr>
                                        </thead>
                                        <tbody id="invoice-items">
                                            <tr class="initial-placeholder"><td class="p-2 text-gray-400 border-b">Tus servicios aparecerán aquí...</td><td class="text-right p-2 text-gray-400 border-b">$0.00</td><td class="no-print"></td></tr>
                                        </tbody>
                                    </table>
                                    <div class="flex justify-end">
                                        <div class="w-full md:w-2/3 lg:w-1/2 space-y-2">
                                            <div class="flex justify-between text-gray-700 p-1">
                                                <span>Subtotal</span>
                                                <span id="previewSubtotal">$0.00</span>
                                            </div>
                                            <div class="flex justify-between text-gray-700 p-1" id="tax-row" style="display: none;">
                                                <span>Impuestos (<span id="tax-rate-preview">0</span>%)</span>
                                                <span id="previewTaxAmount">$0.00</span>
                                            </div>
                                            <div class="flex justify-between text-[var(--color-primary)] font-bold text-lg bg-[var(--color-highlight)] p-2 rounded-md">
                                                <span>TOTAL</span>
                                                <span id="previewTotal">$0.00</span>
                                            </div>
                                        </div>
                                    </div>
                                    <div class="mt-10 text-xs text-gray-500">
                                        <h4 class="font-bold text-gray-800 mb-1">Terms and Conditions</h4>
                                        <p contenteditable="true">Payment is due within 30 days of the invoice date. The customer is responsible for all applicable taxes.</p>
                                    </div>
                                    <div id="payment-stamp" class="payment-stamp hidden"></div>
                                </div>
                            </div>
<button id="downloadBtn" class="w-full mt-6 bg-[var(--color-highlight)] text-brand-dark font-bold py-4 px-6 rounded-lg hover:scale-105 transition-transform shadow-lg text-lg flex items-center justify-center uppercase">
    <i data-lucide="download" class="w-6 h-6 mr-3"></i>
    Descargar Factura En PDF
</button>
                        </div>
                    </div>
                </div>
            </section>
        </div>
    </main>
</div>

<script type="module">
// --- CARGA DOMCONTENT ---
document.addEventListener('DOMContentLoaded', function() {
    lucide.createIcons();
    
    // MENU MOBILE
    const mobileMenuButton = document.getElementById('mobile-menu-button');
    const sidebar = document.getElementById('sidebar');
    const sidebarOverlay = document.getElementById('sidebar-overlay');

    mobileMenuButton.addEventListener('click', () => {
        sidebar.classList.toggle('-translate-x-full');
        sidebarOverlay.classList.toggle('hidden');
    });

    sidebarOverlay.addEventListener('click', () => {
        sidebar.classList.add('-translate-x-full');
        sidebarOverlay.classList.add('hidden');
    });

    // --- NOTIFICACIONES TOAST 
    const urlParams = new URLSearchParams(window.location.search);
    const notificationType = urlParams.get('notification_type');
    const notificationMessage = urlParams.get('notification_message');

    if (notificationType && notificationMessage) {
        if (typeof showToast === 'function') {
            showToast(notificationMessage, notificationType);
        } else {
            console.error("showToast function is not defined. Toast notification might not display.");
        }
    }
    
    // VIDEO PLAYER
    const playOverlay = document.getElementById('playOverlay');
    const videoPlayer = document.getElementById('videoPlayer');
    
    if(playOverlay && videoPlayer) {
        playOverlay.addEventListener('click', () => {
            playOverlay.style.display = 'none';
            videoPlayer.play();
        });
    }
    
    window.jsPDF = window.jspdf.jsPDF;

    // --- DOM ELEMENTS ---
    const form = document.getElementById('invoice-form');
    const downloadBtn = document.getElementById('downloadBtn');
    const addItemBtn = document.getElementById('add-item-btn');
    const invoiceItemsBody = document.getElementById('invoice-items');
    const yourPhoneInput = document.getElementById('yourPhone');
    const serviceItemsContainer = document.getElementById('service-items-container');
    const logoUploadInput = document.getElementById('logoUpload');
    const logoPreviewImg = document.getElementById('logoPreview');
    const paymentStatusSelect = document.getElementById('payment-status');
    const paymentStamp = document.getElementById('payment-stamp');
    const initialPlaceholder = document.querySelector('.initial-placeholder');
    
    // --- MASK ---
    if (yourPhoneInput) {
        IMask(yourPhoneInput, { mask: '(000) 000-0000' });
    }

    // --- EVENT HANDLERS ---
    form.addEventListener('input', updatePreview);
    downloadBtn.addEventListener('click', generatePDF);
    paymentStatusSelect.addEventListener('change', updatePaymentStatus);
    addItemBtn.addEventListener('click', () => addManualItem());

    logoUploadInput.addEventListener('change', function(event) {
        const file = event.target.files[0];
        if (file) {
            const reader = new FileReader();
            reader.onload = function(e) {
                logoPreviewImg.src = e.target.result;
            };
            reader.readAsDataURL(file);
        }
    });

    // --- LOGIC FUNCTIONS ---
    function createItemRow(id, description, price) {
        const row = document.createElement('tr');
        row.dataset.id = id;
        
        row.innerHTML = `
            <td class="p-2 border-b border-gray-100" contenteditable="true">${description}</td>
            <td class="text-right p-2 item-price border-b border-gray-100" contenteditable="true">$${parseFloat(price).toFixed(2)}</td>
            <td class="p-2 text-center align-middle border-b border-gray-100 no-print">
                <button type="button" class="delete-item-btn" title="Eliminar servicio">&times;</button>
            </td>
        `;
        row.querySelector('.delete-item-btn').addEventListener('click', () => {
            const itemForm = document.querySelector(`.manual-item-form[data-id="${id}"]`);
            if (itemForm) {
                itemForm.remove();
            }
            updatePreview();
        });
        return row;
    }

    function addManualItem() {
        const itemId = `item-${Date.now()}`;
        const newItemContainer = document.createElement('div');
        newItemContainer.className = 'flex items-end space-x-2 my-2 manual-item-form';
        newItemContainer.dataset.id = itemId;
        
        newItemContainer.innerHTML = `
            <div class="flex-grow">
                <label class="block text-sm font-bold text-gray-600 mb-1">Servicio</label>
                <input type="text" placeholder="Nombre Del Servicio" class="w-full p-3 bg-gray-50 border border-gray-300 rounded-lg manual-item-desc focus:outline-none focus:ring-2 focus:ring-[var(--color-highlight)]">
            </div>
            <div class="w-1/3">
                <label class="block text-sm font-bold text-gray-600 mb-1">Precio</label>
                <input type="number" placeholder="Precio" step="0.01" min="0" class="w-full p-3 bg-gray-50 border border-gray-300 rounded-lg manual-item-price focus:outline-none focus:ring-2 focus:ring-[var(--color-highlight)]">
            </div>
            <button type="button" class="delete-manual-item-btn text-red-500 hover:text-red-700 transition pb-2"><i data-lucide="trash-2"></i></button>
        `;
        serviceItemsContainer.appendChild(newItemContainer);
        newItemContainer.querySelector('.manual-item-desc').focus();
        lucide.createIcons();

        newItemContainer.querySelector('.delete-manual-item-btn').addEventListener('click', () => {
            newItemContainer.remove();
            updatePreview();
        });
    }

    function updatePaymentStatus() {
        const status = paymentStatusSelect.value;
        paymentStamp.classList.add('hidden');
        paymentStamp.classList.remove('unpaid-stamp', 'paid-stamp');
        
        if (status === 'unpaid') {
            paymentStamp.textContent = 'UNPAID';
            paymentStamp.classList.remove('hidden');
            paymentStamp.classList.add('unpaid-stamp');
        } else if (status === 'paid') {
            paymentStamp.textContent = 'PAID IN FULL';
            paymentStamp.classList.remove('hidden');
            paymentStamp.classList.add('paid-stamp');
        }
    }

    function updatePreview() {
        document.getElementById('previewCompanyName').textContent = document.getElementById('companyName').value || "Nombre De Tu Empresa";
        document.getElementById('previewYourName').textContent = document.getElementById('yourName').value || "Tu Nombre";
        document.getElementById('previewYourEmail').textContent = document.getElementById('yourEmail').value || "tu.email@ejemplo.com";
        document.getElementById('previewYourPhone').textContent = document.getElementById('yourPhone').value || "(555) 123-4567";
        document.getElementById('previewClientName').textContent = document.getElementById('clientName').value || "Nombre Del Cliente";
        document.getElementById('previewClientAddress').textContent = document.getElementById('clientAddress').value || "Dirección Del Cliente";
        document.getElementById('previewDate').textContent = new Date().toLocaleDateString('en-US');
        if(document.getElementById('previewInvoiceId').textContent === '0001' && document.getElementById('clientName').value) {
            document.getElementById('previewInvoiceId').textContent = Math.floor(1000 + Math.random() * 9000);
        }
        
        invoiceItemsBody.innerHTML = '';
        const manualItems = document.querySelectorAll('.manual-item-form');
        let hasItems = false;
        
        manualItems.forEach(itemDiv => {
            const desc = itemDiv.querySelector('.manual-item-desc').value;
            const price = itemDiv.querySelector('.manual-item-price').value;
            if (desc && price && parseFloat(price) > 0) {
                invoiceItemsBody.appendChild(createItemRow(itemDiv.dataset.id, desc, price));
                hasItems = true;
            }
        });

        if (!hasItems) {
            invoiceItemsBody.appendChild(initialPlaceholder);
        }
        
        recalculateTotal();
    }

    function recalculateTotal() {
        let subtotal = 0;
        const items = invoiceItemsBody.querySelectorAll('.item-price');
        
        items.forEach(priceCell => {
            subtotal += parseFloat(priceCell.textContent.replace('$', '')) || 0;
        });

        const taxRate = parseFloat(document.getElementById('tax-rate').value) || 0;
        const taxAmount = subtotal * (taxRate / 100);
        const total = subtotal + taxAmount;

        document.getElementById('previewSubtotal').textContent = `$${subtotal.toFixed(2)}`;
        
        const taxRow = document.getElementById('tax-row');
        if (taxRate > 0) {
            document.getElementById('tax-rate-preview').textContent = taxRate;
            document.getElementById('previewTaxAmount').textContent = `$${taxAmount.toFixed(2)}`;
            taxRow.style.display = 'flex';
        } else {
            taxRow.style.display = 'none';
        }
        document.getElementById('previewTotal').textContent = `$${total.toFixed(2)}`;
    }

    function generatePDF() {
        const invoiceElement = document.getElementById('pdf-preview-content');
        const clientName = document.getElementById('clientName').value.trim().replace(/\s+/g, '_') || "cliente";
        const invoiceId = document.getElementById('previewInvoiceId').textContent;
        const elementsToHide = document.querySelectorAll('.no-print');
        const originalDownloadText = downloadBtn.innerHTML;

        downloadBtn.innerHTML = `<i data-lucide="loader-circle" class="w-6 h-6 mr-3 animate-spin"></i> Generando PDF...`;
        lucide.createIcons();
        downloadBtn.disabled = true;

        elementsToHide.forEach(el => el.style.display = 'none');
        
        try {
            if (document.activeElement && typeof document.activeElement.blur === 'function') {
                document.activeElement.blur();
            }
            
            html2canvas(invoiceElement, { scale: 3, useCORS: true }).then(canvas => {
                const pdf = new jsPDF({ orientation: 'portrait', unit: 'in', format: 'letter' });
                const margin = 0.5;
                const pdfWidth = pdf.internal.pageSize.getWidth();
                const contentWidth = pdfWidth - (margin * 2);
                
                const imgData = canvas.toDataURL('image/png');
                const imgProps = pdf.getImageProperties(imgData);
                const contentHeight = (imgProps.height * contentWidth) / imgProps.width;

                pdf.addImage(imgData, 'PNG', margin, margin, contentWidth, contentHeight);
                pdf.save(`Factura-${invoiceId}-para-${clientName}.pdf`);
            });
        } finally {
            elementsToHide.forEach(el => el.style.display = '');
            downloadBtn.innerHTML = originalDownloadText;
            downloadBtn.disabled = false;
            lucide.createIcons();
        }
    }
    updatePreview();
});
</script>
</body>
</html>