<!DOCTYPE html>
<html lang="es">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Nueva Cotización</title>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/css/bootstrap.min.css" rel="stylesheet">
    <link href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.0.0/css/all.min.css" rel="stylesheet">
</head>
<body>
    <div class="container mt-5">
        <div class="d-flex justify-content-between align-items-center mb-4">
            <h2><i class="fas fa-file-invoice"></i> Nueva Cotización</h2>
            <a href="<?= base_url('index.php/cotizaciones') ?>" class="btn btn-secondary">
                <i class="fas fa-arrow-left"></i> Volver
            </a>
        </div>

        <form action="<?= base_url('index.php/cotizaciones/guardar') ?>" method="POST">
            <input type="hidden" name="<?= $this->security->get_csrf_token_name(); ?>" value="<?= $this->security->get_csrf_hash(); ?>">

            <div class="card mb-3">
                <div class="card-header">
                    <h5>Información General</h5>
                </div>
                <div class="card-body">
                    <div class="row g-3">
                        <div class="col-md-3">
                            <label class="form-label">Número de Cotización</label>
                            <input type="text" class="form-control" value="<?= $numero ?>" readonly>
                        </div>

                        <div class="col-md-3">
                            <label class="form-label">Fecha *</label>
                            <input type="date" name="fecha" class="form-control" value="<?= date('Y-m-d') ?>" required>
                        </div>

                        <div class="col-md-3">
                            <label class="form-label">Vigencia (días) *</label>
                            <input type="number" name="vigencia_dias" class="form-control" value="30" required>
                        </div>

                        <div class="col-md-3">
                            <label class="form-label">Moneda *</label>
                            <select name="moneda" id="moneda" class="form-select" required>
                                <option value="MXN" selected>MXN – Peso mexicano</option>
                                <option value="USD">USD – Dólar estadounidense</option>
                            </select>
                        </div>

                        <div class="col-md-12">
                            <div class="mb-2">
                                <label class="form-label d-block">Tipo de Inversión *</label>
                                <div class="form-check form-check-inline">
                                    <input class="form-check-input" type="radio" name="tipo_inversion" id="inversion_mensual" value="INVERSIÓN MENSUAL" checked>
                                    <label class="form-check-label" for="inversion_mensual">INVERSIÓN MENSUAL</label>
                                </div>
                                <div class="form-check form-check-inline">
                                    <input class="form-check-input" type="radio" name="tipo_inversion" id="inversion_implementacion" value="INVERSIÓN IMPLEMENTACIÓN">
                                    <label class="form-check-label" for="inversion_implementacion">INVERSIÓN IMPLEMENTACIÓN</label>
                                </div>
                                <div class="form-check form-check-inline">
                                    <input class="form-check-input" type="radio" name="tipo_inversion" id="inversion_inicial" value="INVERSIÓN INICIAL CON 1 MES DE LICENCIA">
                                    <label class="form-check-label" for="inversion_inicial">INVERSIÓN INICIAL CON 1 MES DE LICENCIA</label>
                                </div>
                                <div class="form-check form-check-inline">
                                    <input class="form-check-input" type="radio" name="tipo_inversion" id="inversion_total_anual" value="INVERSIÓN TOTAL ANUAL">
                                    <label class="form-check-label" for="inversion_total_anual">INVERSIÓN TOTAL ANUAL</label>
                                </div>
                            </div>
                        </div>

                        <div class="col-md-12">
                            <label class="form-label">Cliente *</label>
                            <select name="cliente_id" class="form-select" required>
                                <option value="">Seleccione un cliente</option>
                                <?php foreach($clientes as $cliente): ?>
                                    <option value="<?= $cliente->id ?>">
                                        <?= $cliente->nombre ?> <?= $cliente->empresa ? '- ' . $cliente->empresa : '' ?>
                                    </option>
                                <?php endforeach; ?>
                            </select>
                        </div>
                    </div>
                </div>
            </div>

            <!-- Items -->
            <div class="card mb-3">
                <div class="card-header d-flex justify-content-between align-items-center">
                    <h5>Items de la Cotización</h5>
                    <button type="button" class="btn btn-sm btn-primary" onclick="agregarItem()">
                        <i class="fas fa-plus"></i> Agregar Item
                    </button>
                </div>
                <div class="card-body">
                    <div id="items-container">
                        <div class="item-row border p-3 mb-3 rounded">
                            <div class="row g-3">
                                <div class="col-md-3">
                                    <label class="form-label">Servicio *</label>
                                    <input type="text" name="servicio[]" class="form-control snip-target" required>
                                </div>
                                <div class="col-md-4">
                                    <label class="form-label">Descripción *</label>
                                    <textarea name="descripcion[]" class="form-control snip-target" rows="3" required></textarea>
                                </div>
                                <div class="col-md-2">
                                    <label class="form-label">Cantidad *</label>
                                    <input type="number" name="cantidad[]" class="form-control cantidad" value="1" min="1" required onchange="calcularTotales()">
                                </div>
                                <div class="col-md-2">
                                    <label class="form-label">Precio Unit. *</label>
                                    <input type="number" step="any" name="precio_unitario[]" class="form-control precio" required onchange="calcularTotales()">
                                </div>
                                <div class="col-md-1 d-flex align-items-end">
                                    <button type="button" class="btn btn-danger btn-sm w-100" onclick="eliminarItem(this)" style="margin-bottom: 8px;">
                                        <i class="fas fa-trash"></i>
                                    </button>
                                </div>
                            </div>
                        </div>
                    </div>

                    <div class="row mt-3 g-3">
                        <div class="col-md-3">
                            <div class="form-check mt-2">
                                <input class="form-check-input" type="checkbox" id="aplicar_iva" name="aplicar_iva" checked>
                                <label class="form-check-label" for="aplicar_iva">Aplicar IVA</label>
                            </div>
                        </div>
                        <div class="col-md-3">
                            <label class="form-label">IVA (%)</label>
                            <input type="number" step="any" min="0" id="iva_porcentaje" name="iva_porcentaje" class="form-control" value="16" oninput="calcularTotales()">
                            <div class="form-text">MXN: 16% • USD: 0% típico</div>
                        </div>
                    </div>
                </div>
            </div>

            <!-- Observaciones -->
            <div class="card mb-3">
                <div class="card-header">
                    <h5>Observaciones</h5>
                </div>
                <div class="card-body">
                    <textarea name="observaciones" class="form-control snip-target" rows="5" placeholder="Términos y condiciones adicionales..."></textarea>
                </div>
            </div>

            <!-- Totales -->
            <div class="card mb-3">
                <div class="card-body">
                    <div class="row">
                        <div class="col-md-8"></div>
                        <div class="col-md-4">
                            <table class="table">
                                <tr><td><strong>Subtotal:</strong></td><td class="text-end"><span id="currencySymbol">$</span><span id="subtotal">0.00</span> <span id="currencyCode">MXN</span></td></tr>
                                <tr>
                                    <td><strong>Descuento:</strong></td>
                                    <td class="text-end">
                                        <div class="input-group input-group-sm">
                                            <span class="input-group-text" id="currencySymbolDesc">$</span>
                                            <input type="number" step="any" min="0" name="descuento" id="descuento" class="form-control text-end" value="0.00" oninput="calcularTotales()">
                                            <span class="input-group-text" id="currencyCodeDesc">MXN</span>
                                        </div>
                                    </td>
                                </tr>
                                <tr><td><strong>Base (Subt. - Desc.):</strong></td><td class="text-end"><span id="currencySymbolBase">$</span><span id="base">0.00</span> <span id="currencyCodeBase">MXN</span></td></tr>
                                <tr><td><strong>IVA (<span id="ivaLabel">16</span>%):</strong></td><td class="text-end"><span id="currencySymbolIva">$</span><span id="iva">0.00</span> <span id="currencyCodeIva">MXN</span></td></tr>
                                <tr class="table-primary"><td><strong>TOTAL:</strong></td><td class="text-end"><strong><span id="currencySymbolTotal">$</span><span id="total">0.00</span> <span id="currencyCodeTotal">MXN</span></strong></td></tr>
                            </table>
                        </div>
                    </div>
                </div>
            </div>

            <div class="text-end mb-5">
                <button type="submit" class="btn btn-success btn-lg">
                    <i class="fas fa-save"></i> Guardar Cotización
                </button>
            </div>
        </form>
    </div>

    <!-- FAB + Panel Snippets -->
    <style>
        #snipFab { position: fixed; right: 18px; bottom: 18px; z-index: 1040;
        width: 56px; height: 56px; border-radius: 50%;
        display:flex; align-items:center; justify-content:center; box-shadow: 0 8px 20px rgba(0,0,0,.2); }
        .offcanvas-end { width: 420px; }
        .snip-item { border:1px solid #eee; border-radius:8px; padding:10px; margin-bottom:10px; }
        .snip-actions { gap:6px; }
    </style>

    <button id="snipFab" type="button" class="btn btn-primary" data-bs-toggle="offcanvas" data-bs-target="#snipPanel">
        <i class="fa fa-sticky-note"></i>
    </button>

    <div class="offcanvas offcanvas-end" tabindex="-1" id="snipPanel">
        <div class="offcanvas-header">
            <h5 class="offcanvas-title"><i class="fa fa-bolt"></i> Rápidos / Notas</h5>
            <button type="button" class="btn-close" data-bs-dismiss="offcanvas"></button>
        </div>
        <div class="offcanvas-body">
            <div class="mb-3 border rounded p-2">
                <div class="row g-2">
                    <div class="col-5"><select id="snipTipo" class="form-select"><option value="servicio">Servicio</option><option value="descripcion">Descripción</option><option value="observacion">Observación</option></select></div>
                    <div class="col-7"><input id="snipTitulo" type="text" class="form-control" placeholder="Título (obligatorio)"></div>
                    <div class="col-12"><textarea id="snipContenido" class="form-control" rows="3" placeholder="Contenido (obligatorio)"></textarea></div>
                    <div class="col-6 d-grid"><button type="button" class="btn btn-outline-secondary" id="btnSnapFromField">Tomar del campo activo</button></div>
                    <div class="col-6 d-grid"><button type="button" class="btn btn-success" id="btnSaveSnippet">Guardar</button></div>
                </div>
            </div>

            <div class="row g-2 mb-2">
                <div class="col-6"><select id="snipFilterTipo" class="form-select"><option value="">Todos</option><option value="servicio">Servicio</option><option value="descripcion">Descripción</option><option value="observacion">Observación</option></select></div>
                <div class="col-6"><input id="snipSearch" type="search" class="form-control" placeholder="Buscar..."></div>
            </div>

            <div id="snipList"></div>
        </div>
    </div>

    <!-- === SCRIPTS === -->
    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/js/bootstrap.bundle.min.js"></script>
    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/js/bootstrap.bundle.min.js"></script>
<script>
    // ====== Totales ======
    function formateaNumero(n){ return (isFinite(n) ? n : 0).toFixed(2); }
    const monedaSelect = document.getElementById('moneda');
    const aplicarIvaChk = document.getElementById('aplicar_iva');
    const ivaPorcentaje = document.getElementById('iva_porcentaje');
    const ivaLabel = document.getElementById('ivaLabel');

    function getCurrencyMeta(code){ return code === 'USD' ? {symbol:'$',code:'USD',defaultIva:0} : {symbol:'$',code:'MXN',defaultIva:16}; }
    function syncCurrencyUi(){
        const m = getCurrencyMeta(monedaSelect.value);
        document.getElementById('currencySymbol').textContent=m.symbol;
        document.getElementById('currencySymbolDesc').textContent=m.symbol;
        document.getElementById('currencySymbolBase').textContent=m.symbol;
        document.getElementById('currencySymbolIva').textContent=m.symbol;
        document.getElementById('currencySymbolTotal').textContent=m.symbol;

        document.getElementById('currencyCode').textContent=m.code;
        document.getElementById('currencyCodeDesc').textContent=m.code;
        document.getElementById('currencyCodeBase').textContent=m.code;
        document.getElementById('currencyCodeIva').textContent=m.code;
        document.getElementById('currencyCodeTotal').textContent=m.code;

        if (m.code === 'USD'){ aplicarIvaChk.checked=false; ivaPorcentaje.value=m.defaultIva; }
        else { aplicarIvaChk.checked=true; ivaPorcentaje.value=m.defaultIva; }
        ivaPorcentaje.disabled = !aplicarIvaChk.checked;
        ivaLabel.textContent = formateaNumero(parseFloat(ivaPorcentaje.value||0)).replace('.00','');
        calcularTotales();
    }
    function calcularTotales(){
        const cantidades=document.querySelectorAll('.cantidad');
        const precios=document.querySelectorAll('.precio');
        let subtotal=0;
        for(let i=0;i<cantidades.length;i++){
            const c=parseFloat(cantidades[i].value)||0;
            const p=parseFloat(precios[i].value)||0;
            subtotal += c*p;
        }
        const descInput=document.getElementById('descuento');
        let descuento=parseFloat(descInput.value)||0;
        if(descuento<0)descuento=0;
        if(descuento>subtotal)descuento=subtotal;
        descInput.value=formateaNumero(descuento);

        const base=subtotal-descuento;
        let iva=0;
        if(aplicarIvaChk.checked){
            const pct=Math.max(0, parseFloat(ivaPorcentaje.value)||0);
            iva=base*(pct/100);
            ivaLabel.textContent=(pct%1===0)?pct.toString():pct.toFixed(2);
        } else { iva=0; ivaLabel.textContent='0'; }
        const total=base+iva;

        document.getElementById('subtotal').textContent=formateaNumero(subtotal);
        document.getElementById('base').textContent=formateaNumero(base);
        document.getElementById('iva').textContent=formateaNumero(iva);
        document.getElementById('total').textContent=formateaNumero(total);
    }
    function agregarItem(){
        const container=document.getElementById('items-container');
        const div=document.createElement('div');
        div.className='item-row border p-3 mb-3 rounded';
        div.innerHTML=`
            <div class="row g-3">
                <div class="col-md-3">
                    <label class="form-label">Servicio *</label>
                    <input type="text" name="servicio[]" class="form-control snip-target" required>
                </div>
                <div class="col-md-4">
                    <label class="form-label">Descripción *</label>
                    <textarea name="descripcion[]" class="form-control snip-target" rows="3" required></textarea>
                </div>
                <div class="col-md-2">
                    <label class="form-label">Cantidad *</label>
                    <input type="number" name="cantidad[]" class="form-control cantidad" value="1" min="1" required onchange="calcularTotales()">
                </div>
                <div class="col-md-2">
                    <label class="form-label">Precio Unit. *</label>
                    <input type="number" step="any" name="precio_unitario[]" class="form-control precio" required onchange="calcularTotales()">
                </div>
                <div class="col-md-1 d-flex align-items-end">
                    <button type="button" class="btn btn-danger btn-sm w-100" onclick="eliminarItem(this)" style="margin-bottom: 8px;">
                        <i class="fas fa-trash"></i>
                    </button>
                </div>
            </div>`;
        container.appendChild(div);
    }
    function eliminarItem(btn){
        const items=document.querySelectorAll('.item-row');
        if(items.length>1){ btn.closest('.item-row').remove(); calcularTotales(); }
        else alert('Debe haber al menos un item en la cotización');
    }
    document.addEventListener('DOMContentLoaded', ()=>{ syncCurrencyUi(); calcularTotales(); });
    monedaSelect.addEventListener('change', syncCurrencyUi);
    aplicarIvaChk.addEventListener('change', ()=>{ ivaPorcentaje.disabled=!aplicarIvaChk.checked; calcularTotales(); });
    ivaPorcentaje.addEventListener('input', calcularTotales);

    // ====== Snippets (Rápidos) ======
    let CSRF_NAME='<?= $this->security->get_csrf_token_name(); ?>';
    let CSRF_HASH='<?= $this->security->get_csrf_hash(); ?>';
    let lastFocused=null;

    // 🔁 Nueva función para refrescar token
    function refreshCsrfToken(data) {
        if (data && data.csrf && data.csrf.hash) {
            CSRF_HASH = data.csrf.hash;
        }
    }

    document.addEventListener('focusin',(e)=>{ if(e.target?.classList?.contains('snip-target')) lastFocused=e.target; });
    function insertAtCaret(el,text){ el?.focus(); if(typeof el.selectionStart==='number'){const s=el.selectionStart,e=el.selectionEnd; el.value=el.value.substring(0,s)+text+el.value.substring(e); el.selectionStart=el.selectionEnd=s+text.length;}else{ el.value+=text; } }
    function qs(id){ return document.getElementById(id); }
    function encodeForm(obj){ return Object.entries(obj).map(([k,v])=>encodeURIComponent(k)+'='+encodeURIComponent(v)).join('&'); }
    function escapeHtml(s){ return String(s).replace(/[&<>"']/g,m=>({ '&':'&amp;','<':'&lt;','>':'&gt;','"':'&quot;',"'":'&#39;' }[m])); }

    async function loadSnippets(){
        const tipo=qs('snipFilterTipo').value; const q=qs('snipSearch').value.trim();
        const url=new URL('<?= base_url('index.php/snippets'); ?>', window.location.origin);
        if(tipo) url.searchParams.set('tipo',tipo); if(q) url.searchParams.set('q',q);
        const r=await fetch(url.toString(),{credentials:'same-origin'});
        const d=await r.json();
        refreshCsrfToken(d);

        const list=qs('snipList'); list.innerHTML='';
        if(!d.ok || !d.items?.length){ list.innerHTML='<div class="text-muted small">No hay notas aún.</div>'; return; }
        d.items.forEach(row=>{
            const div=document.createElement('div'); div.className='snip-item';
            div.innerHTML=`
              <div class="d-flex justify-content-between">
                <div><span class="badge bg-secondary me-2">${row.tipo}</span><strong>${escapeHtml(row.titulo)}</strong></div>
                <div class="snip-actions d-flex">
                  <button class="btn btn-sm ${row.pinned?'btn-warning':'btn-outline-warning'} btn-pin" title="Fijar"><i class="fa fa-thumbtack"></i></button>
                  <button class="btn btn-sm btn-outline-danger btn-del" title="Eliminar"><i class="fa fa-trash"></i></button>
                </div>
              </div>
              <div class="mt-2 small" style="white-space:pre-wrap">${row.contenido}</div>
              <div class="mt-2 d-flex justify-content-between align-items-center">
                <button class="btn btn-sm btn-primary btn-paste"><i class="fa fa-paste"></i> Pegar</button>
                <span class="text-muted small">Usos: ${row.uso_count}</span>
              </div>`;

            // Pegar
            div.querySelector('.btn-paste').onclick=async()=>{
                if(!lastFocused){ alert('Selecciona un campo para pegar.'); return; }
                insertAtCaret(lastFocused,row.contenido);
                const r = await fetch('<?= base_url('index.php/snippets'); ?>/'+row.id+'/used',{
                    method:'POST',headers:{'Content-Type':'application/x-www-form-urlencoded'},
                    body:encodeForm({[CSRF_NAME]:CSRF_HASH})
                });
                const data = await r.json();
                refreshCsrfToken(data);
                loadSnippets();
            };

            // Borrar
            div.querySelector('.btn-del').onclick=async()=>{
                if(!confirm('¿Eliminar esta nota?')) return;
                const r = await fetch('<?= base_url('index.php/snippets'); ?>/'+row.id+'/delete',{
                    method:'POST',headers:{'Content-Type':'application/x-www-form-urlencoded'},
                    body:encodeForm({[CSRF_NAME]:CSRF_HASH})
                });
                const data = await r.json();
                refreshCsrfToken(data);
                loadSnippets();
            };

            // Fijar
            div.querySelector('.btn-pin').onclick=async()=>{
                const r = await fetch('<?= base_url('index.php/snippets'); ?>/'+row.id,{
                    method:'POST',headers:{'Content-Type':'application/x-www-form-urlencoded'},
                    body:encodeForm({pinned: row.pinned?0:1, [CSRF_NAME]:CSRF_HASH})
                });
                const data = await r.json();
                refreshCsrfToken(data);
                loadSnippets();
            };
            list.appendChild(div);
        });
    }

    function getSel(el){ if(typeof el.selectionStart==='number') return el.value.substring(el.selectionStart, el.selectionEnd); return ''; }

    // Guardar snippet
    qs('btnSaveSnippet').addEventListener('click', async ()=>{
        const tipo=qs('snipTipo').value; const titulo=qs('snipTitulo').value.trim(); const contenido=qs('snipContenido').value;
        if(!titulo || !contenido){ alert('Título y contenido son obligatorios'); return; }
        const r = await fetch('<?= base_url('index.php/snippets'); ?>',{
            method:'POST', headers:{'Content-Type':'application/x-www-form-urlencoded'},
            body:encodeForm({tipo,titulo,contenido,pinned:0,[CSRF_NAME]:CSRF_HASH})
        });
        const data = await r.json();
        refreshCsrfToken(data);
        qs('snipTitulo').value=''; qs('snipContenido').value='';
        loadSnippets();
    });

    qs('btnSnapFromField').addEventListener('click', ()=>{
        if(!lastFocused){ alert('Haz clic en un campo (servicio/descripcion/observaciones)'); return; }
        const name=(lastFocused.getAttribute('name')||'').toLowerCase();
        let tipo='descripcion'; if(name.includes('observaciones'))tipo='observacion'; else if(name.includes('servicio'))tipo='servicio';
        qs('snipTipo').value=tipo;
        const val=lastFocused.value||''; const sel=getSel(lastFocused)||'';
        qs('snipContenido').value= sel || val;
        qs('snipTitulo').value= (sel || val).split(/\s+/).slice(0,8).join(' ').substring(0,160);
    });

    qs('snipFilterTipo').addEventListener('change', loadSnippets);
    qs('snipSearch').addEventListener('input', ()=>{ clearTimeout(window.__snT); window.__snT=setTimeout(loadSnippets,250); });
    document.addEventListener('DOMContentLoaded', loadSnippets);
</script>
</body>
</html>
