<?php
require_once '../../core/config.php';
require_once '../../core/session.php';
require_once '../../core/permissions.php';
require_once '../../core/format.php';
require_once __DIR__ . '/../customers/_customer_quick_fields.php';
require_once '../../services/crm/SupplierDirectoryService.php';

require_login();
require_permission('module.customers');

$page_title = 'Proveedores';
$search = trim((string)($_GET['q'] ?? ''));
$status = trim((string)($_GET['status'] ?? ''));
$service = new SupplierDirectoryService();
$suppliers = $service->listSuppliers($search, $status);

$kpis = array('suppliers' => count($suppliers), 'active' => 0, 'open_documents' => 0, 'open_balance' => 0.0);
foreach ($suppliers as $supplier) {
    if (($supplier['supplier_status'] ?? '') === 'active') $kpis['active']++;
    $kpis['open_documents'] += (int)($supplier['open_documents'] ?? 0);
    $kpis['open_balance'] += (float)($supplier['open_balance'] ?? 0);
}

$statusLabels = array('active' => 'Activo', 'inactive' => 'Inactivo', 'blocked' => 'Bloqueado');

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

<main class="app-main" id="suppliers-main">
    <?php require_once '../../layouts/topbar.php'; ?>
    <section class="content suppliers-content">
        <div class="page-header page-header-compact suppliers-header">
            <div class="page-header-content">
                <span class="label">Directorio financiero</span>
                <h1>Proveedores</h1>
                <p class="text-secondary">Contrapartes de compra, condiciones de pago y centros financieros predeterminados.</p>
            </div>
            <div class="cluster actions-cluster">
                <button type="button" class="btn btn-primary icon-btn-mobile" id="openSupplierCreateBtn">
                    <i data-lucide="plus"></i><span class="mobile-hidden">Nuevo proveedor</span>
                </button>
            </div>
        </div>

        <?php if (isset($_GET['created'])): ?>
            <div class="alert alert-success supplier-alert">Proveedor guardado correctamente.</div>
        <?php endif; ?>

        <div class="supplier-kpis">
            <article class="supplier-kpi"><span>Proveedores</span><strong><?php echo (int)$kpis['suppliers']; ?></strong></article>
            <article class="supplier-kpi"><span>Activos</span><strong><?php echo (int)$kpis['active']; ?></strong></article>
            <article class="supplier-kpi"><span>DTE con saldo</span><strong><?php echo (int)$kpis['open_documents']; ?></strong></article>
            <article class="supplier-kpi"><span>Saldo por pagar</span><strong>$<?php echo number_format($kpis['open_balance'], 0, ',', '.'); ?></strong></article>
        </div>

        <section class="card supplier-filter-card">
            <form method="GET" action="/modules/suppliers/" class="supplier-filter-form" data-spa-form="true">
                <div class="form-field supplier-search-field">
                    <label class="sr-only" for="supplierSearch">Buscar proveedor</label>
                    <input class="input" id="supplierSearch" name="q" value="<?php echo safe_text($search); ?>" placeholder="Buscar proveedor, RUT, contacto o email">
                </div>
                <div class="form-field supplier-status-field">
                    <label class="sr-only" for="supplierStatus">Estado</label>
                    <select class="select" id="supplierStatus" name="status">
                        <option value="">Todos los estados</option>
                        <?php foreach ($statusLabels as $value => $label): ?>
                            <option value="<?php echo safe_text($value); ?>" <?php echo $status === $value ? 'selected' : ''; ?>><?php echo safe_text($label); ?></option>
                        <?php endforeach; ?>
                    </select>
                </div>
                <button class="btn btn-primary" type="submit"><i data-lucide="search"></i><span>Buscar</span></button>
                <?php if ($search !== '' || $status !== ''): ?>
                    <a class="btn btn-outline" href="/modules/suppliers/"><i data-lucide="x"></i><span class="mobile-hidden">Limpiar</span></a>
                <?php endif; ?>
            </form>
        </section>

        <section class="card supplier-table-card">
            <div class="card-header supplier-table-header">
                <div>
                    <h3>Directorio de proveedores</h3>
                    <p class="text-secondary text-sm"><?php echo count($suppliers); ?> resultado(s)</p>
                </div>
            </div>
            <div class="supplier-table-scroll">
                <table class="supplier-table">
                    <colgroup>
                        <col class="col-supplier"><col class="col-contact"><col class="col-terms"><col class="col-center"><col class="col-docs"><col class="col-balance"><col class="col-status"><col class="col-action">
                    </colgroup>
                    <thead>
                        <tr>
                            <th class="col-supplier">Proveedor</th>
                            <th class="col-contact">Contacto</th>
                            <th class="col-terms">Condición</th>
                            <th class="col-center">Centro de costo</th>
                            <th class="col-docs">DTE</th>
                            <th class="col-balance">Saldo abierto</th>
                            <th class="col-status">Estado</th>
                            <th class="col-action"><span class="sr-only">Acción</span></th>
                        </tr>
                    </thead>
                    <tbody>
                    <?php foreach ($suppliers as $supplier): ?>
                        <?php
                            $displayName = $supplier['commercial_name'] ?: ($supplier['customer_name'] ?: $supplier['legal_name']);
                            $supplierStatus = $supplier['supplier_status'] ?: 'active';
                            $statusClass = $supplierStatus === 'active' ? 'badge-success' : ($supplierStatus === 'blocked' ? 'badge-error' : '');
                        ?>
                        <tr>
                            <td class="col-supplier">
                                <strong><?php echo safe_text($displayName); ?></strong>
                                <small><?php echo safe_text($supplier['customer_tax_id'] ? format_rut($supplier['customer_tax_id']) : 'Sin RUT'); ?></small>
                            </td>
                            <td class="col-contact">
                                <span><?php echo safe_text($supplier['contact_name'] ?: 'Sin contacto'); ?></span>
                                <small><?php echo safe_text($supplier['email'] ?: 'Sin email'); ?></small>
                            </td>
                            <td class="col-terms"><?php echo safe_text($supplier['supplier_payment_term_label'] ?: icylab_payment_terms_label($supplier['payment_terms'] ?? 'contado')); ?></td>
                            <td class="col-center"><?php echo safe_text($supplier['cost_center_name'] ?: 'Sin centro'); ?></td>
                            <td class="col-docs"><strong><?php echo (int)$supplier['documents_count']; ?></strong><small><?php echo (int)$supplier['open_documents']; ?> con saldo</small></td>
                            <td class="col-balance"><strong>$<?php echo number_format((float)$supplier['open_balance'], 0, ',', '.'); ?></strong></td>
                            <td class="col-status"><span class="badge <?php echo $statusClass; ?>"><?php echo safe_text($statusLabels[$supplierStatus] ?? ucfirst($supplierStatus)); ?></span></td>
                            <td class="col-action"><a class="btn btn-sm btn-outline" href="/modules/suppliers/view.php?id=<?php echo (int)$supplier['id']; ?>" aria-label="Ver proveedor <?php echo safe_text($displayName); ?>"><i data-lucide="chevron-right"></i></a></td>
                        </tr>
                    <?php endforeach; ?>
                    <?php if (!$suppliers): ?>
                        <tr><td colspan="8" class="text-center text-secondary py-8">No hay proveedores que coincidan con los filtros.</td></tr>
                    <?php endif; ?>
                    </tbody>
                </table>
            </div>
        </section>
    </section>

    <div id="supplierCreateModal" class="supplier-modal-backdrop" aria-hidden="true">
        <div class="supplier-modal-box" role="dialog" aria-modal="true" aria-labelledby="supplierCreateTitle">
            <header class="supplier-modal-header">
                <div>
                    <h2 id="supplierCreateTitle">Crear proveedor</h2>
                    <p>El RUT se reutiliza como contraparte única si ya existe como cliente.</p>
                </div>
                <button type="button" class="icon-btn" data-close-supplier-modal aria-label="Cerrar"><i data-lucide="x"></i></button>
            </header>
            <div class="supplier-modal-body">
                <form id="supplierCreateForm" action="/modules/suppliers/supplier_store.php" method="POST" data-no-spa="true">
                    <?php icylab_render_customer_quick_fields(array(
                        'entity_mode' => 'supplier',
                        'entity_label' => 'Proveedor',
                        'name_field' => 'customer_name',
                        'tax_field' => 'customer_tax_id',
                        'tax_id' => 'supplierCreateTaxId',
                        'phone_prefix_id' => 'supplier_create_phone_prefix',
                        'phone_number_id' => 'supplier_create_phone_number',
                        'phone_hidden_id' => 'supplier_create_real_phone',
                        'cost_center_field' => 'supplier_default_cost_center_id',
                        'values' => array('country' => 'Chile', 'supplier_status' => 'active'),
                        'required' => array('customer_name', 'country', 'address', 'district', 'city', 'region')
                    )); ?>
                </form>
            </div>
            <footer class="supplier-modal-footer">
                <button type="button" class="btn btn-outline" data-close-supplier-modal><i data-lucide="x"></i><span>Cancelar</span></button>
                <button type="submit" form="supplierCreateForm" class="btn btn-primary"><i data-lucide="save"></i><span>Guardar proveedor</span></button>
            </footer>
        </div>
    </div>

    <style>
    #suppliers-main{height:100dvh;max-height:100dvh;overflow:hidden;display:flex;flex-direction:column}
    #suppliers-main .suppliers-content{flex:1 1 0;min-height:0;overflow:hidden;display:flex;flex-direction:column;gap:12px;padding-bottom:12px}
    .suppliers-header{flex:0 0 auto;margin-bottom:0!important}.supplier-alert{flex:0 0 auto;margin:0}
    .supplier-kpis{display:grid;grid-template-columns:repeat(4,minmax(0,1fr));gap:12px;flex:0 0 auto}
    .supplier-kpi{background:var(--surface-1);border:1px solid var(--border-subtle);border-radius:var(--radius-lg);padding:16px;box-shadow:var(--shadow-sm);min-width:0}
    .supplier-kpi span{display:block;color:var(--text-muted);font-size:.74rem;font-weight:700;text-transform:uppercase;letter-spacing:.035em}.supplier-kpi strong{display:block;margin-top:7px;font-size:1.3rem;color:var(--text-primary);overflow:hidden;text-overflow:ellipsis}
    .supplier-filter-card{flex:0 0 auto;margin:0}.supplier-filter-form{padding:14px;display:grid;grid-template-columns:minmax(240px,1fr) 210px auto auto;gap:10px;align-items:end}.supplier-filter-form .form-field{margin:0}
    .supplier-table-card{flex:1 1 0;min-height:0;display:flex;flex-direction:column;overflow:hidden;margin:0}.supplier-table-header{flex:0 0 auto;padding:14px 16px}.supplier-table-header h3,.supplier-table-header p{margin:0}.supplier-table-scroll{flex:1 1 0;min-height:0;overflow-y:auto;overflow-x:hidden}
    .supplier-table{width:100%;border-collapse:separate;border-spacing:0;table-layout:fixed}.supplier-table th{position:sticky;top:0;z-index:2;background:var(--surface-2);color:var(--text-primary);font-size:.72rem;text-transform:uppercase;letter-spacing:.03em;text-align:left;padding:11px 12px;border-bottom:1px solid var(--border-default)}.supplier-table td{padding:12px;border-bottom:1px solid var(--border-subtle);vertical-align:middle;overflow:hidden;text-overflow:ellipsis}.supplier-table td small{display:block;color:var(--text-muted);margin-top:3px;white-space:nowrap;overflow:hidden;text-overflow:ellipsis}.supplier-table tr:hover td{background:var(--surface-2)}
    .supplier-table .col-supplier{width:22%}.supplier-table .col-contact{width:18%}.supplier-table .col-terms{width:12%}.supplier-table .col-center{width:16%}.supplier-table .col-docs{width:9%}.supplier-table .col-balance{width:12%}.supplier-table .col-status{width:8%}.supplier-table .col-action{width:58px;text-align:right}
    .supplier-modal-backdrop{position:fixed;inset:0;z-index:var(--z-modal);display:none;align-items:center;justify-content:center;padding:24px;background:rgba(0,0,0,.62);backdrop-filter:blur(4px);opacity:0;transition:opacity var(--motion-base)}.supplier-modal-backdrop.is-open{display:flex;opacity:1}.supplier-modal-box{width:min(980px,calc(100vw - 48px));height:min(760px,calc(100dvh - 64px));background:var(--surface-1);border:1px solid var(--border-default);border-radius:var(--radius-xl);box-shadow:var(--shadow-lg);display:flex;flex-direction:column;overflow:hidden}.supplier-modal-header,.supplier-modal-footer{flex:0 0 auto;padding:18px 24px;border-color:var(--border-subtle);background:var(--surface-1)}.supplier-modal-header{display:flex;align-items:flex-start;justify-content:space-between;gap:20px;border-bottom:1px solid var(--border-subtle)}.supplier-modal-header h2,.supplier-modal-header p{margin:0}.supplier-modal-header p{margin-top:4px;color:var(--text-muted)}.supplier-modal-body{flex:1 1 auto;min-height:0;overflow-y:auto;padding:22px 24px}.supplier-modal-footer{display:flex;justify-content:flex-end;gap:10px;border-top:1px solid var(--border-subtle)}body.billing-modal-open{overflow:hidden}
    @media(max-width:760px){#suppliers-main .suppliers-content{overflow-y:auto;padding:12px}.supplier-kpis{grid-template-columns:repeat(2,minmax(0,1fr))}.supplier-filter-form{grid-template-columns:minmax(0,1fr) auto}.supplier-status-field{grid-column:1/-1}.supplier-filter-form .btn span.mobile-hidden{display:none}.supplier-table-card{min-height:360px;flex:0 0 52dvh}.supplier-table-scroll{overflow-y:auto;overflow-x:hidden}.supplier-table .col-contact,.supplier-table .col-terms,.supplier-table .col-center,.supplier-table .col-docs,.supplier-table .col-status{display:none}.supplier-table .col-supplier{width:auto}.supplier-table .col-balance{width:108px}.supplier-table .col-action{width:54px}.supplier-table th,.supplier-table td{padding:10px 7px}.supplier-modal-backdrop{padding:100px 12px}.supplier-modal-box{width:100%;height:calc(100dvh - 200px);min-height:430px;max-height:720px;border-radius:var(--radius-xl)}.supplier-modal-header{padding:15px 16px}.supplier-modal-header h2{font-size:1.25rem}.supplier-modal-header p{font-size:.82rem}.supplier-modal-body{padding:16px}.supplier-modal-footer{padding:12px 16px}.supplier-modal-footer .btn{min-width:0;padding-inline:12px}.supplier-modal-footer .btn span{white-space:nowrap}.customer-quick-grid{grid-template-columns:1fr!important}.customer-quick-grid>[class*="span-"]{grid-column:1/-1!important}}
    @media(max-width:420px){.supplier-modal-backdrop{padding:76px 8px}.supplier-modal-box{height:calc(100dvh - 152px);min-height:390px}.supplier-kpi{padding:12px}.supplier-kpi strong{font-size:1.08rem}}
    </style>

    <script src="/assets/js/customer-location.js?v=1.2.6"></script>
    <script>
    (function(){
        if (window.__supplierIndexCleanup) window.__supplierIndexCleanup();
        var controller = new AbortController();
        var signal = controller.signal;
        var modal = document.getElementById('supplierCreateModal');
        var form = document.getElementById('supplierCreateForm');
        function openModal(){
            if (!modal) return;
            if (form) form.reset();
            modal.style.display = 'flex';
            requestAnimationFrame(function(){ modal.classList.add('is-open'); });
            modal.setAttribute('aria-hidden','false');
            document.body.classList.add('billing-modal-open');
            var first = modal.querySelector('input:not([type=hidden])'); if(first) setTimeout(function(){first.focus();},80);
            if (window.lucide) window.lucide.createIcons();
        }
        function closeModal(){
            if (!modal) return;
            modal.classList.remove('is-open');
            modal.setAttribute('aria-hidden','true');
            document.body.classList.remove('billing-modal-open');
            setTimeout(function(){ if(!modal.classList.contains('is-open')) modal.style.display='none'; },180);
        }
        function syncPhone(){
            var prefix=document.getElementById('supplier_create_phone_prefix');
            var number=document.getElementById('supplier_create_phone_number');
            var hidden=document.getElementById('supplier_create_real_phone');
            if(!prefix||!number||!hidden)return;
            var digits=number.value.replace(/[^0-9\s-]/g,''); number.value=digits;
            hidden.value=digits.replace(/[^0-9]/g,'').length ? prefix.value+' '+digits : '';
        }
        document.getElementById('openSupplierCreateBtn')?.addEventListener('click',openModal,{signal:signal});
        modal?.addEventListener('pointerdown',function(e){if(e.target===modal)closeModal();},{signal:signal});
        modal?.querySelectorAll('[data-close-supplier-modal]').forEach(function(btn){btn.addEventListener('click',closeModal,{signal:signal});});
        document.addEventListener('keydown',function(e){if(e.key==='Escape'&&modal?.classList.contains('is-open'))closeModal();},{signal:signal});
        document.getElementById('supplier_create_phone_prefix')?.addEventListener('change',syncPhone,{signal:signal});
        document.getElementById('supplier_create_phone_number')?.addEventListener('input',syncPhone,{signal:signal});
        form?.addEventListener('submit',syncPhone,{signal:signal});
        window.__supplierIndexCleanup=function(){controller.abort();document.body.classList.remove('billing-modal-open');};
    })();
    </script>
</main>
<?php require_once '../../layouts/footer.php'; ?>
