<?php
// =================================================================
// BLOQUE 1: CONFIGURACIÓN
// =================================================================
require_once '../db/business_config.php';
?>
<!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 <?php echo BUSINESS_NAME; ?> | <?php echo PHONE_PRIMARY; ?> — OrozDesign Multimedia</title>
    <meta name="description" content=" — Call Us At <?php echo PHONE_PRIMARY; ?> | <?php echo BUSINESS_NAME; ?> ">

<link rel="icon" type="image/png" sizes="32x32" href="../<?php echo LOGO_FILENAME; ?>">
<link rel="icon" type="image/png" sizes="16x16" href="../<?php echo LOGO_FILENAME; ?>">
<link rel="shortcut icon" href="../<?php echo LOGO_FILENAME; ?>">

<?php require_once '../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@400;700;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">
    
    <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>
    </head>
<body>

<?php require_once '../gtm-body.php'; ?>

<header class="block bg-white border-b border-black/5 shadow-[0_8px_30px_rgba(0,0,0,0.06)]">
  <div class="max-w-7xl mx-auto px-6 lg:px-8 py-5">
    <div class="flex items-center justify-between">
      <div class="flex-shrink-0">
          <a href="dashboard.php" aria-label="Home" class="inline-flex items-center">
            <img
              src="../<?php echo htmlspecialchars(LOGO_FILENAME); ?>"
              alt="<?php echo htmlspecialchars(BUSINESS_NAME); ?> logo"
              class="h-14 lg:h-16 w-auto object-contain"
              loading="eager" decoding="async"
            >
          </a>
      </div>
      <a href="dashboard.php" class="inline-flex items-center gap-2 px-4 py-2 rounded-lg font-bold bg-brand-secondary text-brand-primary transition">
        <i data-lucide="arrow-big-left-dash" class="w-5 h-5"></i>
        <span>REGRESAR AL PORTAL</span>
      </a>
    </div>
  </div>
      <div class="h-1.5 w-full" style="background:#07162d"></div>
</header>

    <div id="content-area" class="p-4 md:p-8">

        <section id="estimator-section">
            <div class="grid grid-cols-1 lg:grid-cols-5 gap-8 max-w-7xl mx-auto">

                <div class="lg:col-span-2">
                    <div class="bg-white p-6 md:p-8 rounded-xl shadow-lg">
                        <form id="invoice-form" class="space-y-8">
                            <div>
                                <h2 class="text-2xl font-black pb-0 mb-1 flex items-center uppercase text-[var(--brand-primary)]">
                                    <i data-lucide="file-pen-line" class="w-6 h-6 mr-3 text-[var(--brand-accent)]"></i>
                                    <span class="text-[var(--brand-accent)] mr-2">PASO 1:</span> Ingresa los Datos
                                </h2>
                            </div>
                            <div class="space-y-4">
                                <h3 class="font-extrabold text-lg capitalize text-[var(--brand-primary)]">Datos De Tu Negocio</h3>
                                <input type="text" id="companyName" name="companyName" placeholder="Nombre De Tu Empresa" class="block w-full rounded-xl border border-gray-200 bg-white pl-4 pr-3 h-12 text-[16px] placeholder-gray-400 shadow-sm focus:outline-none focus:ring-2 focus:ring-[var(--brand-accent)] focus:border-transparent" value="<?php echo htmlspecialchars(BUSINESS_NAME); ?>">
                                <input type="text" id="yourName" name="yourName" placeholder="Tu Nombre (Opcional)" class="block w-full rounded-xl border border-gray-200 bg-white pl-4 pr-3 h-12 text-[16px] placeholder-gray-400 shadow-sm focus:outline-none focus:ring-2 focus:ring-[var(--brand-accent)] focus:border-transparent" value="<?php echo htmlspecialchars(BUSINESS_OWNER); ?>">
                                <input type="email" id="yourEmail" name="yourEmail" placeholder="Tu Email" class="block w-full rounded-xl border border-gray-200 bg-white pl-4 pr-3 h-12 text-[16px] placeholder-gray-400 shadow-sm focus:outline-none focus:ring-2 focus:ring-[var(--brand-accent)] focus:border-transparent" value="<?php echo htmlspecialchars(EMAIL_PRIMARY); ?>">
                                <input type="tel" id="yourPhone" name="yourPhone" placeholder="(XXX) XXX-XXXX" class="block w-full rounded-xl border border-gray-200 bg-white pl-4 pr-3 h-12 text-[16px] placeholder-gray-400 shadow-sm focus:outline-none focus:ring-2 focus:ring-[var(--brand-accent)] focus:border-transparent" value="<?php echo htmlspecialchars(PHONE_PRIMARY); ?>">
                                <div>
                                    <label for="logoUpload" class="block font-extrabold capitalize text-[var(--brand-primary)] 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-extrabold text-lg capitalize text-[var(--brand-primary)]">Datos Del Cliente</h3>
                                <input type="text" id="clientName" name="clientName" placeholder="Nombre Del Cliente" class="block w-full rounded-xl border border-gray-200 bg-white pl-4 pr-3 h-12 text-[16px] placeholder-gray-400 shadow-sm focus:outline-none focus:ring-2 focus:ring-[var(--brand-accent)] focus:border-transparent">
                                <input type="text" id="clientAddress" name="clientAddress" placeholder="Dirección Del Cliente (Opcional)" class="block w-full rounded-xl border border-gray-200 bg-white pl-4 pr-3 h-12 text-[16px] placeholder-gray-400 shadow-sm focus:outline-none focus:ring-2 focus:ring-[var(--brand-accent)] focus:border-transparent">
                            </div>
                            <div class="space-y-4">
                                <h3 class="font-extrabold text-lg capitalize text-[var(--brand-primary)]">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-[var(--brand-primary)] text-white font-bold py-3 px-6 rounded-lg hover:brightness-125 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-extrabold capitalize text-[var(--brand-primary)] mb-2 text-lg">Impuesto (%)</label>
                                    <input type="number" id="tax-rate" name="tax-rate" placeholder="Ej: 7" step="0.1" min="0" class="block w-full rounded-xl border border-gray-200 bg-white pl-4 pr-3 h-12 text-[16px] placeholder-gray-400 shadow-sm focus:outline-none focus:ring-2 focus:ring-[var(--brand-accent)] focus:border-transparent">
                                </div>
                            </div>
                        </form>
                    </div>
                </div>

                <div class="lg:col-span-3">
                    <div class="bg-white p-6 md:p-8 rounded-xl shadow-lg">
                        <div>
                            <h2 class="text-2xl font-black pb-0 mb-1 flex items-center uppercase text-[var(--brand-primary)]">
                                <i data-lucide="eye" class="w-6 h-6 mr-3 text-[var(--brand-accent)]"></i>
                                <span class="text-[var(--brand-accent)] mr-2">PASO 2:</span> Revisa y Descarga
                            </h2>
                        </div>
                        <div class="mb-4 mt-8">
                            <label for="payment-status" class="block font-extrabold capitalize text-[var(--brand-primary)] mb-2 text-lg">Estado De La Factura</label>
                            <select id="payment-status" class="block w-full rounded-xl border border-gray-200 bg-white pl-4 pr-10 h-12 text-[16px] shadow-sm appearance-none focus:outline-none focus:ring-2 focus:ring-[var(--brand-accent)] focus:border-transparent">
                                <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 htmlspecialchars(LOGO_FILENAME); ?>" alt="Company Logo" class="h-16 mb-4 object-contain">
                                        <h2 id="previewCompanyName" class="text-xl font-black text-gray-800" contenteditable="true"></h2>
                                        <p id="previewYourName" class="text-sm text-gray-600" contenteditable="true"></p>
                                        <p id="previewYourEmail" class="text-sm text-gray-600" contenteditable="true"></p>
                                        <p id="previewYourPhone" class="text-sm text-gray-600" contenteditable="true"></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"></p>
                                    <p id="previewClientAddress" class="text-gray-700 text-sm" contenteditable="true"></p>
                                </div>
                                <table class="w-full mb-6 text-sm">
                                    <thead>
                                        <tr class="bg-[var(--brand-primary)] text-white">
                                            <th class="text-left p-2 font-bold tracking-wider rounded-l-md">DESCRIPTION</th>
                                            <th class="text-right p-2 font-bold tracking-wider">PRICE</th>
                                            <th class="w-10 no-print rounded-r-md"></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>Taxes (<span id="tax-rate-preview">0</span>%)</span>
                                            <span id="previewTaxAmount">$0.00</span>
                                        </div>
                                        <div class="flex justify-between text-[var(--brand-primary)] font-extrabold text-lg bg-[var(--brand-secondary)]/20 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(--brand-accent)] text-white font-extrabold py-4 px-6 rounded-lg shadow-lg text-lg flex items-center justify-center uppercase transition-transform hover:-translate-y-0.5 active:translate-y-0">
                            <i data-lucide="download" class="w-6 h-6 mr-3"></i>
                            Descargar Factura Digital
                        </button>
                    </div>
                </div>
            </div>
        </section>
    </div>

    <footer class="mt-auto bg-[var(--brand-dark)] text-white py-6">
        <div class="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8 text-center">
            <p class="text-xs text-gray-500 text-center">© <?php echo date('Y'); ?> <?php echo htmlspecialchars(BUSINESS_NAME); ?>. Todos Los Derechos Reservados</p>
            <div class="footer-logo-container flex justify-center mt-4">
                <a href="https://orozdesign.com/?utm_source=LinksWebs&amp;utm_medium=Organico&amp;utm_campaign=LocalCRM-ToolKit" target="_blank">
                    <img src="https://orozdesign.net/admin/orozdesign/PoweredByOROZCO.png" alt="OrozDesign Multimedia" height="25px" width="auto" onerror="this.onerror=null; this.src='https://placehold.co/100x25/f5f5f5/2a9d8f?text=Powered+by+OROZCO';"/>
                </a>
            </div>
    </footer>
    
<script type="module">
document.addEventListener('DOMContentLoaded', function() {
    lucide.createIcons();
    window.jsPDF = window.jspdf.jsPDF;

    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');
    
    if (yourPhoneInput) IMask(yourPhoneInput, { mask: '(000) 000-0000' });
    if(form) form.addEventListener('input', updatePreview);
    if(downloadBtn) downloadBtn.addEventListener('click', generatePDF);
    if(paymentStatusSelect) paymentStatusSelect.addEventListener('change', updatePaymentStatus);
    if(addItemBtn) addItemBtn.addEventListener('click', () => addManualItem());

    if(logoUploadInput) {
        logoUploadInput.addEventListener('change', function(event) {
            const file = event.target.files[0];
            if (file) {
                const reader = new FileReader();
                reader.onload = function(e) {
                    if(logoPreviewImg) logoPreviewImg.src = e.target.result;
                };
                reader.readAsDataURL(file);
            }
        });
    }
    
    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', () => {
            document.querySelector(`.manual-item-form[data-id="${id}"]`)?.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="block w-full rounded-xl border border-gray-200 bg-white pl-4 pr-3 h-12 text-[16px] placeholder-gray-400 shadow-sm focus:outline-none focus:ring-2 focus:ring-[var(--brand-accent)] focus:border-transparent manual-item-desc"></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="block w-full rounded-xl border border-gray-200 bg-white pl-4 pr-3 h-12 text-[16px] placeholder-gray-400 shadow-sm focus:outline-none focus:ring-2 focus:ring-[var(--brand-accent)] focus:border-transparent manual-item-price"></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>`;
        if(serviceItemsContainer) serviceItemsContainer.appendChild(newItemContainer);
        newItemContainer.querySelector('.manual-item-desc').focus();
        lucide.createIcons();
        newItemContainer.querySelector('.delete-manual-item-btn').addEventListener('click', () => {
            newItemContainer.remove();
            updatePreview();
        });
    }

    function updatePaymentStatus() {
        if (!paymentStamp) return;
        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() {
        // --- Actualización de datos básicos ---
        document.getElementById('previewCompanyName').textContent = document.getElementById('companyName').value || "Nombre De Tu Empresa";
        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('previewDate').textContent = new Date().toLocaleDateString('en-US');

        // --- CAMBIO: Lógica para ocultar campos si están vacíos ---
        const yourNameValue = document.getElementById('yourName').value.trim();
        const previewYourNameEl = document.getElementById('previewYourName');
        if (yourNameValue) {
            previewYourNameEl.textContent = yourNameValue;
            previewYourNameEl.style.display = 'block';
        } else {
            previewYourNameEl.style.display = 'none';
        }

        const clientAddressValue = document.getElementById('clientAddress').value.trim();
        const previewClientAddressEl = document.getElementById('previewClientAddress');
        if (clientAddressValue) {
            previewClientAddressEl.textContent = clientAddressValue;
            previewClientAddressEl.style.display = 'block';
        } else {
            previewClientAddressEl.style.display = 'none';
        }
        // --- FIN DEL CAMBIO ---

        const invoiceIdEl = document.getElementById('previewInvoiceId');
        if (invoiceIdEl.textContent === '0001' && document.getElementById('clientName').value) {
            invoiceIdEl.textContent = Math.floor(1000 + Math.random() * 9000);
        }

        if(invoiceItemsBody) invoiceItemsBody.innerHTML = '';
        let hasItems = false;
        document.querySelectorAll('.manual-item-form').forEach(itemDiv => {
            const desc = itemDiv.querySelector('.manual-item-desc').value;
            const price = itemDiv.querySelector('.manual-item-price').value;
            if (desc && price && parseFloat(price) > 0) {
                if(invoiceItemsBody) invoiceItemsBody.appendChild(createItemRow(itemDiv.dataset.id, desc, price));
                hasItems = true;
            }
        });
        if (!hasItems && invoiceItemsBody && initialPlaceholder) invoiceItemsBody.appendChild(initialPlaceholder);
        
        recalculateTotal();
    }

    function recalculateTotal() {
        let subtotal = 0;
        if(invoiceItemsBody) {
            invoiceItemsBody.querySelectorAll('.item-price').forEach(cell => {
                subtotal += parseFloat(cell.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)}`;
            if(taxRow) taxRow.style.display = 'flex';
        } else {
            if(taxRow) taxRow.style.display = 'none';
        }
        document.getElementById('previewTotal').textContent = `$${total.toFixed(2)}`;
    }

    function generatePDF() {
        const invoiceElement = document.getElementById('pdf-preview-content');
        if(!invoiceElement || !downloadBtn) return;
        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 {
            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();
            });
        } catch (e) {
            elementsToHide.forEach(el => el.style.display = '');
            downloadBtn.innerHTML = originalDownloadText;
            downloadBtn.disabled = false;
            lucide.createIcons();
        }
    }
    
    updatePreview();
});
</script>
</body>
</html>