<?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_once '../../core/format.php';

require_login();
if (!user_can('billing.documents') && !user_can('billing.view') && !user_can('module.billing') && current_user_role() !== 'admin') {
    http_response_code(403);
    die('No tienes permisos para acceder a la consulta de documentos tributarios.');
}

$page_title = 'Consulta documentos tributarios';
$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="billingDocumentsMain" data-spa-module="billing:documents">
    <?php require_once '../../layouts/topbar.php'; ?>
    <section id="documentsMain" class="content documents-main billing-page-shell billing-phase-content billing-crm-content crm-ui-page-content crm-ui-page">
            <div class="documents-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>Consulta documentos tributarios</h2>
                    <p class="text-muted">Consulta unificada de todos los DTE emitidos y recibidos, separados por origen.</p>
                </div>
                <div class="documents-header-actions cluster top-actions-cluster billing-page-header-actions crm-ui-page-actions">
                    <input type="hidden" id="documentsEnv" value="<?php echo htmlspecialchars($billingEnvironment, ENT_QUOTES, 'UTF-8'); ?>">
                    <details class="billing-actions-menu" data-billing-actions-scope="documents" data-close-outside><summary class="btn btn-outline"><i data-lucide="ellipsis-vertical"></i><span>Acciones</span></summary><div class="billing-actions-menu__panel"><button type="button" data-billing-bulk-action="xlsx"><i data-lucide="sheet"></i>Descargar XLSX</button><button type="button" data-billing-bulk-action="refresh"><i data-lucide="refresh-cw"></i>Sincronizar estados FACTO</button></div></details>
                    <a class="btn btn-outline btn-icon-mobile" href="/modules/billing/" title="Emitir documento"><i data-lucide="file-plus-2"></i><span class="mobile-hidden">Emitir documento</span></a>
                    <button type="button" class="btn btn-primary btn-icon-mobile" id="reloadDocumentsBtn" title="Actualizar documentos"><i data-lucide="refresh-cw"></i><span class="mobile-hidden">Actualizar</span></button>
                </div>
            </div>

            <div id="documentsLoadError" class="documents-warning billing-alert billing-alert-warning" style="display:none;"></div>

            <section class="filter-bar-container documents-toolbar billing-toolbar billing-filter-bar billing-filter-bar--dates crm-ui-filter">
                <input type="search" id="documentsSearch" class="documents-input input" placeholder="Buscar contraparte, RUT, folio o cotización" autocomplete="off">
                <select id="documentsOrigin" class="documents-input input" aria-label="Origen tributario">
                    <option value="all">Emitidos y recibidos</option>
                    <option value="issued">Sólo emitidos</option>
                    <option value="received">Sólo recibidos</option>
                </select>
                <select id="documentsFamily" class="documents-input input">
                    <option value="all">Todos los documentos</option>
                    <option value="invoice">Facturas</option>
                    <option value="credit_note">Notas de crédito</option>
                    <option value="debit_note">Notas de débito</option>
                    <option value="dispatch_guide">Guías de despacho</option>
                    <option value="export">Facturas de exportación</option>
                    <option value="receipt">Boletas</option>
                    <option value="other">Otros documentos</option>
                </select>
                <div class="billing-filter-date-group crm-ui-date-group">
                    <label class="billing-date-filter-field crm-ui-date-field"><span>Desde</span><input type="date" id="documentsFrom" class="documents-input input" aria-label="Desde"><em>dd/mm/aaaa</em></label>
                    <label class="billing-date-filter-field crm-ui-date-field"><span>Hasta</span><input type="date" id="documentsTo" class="documents-input input" aria-label="Hasta"><em>dd/mm/aaaa</em></label>
                </div>
            </section>

            <div id="documentsGroups" class="billing-document-groups" aria-live="polite"></div>
    </section>

        <div id="documentModal" 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 documents-modal-box billing-modal-box crm-ui-modal-box" id="documentModalBox" data-active-layer="documentLayerDetail">

                <div id="documentLayerDetail" class="documents-modal-layer billing-modal-layer active crm-ui-modal-layer">
                    <div class="product-modal-header documents-layer-header billing-modal-header crm-ui-modal-header">
                        <button type="button" class="btn btn-outline action-square-btn documents-flow-close billing-modal-close crm-ui-modal-icon-btn" title="Volver" aria-label="Volver">
                            <i data-lucide="arrow-left"></i>
                        </button>
                        <div class="documents-layer-title billing-modal-heading crm-ui-modal-heading">
                            <h2 id="documentDetailTitle">Documento tributario</h2>
                            <p id="documentDetailSubtitle" class="documents-muted"></p>
                        </div>
                        <button type="button" class="btn btn-outline action-square-btn documents-flow-close billing-modal-close crm-ui-modal-icon-btn" title="Cerrar" aria-label="Cerrar">
                            <i data-lucide="x"></i>
                        </button>
                    </div>
                    <div class="product-modal-body crm-ui-modal-body" id="documentDetailBody"></div>
                    <div class="product-modal-footer billing-modal-footer crm-ui-modal-footer" id="documentDetailFooter"></div>
                </div>

                <div id="documentLayerAdjustment" class="documents-modal-layer billing-modal-layer crm-ui-modal-layer">
                    <div class="product-modal-header documents-layer-header billing-modal-header crm-ui-modal-header">
                        <button type="button" class="btn btn-outline action-square-btn billing-modal-back crm-ui-modal-icon-btn" data-layer-back="detail" title="Volver al documento" aria-label="Volver al documento">
                            <i data-lucide="arrow-left"></i>
                        </button>
                        <div class="documents-layer-title billing-modal-heading crm-ui-modal-heading">
                            <h2 id="adjustmentLayerTitle">Documento complementario</h2>
                            <p id="adjustmentLayerSubtitle" class="documents-muted"></p>
                        </div>
                        <button type="button" class="btn btn-outline action-square-btn documents-flow-close billing-modal-close crm-ui-modal-icon-btn" title="Cerrar" aria-label="Cerrar">
                            <i data-lucide="x"></i>
                        </button>
                    </div>
                    <div class="product-modal-body crm-ui-modal-body" id="adjustmentLayerBody"></div>
                    <div class="product-modal-footer billing-modal-footer crm-ui-modal-footer" id="adjustmentLayerFooter"></div>
                </div>

                <div id="documentLayerPreview" class="documents-modal-layer billing-modal-layer crm-ui-modal-layer">
                    <div class="product-modal-header documents-layer-header billing-modal-header crm-ui-modal-header">
                        <button type="button" class="btn btn-outline action-square-btn billing-modal-back crm-ui-modal-icon-btn" data-layer-back="adjustment" title="Volver a preparar" aria-label="Volver a preparar">
                            <i data-lucide="arrow-left"></i>
                        </button>
                        <div class="documents-layer-title billing-modal-heading crm-ui-modal-heading">
                            <h2 id="previewLayerTitle">Preview FACTO sandbox</h2>
                            <p id="previewLayerSubtitle" class="documents-muted"></p>
                        </div>
                        <button type="button" class="btn btn-outline action-square-btn documents-flow-close billing-modal-close crm-ui-modal-icon-btn" title="Cerrar" aria-label="Cerrar">
                            <i data-lucide="x"></i>
                        </button>
                    </div>
                    <div class="product-modal-body crm-ui-modal-body" id="previewLayerBody"></div>
                    <div class="product-modal-footer billing-modal-footer crm-ui-modal-footer" id="previewLayerFooter"></div>
                </div>

                <div id="documentLayerConfirm" class="documents-modal-layer billing-modal-layer crm-ui-modal-layer">
                    <div class="product-modal-header documents-layer-header billing-modal-header crm-ui-modal-header">
                        <button type="button" class="btn btn-outline action-square-btn billing-modal-back crm-ui-modal-icon-btn" data-layer-back="preview" title="Volver al preview" aria-label="Volver al preview">
                            <i data-lucide="arrow-left"></i>
                        </button>
                        <div class="documents-layer-title billing-modal-heading crm-ui-modal-heading">
                            <h2 id="confirmLayerTitle">Confirmar emisión sandbox</h2>
                            <p id="confirmLayerSubtitle" class="documents-muted"></p>
                        </div>
                        <button type="button" class="btn btn-outline action-square-btn documents-flow-close billing-modal-close crm-ui-modal-icon-btn" title="Cerrar" aria-label="Cerrar">
                            <i data-lucide="x"></i>
                        </button>
                    </div>
                    <div class="product-modal-body crm-ui-modal-body" id="confirmLayerBody"></div>
                    <div class="product-modal-footer billing-modal-footer crm-ui-modal-footer" id="confirmLayerFooter"></div>
                </div>

                <div id="documentLayerResult" class="documents-modal-layer billing-modal-layer crm-ui-modal-layer">
                    <div class="product-modal-header documents-layer-header billing-modal-header crm-ui-modal-header">
                        <button type="button" class="btn btn-outline action-square-btn billing-modal-back crm-ui-modal-icon-btn" data-layer-back="detail-refresh" title="Volver al documento" aria-label="Volver al documento">
                            <i data-lucide="arrow-left"></i>
                        </button>
                        <div class="documents-layer-title billing-modal-heading crm-ui-modal-heading">
                            <h2 id="resultLayerTitle">Resultado</h2>
                            <p id="resultLayerSubtitle" class="documents-muted"></p>
                        </div>
                        <button type="button" class="btn btn-outline action-square-btn documents-flow-close billing-modal-close crm-ui-modal-icon-btn" title="Cerrar" aria-label="Cerrar">
                            <i data-lucide="x"></i>
                        </button>
                    </div>
                    <div class="product-modal-body crm-ui-modal-body" id="resultLayerBody"></div>
                    <div class="product-modal-footer billing-modal-footer crm-ui-modal-footer" id="resultLayerFooter"></div>
                </div>

                <div id="documentLayerGuideSource" class="documents-modal-layer billing-modal-layer crm-ui-modal-layer">
                    <div class="product-modal-header documents-layer-header billing-modal-header crm-ui-modal-header">
                        <button type="button" class="btn btn-outline action-square-btn documents-flow-close billing-modal-close crm-ui-modal-icon-btn" title="Volver" aria-label="Volver"><i data-lucide="arrow-left"></i></button>
                        <div class="documents-layer-title billing-modal-heading crm-ui-modal-heading"><h2 id="guideSourceTitle">Nueva guía de despacho</h2><p class="documents-muted">Selecciona una cotización o factura como origen.</p></div>
                        <button type="button" class="btn btn-outline action-square-btn documents-flow-close billing-modal-close crm-ui-modal-icon-btn" title="Cerrar" aria-label="Cerrar"><i data-lucide="x"></i></button>
                    </div>
                    <div class="product-modal-body crm-ui-modal-body" id="guideSourceBody"></div>
                    <div class="product-modal-footer billing-modal-footer crm-ui-modal-footer" id="guideSourceFooter"></div>
                </div>

                <div id="documentLayerGuidePrepare" class="documents-modal-layer billing-modal-layer crm-ui-modal-layer">
                    <div class="product-modal-header documents-layer-header billing-modal-header crm-ui-modal-header">
                        <button type="button" class="btn btn-outline action-square-btn billing-modal-back crm-ui-modal-icon-btn" data-guide-back="source" title="Volver al origen" aria-label="Volver al origen"><i data-lucide="arrow-left"></i></button>
                        <div class="documents-layer-title billing-modal-heading crm-ui-modal-heading"><h2 id="guidePrepareTitle">Preparar guía de despacho</h2><p id="guidePrepareSubtitle" class="documents-muted"></p></div>
                        <button type="button" class="btn btn-outline action-square-btn documents-flow-close billing-modal-close crm-ui-modal-icon-btn" title="Cerrar" aria-label="Cerrar"><i data-lucide="x"></i></button>
                    </div>
                    <div class="product-modal-body crm-ui-modal-body" id="guidePrepareBody"></div>
                    <div class="product-modal-footer billing-modal-footer crm-ui-modal-footer" id="guidePrepareFooter"></div>
                </div>

                <div id="documentLayerGuidePreview" class="documents-modal-layer billing-modal-layer crm-ui-modal-layer">
                    <div class="product-modal-header documents-layer-header billing-modal-header crm-ui-modal-header">
                        <button type="button" class="btn btn-outline action-square-btn billing-modal-back crm-ui-modal-icon-btn" data-guide-back="prepare" title="Volver a preparar" aria-label="Volver a preparar"><i data-lucide="arrow-left"></i></button>
                        <div class="documents-layer-title billing-modal-heading crm-ui-modal-heading"><h2 id="guidePreviewTitle">Preview guía FACTO sandbox</h2><p id="guidePreviewSubtitle" class="documents-muted"></p></div>
                        <button type="button" class="btn btn-outline action-square-btn documents-flow-close billing-modal-close crm-ui-modal-icon-btn" title="Cerrar" aria-label="Cerrar"><i data-lucide="x"></i></button>
                    </div>
                    <div class="product-modal-body crm-ui-modal-body" id="guidePreviewBody"></div>
                    <div class="product-modal-footer billing-modal-footer crm-ui-modal-footer" id="guidePreviewFooter"></div>
                </div>

                <div id="documentLayerGuideConfirm" class="documents-modal-layer billing-modal-layer crm-ui-modal-layer">
                    <div class="product-modal-header documents-layer-header billing-modal-header crm-ui-modal-header">
                        <button type="button" class="btn btn-outline action-square-btn billing-modal-back crm-ui-modal-icon-btn" data-guide-back="preview" title="Volver al preview" aria-label="Volver al preview"><i data-lucide="arrow-left"></i></button>
                        <div class="documents-layer-title billing-modal-heading crm-ui-modal-heading"><h2 id="guideConfirmTitle">Confirmar guía sandbox</h2><p id="guideConfirmSubtitle" class="documents-muted"></p></div>
                        <button type="button" class="btn btn-outline action-square-btn documents-flow-close billing-modal-close crm-ui-modal-icon-btn" title="Cerrar" aria-label="Cerrar"><i data-lucide="x"></i></button>
                    </div>
                    <div class="product-modal-body crm-ui-modal-body" id="guideConfirmBody"></div>
                    <div class="product-modal-footer billing-modal-footer crm-ui-modal-footer" id="guideConfirmFooter"></div>
                </div>

                <div id="documentLayerGuideResult" class="documents-modal-layer billing-modal-layer crm-ui-modal-layer">
                    <div class="product-modal-header documents-layer-header billing-modal-header crm-ui-modal-header">
                        <button type="button" class="btn btn-outline action-square-btn billing-modal-back crm-ui-modal-icon-btn" data-guide-back="close" title="Volver a documentos" aria-label="Volver a documentos"><i data-lucide="arrow-left"></i></button>
                        <div class="documents-layer-title billing-modal-heading crm-ui-modal-heading"><h2 id="guideResultTitle">Resultado guía</h2><p id="guideResultSubtitle" class="documents-muted"></p></div>
                        <button type="button" class="btn btn-outline action-square-btn documents-flow-close billing-modal-close crm-ui-modal-icon-btn" title="Cerrar" aria-label="Cerrar"><i data-lucide="x"></i></button>
                    </div>
                    <div class="product-modal-body crm-ui-modal-body" id="guideResultBody"></div>
                    <div class="product-modal-footer billing-modal-footer crm-ui-modal-footer" id="guideResultFooter"></div>
                </div>

            </div>
        </div>
<?php
        $jsPath = __DIR__ . '/documents.js';
        $jsVersion = file_exists($jsPath) ? filemtime($jsPath) : time();
        $guideJsPath = __DIR__ . '/dispatch_guides.js';
        $guideJsVersion = file_exists($guideJsPath) ? filemtime($guideJsPath) : time();
        ?>
<?php
        $sortJsPath = dirname(__DIR__, 2) . '/assets/js/icy-table-sort.js';
        $sortJsVersion = file_exists($sortJsPath) ? filemtime($sortJsPath) : time();
        $referenceTableJsPath = dirname(__DIR__, 2) . '/assets/js/billing-table-reference.js';
        $referenceTableJsVersion = file_exists($referenceTableJsPath) ? filemtime($referenceTableJsPath) : time();
        ?>
        <script src="/assets/js/icy-table-sort.js?v=<?php echo (int)$sortJsVersion; ?>"></script>
        <script src="/assets/js/billing-table-reference.js?v=<?php echo (int)$referenceTableJsVersion; ?>"></script>
        <script src="/modules/billing/documents.js?v=<?php echo (int)$jsVersion; ?>"></script>
        <script src="/modules/billing/dispatch_guides.js?v=<?php echo (int)$guideJsVersion; ?>"></script>
</main>
<?php require_once '../../layouts/footer.php'; ?>
