<?php
require_once '../../core/config.php';
require_once '../../core/session.php';
require_once '../../core/database.php';
require_once '../../core/auth.php';
require_once '../../core/permissions.php';

require_login();

if (!user_can('billing.inbox') && !user_can('billing.inbox.receive') && !user_can('module.billing') && current_user_role() !== 'admin') {
    http_response_code(403);
    die('No tienes permisos para acceder a Recepcion DTE.');
}

$page_title = 'Recibir DTE';

require_once '../../layouts/header.php';
require_once '../../layouts/sidebar.php';
?>

<main class="app-main billing-integrated-main" id="billingReceiveMain">
    <?php require_once '../../layouts/topbar.php'; ?>
    <section class="content billing-phase-content billing-receive-content">

<div id="receiveMain" class="receive-main">
    <div class="receive-header">
        <div>
            <h1>Recepcion y aprobacion DTE</h1>
            <p>Aprueba, rechaza y registra recepcion de mercaderia o servicios desde documentos recibidos.</p>
        </div>
        <div class="receive-header-actions">
            <select id="receiveEnv" class="receive-input">
                <option value="sandbox">Sandbox</option>
                <option value="production">Produccion</option>
            </select>
            <button type="button" class="btn btn-primary" id="reloadReceiveBtn">Actualizar</button>
        </div>
    </div>

    <div class="receive-tabs" id="receiveTabs">
        <button type="button" class="receive-tab is-active" data-tab="pending">Pendientes · <span>0</span></button>
        <button type="button" class="receive-tab" data-tab="soon">SII aprueba pronto · <span>0</span></button>
        <button type="button" class="receive-tab" data-tab="without_po">Sin orden de compra · <span>0</span></button>
        <button type="button" class="receive-tab" data-tab="approved">Aprobados · <span>0</span></button>
        <button type="button" class="receive-tab" data-tab="rejected">Rechazados · <span>0</span></button>
    </div>

    <div class="receive-card receive-filter-card">
        <h2>Filtros de busqueda</h2>
        <div class="receive-filters">
            <select id="receiveStatus" class="receive-input">
                <option value="">Estado segun pestaña</option>
                <option value="all">Todos</option>
                <option value="pending">Pendiente</option>
                <option value="approved">Aprobado</option>
                <option value="approved_with_observations">Aprobado con reparo</option>
                <option value="merchandise_received">Mercaderia/servicio recibido</option>
                <option value="rejected">Rechazado</option>
                <option value="error">Error</option>
            </select>
            <select id="receiveType" class="receive-input"><option value="all">Tipo de documento: todos</option></select>
            <input id="receiveRut" class="receive-input" placeholder="RUT proveedor">
            <input id="receiveFolio" class="receive-input" placeholder="Folio">
            <input id="receivePo" class="receive-input" placeholder="Numero de orden de compra">
            <button type="button" class="btn btn-success" id="searchReceiveBtn">Buscar</button>
        </div>
    </div>

    <div class="receive-card receive-results-card">
        <div class="receive-results-head">
            <div>
                <h2>Documentos leidos desde FACTO/SII</h2>
                <p id="receiveResultsHint">Documentos recibidos pendientes de decision.</p>
            </div>
            <div class="receive-bulk-actions">
                <span class="receive-selected-count"><strong id="receiveSelectedCount">0</strong> seleccionados</span>
                <button type="button" class="btn btn-success" id="openBulkReceiveBtn" disabled>Aprobar / rechazar seleccionados</button>
                <button type="button" class="btn btn-outline" id="clearReceiveFiltersBtn">Nueva busqueda</button>
            </div>
        </div>
        <div class="receive-table-wrap">
            <table class="receive-table">
                <thead>
                    <tr>
                        <th style="width:42px;"><input type="checkbox" id="receiveSelectAll" aria-label="Seleccionar documentos visibles"></th>
                        <th>RUT</th>
                        <th>Proveedor</th>
                        <th>Tipo</th>
                        <th>Folio</th>
                        <th>Fecha emision</th>
                        <th>Condicion</th>
                        <th>Total</th>
                        <th>Orden compra</th>
                        <th>Vence</th>
                        <th>SII aprueba en</th>
                        <th>Rec. SII</th>
                        <th>Rec. FACTO</th>
                        <th>Estado</th>
                        <th></th>
                    </tr>
                </thead>
                <tbody id="receiveRows"><tr><td colspan="15">Cargando...</td></tr></tbody>
            </table>
        </div>
        <div class="receive-info-note"><strong>Como funciona la aprobacion SII:</strong> los DTE recibidos tienen plazo acotado para aprobar o reclamar. Si no actuas, el documento puede avanzar a aceptacion tacita.</div>
    </div>
</div>

<div id="receiveModal" class="product-modal-backdrop" style="display:none;">
    <div class="product-modal-box receive-modal-box">
        <div class="product-modal-header">
            <div>
                <h2 id="receiveModalTitle">Aprobacion / Rechazo comercial</h2>
                <p id="receiveModalSubtitle" class="receive-muted"></p>
            </div>
            <button type="button" class="product-modal-close" id="closeReceiveModalBtn">×</button>
        </div>
        <div class="product-modal-body" id="receiveModalBody"></div>
        <div class="product-modal-footer" id="receiveModalFooter"></div>
    </div>
</div>

<style>
.receive-main{padding:18px;display:flex;flex-direction:column;gap:16px;min-height:100%;}
.receive-header{display:flex;align-items:flex-start;justify-content:space-between;gap:16px;}
.receive-header h1{margin:0;font-size:1.45rem;font-weight:800;color:#111827;}
.receive-header p{margin:4px 0 0;color:#6b7280;font-size:.9rem;}
.receive-header-actions{display:flex;gap:8px;align-items:center;}
.receive-card{background:#fff;border:1px solid #e5e7eb;border-radius:16px;box-shadow:0 2px 8px rgba(15,23,42,.05);}
.receive-filter-card{padding:16px;}
.receive-filter-card h2,.receive-results-head h2{font-size:1rem;text-transform:uppercase;letter-spacing:.04em;margin:0 0 14px;color:#1f2937;}
.receive-filters{display:grid;grid-template-columns:repeat(4,minmax(0,1fr));gap:12px;align-items:end;}
.receive-input{height:42px;border:1px solid #d1d5db;border-radius:10px;padding:0 12px;font-size:.9rem;background:#fff;color:#111827;min-width:0;}
.receive-tabs{display:flex;gap:8px;align-items:center;overflow:auto;padding:2px 0;}
.receive-tab{border:0;background:#fff;color:#475569;border-radius:999px;padding:9px 14px;font-weight:700;white-space:nowrap;cursor:pointer;}
.receive-tab.is-active{background:#e0f2fe;color:#0369a1;}
.receive-results-card{display:flex;flex-direction:column;min-height:0;}
.receive-results-head{display:flex;align-items:center;justify-content:space-between;gap:12px;padding:16px;border-bottom:1px solid #e5e7eb;}
.receive-results-head p{margin:0;color:#64748b;font-size:.86rem;}
.receive-bulk-actions{display:flex;align-items:center;justify-content:flex-end;gap:8px;flex-wrap:wrap;}
.receive-selected-count{background:#f1f5f9;color:#0f172a;border:1px solid #e2e8f0;border-radius:10px;padding:8px 11px;font-weight:700;font-size:.86rem;}
.receive-table input[type=checkbox],.receive-section input[type=checkbox]{width:16px;height:16px;accent-color:#16a34a;}
.receive-table-wrap{overflow:auto;max-height:calc(100vh - 360px);}
.receive-table{width:100%;border-collapse:separate;border-spacing:0;font-size:.82rem;min-width:1180px;}
.receive-table th{position:sticky;top:0;background:#2b2f2e;color:#fff;z-index:1;text-align:left;font-size:.72rem;text-transform:uppercase;letter-spacing:.03em;padding:10px;}
.receive-table td{border-bottom:1px solid #e5e7eb;padding:10px;vertical-align:middle;color:#111827;}
.receive-table tr:hover td{background:#f8fafc;}
.receive-status{display:inline-flex;align-items:center;border-radius:999px;padding:4px 8px;font-size:.72rem;font-weight:800;background:#eef2ff;color:#3730a3;}
.receive-status.pending{background:#fef3c7;color:#92400e;}.receive-status.approved,.receive-status.merchandise_received{background:#dcfce7;color:#166534;}.receive-status.rejected{background:#fee2e2;color:#991b1b;}.receive-status.error{background:#fee2e2;color:#991b1b;}
.receive-dot{display:inline-block;width:8px;height:8px;border-radius:50%;background:#84cc16;margin-right:4px;}
.receive-info-note{background:#e0f2fe;color:#0369a1;padding:12px 16px;font-size:.86rem;border-radius:0 0 16px 16px;}
.receive-muted{color:#6b7280;font-size:.86rem;margin:0;}
.receive-modal-box{width:96vw;max-width:1440px;height:88vh;max-height:88vh;}
.receive-decision-grid{display:grid;grid-template-columns:minmax(0,1fr) minmax(380px,48%);gap:16px;min-height:0;}
.receive-decision-left{display:flex;flex-direction:column;gap:12px;min-width:0;}
.receive-section{border:1px solid #e5e7eb;border-radius:14px;padding:12px;background:#fff;}
.receive-section h3{font-size:.95rem;margin:0 0 10px;color:#111827;}
.receive-glossary{background:#f8fafc;border:1px solid #e5e7eb;border-radius:12px;padding:12px;font-size:.84rem;color:#475569;}
.receive-warning{background:#fff7ed;border:1px solid #fed7aa;color:#9a3412;border-radius:12px;padding:12px;font-size:.88rem;font-weight:700;}
.receive-form-grid{display:grid;grid-template-columns:1fr 1fr;gap:10px;}
.receive-field{display:flex;flex-direction:column;gap:5px;margin-bottom:10px;}
.receive-field label{font-size:.75rem;font-weight:800;color:#374151;text-transform:uppercase;letter-spacing:.04em;}
.receive-field input,.receive-field select,.receive-field textarea{border:1px solid #d1d5db;border-radius:10px;padding:9px 10px;font-size:.88rem;background:#fff;}
.receive-field textarea{min-height:78px;resize:vertical;}
.receive-lines-wrap{overflow:auto;max-height:260px;border:1px solid #e5e7eb;border-radius:12px;}
.receive-lines{width:100%;border-collapse:separate;border-spacing:0;min-width:820px;font-size:.82rem;}
.receive-lines th{position:sticky;top:0;background:#f8fafc;text-align:left;color:#334155;font-size:.72rem;text-transform:uppercase;padding:9px;border-bottom:1px solid #e5e7eb;}
.receive-lines td{padding:8px;border-bottom:1px solid #f1f5f9;vertical-align:top;}
.receive-lines input,.receive-lines select{width:100%;border:1px solid #d1d5db;border-radius:8px;padding:7px;font-size:.82rem;}
.receive-pdf-box{background:#222;border-radius:12px;padding:12px;height:100%;min-height:64vh;display:flex;flex-direction:column;gap:8px;}
.receive-pdf-toolbar{display:flex;align-items:center;justify-content:space-between;color:#fff;font-size:.86rem;}
.receive-pdf-frame{width:100%;height:100%;min-height:58vh;border:0;border-radius:8px;background:#fff;}
.receive-result-grid{display:grid;grid-template-columns:1fr 1fr;gap:12px;}
#receiveMain .btn, #receiveModal .btn{border:0;border-radius:10px;padding:9px 13px;font-weight:800;cursor:pointer;text-decoration:none;display:inline-flex;align-items:center;justify-content:center;gap:6px;font-size:.86rem;}
#receiveMain .btn-primary, #receiveModal .btn-primary{background:#2563eb;color:#fff;}#receiveMain .btn-success, #receiveModal .btn-success{background:#16a34a;color:#fff;}#receiveMain .btn-danger, #receiveModal .btn-danger{background:#dc2626;color:#fff;}#receiveMain .btn-ghost, #receiveModal .btn-ghost{background:#f3f4f6;color:#111827;}#receiveMain .btn-outline, #receiveModal .btn-outline{background:#fff;border:1px solid #d1d5db;color:#111827;}#receiveMain .btn-warning, #receiveModal .btn-warning{background:#f59e0b;color:#111827;}#receiveMain .btn:disabled, #receiveModal .btn:disabled{opacity:.45;cursor:not-allowed;}
.receive-bulk-grid{display:grid;grid-template-columns:minmax(0,1fr) minmax(320px,36%);gap:14px;}
.receive-bulk-list{border:1px solid #e5e7eb;border-radius:12px;overflow:auto;max-height:420px;background:#fff;}
.receive-bulk-doc{display:grid;grid-template-columns:1.1fr .8fr .8fr .8fr;gap:8px;padding:10px 12px;border-bottom:1px solid #f1f5f9;font-size:.84rem;}
.receive-bulk-doc:first-child{background:#f8fafc;font-weight:800;text-transform:uppercase;font-size:.72rem;color:#334155;position:sticky;top:0;z-index:1;}
.receive-bulk-summary{background:#eff6ff;border:1px solid #bfdbfe;color:#1e40af;border-radius:12px;padding:12px;font-size:.88rem;margin-bottom:10px;}
.receive-bulk-error-list{margin:8px 0 0;padding-left:18px;color:#991b1b;}
@media(max-width:980px){.receive-header{flex-direction:column}.receive-header-actions{width:100%}.receive-header-actions>*{flex:1}.receive-filters{grid-template-columns:1fr}.receive-table-wrap{max-height:58vh}.receive-decision-grid{grid-template-columns:1fr}.receive-modal-box{width:96vw;height:92vh;max-height:92vh}.receive-pdf-box{min-height:420px}.receive-form-grid{grid-template-columns:1fr}.receive-bulk-grid{grid-template-columns:1fr}.receive-bulk-actions{justify-content:stretch}.receive-bulk-actions>*{flex:1}}
</style>

<script>
(function(){
    const state = { env:'sandbox', tab:'pending', rows:[], options:null, current:null, selected:new Set() };
    const $ = id => document.getElementById(id);
    const fmtMoney = v => '$' + Math.round(Number(v || 0)).toLocaleString('es-CL');
    const esc = s => String(s == null ? '' : s).replace(/[&<>'"]/g, c => ({'&':'&amp;','<':'&lt;','>':'&gt;',"'":'&#39;','"':'&quot;'}[c]));
    const stLabel = s => ({pending:'Pendiente',approved:'Aprobado',approved_with_observations:'Aprobado c/reparo',rejected:'Rechazado',merchandise_received:'Recibido',error:'Error'}[s] || s || 'Pendiente');
    const factoStatusLabel = s => ({'':'No informado','1':'Pendiente FACTO','2':'Aprobado FACTO','3':'Aprobado con reparo','4':'Rechazado FACTO','5':'Recepcion registrada'}[String(s == null ? '' : s)] || ('Estado FACTO ' + s));
    const isLocalPending = r => ['pending','error',''].includes(String(r.icylab_reception_status || 'pending'));
    const isFactoDecisionPending = r => String(r.inbox_document_status || '') === '1';
    const canApproveReject = r => isLocalPending(r) && isFactoDecisionPending(r);
    const dayDiff = (d) => { if(!d) return null; const base = new Date(d); if(isNaN(base)) return null; base.setDate(base.getDate()+8); const now = new Date(); now.setHours(0,0,0,0); base.setHours(0,0,0,0); return Math.ceil((base-now)/86400000); };

    async function jsonFetch(url, options){
        const res = await fetch(url, options || {});
        const text = await res.text();
        let data; try { data = JSON.parse(text); } catch(e) { throw new Error(text || 'Respuesta no valida.'); }
        if (!res.ok || data.success === false) throw new Error(data.message || 'Error de solicitud.');
        return data;
    }
    async function postJson(url, options){
        const res = await fetch(url, options || {});
        const text = await res.text();
        let data; try { data = JSON.parse(text); } catch(e) { throw new Error(text || 'Respuesta no valida.'); }
        if (!res.ok && !data.message) throw new Error('Error de solicitud.');
        return data;
    }
    function formData(obj){ const fd = new FormData(); Object.keys(obj).forEach(k => fd.append(k, obj[k] == null ? '' : obj[k])); return fd; }

    async function loadReceive(){
        state.env = $('receiveEnv').value;
        $('receiveRows').innerHTML = '<tr><td colspan="15">Cargando...</td></tr>';
        const q = new URLSearchParams({
            env: state.env, tab: state.tab, status: $('receiveStatus').value,
            document_type_id: $('receiveType').value, rut: $('receiveRut').value,
            folio: $('receiveFolio').value, purchase_order: $('receivePo').value, limit: '100'
        });
        try {
            const data = await jsonFetch('receive_list_ajax.php?' + q.toString());
            state.rows = data.data.rows || [];
            state.options = data.data.options || {};
            const visible = new Set(state.rows.map(r => String(r.id)));
            const actionable = new Set(state.rows.filter(canApproveReject).map(r => String(r.id)));
            state.selected.forEach(id => { if (!visible.has(String(id)) || !actionable.has(String(id))) state.selected.delete(id); });
            renderTabs(data.data.tabs || {});
            renderTypeOptions();
            renderRows();
            updateBulkBar();
        } catch(e) {
            $('receiveRows').innerHTML = '<tr><td colspan="15">' + esc(e.message) + '</td></tr>';
        }
    }

    function renderTabs(tabs){
        const values = {
            pending: tabs.pending_count || 0,
            soon: tabs.soon_count || 0,
            without_po: tabs.without_po_count || 0,
            approved: tabs.approved_count || 0,
            rejected: tabs.rejected_count || 0
        };
        document.querySelectorAll('.receive-tab').forEach(btn => {
            btn.classList.toggle('is-active', btn.dataset.tab === state.tab);
            const span = btn.querySelector('span'); if (span) span.textContent = values[btn.dataset.tab] || 0;
        });
    }

    function renderTypeOptions(){
        const select = $('receiveType');
        const current = select.value || 'all';
        const types = (state.options && state.options.document_types) ? state.options.document_types : [];
        select.innerHTML = '<option value="all">Tipo de documento: todos</option>' + types.map(t => `<option value="${esc(t.document_type_id)}">${esc(t.document_type_taxbureau || t.document_type_id)}</option>`).join('');
        select.value = current;
    }

    function renderRows(){
        if (!state.rows.length) {
            $('receiveRows').innerHTML = '<tr><td colspan="15">Sin documentos para los filtros seleccionados.</td></tr>';
            updateBulkBar();
            return;
        }
        $('receiveRows').innerHTML = state.rows.map(r => {
            const status = r.icylab_reception_status || 'pending';
            const days = dayDiff(r.receive_date || r.document_date);
            const sii = days === null ? '-' : (days < 0 ? 'Tacito' : days + ' d');
            const recSii = r.reception_confirmation_status ? 'Si' : 'No';
            const recFacto = r.product_receipt_status ? 'Si' : 'No';
            const selectable = canApproveReject(r);
            const checked = state.selected.has(String(r.id)) ? 'checked' : '';
            const actionLabel = selectable ? 'Aprobar / Rechazar' : 'Ver / revisar';
            const actionClass = selectable ? 'btn btn-success' : 'btn btn-outline';
            const notPendingHint = selectable ? '' : ` title="${esc('FACTO no permite aprobar/rechazar si el documento no esta pendiente. ' + factoStatusLabel(r.inbox_document_status || ''))}"`;
            return `<tr>
                <td><input type="checkbox" class="receive-row-check" data-select-receive-id="${esc(r.id)}" ${checked} ${selectable ? '' : 'disabled'} aria-label="Seleccionar DTE ${esc(r.document_number || '')}"></td>
                <td>${esc(r.issuer_tax_id_code || '-')}</td>
                <td><strong>${esc(r.supplier_name || r.issuer_name || 'Sin proveedor')}</strong></td>
                <td>${esc(r.document_type_taxbureau || r.document_type_id || '-')}</td>
                <td>${esc(r.document_number || '-')}</td>
                <td>${esc(r.document_date || '-')}</td>
                <td>${esc(r.payment_due_date ? 'Definida' : '30 dias')}</td>
                <td><strong>${fmtMoney(r.total_amount)}</strong></td>
                <td>${esc(r.purchase_order || '-')}</td>
                <td>${esc(r.payment_due_date || '-')}</td>
                <td>${days !== null && days >= 0 ? '<span class="receive-dot"></span>' : ''}${esc(sii)}</td>
                <td>${esc(recSii)}</td>
                <td>${esc(recFacto)}</td>
                <td><span class="receive-status ${esc(status)}">${esc(stLabel(status))}</span><br><small class="receive-muted">${esc(factoStatusLabel(r.inbox_document_status || ''))}</small></td>
                <td><button type="button" class="${actionClass}" data-receive-id="${esc(r.id)}"${notPendingHint}>${actionLabel}</button></td>
            </tr>`;
        }).join('');
    }


    function updateBulkBar(){
        const count = state.selected.size;
        const countEl = $('receiveSelectedCount');
        if (countEl) countEl.textContent = String(count);
        const btn = $('openBulkReceiveBtn');
        if (btn) btn.disabled = count === 0;
        const all = $('receiveSelectAll');
        if (all) {
            const selectable = state.rows.filter(r => ['pending','error',''].includes(String(r.icylab_reception_status || 'pending')));
            const selectedVisible = selectable.filter(r => state.selected.has(String(r.id))).length;
            all.checked = selectable.length > 0 && selectedVisible === selectable.length;
            all.indeterminate = selectedVisible > 0 && selectedVisible < selectable.length;
            all.disabled = selectable.length === 0;
        }
    }

    function getSelectedRows(){
        const ids = new Set(Array.from(state.selected).map(String));
        return state.rows.filter(r => ids.has(String(r.id)));
    }

    function renderBulkDecision(){
        const rows = getSelectedRows();
        $('receiveModalTitle').textContent = 'Recepcion masiva de documentos';
        $('receiveModalSubtitle').textContent = rows.length + ' DTE seleccionados · ' + state.env;
        const total = rows.reduce((acc, r) => acc + Number(r.total_amount || 0), 0);
        const docsHtml = ['<div class="receive-bulk-doc"><span>Proveedor</span><span>Folio</span><span>Fecha</span><span>Total</span></div>'].concat(rows.map(r => `<div class="receive-bulk-doc"><span>${esc(r.issuer_name || r.supplier_name || '-')}</span><span>${esc(r.document_number || '-')}</span><span>${esc(r.document_date || '-')}</span><span><strong>${fmtMoney(r.total_amount)}</strong></span></div>`)).join('');
        $('receiveModalBody').innerHTML = `<div class="receive-bulk-grid">
            <div>
                <div class="receive-bulk-summary"><strong>${rows.length} documentos seleccionados.</strong><br>Total referencial: <strong>${fmtMoney(total)}</strong>. Esta accion aplicara la misma decision a todos los documentos seleccionados.</div>
                <div class="receive-section">
                    <h3>Decision masiva</h3>
                    <div class="receive-warning">Operacion sensible. Al aprobar o rechazar se intenta informar a FACTO/SII/proveedor por cada DTE. La operacion puede tener resultados parciales.</div>
                    <div class="receive-form-grid">
                        <div class="receive-field"><label>Operacion</label><select id="receiveBulkDecisionType"><option value="approved">Aprobar</option><option value="approved_with_observations">Aprobar con reparo</option><option value="rejected">Rechazar</option><option value="merchandise_received">Solo registrar recepcion</option></select></div>
                        <div class="receive-field"><label>Email contacto</label><input id="receiveBulkContactEmail" value="contacto@icylab.cl"></div>
                    </div>
                    <label style="display:flex;gap:8px;align-items:center;margin:8px 0;font-weight:700;color:#374151;"><input type="checkbox" id="receiveBulkConfirmed" checked> Recepcion de mercaderia o servicios</label>
                    <div class="receive-form-grid">
                        <div class="receive-field"><label>Lugar recepcion</label><input id="receiveBulkPlace" value="Casa matriz"></div>
                        <div class="receive-field"><label>Documentos</label><input value="${rows.length} seleccionados" readonly></div>
                    </div>
                    <div class="receive-field"><label>Observaciones / motivo rechazo</label><textarea id="receiveBulkNotes" placeholder="Observacion comun para todos los DTE seleccionados"></textarea></div>
                    <p class="receive-muted">En recepcion masiva las lineas se registran con cantidad recibida igual a la cantidad facturada. Para ajustar cantidades, bodega o SKU por item, usa la aprobacion individual.</p>
                </div>
            </div>
            <div class="receive-section">
                <h3>Documentos seleccionados</h3>
                <div class="receive-bulk-list">${docsHtml}</div>
            </div>
        </div>`;
        $('receiveModalFooter').innerHTML = `<button type="button" class="btn btn-ghost" id="cancelReceiveBtn">Cancelar</button><button type="button" class="btn btn-success" id="saveBulkReceiveDecisionBtn">Guardar recepcion masiva</button>`;
        $('receiveModal').style.display = 'flex';
        $('receiveModal').classList.add('show');
    }

    async function saveBulkDecision(){
        const rows = getSelectedRows();
        if (!rows.length) { alert('Selecciona documentos para recepcion masiva.'); return; }
        const type = $('receiveBulkDecisionType').value;
        const confirmed = $('receiveBulkConfirmed').checked;
        const notes = $('receiveBulkNotes').value.trim();
        if (['approved','approved_with_observations','rejected'].includes(type) && !isFactoDecisionPending(state.current || {})) { alert('FACTO ya no permite aprobar/rechazar este documento porque no esta pendiente. Actualiza el listado.'); return; }
        if (type !== 'rejected' && !confirmed) { alert('Para aprobar debes confirmar recepcion de mercaderia o servicio.'); return; }
        if (confirmed && !$('receiveBulkPlace').value.trim()) { alert('Debes indicar lugar de recepcion.'); return; }
        if (type === 'rejected' && !notes) { alert('Para rechazar debes registrar motivo u observacion.'); return; }
        const label = type === 'rejected' ? 'RECHAZAR' : (type === 'approved_with_observations' ? 'APROBAR CON REPARO' : (type === 'merchandise_received' ? 'REGISTRAR RECEPCION' : 'APROBAR'));
        if (!confirm('Estas seguro de ' + label + ' ' + rows.length + ' documentos seleccionados?')) return;
        const btn = $('saveBulkReceiveDecisionBtn'); btn.disabled = true; btn.textContent = 'Procesando...';
        try {
            const data = await jsonFetch('receive_bulk_decide_ajax.php', {method:'POST', body: formData({
                environment: state.env,
                ids_json: JSON.stringify(rows.map(r => r.id)),
                decision_type: type,
                reception_confirmed: confirmed ? '1' : '',
                reception_place: $('receiveBulkPlace').value,
                contact_email: $('receiveBulkContactEmail').value,
                notes: notes
            })});
            state.selected.clear();
            renderBulkResult(data);
            await loadReceive();
        } catch(e) {
            renderBulkResult({success:false,message:e.message,summary:{processed:0,success:0,error:rows.length},results:[]});
        }
    }

    function renderBulkResult(data){
        const s = data.summary || {};
        const ok = data.success !== false && Number(s.error || 0) === 0;
        $('receiveModalTitle').textContent = ok ? 'Recepcion masiva completada' : 'Recepcion masiva con observaciones';
        $('receiveModalSubtitle').textContent = 'Procesados: ' + (s.processed || 0) + ' · OK: ' + (s.success || 0) + ' · Error: ' + (s.error || 0);
        const results = data.results || [];
        const rows = ['<div class="receive-bulk-doc"><span>Proveedor</span><span>Folio</span><span>Estado</span><span>Resultado</span></div>'].concat(results.map(r => `<div class="receive-bulk-doc"><span>${esc(r.issuer_name || '-')}</span><span>${esc(r.document_number || '-')}</span><span>${r.success ? 'OK' : 'Error'}</span><span>${esc(r.message || '-')}</span></div>`)).join('');
        $('receiveModalBody').innerHTML = `<div class="receive-section">
            <div class="${ok ? 'receive-info-note' : 'receive-warning'}" style="border-radius:12px;margin-bottom:12px;">${esc(data.message || 'Proceso masivo finalizado.')}</div>
            <div class="receive-result-grid">
                <div class="receive-section"><h3>Resumen</h3><p><strong>Procesados:</strong><br>${esc(s.processed || 0)}</p><p><strong>Correctos:</strong><br>${esc(s.success || 0)}</p><p><strong>Con error:</strong><br>${esc(s.error || 0)}</p></div>
                <div class="receive-section"><h3>Regla aplicada</h3><p><strong>Decision:</strong><br>${esc(stLabel(s.decision_type || ''))}</p><p><strong>Ambiente:</strong><br>${esc(state.env)}</p></div>
            </div>
            <div class="receive-section" style="margin-top:12px;"><h3>Detalle por documento</h3><div class="receive-bulk-list">${rows}</div></div>
        </div>`;
        $('receiveModalFooter').innerHTML = `<button type="button" class="btn btn-success" id="backToReceiveListBtn">Volver a listado documentos</button>`;
    }

    async function openDecision(id){
        const q = new URLSearchParams({id:id, env:state.env});
        const data = await jsonFetch('receive_detail_ajax.php?' + q.toString());
        state.current = data.document;
        state.options = data.options || state.options;
        renderDecision(data.document);
        $('receiveModal').style.display = 'flex';
        $('receiveModal').classList.add('show');
    }

    function renderDecision(d){
        $('receiveModalTitle').textContent = 'Aprobacion / Rechazo comercial';
        $('receiveModalSubtitle').textContent = (d.document_type_taxbureau || 'DTE recibido') + ' · Folio ' + (d.document_number || '-') + ' · ' + (d.issuer_name || 'Proveedor');
        const pdfUrl = d.pdf_file_path ? `receive_file.php?id=${encodeURIComponent(d.id)}&env=${encodeURIComponent(state.env)}&type=pdf` : '';
        const xmlUrl = d.xml_file_path ? `receive_file.php?id=${encodeURIComponent(d.id)}&env=${encodeURIComponent(state.env)}&type=xml` : '';
        const productOptions = ((state.options && state.options.products) ? state.options.products : []).map(p => `<option value="${esc(p.id)}" data-sku="${esc(p.sku || '')}">${esc((p.sku ? p.sku + ' · ' : '') + p.name)}</option>`).join('');
        const factoPending = isFactoDecisionPending(d);
        const externalWarning = factoPending ? '' : `<div class="receive-warning">FACTO ya no tiene este DTE en estado pendiente. Estado actual: ${esc(factoStatusLabel(d.inbox_document_status || ''))}. No se puede aprobar, aprobar con reparo ni rechazar nuevamente. Actualiza el listado o revisa el documento en FACTO.</div>`;
        const lines = (d.lines || []).map((l, i) => `<tr data-line-row="${i}">
            <td>${esc(l.description || '')}<input type="hidden" data-line-field="description" value="${esc(l.description || '')}"></td>
            <td>${esc(l.quantity_invoiced || 0)}<input type="hidden" data-line-field="quantity_invoiced" value="${esc(l.quantity_invoiced || 0)}"></td>
            <td><input type="number" step="0.0001" min="0" data-line-field="quantity_received" value="${esc(l.quantity_received || l.quantity_invoiced || 0)}"></td>
            <td><input type="text" data-line-field="warehouse_destination" placeholder="Bodega destino"></td>
            <td><select data-line-field="matched_product_id"><option value="">Sin coincidencia</option>${productOptions}</select><input type="text" data-line-field="free_sku" placeholder="SKU o codigo libre"></td>
            <td><input type="text" data-line-field="notes" placeholder="Nota linea"></td>
        </tr>`).join('');

        $('receiveModalBody').innerHTML = `<div class="receive-decision-grid">
            <div class="receive-decision-left">
                <div class="receive-section">
                    <h3>Aprobacion comercial</h3>
                    <div class="receive-glossary">
                        <strong>DTE:</strong> documento tributario electronico recibido. <strong>Recepcion:</strong> conformidad de mercaderia o servicio. <strong>Credito fiscal IVA:</strong> requiere respaldo operativo de recepcion.
                    </div>
                    <div class="receive-warning">La aprobacion o rechazo comercial puede informar a FACTO/SII/proveedor. Operacion sensible; valida el PDF antes de confirmar.</div>
                    ${externalWarning}
                    <div class="receive-form-grid">
                        <div class="receive-field"><label>Operacion</label><select id="receiveDecisionType"><option value="approved">Aprobar</option><option value="approved_with_observations">Aprobar con reparo</option><option value="rejected">Rechazar</option><option value="merchandise_received">Solo registrar recepcion</option></select></div>
                        <div class="receive-field"><label>Email contacto</label><input id="receiveContactEmail" value="${esc(d.sender_email || 'contacto@icylab.cl')}"></div>
                    </div>
                    <label style="display:flex;gap:8px;align-items:center;margin:8px 0;font-weight:700;color:#374151;"><input type="checkbox" id="receiveConfirmed" checked> Recepcion de mercaderia o servicios</label>
                    <div class="receive-form-grid">
                        <div class="receive-field"><label>Lugar recepcion</label><input id="receivePlace" value="Casa matriz"></div>
                        <div class="receive-field"><label>Proveedor</label><input value="${esc(d.issuer_name || '')}" readonly></div>
                    </div>
                    <div class="receive-field"><label>Observaciones / motivo rechazo</label><textarea id="receiveNotes" placeholder="Observacion interna o motivo de rechazo"></textarea></div>
                </div>
                <div class="receive-section">
                    <h3>Detalle de items a recibir</h3>
                    <p class="receive-muted">Ajusta cantidad recibida si difiere de lo facturado. La coincidencia con catalogo prepara inventario y compras.</p>
                    <div class="receive-lines-wrap"><table class="receive-lines"><thead><tr><th>Producto en DTE</th><th>Facturado</th><th>Recibido</th><th>Bodega destino</th><th>Coincidencia catalogo / SKU</th><th>Nota</th></tr></thead><tbody>${lines}</tbody></table></div>
                </div>
            </div>
            <div class="receive-pdf-box">
                <div class="receive-pdf-toolbar"><span>Vista previa del documento</span><span>${xmlUrl ? `<a class="btn btn-outline" href="${xmlUrl}">XML</a>` : ''} ${pdfUrl ? `<a class="btn btn-outline" href="${pdfUrl}" target="_blank">Abrir PDF</a>` : ''}</span></div>
                ${pdfUrl ? `<iframe class="receive-pdf-frame" src="${pdfUrl}"></iframe>` : '<div style="background:#fff;border-radius:8px;padding:18px;">PDF no disponible.</div>'}
            </div>
        </div>`;
        $('receiveModalFooter').innerHTML = `<button type="button" class="btn btn-ghost" id="cancelReceiveBtn">Cancelar</button><button type="button" class="btn btn-success" id="saveReceiveDecisionBtn" ${factoPending ? '' : 'disabled'}>${factoPending ? 'Guardar aprobacion' : 'No disponible en FACTO'}</button>`;
    }

    function collectLines(){
        return Array.from(document.querySelectorAll('[data-line-row]')).map((tr, idx) => {
            const obj = { line_index: idx };
            tr.querySelectorAll('[data-line-field]').forEach(el => { obj[el.dataset.lineField] = el.value; });
            const sel = tr.querySelector('select[data-line-field="matched_product_id"]');
            if (sel && sel.selectedOptions[0]) obj.matched_sku = sel.selectedOptions[0].dataset.sku || '';
            return obj;
        });
    }

    async function saveDecision(){
        const type = $('receiveDecisionType').value;
        const confirmed = $('receiveConfirmed').checked;
        const notes = $('receiveNotes').value.trim();
        if (type !== 'rejected' && !confirmed) { alert('Para aprobar debes confirmar recepcion de mercaderia o servicio.'); return; }
        if (confirmed && !$('receivePlace').value.trim()) { alert('Debes indicar lugar de recepcion.'); return; }
        if (type === 'rejected' && !notes) { alert('Para rechazar debes registrar motivo u observacion.'); return; }
        const label = type === 'rejected' ? 'RECHAZAR' : (type === 'approved_with_observations' ? 'APROBAR CON REPARO' : 'APROBAR');
        if (!confirm('Estas seguro de ' + label + ' este documento y sus detalles?')) return;
        const btn = $('saveReceiveDecisionBtn'); btn.disabled = true; btn.textContent = 'Procesando...';
        try {
            const data = await postJson('receive_decide_ajax.php', {method:'POST', body: formData({
                id: state.current.id, environment: state.env, decision_type: type,
                reception_confirmed: confirmed ? '1' : '', reception_place: $('receivePlace').value,
                contact_email: $('receiveContactEmail').value, notes: notes,
                lines_json: JSON.stringify(collectLines())
            })});
            renderResult(data);
            if (data.success !== false) await loadReceive();
        } catch(e) {
            renderResult({success:false,message:e.message,document:state.current});
        }
    }

    function renderResult(data){
        const ok = data.success !== false;
        const blocked = !!data.blocked || !!data.status_conflict;
        const d = data.document || state.current || {};
        $('receiveModalTitle').textContent = ok ? 'Documento procesado' : (blocked ? 'Documento no accionable' : 'Error de procesamiento');
        $('receiveModalSubtitle').textContent = (d.document_number ? 'Folio ' + d.document_number : 'Recepcion DTE');
        $('receiveModalBody').innerHTML = `<div class="receive-section">
            <div class="${ok || blocked ? 'receive-info-note' : 'receive-warning'}" style="border-radius:12px;margin-bottom:12px;">${esc(data.message || (ok ? 'Documento procesado correctamente.' : 'No se pudo procesar el documento.'))}</div>
            <div class="receive-result-grid">
                <div class="receive-section"><h3>Resultado</h3><p><strong>Agregado al libro de compras:</strong><br>${ok ? 'Si' : 'No confirmado'}</p><p><strong>Informado al SII:</strong><br>${ok ? 'Si' : 'No confirmado'}</p><p><strong>Informado al proveedor:</strong><br>${ok ? 'Si' : 'No confirmado'}</p></div>
                <div class="receive-section"><h3>Documento</h3><p><strong>Proveedor:</strong><br>${esc(d.issuer_name || '-')}</p><p><strong>Folio:</strong><br>${esc(d.document_number || '-')}</p><p><strong>Estado ICYLAB:</strong><br>${esc(stLabel(d.icylab_reception_status || 'pending'))}</p><p><strong>Estado FACTO:</strong><br>${esc(factoStatusLabel(d.inbox_document_status || ''))}</p></div>
            </div>
        </div>`;
        $('receiveModalFooter').innerHTML = `<button type="button" class="btn btn-success" id="backToReceiveListBtn">Volver a listado documentos</button>`;
    }

    function closeModal(){ $('receiveModal').style.display='none'; $('receiveModal').classList.remove('show'); }

    document.addEventListener('click', e => {
        const tab = e.target.closest('.receive-tab');
        if (tab) { state.tab = tab.dataset.tab; loadReceive(); return; }
        const selected = e.target.closest('[data-select-receive-id]');
        if (selected) { if (selected.checked) state.selected.add(String(selected.dataset.selectReceiveId)); else state.selected.delete(String(selected.dataset.selectReceiveId)); updateBulkBar(); return; }
        if (e.target.id === 'receiveSelectAll') { state.rows.forEach(r => { if (canApproveReject(r)) { if (e.target.checked) state.selected.add(String(r.id)); else state.selected.delete(String(r.id)); } }); renderRows(); updateBulkBar(); return; }
        const detail = e.target.closest('[data-receive-id]');
        if (detail) { openDecision(detail.dataset.receiveId).catch(err => alert(err.message)); return; }
        if (e.target.id === 'reloadReceiveBtn' || e.target.id === 'searchReceiveBtn') loadReceive();
        if (e.target.id === 'openBulkReceiveBtn') renderBulkDecision();
        if (e.target.id === 'clearReceiveFiltersBtn') { $('receiveStatus').value=''; $('receiveType').value='all'; $('receiveRut').value=''; $('receiveFolio').value=''; $('receivePo').value=''; state.selected.clear(); loadReceive(); }
        if (e.target.id === 'closeReceiveModalBtn' || e.target.id === 'cancelReceiveBtn' || e.target.id === 'backToReceiveListBtn') closeModal();
        if (e.target.id === 'saveReceiveDecisionBtn') saveDecision();
        if (e.target.id === 'saveBulkReceiveDecisionBtn') saveBulkDecision();
    });
    ['receiveEnv','receiveStatus','receiveType'].forEach(id => { const el = $(id); if(el) el.addEventListener('change', loadReceive); });
    ['receiveRut','receiveFolio','receivePo'].forEach(id => { const el = $(id); if(el) el.addEventListener('keydown', e => { if(e.key === 'Enter') loadReceive(); }); });
    loadReceive();
})();
</script>

    </section>
</main>
<?php require_once '../../layouts/footer.php'; ?>
