<?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.receivables') && !user_can('billing.payments') && !user_can('module.billing') && current_user_role() !== 'admin') {
    http_response_code(403);
    die('No tienes permisos para acceder a Cuentas por cobrar.');
}

$page_title = 'Cuentas por cobrar';
$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="billingReceivablesMain" data-spa-module="collections:receivables">
    <?php require_once '../../layouts/topbar.php'; ?>
    <section id="receivablesMain" class="content receivables-main billing-page-shell billing-phase-content billing-crm-content crm-ui-page-content crm-ui-page">
            <div class="receivables-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>Cuentas por cobrar</h2>
                    <p class="text-muted">Facturas afectas y exentas que generan cuentas por cobrar, pagos y saldos pendientes.</p>
                </div>
                <div class="receivables-header-actions cluster top-actions-cluster billing-page-header-actions crm-ui-page-actions">
                    <input type="hidden" id="receivablesEnv" value="<?php echo htmlspecialchars($billingEnvironment, ENT_QUOTES, 'UTF-8'); ?>">
                    <details class="billing-actions-menu" data-billing-actions-scope="receivables" 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>Recalcular estados</button></div></details>
                    <button type="button" class="btn btn-primary btn-icon-mobile" id="reloadReceivablesBtn" title="Actualizar cuentas por cobrar"><i data-lucide="refresh-cw"></i><span class="mobile-hidden">Actualizar</span></button>
                </div>
            </div>

            <section class="filter-bar-container receivables-toolbar billing-toolbar billing-filter-bar billing-filter-bar--dates crm-ui-filter">
                <input type="search" id="receivablesSearch" class="receivables-input input" placeholder="Buscar cliente, RUT, folio o cotización" autocomplete="off">
                <select id="receivablesStatus" class="receivables-input input">
                    <option value="open" selected>Impagos / parciales</option><option value="all">Todos los estados</option><option value="por_cobrar">Por cobrar</option><option value="atrasado">Atrasado</option><option value="parcial">Parcial</option><option value="pagado">Pagado</option><option value="incobrable">Incobrable</option><option value="anulado">Anulado</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="receivablesFrom" class="receivables-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="receivablesTo" class="receivables-input input" aria-label="Hasta"><em>dd/mm/aaaa</em></label>
                </div>
            </section>

            <section id="receivablesIndicators" class="billing-table-indicators" aria-live="polite"></section>

            <section class="card receivables-card billing-data-card crm-ui-table-card">
                <div class="receivables-bulkbar billing-bulkbar crm-ui-bulkbar">
                    <div class="billing-selection-summary crm-ui-bulkbar-summary"><strong id="receivablesSelectedCount">0 seleccionados</strong><span id="receivablesSelectedTotal" class="receivables-muted">Cobro bruto seleccionado: $0</span></div>
                    <div class="receivables-actions billing-selection-actions crm-ui-bulkbar-actions">
                        <button type="button" class="btn btn-primary" id="bulkCollectionBtn" disabled><i data-lucide="banknote-arrow-down"></i><span>Registrar cobro</span></button>
                        <button type="button" class="btn btn-outline" id="clearReceivablesSelectionBtn" disabled><i data-lucide="x"></i><span>Limpiar selección</span></button>
                    </div>
                </div>
            </section>
            <div id="receivablesGroups" class="billing-document-groups" aria-live="polite"></div>
    </section>

        <div id="receivableModal" 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 receivables-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="receivableModalTitle">Documento emitido</h2>
                        <p id="receivableModalSubtitle" class="receivables-muted"></p>
                    </div>
                    <button type="button" class="btn btn-outline action-square-btn billing-modal-close crm-ui-modal-icon-btn" id="closeReceivableModalBtn" aria-label="Cerrar"><i data-lucide="x"></i></button>
                </div>
                <div class="product-modal-body crm-ui-modal-body" id="receivableModalBody"></div>
                <div class="product-modal-footer billing-modal-footer crm-ui-modal-footer" id="receivableModalFooter"></div>
            </div>
        </div>

        <div id="receivableBulkModal" 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 receivables-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>Registro masivo de cobro</h2>
                        <p id="receivableBulkSubtitle" class="receivables-muted"></p>
                    </div>
                    <button type="button" class="btn btn-outline action-square-btn billing-modal-close crm-ui-modal-icon-btn" id="closeReceivableBulkBtn" aria-label="Cerrar"><i data-lucide="x"></i></button>
                </div>
                <div class="product-modal-body crm-ui-modal-body" id="receivableBulkBody"></div>
                <div class="product-modal-footer billing-modal-footer crm-ui-modal-footer" id="receivableBulkFooter"></div>
            </div>
        </div>
<?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();
$receivablesJsVersion = @filemtime(__DIR__ . '/receivables.js') ?: 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/receivables.js?v=<?php echo (int)$receivablesJsVersion; ?>"></script>
</main>
<?php require_once '../../layouts/footer.php'; ?>
