<?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');

$id = isset($_GET['id']) ? (int)$_GET['id'] : 0;
$service = new SupplierDirectoryService();
$supplier = $service->getSupplier($id);
if (!$supplier) {
    http_response_code(404);
    die('Proveedor no encontrado.');
}
$documents = $service->getDocuments($id, 120);
$summary = $service->summarizeDocuments($documents);
$page_title = 'Ficha Proveedor';
$displayName = $supplier['commercial_name'] ?: ($supplier['customer_name'] ?: $supplier['legal_name']);
$statusLabels = array('active' => 'Activo', 'inactive' => 'Inactivo', 'blocked' => 'Bloqueado');
$documentLabels = array('33' => 'Factura', '34' => 'Factura exenta', '52' => 'Guía', '56' => 'Nota débito', '61' => 'Nota crédito');

require_once '../../layouts/header.php';
require_once '../../layouts/sidebar.php';
?>
<main class="app-main" id="supplier-view-main">
    <?php require_once '../../layouts/topbar.php'; ?>
    <section class="content supplier-view-content">
        <div class="page-header page-header-compact supplier-view-header">
            <div class="page-header-content">
                <span class="label">Proveedor 360 financiero</span>
                <h1><?php echo safe_text($displayName); ?></h1>
                <p class="text-secondary">
                    <?php echo safe_text($supplier['legal_name'] ?: $supplier['customer_name']); ?>
                    <?php if (!empty($supplier['customer_tax_id'])): ?> · <?php echo safe_text(format_rut($supplier['customer_tax_id'])); ?><?php endif; ?>
                    · <?php echo safe_text($statusLabels[$supplier['supplier_status']] ?? ucfirst((string)$supplier['supplier_status'])); ?>
                </p>
            </div>
            <div class="cluster actions-cluster">
                <a class="btn btn-outline icon-btn-mobile" href="/modules/suppliers/"><i data-lucide="chevron-left"></i><span class="mobile-hidden">Volver</span></a>
                <button type="button" class="btn btn-primary icon-btn-mobile" id="openSupplierEditBtn"><i data-lucide="edit-3"></i><span class="mobile-hidden">Editar proveedor</span></button>
            </div>
        </div>

        <?php if (isset($_GET['updated'])): ?><div class="alert alert-success supplier-view-alert">Proveedor actualizado correctamente.</div><?php endif; ?>
        <?php if (isset($_GET['linked_existing'])): ?><div class="alert alert-success supplier-view-alert">La contraparte existente fue habilitada también como proveedor, sin duplicar el RUT.</div><?php endif; ?>

        <div class="supplier-view-kpis">
            <article><span>DTE recibidos</span><strong><?php echo (int)$summary['documents']; ?></strong></article>
            <article><span>Total recibido</span><strong>$<?php echo number_format($summary['total'], 0, ',', '.'); ?></strong></article>
            <article><span>Saldo abierto</span><strong>$<?php echo number_format($summary['open_balance'], 0, ',', '.'); ?></strong></article>
            <article><span>Documentos vencidos</span><strong><?php echo (int)$summary['overdue']; ?></strong></article>
        </div>

        <div class="supplier-profile-grid">
            <section class="card supplier-profile-card">
                <div class="card-header"><h3>Identificación y contacto</h3></div>
                <div class="card-body supplier-data-grid">
                    <div><span>Razón social</span><strong><?php echo safe_text($supplier['legal_name'] ?: $supplier['customer_name']); ?></strong></div>
                    <div><span>RUT / ID fiscal</span><strong><?php echo safe_text($supplier['customer_tax_id'] ? format_rut($supplier['customer_tax_id']) : 'Sin RUT'); ?></strong></div>
                    <div><span>Giro</span><strong><?php echo safe_text($supplier['business_activity'] ?: 'Sin giro informado'); ?></strong></div>
                    <div><span>Contacto</span><strong><?php echo safe_text($supplier['contact_name'] ?: 'Sin contacto'); ?></strong></div>
                    <div><span>Email</span><strong><?php echo safe_text($supplier['email'] ?: 'Sin email'); ?></strong></div>
                    <div><span>Teléfono</span><strong><?php echo safe_text($supplier['phone'] ?: 'Sin teléfono'); ?></strong></div>
                    <div class="span-2"><span>Dirección</span><strong><?php echo safe_text(trim(($supplier['address'] ?? '') . ', ' . ($supplier['district'] ?? '') . ', ' . ($supplier['city'] ?? '') . ', ' . ($supplier['region'] ?? ''), ', ')); ?></strong></div>
                </div>
            </section>
            <section class="card supplier-profile-card">
                <div class="card-header"><h3>Configuración financiera</h3></div>
                <div class="card-body supplier-data-grid">
                    <div><span>Condición de pago</span><strong><?php echo safe_text($supplier['supplier_payment_term_label'] ?: icylab_payment_terms_label($supplier['payment_terms'] ?? 'contado')); ?></strong></div>
                    <div><span>Días de pago</span><strong><?php echo isset($supplier['supplier_payment_term_days']) ? (int)$supplier['supplier_payment_term_days'] . ' días' : 'No definido'; ?></strong></div>
                    <div><span>Centro de costo</span><strong><?php echo safe_text($supplier['cost_center_name'] ?: 'Sin centro de costo'); ?></strong></div>
                    <div><span>Centro de ingreso</span><strong><?php echo safe_text($supplier['income_center_name'] ?: 'Sin centro de ingreso'); ?></strong></div>
                    <div><span>Tipo de contraparte</span><strong><?php echo safe_text(($supplier['counterparty_type'] ?? 'supplier') === 'both' ? 'Cliente y proveedor' : 'Proveedor'); ?></strong></div>
                    <div><span>Origen</span><strong><?php echo safe_text($supplier['source'] ?: 'manual'); ?></strong></div>
                </div>
                <div class="card-footer supplier-profile-actions">
                    <a class="btn btn-outline" href="/modules/billing/payables.php?q=<?php echo rawurlencode((string)$supplier['customer_tax_id']); ?>"><i data-lucide="receipt-text"></i><span>Ver cuentas por pagar</span></a>
                    <a class="btn btn-outline" href="/modules/billing/suppliers_aging.php"><i data-lucide="chart-no-axes-column-decreasing"></i><span>Ver aging</span></a>
                </div>
            </section>
        </div>

        <section class="card supplier-documents-card">
            <div class="card-header supplier-documents-header">
                <div><h3>Documentos tributarios recibidos</h3><p class="text-secondary text-sm">Historial asociado por contraparte maestra.</p></div>
            </div>
            <div class="supplier-documents-scroll">
                <table class="supplier-documents-table">
                    <colgroup><col class="col-doc"><col class="col-date"><col class="col-total"><col class="col-paid"><col class="col-balance"><col class="col-center"><col class="col-status"><col class="col-action"></colgroup>
                    <thead><tr><th class="col-doc">Documento</th><th class="col-date">Emisión</th><th class="col-total">Total</th><th class="col-paid">Pagado</th><th class="col-balance">Saldo</th><th class="col-center">Centro</th><th class="col-status">Estado</th><th class="col-action"><span class="sr-only">Acción</span></th></tr></thead>
                    <tbody>
                    <?php foreach ($documents as $document): ?>
                        <?php $status = (string)$document['payment_status']; $badgeClass = $status === 'pagado' ? 'badge-success' : ($status === 'vencido' ? 'badge-error' : ''); ?>
                        <tr>
                            <td class="col-doc"><strong><?php echo safe_text($documentLabels[$document['document_type_taxbureau']] ?? ('DTE ' . ($document['document_type_taxbureau'] ?: '-'))); ?></strong><small>Folio <?php echo safe_text($document['document_number'] ?: '-'); ?> · <?php echo safe_text($document['environment']); ?></small></td>
                            <td class="col-date"><?php echo safe_text($document['document_date'] ? date('d-m-Y', strtotime($document['document_date'])) : '-'); ?></td>
                            <td class="col-total"><strong>$<?php echo number_format((float)$document['total_amount'], 0, ',', '.'); ?></strong></td>
                            <td class="col-paid">$<?php echo number_format((float)$document['paid_amount'], 0, ',', '.'); ?></td>
                            <td class="col-balance"><strong>$<?php echo number_format((float)$document['balance_amount'], 0, ',', '.'); ?></strong></td>
                            <td class="col-center"><?php echo safe_text($document['finance_center_name'] ?: 'Sin centro'); ?></td>
                            <td class="col-status"><span class="badge <?php echo $badgeClass; ?>"><?php echo safe_text(ucfirst(str_replace('_', ' ', $status))); ?></span></td>
                            <td class="col-action"><a class="btn btn-sm btn-outline" href="/modules/billing/payables.php?q=<?php echo rawurlencode((string)$document['document_number']); ?>" aria-label="Abrir cuenta por pagar"><i data-lucide="chevron-right"></i></a></td>
                        </tr>
                    <?php endforeach; ?>
                    <?php if (!$documents): ?><tr><td colspan="8" class="text-center text-secondary py-8">Este proveedor aún no tiene DTE vinculados.</td></tr><?php endif; ?>
                    </tbody>
                </table>
            </div>
        </section>
    </section>

    <div id="supplierEditModal" class="supplier-edit-backdrop" aria-hidden="true">
        <div class="supplier-edit-box" role="dialog" aria-modal="true" aria-labelledby="supplierEditTitle">
            <header class="supplier-edit-header">
                <div><h2 id="supplierEditTitle">Editar proveedor</h2><p>Los cambios se aplican a recepción DTE, cuentas por pagar y ficha de contraparte.</p></div>
                <button type="button" class="icon-btn" data-close-supplier-edit aria-label="Cerrar"><i data-lucide="x"></i></button>
            </header>
            <div class="supplier-edit-body">
                <form id="supplierEditForm" action="/modules/suppliers/supplier_update.php" method="POST" data-no-spa="true">
                    <input type="hidden" name="id" value="<?php echo (int)$supplier['id']; ?>">
                    <?php icylab_render_customer_quick_fields(array(
                        'entity_mode' => 'supplier',
                        'entity_label' => 'Proveedor',
                        'name_field' => 'customer_name',
                        'tax_field' => 'customer_tax_id',
                        'tax_id' => 'supplierEditTaxId',
                        'phone_prefix_id' => 'supplier_edit_phone_prefix',
                        'phone_number_id' => 'supplier_edit_phone_number',
                        'phone_hidden_id' => 'supplier_edit_real_phone',
                        'cost_center_field' => 'supplier_default_cost_center_id',
                        'values' => $supplier,
                        'required' => array('customer_name', 'country', 'address', 'district', 'city', 'region')
                    )); ?>
                    <div class="form-field supplier-status-edit">
                        <label class="label">Estado del proveedor</label>
                        <select class="select" name="supplier_status">
                            <?php foreach ($statusLabels as $value => $label): ?><option value="<?php echo safe_text($value); ?>" <?php echo ($supplier['supplier_status'] ?? 'active') === $value ? 'selected' : ''; ?>><?php echo safe_text($label); ?></option><?php endforeach; ?>
                        </select>
                    </div>
                </form>
            </div>
            <footer class="supplier-edit-footer">
                <button type="button" class="btn btn-outline" data-close-supplier-edit><i data-lucide="x"></i><span>Cancelar</span></button>
                <button type="submit" form="supplierEditForm" class="btn btn-primary"><i data-lucide="save"></i><span>Guardar cambios</span></button>
            </footer>
        </div>
    </div>

    <style>
    #supplier-view-main{height:100dvh;max-height:100dvh;overflow:hidden;display:flex;flex-direction:column}#supplier-view-main .supplier-view-content{flex:1 1 0;min-height:0;overflow-y:auto;display:flex;flex-direction:column;gap:12px;padding-bottom:12px}.supplier-view-header,.supplier-view-alert{flex:0 0 auto;margin:0!important}
    .supplier-view-kpis{display:grid;grid-template-columns:repeat(4,minmax(0,1fr));gap:12px}.supplier-view-kpis article{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-view-kpis span,.supplier-data-grid span{display:block;color:var(--text-muted);font-size:.74rem;font-weight:700;text-transform:uppercase;letter-spacing:.03em}.supplier-view-kpis strong{display:block;margin-top:7px;font-size:1.25rem;overflow:hidden;text-overflow:ellipsis}
    .supplier-profile-grid{display:grid;grid-template-columns:1fr 1fr;gap:12px}.supplier-profile-card{margin:0;overflow:hidden}.supplier-profile-card .card-header{padding:14px 18px}.supplier-profile-card h3{margin:0}.supplier-data-grid{display:grid;grid-template-columns:1fr 1fr;gap:18px;padding:18px}.supplier-data-grid>div{min-width:0}.supplier-data-grid strong{display:block;margin-top:5px;font-size:.94rem;overflow-wrap:anywhere}.supplier-data-grid .span-2{grid-column:1/-1}.supplier-profile-actions{display:flex;gap:10px;flex-wrap:wrap;padding:14px 18px;border-top:1px solid var(--border-subtle)}
    .supplier-documents-card{min-height:360px;height:46dvh;display:flex;flex-direction:column;overflow:hidden;margin:0}.supplier-documents-header{flex:0 0 auto;padding:14px 18px}.supplier-documents-header h3,.supplier-documents-header p{margin:0}.supplier-documents-scroll{flex:1 1 0;min-height:0;overflow-y:auto;overflow-x:hidden}.supplier-documents-table{width:100%;table-layout:fixed;border-collapse:separate;border-spacing:0}.supplier-documents-table th{position:sticky;top:0;z-index:2;background:var(--surface-2);color:var(--text-primary);font-size:.7rem;text-transform:uppercase;text-align:left;padding:10px;border-bottom:1px solid var(--border-default)}.supplier-documents-table td{padding:11px 10px;border-bottom:1px solid var(--border-subtle);overflow:hidden;text-overflow:ellipsis}.supplier-documents-table td small{display:block;margin-top:3px;color:var(--text-muted);white-space:nowrap;overflow:hidden;text-overflow:ellipsis}.supplier-documents-table .col-doc{width:18%}.supplier-documents-table .col-date{width:10%}.supplier-documents-table .col-total,.supplier-documents-table .col-paid,.supplier-documents-table .col-balance{width:11%}.supplier-documents-table .col-center{width:17%}.supplier-documents-table .col-status{width:13%}.supplier-documents-table .col-action{width:54px;text-align:right}
    .supplier-edit-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-edit-backdrop.is-open{display:flex;opacity:1}.supplier-edit-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-edit-header,.supplier-edit-footer{flex:0 0 auto;padding:18px 24px;background:var(--surface-1)}.supplier-edit-header{display:flex;justify-content:space-between;align-items:flex-start;gap:18px;border-bottom:1px solid var(--border-subtle)}.supplier-edit-header h2,.supplier-edit-header p{margin:0}.supplier-edit-header p{margin-top:4px;color:var(--text-muted)}.supplier-edit-body{flex:1 1 auto;min-height:0;overflow-y:auto;padding:22px 24px}.supplier-edit-footer{display:flex;justify-content:flex-end;gap:10px;border-top:1px solid var(--border-subtle)}.supplier-status-edit{margin-top:18px;max-width:320px}body.billing-modal-open{overflow:hidden}
    @media(max-width:760px){#supplier-view-main .supplier-view-content{padding:12px}.supplier-view-kpis{grid-template-columns:repeat(2,minmax(0,1fr))}.supplier-profile-grid{grid-template-columns:1fr}.supplier-data-grid{grid-template-columns:1fr}.supplier-data-grid .span-2{grid-column:auto}.supplier-documents-card{height:52dvh;min-height:360px}.supplier-documents-table .col-date,.supplier-documents-table .col-total,.supplier-documents-table .col-paid,.supplier-documents-table .col-center,.supplier-documents-table .col-status{display:none}.supplier-documents-table .col-doc{width:auto}.supplier-documents-table .col-balance{width:105px}.supplier-documents-table .col-action{width:52px}.supplier-documents-table th,.supplier-documents-table td{padding:9px 6px}.supplier-edit-backdrop{padding:100px 12px}.supplier-edit-box{width:100%;height:calc(100dvh - 200px);min-height:430px;max-height:720px}.supplier-edit-header{padding:15px 16px}.supplier-edit-header h2{font-size:1.25rem}.supplier-edit-header p{font-size:.82rem}.supplier-edit-body{padding:16px}.supplier-edit-footer{padding:12px 16px}.customer-quick-grid{grid-template-columns:1fr!important}.customer-quick-grid>[class*="span-"]{grid-column:1/-1!important}}
    @media(max-width:420px){.supplier-edit-backdrop{padding:76px 8px}.supplier-edit-box{height:calc(100dvh - 152px);min-height:390px}}
    </style>
    <script src="/assets/js/customer-location.js?v=1.2.6"></script>
    <script>
    (function(){
        if(window.__supplierViewCleanup)window.__supplierViewCleanup();
        var controller=new AbortController(),signal=controller.signal;
        var modal=document.getElementById('supplierEditModal'),form=document.getElementById('supplierEditForm');
        function openModal(){if(!modal)return;modal.style.display='flex';requestAnimationFrame(function(){modal.classList.add('is-open');});modal.setAttribute('aria-hidden','false');document.body.classList.add('billing-modal-open');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 p=document.getElementById('supplier_edit_phone_prefix'),n=document.getElementById('supplier_edit_phone_number'),h=document.getElementById('supplier_edit_real_phone');if(!p||!n||!h)return;var value=n.value.replace(/[^0-9\s-]/g,'');n.value=value;h.value=value.replace(/[^0-9]/g,'').length?p.value+' '+value:'';}
        document.getElementById('openSupplierEditBtn')?.addEventListener('click',openModal,{signal:signal});
        modal?.addEventListener('pointerdown',function(e){if(e.target===modal)closeModal();},{signal:signal});
        modal?.querySelectorAll('[data-close-supplier-edit]').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_edit_phone_prefix')?.addEventListener('change',syncPhone,{signal:signal});
        document.getElementById('supplier_edit_phone_number')?.addEventListener('input',syncPhone,{signal:signal});form?.addEventListener('submit',syncPhone,{signal:signal});
        window.__supplierViewCleanup=function(){controller.abort();document.body.classList.remove('billing-modal-open');};
    })();
    </script>
</main>
<?php require_once '../../layouts/footer.php'; ?>
