<?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';
$billingEnvironment = defined('FACTO_DEFAULT_ENVIRONMENT') ? FACTO_DEFAULT_ENVIRONMENT : 'production';
$billingEnvironment = $billingEnvironment === 'sandbox' ? 'sandbox' : 'production';

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

<main class="app-main billing-integrated-main crm-ui-main" id="billingReceiveMain" data-spa-module="billing:inbox">
    <?php require_once '../../layouts/topbar.php'; ?>
    <section id="receiveMain" class="content receive-main billing-page-shell billing-phase-content billing-receive-content billing-crm-content crm-ui-page-content crm-ui-page">
            <div class="receive-header page-header header-responsive billing-page-header crm-ui-page-header">
                <div class="page-header-content crm-ui-page-header-copy"><span class="label">FINANZAS</span><h2>Recepción y aprobación DTE</h2><p class="text-muted">Aprueba, rechaza y registra recepción de mercadería o servicios desde documentos recibidos.</p></div>
                <div class="receive-header-actions cluster top-actions-cluster billing-page-header-actions crm-ui-page-actions">
                    <input type="hidden" id="receiveEnv" value="<?php echo htmlspecialchars($billingEnvironment, ENT_QUOTES, 'UTF-8'); ?>">
                    <label class="receive-field crm-ui-field" style="min-width:190px"><span>Período tributario</span><input type="month" id="receivePeriod" class="receive-input input" value="<?php echo date('Y-m'); ?>"></label>
                    <button type="button" class="btn btn-primary btn-icon-mobile" id="reloadReceiveBtn" title="Actualizar DTE recibidos"><i data-lucide="refresh-cw"></i><span class="mobile-hidden">Actualizar</span></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_commercial">Aprobados comercialmente · <span>0</span></button><button type="button" class="receive-tab" data-tab="merchandise_received">Recepción mercadería · <span>0</span></button><button type="button" class="receive-tab" data-tab="rejected">Rechazados · <span>0</span></button></div>
            <label class="receive-mobile-tab-control" for="receiveMobileTab">
                <select id="receiveMobileTab" class="receive-input input" aria-label="Bandeja de documentos recibidos">
                    <option value="pending">Pendientes · 0</option>
                    <option value="soon">SII aprueba pronto · 0</option>
                    <option value="without_po">Sin orden de compra · 0</option>
                    <option value="approved_commercial">Aprobados comercialmente · 0</option>
                    <option value="merchandise_received">Recepción mercadería · 0</option>
                    <option value="rejected">Rechazados · 0</option>
                </select>
            </label>

            <section class="filter-bar-container receive-filter-card receive-filters billing-filter-bar billing-filter-bar--receive crm-ui-filter">
                <select id="receiveStatus" class="receive-input input"><option value="">Estado según pestaña</option><option value="all">Cualquier estado</option><option value="pending">Pendiente</option><option value="approved_commercial">Aprobado comercialmente</option><option value="approved_with_observations">Aprobado con reparo</option><option value="merchandise_received">Recepción de mercadería/servicio</option><option value="rejected">Rechazado</option></select>
                <select id="receiveType" class="receive-input input"><option value="all">Tipo de documento: todos</option></select>
                <input id="receiveRut" class="receive-input input" placeholder="RUT proveedor">
                <input id="receiveFolio" class="receive-input input" placeholder="Folio">
                <input id="receivePo" class="receive-input input" placeholder="Número de orden de compra">
                <div class="crm-ui-filter-actions"><button type="button" class="btn btn-primary" id="searchReceiveBtn"><i data-lucide="search"></i><span>Buscar</span></button></div>
            </section>

            <section class="card receive-results-card billing-data-card billing-table-card crm-ui-table-card">
                <div class="receive-results-head billing-bulkbar crm-ui-table-toolbar crm-ui-bulkbar">
                    <div class="receive-results-copy crm-ui-table-toolbar-copy"><h3>Documentos leídos desde FACTO/SII</h3><p id="receiveResultsHint">Documentos recibidos pendientes de decisión.</p></div>
                    <div class="receive-bulk-actions billing-selection-actions crm-ui-bulkbar-actions"><span class="receive-selected-count"><strong id="receiveSelectedCount">0</strong> seleccionados</span><button type="button" class="btn btn-primary" id="openBulkReceiveBtn" disabled><i data-lucide="list-checks"></i><span>Aprobar / rechazar</span></button><button type="button" class="btn btn-outline" id="clearReceiveFiltersBtn"><i data-lucide="rotate-ccw"></i><span>Nueva búsqueda</span></button></div>
                </div>
                <div class="table-wrap receive-table-wrap billing-table-scroll crm-ui-table-scroll">
                    <table class="table receive-table billing-responsive-table billing-crm-table crm-ui-table crm-ui-mobile-table" style="--crm-mobile-columns: 46px minmax(0, 1fr) 94px 64px;">
                        <colgroup><col class="col-select"><col class="col-counterparty"><col class="col-document"><col class="col-date"><col class="col-amount"><col class="col-due"><col class="col-sii"><col class="col-status"><col class="col-action"></colgroup>
                        <thead><tr><th class="col-select"><input type="checkbox" id="receiveSelectAll" aria-label="Seleccionar documentos visibles"></th><th class="col-counterparty crm-mobile-primary">Proveedor</th><th class="col-document crm-mobile-hidden">Documento</th><th class="col-date crm-mobile-hidden">Emisión</th><th class="col-amount crm-mobile-metric">Total</th><th class="col-due crm-mobile-hidden">Vence</th><th class="col-sii crm-mobile-hidden">SII</th><th class="col-status crm-mobile-hidden">Estado</th><th class="col-action crm-ui-action-cell">Acción</th></tr></thead>
                        <tbody id="receiveRows"><tr><td colspan="9">Cargando...</td></tr></tbody>
                    </table>
                </div>
                <div class="receive-info-note"><strong>Cómo funciona la aprobación SII:</strong> los DTE recibidos tienen plazo acotado para aprobar o reclamar. Si no actúas, el documento puede avanzar a aceptación tácita.</div>
            </section>
    </section>

<div id="receiveModal" class="product-modal-backdrop crm-ui-modal-backdrop" data-crm-dismissable="true" style="display:none;" aria-hidden="true" role="dialog" aria-modal="true">
    <div class="product-modal-box receive-modal-box billing-modal-box crm-ui-modal-box">
        <div class="product-modal-header billing-modal-header billing-modal-header--no-back crm-ui-modal-header crm-ui-modal-header--no-back">
            <div class="billing-modal-heading crm-ui-modal-heading">
                <h2 id="receiveModalTitle">Aprobacion / Rechazo comercial</h2>
                <p id="receiveModalSubtitle" class="receive-muted"></p>
            </div>
            <button type="button" class="btn btn-outline action-square-btn billing-modal-close crm-ui-modal-icon-btn" id="closeReceiveModalBtn" aria-label="Cerrar"><i data-lucide="x"></i></button>
        </div>
        <div class="product-modal-body crm-ui-modal-body" id="receiveModalBody"></div>
        <div class="product-modal-footer billing-modal-footer crm-ui-modal-footer" id="receiveModalFooter"></div>
    </div>
</div>
<script>
(function(){
    const __pageBindings = [];
    const on = (target, eventName, handler, options) => {
        if (!target || typeof target.addEventListener !== 'function') return;
        target.addEventListener(eventName, handler, options || false);
        __pageBindings.push([target, eventName, handler, options || false]);
    };
    window.ICY_PAGE_CLEANUPS = window.ICY_PAGE_CLEANUPS || [];
    window.ICY_PAGE_CLEANUPS.push(() => {
        __pageBindings.forEach(([target, eventName, handler, options]) => {
            try { target.removeEventListener(eventName, handler, options); } catch (_) {}
        });
    });
    const state = { env:'production', tab:'pending', rows:[], options:null, current:null, selected:new Set() };
    const $ = id => document.getElementById(id);
    function refreshIcons(){ if (window.lucide && typeof window.lucide.createIcons === 'function') window.lucide.createIcons(); }
    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 => 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, tax_period: $('receivePeriod').value, 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>';
        }
    }

    async function syncReceive(){
        const button = $('reloadReceiveBtn');
        if (button) button.disabled = true;
        try {
            const data = await jsonFetch('receive_sync_ajax.php', {
                method: 'POST',
                body: formData({environment: $('receiveEnv').value || 'production'})
            });
            await loadReceive();
            window.alert(data.message || 'Recepción DTE actualizada.');
        } catch (e) {
            window.alert(e.message);
        } finally {
            if (button) button.disabled = false;
        }
    }

    function renderTabs(tabs){
        const values = {
            pending: tabs.pending_count || 0,
            soon: tabs.soon_count || 0,
            without_po: tabs.without_po_count || 0,
            approved_commercial: tabs.approved_commercial_count || 0,
            merchandise_received: tabs.merchandise_received_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;
        });
        const mobileTab = $('receiveMobileTab');
        if (mobileTab) {
            const labels = {
                pending: 'Pendientes',
                soon: 'SII aprueba pronto',
                without_po: 'Sin orden de compra',
                approved_commercial: 'Aprobados comercialmente',
                merchandise_received: 'Recepción mercadería',
                rejected: 'Rechazados'
            };
            Array.from(mobileTab.options).forEach(option => {
                option.textContent = `${labels[option.value] || option.value} · ${values[option.value] || 0}`;
            });
            mobileTab.value = state.tab;
        }
    }

    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="9">Sin documentos para los filtros seleccionados.</td></tr>';
            updateBulkBar();
            return;
        }
        $('receiveRows').innerHTML = state.rows.map(r => {
            const status = String(r.inbox_document_status || '');
            const days = dayDiff(r.receive_date || r.document_date);
            const sii = days === null ? '-' : (days < 0 ? 'Tácito' : days + ' d');
            const recSii = r.reception_confirmation_status ? 'Sí' : 'No';
            const recFacto = r.product_receipt_status ? 'Sí' : 'No';
            const selectable = canApproveReject(r);
            const checked = state.selected.has(String(r.id)) ? 'checked' : '';
            const notPendingHint = selectable ? '' : ` title="${esc('FACTO no permite aprobar/rechazar si el documento no está pendiente. ' + factoStatusLabel(r.inbox_document_status || ''))}"`;
            return `<tr>
                <td class="col-select"><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 class="col-counterparty crm-mobile-primary"><div class="crm-ui-cell-stack"><strong>${esc(r.supplier_name || r.issuer_name || 'Sin proveedor')}</strong><small>${esc(r.issuer_tax_id_code || 'Sin RUT')} · Folio ${esc(r.document_number || '-')}</small></div></td>
                <td class="col-document crm-mobile-hidden"><strong>${esc(r.document_type_taxbureau || r.document_type_id || '-')}</strong><small>Folio ${esc(r.document_number || '-')}</small></td>
                <td class="col-date crm-mobile-hidden">${esc(r.document_date || '-')}</td>
                <td class="col-amount crm-mobile-metric"><strong>${fmtMoney(r.total_amount)}</strong></td>
                <td class="col-due crm-mobile-hidden">${esc(r.payment_due_date || '-')}</td>
                <td class="col-sii crm-mobile-hidden">${days !== null && days >= 0 ? '<span class="receive-dot"></span>' : ''}${esc(sii)}<small>Rec. SII ${esc(recSii)} · FACTO ${esc(recFacto)}</small></td>
                <td class="col-status crm-mobile-hidden"><span class="receive-status status-${esc(status)}">${esc(factoStatusLabel(status))}</span><small class="receive-muted">ICYLAB: ${esc(stLabel(r.icylab_reception_status || 'pending'))}</small></td>
                <td class="col-action crm-ui-action-cell"><button type="button" class="btn btn-outline crm-ui-action-btn" data-receive-id="${esc(r.id)}"${notPendingHint} aria-label="Ver DTE ${esc(r.document_number||'')}"><i data-lucide="eye" aria-hidden="true"></i></button></td>
            </tr>`;
        }).join('');
        refreshIcons();
    }


    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(canApproveReject);
            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 crm-ui-section"><span>Proveedor</span><span>Folio</span><span>Fecha</span><span>Total</span></div>'].concat(rows.map(r => `<div class="receive-bulk-doc crm-ui-section"><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 crm-ui-form-grid">
            <div>
                <div class="receive-bulk-summary crm-ui-summary-card"><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 crm-ui-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 crm-ui-form-grid">
                        <div class="receive-field crm-ui-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 crm-ui-field"><label>Email contacto</label><input id="receiveBulkContactEmail" value="contacto@icylab.cl"></div>
                    </div>
                    <p class="receive-muted">La aprobación comercial y la recepción de mercadería son estados FACTO distintos. “Solo registrar recepción” enviará el estado 5.</p>
                    <div class="receive-form-grid crm-ui-form-grid">
                        <div class="receive-field crm-ui-field"><label>Lugar recepcion</label><input id="receiveBulkPlace" value="Casa matriz"></div>
                        <div class="receive-field crm-ui-field"><label>Documentos</label><input value="${rows.length} seleccionados" readonly></div>
                    </div>
                    <div class="receive-field crm-ui-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 crm-ui-section">
                <h3>Documentos seleccionados</h3>
                <div class="receive-bulk-list crm-ui-inner-table-wrap">${docsHtml}</div>
            </div>
        </div>`;
        $('receiveModalFooter').innerHTML = `<div class="modal-footer-actions-left"><button type="button" class="btn btn-outline" id="cancelReceiveBtn"><i data-lucide="x"></i><span>Cancelar</span></button></div><div class="modal-footer-actions-right"><button type="button" class="btn btn-primary" id="saveBulkReceiveDecisionBtn"><i data-lucide="check"></i><span>Guardar recepción masiva</span></button></div>`; refreshIcons();
        $('receiveModal').style.display = 'flex';
        $('receiveModal').classList.add('show');
        $('receiveModal').setAttribute('aria-hidden', 'false');
        document.body.classList.add('is-modal-open');
    }

    async function saveBulkDecision(){
        const rows = getSelectedRows();
        if (!rows.length) { alert('Selecciona documentos para recepcion masiva.'); return; }
        const type = $('receiveBulkDecisionType').value;
        const confirmed = type === 'merchandise_received';
        const notes = $('receiveBulkNotes').value.trim();
        if (rows.some(r => !isFactoDecisionPending(r))) { alert('Uno o más documentos ya no están pendientes en FACTO. Actualiza el listado.'); 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; }
        if (type === 'approved_with_observations' && !notes) { alert('Para aprobar con reparo debes registrar la observación.'); 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 crm-ui-section"><span>Proveedor</span><span>Folio</span><span>Estado</span><span>Resultado</span></div>'].concat(results.map(r => `<div class="receive-bulk-doc crm-ui-section"><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 crm-ui-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 crm-ui-form-grid">
                <div class="receive-section crm-ui-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 crm-ui-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 crm-ui-section" style="margin-top:12px;"><h3>Detalle por documento</h3><div class="receive-bulk-list crm-ui-inner-table-wrap">${rows}</div></div>
        </div>`;
        $('receiveModalFooter').innerHTML = `<div class="modal-footer-actions-right"><button type="button" class="btn btn-primary" id="backToReceiveListBtn"><i data-lucide="arrow-left"></i><span>Volver al listado</span></button></div>`; refreshIcons();
    }

    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');
        $('receiveModal').setAttribute('aria-hidden', 'false');
        document.body.classList.add('is-modal-open');
    }

    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 = `receive_file.php?id=${encodeURIComponent(d.id)}&env=${encodeURIComponent(state.env)}&type=pdf`;
        const xmlUrl = `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 crm-ui-form-grid">
            <div class="receive-decision-left">
                <div class="receive-section crm-ui-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 crm-ui-form-grid">
                        <div class="receive-field crm-ui-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 crm-ui-field"><label>Email contacto</label><input id="receiveContactEmail" value="${esc(d.sender_email || 'contacto@icylab.cl')}"></div>
                    </div>
                    <p class="receive-muted">La aprobación comercial y la recepción de mercadería son estados FACTO distintos. “Solo registrar recepción” enviará el estado 5.</p>
                    <div class="receive-form-grid crm-ui-form-grid">
                        <div class="receive-field crm-ui-field"><label>Lugar recepcion</label><input id="receivePlace" value="Casa matriz"></div>
                        <div class="receive-field crm-ui-field"><label>Proveedor</label><input value="${esc(d.issuer_name || '')}" readonly></div>
                    </div>
                    <div class="receive-field crm-ui-field"><label>Observaciones / motivo rechazo</label><textarea id="receiveNotes" placeholder="Observacion interna o motivo de rechazo"></textarea></div>
                </div>
                <div class="receive-section crm-ui-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 crm-ui-inner-table-wrap"><table class="receive-lines crm-ui-inner-table"><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><a class="btn btn-outline" href="${xmlUrl}" target="_blank" rel="noopener">Ver XML</a> <a class="btn btn-outline" href="${pdfUrl}" target="_blank" rel="noopener">Abrir PDF</a></span></div>
                <iframe class="receive-pdf-frame" src="${pdfUrl}"></iframe>
            </div>
        </div>`;
        $('receiveModalFooter').innerHTML = `<div class="modal-footer-actions-left"><button type="button" class="btn btn-outline" id="cancelReceiveBtn"><i data-lucide="x"></i><span>Cancelar</span></button></div><div class="modal-footer-actions-right"><button type="button" class="btn btn-primary" id="saveReceiveDecisionBtn" ${factoPending ? '' : 'disabled'}><i data-lucide="check"></i><span>${factoPending ? 'Guardar aprobación' : 'No disponible en FACTO'}</span></button></div>`; refreshIcons();
    }

    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 = type === 'merchandise_received';
        const notes = $('receiveNotes').value.trim();
        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; }
        if (type === 'approved_with_observations' && !notes) { alert('Para aprobar con reparo debes registrar la observación.'); 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 crm-ui-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 crm-ui-form-grid">
                <div class="receive-section crm-ui-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 crm-ui-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 = `<div class="modal-footer-actions-right"><button type="button" class="btn btn-primary" id="backToReceiveListBtn"><i data-lucide="arrow-left"></i><span>Volver al listado</span></button></div>`; refreshIcons();
    }

    function syncModalBodyLock(){
        const hasOpenModal = Array.from(document.querySelectorAll('.product-modal-backdrop.show')).some((modal) => modal.getAttribute('aria-hidden') !== 'true');
        document.body.classList.toggle('is-modal-open', hasOpenModal);
    }
    function closeModal(){ $('receiveModal').style.display='none'; $('receiveModal').classList.remove('show'); $('receiveModal').setAttribute('aria-hidden','true'); syncModalBodyLock(); }

    on(document, 'click', e => {
        if (e.target === $('receiveModal')) { closeModal(); return; }
        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; }
        const detail = e.target.closest('[data-receive-id]');
        if (detail) { openDecision(detail.dataset.receiveId).catch(err => alert(err.message)); return; }
        const action = e.target.closest('button, a');
        const actionId = action ? action.id : '';
        if (actionId === 'reloadReceiveBtn') syncReceive();
        if (actionId === 'searchReceiveBtn') loadReceive();
        if (actionId === 'openBulkReceiveBtn') renderBulkDecision();
        if (actionId === 'clearReceiveFiltersBtn') { $('receiveStatus').value=''; $('receiveType').value='all'; $('receiveRut').value=''; $('receiveFolio').value=''; $('receivePo').value=''; state.selected.clear(); loadReceive(); }
        if (actionId === 'closeReceiveModalBtn' || actionId === 'cancelReceiveBtn' || actionId === 'backToReceiveListBtn') closeModal();
        if (actionId === 'saveReceiveDecisionBtn') saveDecision();
        if (actionId === 'saveBulkReceiveDecisionBtn') saveBulkDecision();
    });
    on(document, 'change', function(e){
        if (e.target && e.target.id === 'receiveSelectAll') {
            const shouldSelect = Boolean(e.target.checked);
            state.rows.filter(canApproveReject).forEach(r => {
                const id = String(r.id);
                if (shouldSelect) state.selected.add(id); else state.selected.delete(id);
            });
            renderRows();
            updateBulkBar();
        }
    });

    ['receiveEnv','receivePeriod','receiveStatus','receiveType'].forEach(id => on($(id),'change', loadReceive));
    on($('receiveMobileTab'), 'change', (event) => {
        state.tab = event.target.value || 'pending';
        loadReceive();
    });
    ['receiveRut','receiveFolio','receivePo'].forEach(id => on($(id),'keydown', e => { if(e.key === 'Enter') loadReceive(); }));
    on(document,'keydown', e => { if(e.key === 'Escape' && $('receiveModal')?.classList.contains('show')) closeModal(); });
    loadReceive();
})();
</script>

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