<?php

require_once '../../core/config.php';
require_once '../../core/session.php';
require_once '../../core/format.php';
require_once '../../core/database.php';

require_login();

// Control de seguridad por Rol (Estandarizado)
require_once '../../core/permissions.php';

if (current_user_role() !== 'admin') {
    header('Location: /modules/dashboard/');
    exit;
}

$page_title = 'Configuración de Empresa';
$pdo = db();

$formErrors = $_SESSION['form_errors'] ?? array();
$formOld = $_SESSION['form_old'] ?? array();
unset($_SESSION['form_errors'], $_SESSION['form_old']);

function field_error($field, $formErrors) {
    return isset($formErrors[$field]) ? $formErrors[$field] : '';
}
function field_class($field, $formErrors, $required = false) {
    $classes = array('form-field');
    if ($required) $classes[] = 'is-required';
    if (isset($formErrors[$field])) $classes[] = 'has-error';
    return implode(' ', $classes);
}

// Cargar registros vigentes
$stmt = $pdo->query("SELECT * FROM system_settings WHERE id = 1");
$settings = $stmt->fetch() ?: array();

// Datos de Empresa
$nameValue    = $formOld['company_name'] ?? $settings['company_name'] ?? '';
$taxIdValue   = $formOld['company_tax_id'] ?? $settings['company_tax_id'] ?? '';
$giroValue    = $formOld['company_giro'] ?? $settings['company_giro'] ?? '';
$addressValue = $formOld['company_address'] ?? $settings['company_address'] ?? '';
$comunaValue  = $formOld['company_comuna'] ?? $settings['company_comuna'] ?? '';
$ciudadValue  = $formOld['company_ciudad'] ?? $settings['company_ciudad'] ?? '';
$phoneValue   = $formOld['company_phone'] ?? $settings['company_phone'] ?? '';
$emailValue   = $formOld['company_email'] ?? $settings['company_email'] ?? '';
$webValue     = $formOld['company_website'] ?? $settings['company_website'] ?? '';

// Datos Bancarios
$bNameValue   = $formOld['bank_name'] ?? $settings['bank_name'] ?? '';
$bTypeValue   = $formOld['bank_account_type'] ?? $settings['bank_account_type'] ?? '';
$bNumValue    = $formOld['bank_account_number'] ?? $settings['bank_account_number'] ?? '';
$bHolderValue = $formOld['bank_holder_name'] ?? $settings['bank_holder_name'] ?? '';
$bRutValue    = $formOld['bank_holder_tax_id'] ?? $settings['bank_holder_tax_id'] ?? '';
$bEmailValue  = $formOld['bank_email'] ?? $settings['bank_email'] ?? '';
$commercialFooterValue = $formOld['commercial_document_footer'] ?? $settings['commercial_document_footer'] ?? '';
$quoteDefaultConditionsValue = $formOld['quote_default_conditions'] ?? $settings['quote_default_conditions'] ?? '';
$purchaseOrderDefaultTermsValue = $formOld['purchase_order_default_terms'] ?? $settings['purchase_order_default_terms'] ?? 'Precios y condiciones sujetos a lo indicado en esta orden. Informar cualquier diferencia antes del despacho.';

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

<main class="app-main" id="company-settings-main" data-spa-module="admin:company-settings">
    <?php require_once '../../layouts/topbar.php'; ?>

    <section class="content content-no-scroll">
        
        <div class="page-header page-header-compact fixed-header-section">
            <div class="page-header-content">
                <span class="label">Administración · Sistema</span>
                <h1>Configuración General</h1>
                <p class="text-secondary">Gestiona datos legales, bancarios, módulos, navegación y centros financieros de ICYLAB.</p>
            </div>
        </div>

        <?php if (!empty($formErrors)): ?>
            <div class="alert alert-error fixed-header-section">
                <strong>No se pudieron guardar los cambios.</strong>
                <span>Por favor, revisa las pestañas con campos obligatorios pendientes.</span>
            </div>
        <?php elseif (isset($_GET['success'])): ?>
            <div class="alert alert-success fixed-header-section company-settings-feedback">
                <i data-lucide="circle-check"></i>
                <span>Configuración guardada correctamente.</span>
            </div>
        <?php endif; ?>

        <div class="tabs-container fixed-header-section" role="tablist" aria-label="Secciones de configuración">
            <button type="button" class="tab-trigger active" data-target="tab-empresa" role="tab" aria-selected="true" aria-controls="tab-empresa">
                <i data-lucide="building-2"></i> <span>Empresa</span>
            </button>
            <button type="button" class="tab-trigger" data-target="tab-banco" role="tab" aria-selected="false" aria-controls="tab-banco">
                <i data-lucide="landmark"></i> <span>Datos Bancarios</span>
            </button>
            <button type="button" class="tab-trigger" data-target="tab-modulos" role="tab" aria-selected="false" aria-controls="tab-modulos">
                <i data-lucide="layout-grid"></i> <span>Módulos y Menú</span>
            </button>
            <button type="button" class="tab-trigger" data-target="tab-centros" role="tab" aria-selected="false" aria-controls="tab-centros">
                <i data-lucide="waypoints"></i> <span>Centros financieros</span>
            </button>
        </div>

        <form class="opportunity-form full-height-form" action="/modules/admin/company_settings_store.php" method="POST" enctype="multipart/form-data">
            <input type="hidden" name="_csrf_token" value="<?php echo safe_text(csrf_token()); ?>">
            
            <div class="tabs-scroll-viewport">
                
                <div id="tab-empresa" class="tab-panel active" role="tabpanel">
                    <section class="card form-card mb-4">
                        <div class="card-header">
                            <h3>Identidad Corporativa</h3>
                        </div>
                        <div class="card-body">
                            <div class="form-grid form-grid-2">
                                <div class="<?php echo field_class('company_name', $formErrors, true); ?>">
                                    <label class="label">Razón Social</label>
                                    <input class="input" type="text" name="company_name" value="<?php echo safe_text($nameValue); ?>">
                                    <?php if ($err = field_error('company_name', $formErrors)): ?>
                                        <small class="field-error"><?php echo safe_text($err); ?></small>
                                    <?php endif; ?>
                                </div>

                                <div class="<?php echo field_class('company_tax_id', $formErrors, true); ?>">
                                    <label class="label">RUT Empresa</label>
                                    <input class="input rut-formatter" type="text" name="company_tax_id" value="<?php echo safe_text($taxIdValue); ?>">
                                    <?php if ($err = field_error('company_tax_id', $formErrors)): ?>
                                        <small class="field-error"><?php echo safe_text($err); ?></small>
                                    <?php endif; ?>
                                </div>

                                <div class="<?php echo field_class('company_giro', $formErrors, true); ?>">
                                    <label class="label">Giro Comercial</label>
                                    <input class="input" type="text" name="company_giro" value="<?php echo safe_text($giroValue); ?>">
                                </div>

                                <div class="form-field">
                                    <label class="label">Logotipo Corporativo</label>
                                    <div style="display: flex; gap: 15px; align-items: center; flex-wrap: wrap;">
                                        <?php if (!empty($settings['company_logo'])): ?>
                                            <img src="<?php echo safe_text($settings['company_logo']); ?>" alt="Logo" style="max-height: 40px; background: var(--surface-2); padding: 4px; border-radius: var(--radius-sm); border: 1px solid var(--border-default);">
                                        <?php endif; ?>
                                        <input class="input file-input" type="file" name="company_logo" accept="image/png, image/jpeg" style="flex: 1; min-width: 200px;">
                                    </div>
                                </div>
                            </div>
                        </div>
                    </section>

                    <section class="card form-card">
                        <div class="card-header">
                            <h3>Ubicación y Contacto</h3>
                        </div>
                        <div class="card-body">
                            <div class="form-grid form-grid-2">
                                <div class="<?php echo field_class('company_address', $formErrors, true); ?>">
                                    <label class="label">Dirección Casa Matriz</label>
                                    <input class="input" type="text" name="company_address" value="<?php echo safe_text($addressValue); ?>">
                                </div>
                                <div class="<?php echo field_class('company_comuna', $formErrors, true); ?>">
                                    <label class="label">Comuna</label>
                                    <input class="input" type="text" name="company_comuna" value="<?php echo safe_text($comunaValue); ?>">
                                </div>
                                <div class="<?php echo field_class('company_ciudad', $formErrors, true); ?>">
                                    <label class="label">Ciudad</label>
                                    <input class="input" type="text" name="company_ciudad" value="<?php echo safe_text($ciudadValue); ?>">
                                </div>
                                <div class="<?php echo field_class('company_phone', $formErrors, true); ?>">
                                    <label class="label">Teléfono Casa Matriz</label>
                                    <input class="input" type="text" name="company_phone" value="<?php echo safe_text($phoneValue); ?>">
                                </div>
                                <div class="<?php echo field_class('company_email', $formErrors, true); ?>">
                                    <label class="label">Email General</label>
                                    <input class="input" type="email" name="company_email" value="<?php echo safe_text($emailValue); ?>">
                                </div>
                                <div class="form-field">
                                    <label class="label">Sitio Web</label>
                                    <input class="input" type="text" name="company_website" value="<?php echo safe_text($webValue); ?>">
                                </div>
                            </div>
                        </div>
                    </section>

                    <section class="card form-card mt-4">
                        <div class="card-header">
                            <div>
                                <h3>Documentos comerciales</h3>
                                <p class="text-secondary text-sm mt-2">Configuración compartida por cotizaciones y órdenes de compra ICYLAB.</p>
                            </div>
                        </div>
                        <div class="card-body">
                            <div class="company-commercial-settings">
                                <div class="form-field">
                                    <label class="label" for="quoteDefaultConditions">Condiciones predeterminadas de cotización</label>
                                    <textarea class="input" id="quoteDefaultConditions" name="quote_default_conditions" rows="4" maxlength="1000" placeholder="Ej: Oferta válida por 15 días. Entrega sujeta a disponibilidad."><?php echo safe_text($quoteDefaultConditionsValue); ?></textarea>
                                    <small class="text-secondary">Se precargan al crear una cotización y luego pueden ajustarse caso a caso.</small>
                                    <?php if ($err = field_error('quote_default_conditions', $formErrors)): ?>
                                        <small class="field-error"><?php echo safe_text($err); ?></small>
                                    <?php endif; ?>
                                </div>
                                <div class="form-field">
                                    <label class="label" for="purchaseOrderDefaultTerms">Condiciones predeterminadas de órdenes de compra</label>
                                    <textarea class="input" id="purchaseOrderDefaultTerms" name="purchase_order_default_terms" rows="4" maxlength="2000" placeholder="Condiciones de recepción, despacho y aceptación del proveedor."><?php echo safe_text($purchaseOrderDefaultTermsValue); ?></textarea>
                                    <small class="text-secondary">Se incorporan automáticamente al iniciar una nueva orden de compra.</small>
                                    <?php if ($err = field_error('purchase_order_default_terms', $formErrors)): ?>
                                        <small class="field-error"><?php echo safe_text($err); ?></small>
                                    <?php endif; ?>
                                </div>
                            </div>
                            <div class="form-field company-document-footer-field">
                                <label class="label" for="commercialDocumentFooter">Pie de documentos comerciales</label>
                                <textarea class="input" id="commercialDocumentFooter" name="commercial_document_footer" rows="4" maxlength="500" placeholder="Escribe el texto que aparecerá al pie de las cotizaciones y órdenes de compra."><?php echo safe_text($commercialFooterValue); ?></textarea>
                                <small class="text-secondary">Máximo 500 caracteres. Si queda vacío, el PDF no mostrará pie, numeración de página ni sitio web.</small>
                                <?php if ($err = field_error('commercial_document_footer', $formErrors)): ?>
                                    <small class="field-error"><?php echo safe_text($err); ?></small>
                                <?php endif; ?>
                            </div>
                        </div>
                    </section>
                </div>

                <div id="tab-banco" class="tab-panel" role="tabpanel">
                    <section class="card form-card mb-4">
                        <div class="card-header">
                            <h3>Información de Recaudación para Clientes</h3>
                        </div>
                        <div class="card-body">
                            <div class="form-grid form-grid-2">
                                <div class="<?php echo field_class('bank_name', $formErrors, true); ?>">
                                    <label class="label">Nombre del Banco</label>
                                    <input class="input" type="text" name="bank_name" value="<?php echo safe_text($bNameValue); ?>" placeholder="Ej: Banco Santander">
                                    <?php if ($err = field_error('bank_name', $formErrors)): ?>
                                        <small class="field-error"><?php echo safe_text($err); ?></small>
                                    <?php endif; ?>
                                </div>

                                <div class="<?php echo field_class('bank_account_type', $formErrors, true); ?>">
                                    <label class="label">Tipo de Cuenta</label>
                                    <input class="input" type="text" name="bank_account_type" value="<?php echo safe_text($bTypeValue); ?>" placeholder="Ej: Cuenta Corriente">
                                    <?php if ($err = field_error('bank_account_type', $formErrors)): ?>
                                        <small class="field-error"><?php echo safe_text($err); ?></small>
                                    <?php endif; ?>
                                </div>

                                <div class="<?php echo field_class('bank_account_number', $formErrors, true); ?>">
                                    <label class="label">Número de Cuenta</label>
                                    <input class="input" type="text" name="bank_account_number" value="<?php echo safe_text($bNumValue); ?>">
                                    <?php if ($err = field_error('bank_account_number', $formErrors)): ?>
                                        <small class="field-error"><?php echo safe_text($err); ?></small>
                                    <?php endif; ?>
                                </div>

                                <div class="<?php echo field_class('bank_holder_name', $formErrors, true); ?>">
                                    <label class="label">Titular de la Cuenta</label>
                                    <input class="input" type="text" name="bank_holder_name" value="<?php echo safe_text($bHolderValue); ?>">
                                    <?php if ($err = field_error('bank_holder_name', $formErrors)): ?>
                                        <small class="field-error"><?php echo safe_text($err); ?></small>
                                    <?php endif; ?>
                                </div>

                                <div class="<?php echo field_class('bank_holder_tax_id', $formErrors, true); ?>">
                                    <label class="label">RUT Titular</label>
                                    <input class="input rut-formatter" type="text" name="bank_holder_tax_id" value="<?php echo safe_text($bRutValue); ?>">
                                    <?php if ($err = field_error('bank_holder_tax_id', $formErrors)): ?>
                                        <small class="field-error"><?php echo safe_text($err); ?></small>
                                    <?php endif; ?>
                                </div>

                                <div class="<?php echo field_class('bank_email', $formErrors, true); ?>">
                                    <label class="label">Email para Aviso de Transferencia</label>
                                    <input class="input" type="email" name="bank_email" value="<?php echo safe_text($bEmailValue); ?>">
                                    <?php if ($err = field_error('bank_email', $formErrors)): ?>
                                        <small class="field-error"><?php echo safe_text($err); ?></small>
                                    <?php endif; ?>
                                </div>
                            </div>
                        </div>
                    </section>
                </div>
                
                <div id="tab-modulos" class="tab-panel" role="tabpanel">
                    <section class="card form-card mb-4">
                        <div class="card-header">
                            <div>
                                <h3>Gestor de Módulos Activos</h3>
                                <p class="text-secondary text-sm mt-2">Controla qué módulos están encendidos, su icono, sección y en qué orden aparecen en la barra lateral.</p>
                            </div>
                        </div>
                        <div class="card-body">
                            <div class="table-wrap">
                                <table class="table">
                                    <thead>
                                        <tr>
                                            <th style="width: 15%;">Módulo (Carpeta)</th>
                                            <th style="width: 25%;">Título Visible</th>
                                            <th style="width: 20%;">Sección</th>
                                            <th style="width: 15%;">Icono (Lucide)</th>
                                            <th style="width: 10%;">Orden</th>
                                            <th style="width: 15%; text-align: center;">Activo</th>
                                        </tr>
                                    </thead>
                                    <tbody>
                                        <?php 
                                        $all_modules = get_system_modules(false); 
                                        foreach ($all_modules as $key => $mod): 
                                        ?>
                                        <tr>
                                            <td>
                                                <input type="hidden" name="mod_key[]" value="<?php echo safe_text($key); ?>">
                                                <span class="badge"><?php echo safe_text($key); ?></span>
                                            </td>
                                            <td><input type="text" class="input" name="mod_title[]" value="<?php echo safe_text($mod['title']); ?>"></td>
                                            <td><input type="text" class="input" name="mod_section[]" value="<?php echo safe_text($mod['section']); ?>"></td>
                                            <td><input type="text" class="input" name="mod_icon[]" value="<?php echo safe_text($mod['icon']); ?>"></td>
                                            <td><input type="number" class="input" name="mod_order[]" value="<?php echo (int)$mod['order']; ?>"></td>
                                            <td style="text-align: center;">
                                                <input type="checkbox" name="mod_active[<?php echo safe_text($key); ?>]" value="1" <?php echo $mod['is_active'] ? 'checked' : ''; ?> style="width: 18px; height: 18px; cursor: pointer; accent-color: var(--color-primary);">
                                            </td>
                                        </tr>
                                        <?php endforeach; ?>
                                    </tbody>
                                </table>
                            </div>
                        </div>
                    </section>
                </div>

                <div id="tab-centros" class="tab-panel" role="tabpanel">
                    <section class="card form-card company-centers-card mb-4">
                        <div class="card-header company-centers-header">
                            <div>
                                <h3>Centros de costos e ingresos</h3>
                                <p class="text-secondary text-sm mt-2">Configura la clasificación financiera heredada por clientes, proveedores, documentos emitidos y DTE recibidos.</p>
                            </div>
                            <button type="button" class="btn btn-primary" id="newFinanceCenterBtn"><i data-lucide="plus"></i><span>Nuevo centro</span></button>
                        </div>
                        <div class="card-body company-centers-body">
                            <div class="company-centers-summary" id="financeCentersSummary">
                                <div><span>Activos</span><strong>-</strong></div><div><span>Ingresos</span><strong>-</strong></div><div><span>Costos</span><strong>-</strong></div><div><span>Ambos</span><strong>-</strong></div>
                            </div>
                            <div class="company-centers-table-wrap">
                                <table class="table company-centers-table">
                                    <thead><tr><th>Código</th><th>Centro</th><th>Tipo</th><th>Jerarquía</th><th>Uso</th><th>Estado</th><th></th></tr></thead>
                                    <tbody id="financeCentersRows"><tr><td colspan="7">Cargando centros...</td></tr></tbody>
                                </table>
                            </div>
                        </div>
                    </section>

                    <section class="card form-card company-assignment-card" id="financeCenterAssignmentCard">
                        <div class="card-header company-centers-header">
                            <div>
                                <h3>Asignación automática e integrada</h3>
                                <p class="text-secondary text-sm mt-2">Centraliza la relación entre proveedores, categorías, DTE recibidos y movimientos de costos. Una asignación manual nunca se reemplaza.</p>
                            </div>
                            <button type="button" class="btn btn-primary" id="saveCenterAssignmentBtn"><i data-lucide="save"></i><span>Guardar política</span></button>
                        </div>
                        <div class="card-body company-assignment-body">
                            <div class="alert alert-warning" id="centerAssignmentInstallNotice" hidden></div>
                            <div class="company-assignment-policy">
                                <div class="form-field">
                                    <label class="label" for="centerAssignmentPriority">Orden de prioridad</label>
                                    <select class="select" id="centerAssignmentPriority">
                                        <option value="supplier_category_global">Proveedor → categoría → global</option>
                                        <option value="category_supplier_global">Categoría → proveedor → global</option>
                                    </select>
                                </div>
                                <div class="form-field">
                                    <label class="label" for="centerAssignmentGlobal">Centro global de respaldo</label>
                                    <select class="select" id="centerAssignmentGlobal"><option value="">Sin respaldo global</option></select>
                                </div>
                                <label class="company-center-check"><input type="checkbox" id="centerAssignmentManual" checked> <span>Costos manuales y remuneraciones</span></label>
                                <label class="company-center-check"><input type="checkbox" id="centerAssignmentDte" checked> <span>DTE recibidos y cuentas por pagar</span></label>
                                <label class="company-center-check"><input type="checkbox" id="centerAssignmentRecurring" checked> <span>Reglas y costos recurrentes</span></label>
                            </div>

                            <div class="company-assignment-summary" id="centerAssignmentSummary">
                                <div><span>Proveedores sin centro</span><strong>-</strong></div>
                                <div><span>Categorías sin centro</span><strong>-</strong></div>
                                <div><span>Movimientos pendientes</span><strong>-</strong></div>
                                <div><span>DTE sin centro</span><strong>-</strong></div>
                            </div>

                            <div class="company-assignment-apply">
                                <div>
                                    <strong>Completar asignaciones pendientes</strong>
                                    <small>Solo completa datos vacíos aplicando la prioridad configurada.</small>
                                </div>
                                <input class="input" type="month" id="centerAssignmentPeriod" value="<?php echo safe_text(date('Y-m')); ?>">
                                <button type="button" class="btn btn-outline" id="applyCenterAssignmentBtn"><i data-lucide="wand-sparkles"></i><span>Aplicar al período</span></button>
                            </div>
                            <div class="company-assignment-notice" id="centerAssignmentNotice" hidden></div>

                            <div class="company-assignment-columns">
                                <section>
                                    <div class="company-assignment-list-header"><div><h4>Proveedores</h4><small>La selección también queda visible en la ficha del proveedor.</small></div><input class="input" id="supplierCenterSearch" type="search" placeholder="Buscar proveedor"></div>
                                    <div class="company-assignment-table-wrap"><table class="table"><thead><tr><th>Proveedor</th><th>Centro predeterminado</th></tr></thead><tbody id="supplierCenterRows"><tr><td colspan="2">Cargando...</td></tr></tbody></table></div>
                                </section>
                                <section>
                                    <div class="company-assignment-list-header"><div><h4>Categorías de costos</h4><small>Se integra con movimientos manuales, recurrentes y DTE.</small></div><input class="input" id="categoryCenterSearch" type="search" placeholder="Buscar categoría"></div>
                                    <div class="company-assignment-table-wrap"><table class="table"><thead><tr><th>Categoría</th><th>Centro predeterminado</th></tr></thead><tbody id="categoryCenterRows"><tr><td colspan="2">Cargando...</td></tr></tbody></table></div>
                                </section>
                            </div>
                        </div>
                    </section>
                </div>
            </div>

            <div class="form-actions-fixed">
                <button class="btn btn-primary" type="submit">
                    <i data-lucide="save"></i>
                    <span>Guardar cambios</span>
                </button>
            </div>
            
        </form>

        <div id="financeCenterModal" class="product-modal-backdrop" style="display:none" aria-hidden="true" role="dialog" aria-modal="true">
            <div class="product-modal-box company-settings-modal-box">
                <div class="product-modal-header">
                    <div><h2 class="h3" id="financeCenterModalTitle">Nuevo centro financiero</h2><span class="text-secondary text-sm">Clasificación para ingresos, costos o ambos.</span></div>
                    <button type="button" class="icon-btn" id="closeFinanceCenterModalBtn" aria-label="Cerrar"><i data-lucide="x"></i></button>
                </div>
                <div class="product-modal-body">
                    <form id="financeCenterForm" style="margin:0">
                        <input type="hidden" name="id" value="">
                        <div class="form-grid form-grid-2">
                            <div class="form-field is-required"><label class="label">Código</label><input class="input" name="center_code" maxlength="50" placeholder="Ej: COMERCIAL" required><small class="field-help">Letras, números, guion y guion bajo.</small></div>
                            <div class="form-field is-required"><label class="label">Nombre</label><input class="input" name="center_name" maxlength="150" placeholder="Ej: Ventas comerciales" required></div>
                            <div class="form-field is-required"><label class="label">Tipo</label><select class="select" name="center_type" required><option value="income">Ingreso</option><option value="cost">Costo</option><option value="both">Ingreso y costo</option></select></div>
                            <div class="form-field"><label class="label">Centro superior</label><select class="select" name="parent_id"><option value="">Sin centro superior</option></select></div>
                            <div class="form-field form-field-full"><label class="label">Descripción</label><textarea class="textarea" name="description" rows="3" maxlength="1000" placeholder="Uso previsto y criterios de imputación"></textarea></div>
                            <div class="form-field"><label class="company-center-check"><input type="checkbox" name="is_default" value="1"> <span>Usar como predeterminado para su tipo</span></label></div>
                            <div class="form-field"><label class="company-center-check"><input type="checkbox" name="is_active" value="1" checked> <span>Centro activo</span></label></div>
                        </div>
                    </form>
                </div>
                <div class="product-modal-footer">
                    <div class="modal-footer-actions-left"><button type="button" class="btn btn-outline" id="cancelFinanceCenterBtn"><i data-lucide="x"></i><span>Cancelar</span></button></div>
                    <div class="modal-footer-actions-right"><button type="button" class="btn btn-primary" id="saveFinanceCenterBtn"><i data-lucide="save"></i><span>Guardar centro</span></button></div>
                </div>
            </div>
        </div>
    </section>
</main>

<script>
(function () {
    var bindings = [];
    function on(target, eventName, handler, options) {
        if (!target || !target.addEventListener) return;
        target.addEventListener(eventName, handler, options || false);
        bindings.push([target, eventName, handler, options || false]);
    }
    window.ICY_PAGE_CLEANUPS = window.ICY_PAGE_CLEANUPS || [];
    window.ICY_PAGE_CLEANUPS.push(function () { bindings.forEach(function (b) { try { b[0].removeEventListener(b[1], b[2], b[3]); } catch (_) {} }); });

    var triggers = Array.prototype.slice.call(document.querySelectorAll('#company-settings-main .tab-trigger'));
    var panels = Array.prototype.slice.call(document.querySelectorAll('#company-settings-main .tab-panel'));
    var centers = [];
    var centersLoaded = false;
    var assignmentData = null;
    var assignmentLoaded = false;
    var modal = document.getElementById('financeCenterModal');
    var form = document.getElementById('financeCenterForm');
    var saveBar = document.querySelector('#company-settings-main .form-actions-fixed');

    function esc(value) { return String(value == null ? '' : value).replace(/[&<>'"]/g, function (c) { return {'&':'&amp;','<':'&lt;','>':'&gt;',"'":'&#39;','"':'&quot;'}[c]; }); }
    function icons() { if (window.lucide && typeof window.lucide.createIcons === 'function') window.lucide.createIcons(); }
    function typeLabel(type) { return {cost:'Costo',income:'Ingreso',both:'Ingreso y costo'}[type] || type; }

    function activate(targetId, updateHash) {
        if (!document.getElementById(targetId)) targetId = 'tab-empresa';
        triggers.forEach(function (t) {
            var active = t.getAttribute('data-target') === targetId;
            t.classList.toggle('active', active);
            t.setAttribute('aria-selected', active ? 'true' : 'false');
            t.tabIndex = active ? 0 : -1;
        });
        panels.forEach(function (p) { p.classList.toggle('active', p.id === targetId); });
        if (saveBar) saveBar.classList.toggle('is-hidden', targetId === 'tab-centros');
        if (updateHash) {
            var url = new URL(window.location.href);
            if (targetId === 'tab-centros') url.searchParams.set('tab', 'centros'); else url.searchParams.delete('tab');
            url.hash = targetId;
            history.replaceState(null, '', url.pathname + url.search + url.hash);
        }
        if (targetId === 'tab-centros') {
            if (!centersLoaded) loadCenters();
            if (!assignmentLoaded) loadAssignment();
        }
    }

    triggers.forEach(function (btn) { on(btn, 'click', function () { activate(btn.getAttribute('data-target'), true); }); });

    function formatRutInput(e) {
        var value = e.target.value.replace(/[^0-9kK]/g, '');
        if (!value) { e.target.value = ''; return; }
        if (value.length === 1) { e.target.value = value.toUpperCase(); return; }
        var body = value.slice(0, -1).replace(/\B(?=(\d{3})+(?!\d))/g, '.');
        e.target.value = body + '-' + value.slice(-1).toUpperCase();
    }
    document.querySelectorAll('.rut-formatter').forEach(function (input) { on(input, 'input', formatRutInput); });

    async function request(url, options) {
        options = options || {};
        options.credentials = 'same-origin';
        var response = await fetch(url, options);
        var text = await response.text();
        var json; try { json = JSON.parse(text); } catch (_) { throw new Error(text || 'Respuesta inválida.'); }
        if (!response.ok || json.success === false) throw new Error(json.message || 'No fue posible completar la operación.');
        return json;
    }
    function secureFormData(fd) {
        var token = document.querySelector('meta[name="csrf-token"]');
        if (token && !fd.has('_csrf_token')) fd.append('_csrf_token', token.content);
        return fd;
    }
    async function loadCenters() {
        var rows = document.getElementById('financeCentersRows');
        if (rows) rows.innerHTML = '<tr><td colspan="7">Cargando centros...</td></tr>';
        try {
            var data = await request('/modules/admin/finance_centers_list_ajax.php');
            centers = data.data || []; centersLoaded = true; renderCenters();
        } catch (error) { if (rows) rows.innerHTML = '<tr><td colspan="7">' + esc(error.message) + '</td></tr>'; }
    }
    function renderCenters() {
        var rows = document.getElementById('financeCentersRows');
        if (!rows) return;
        var active = centers.filter(function (c) { return Number(c.is_active) === 1; });
        var summaryValues = [active.length, active.filter(function(c){return c.center_type==='income';}).length, active.filter(function(c){return c.center_type==='cost';}).length, active.filter(function(c){return c.center_type==='both';}).length];
        document.querySelectorAll('#financeCentersSummary strong').forEach(function (node, index) { node.textContent = summaryValues[index] || 0; });
        if (!centers.length) { rows.innerHTML = '<tr><td colspan="7">No hay centros configurados.</td></tr>'; return; }
        rows.innerHTML = centers.map(function (c) {
            var usage = Number(c.counterparties_count||0) + Number(c.issued_documents_count||0) + Number(c.received_documents_count||0) + Number(c.costs_count||0) + Number(c.collections_count||0);
            return '<tr>' +
                '<td><span class="badge">' + esc(c.center_code) + '</span></td>' +
                '<td><strong>' + esc(c.center_name) + '</strong>' + (Number(c.is_default) ? '<small>Predeterminado</small>' : '') + '</td>' +
                '<td>' + esc(typeLabel(c.center_type)) + '</td>' +
                '<td>' + esc(c.parent_name || 'Raíz') + '</td>' +
                '<td>' + usage + '<small>' + Number(c.counterparties_count||0) + ' contrapartes · ' + Number(c.costs_count||0) + ' costos</small></td>' +
                '<td><span class="company-center-status ' + (Number(c.is_active) ? 'is-active' : 'is-inactive') + '">' + (Number(c.is_active) ? 'Activo' : 'Inactivo') + '</span></td>' +
                '<td class="company-center-actions"><button type="button" class="btn btn-outline" data-edit-center="' + esc(c.id) + '" title="Editar"><i data-lucide="pencil"></i><span>Editar</span></button>' + (Number(c.is_system) ? '' : '<button type="button" class="btn btn-outline" data-toggle-center="' + esc(c.id) + '">' + (Number(c.is_active) ? 'Desactivar' : 'Activar') + '</button>') + '</td>' +
                '</tr>';
        }).join('');
        icons();
    }
    function parentOptions(currentId, selectedId) {
        return '<option value="">Sin centro superior</option>' + centers.filter(function(c){return Number(c.is_active)===1 && String(c.id)!==String(currentId||'');}).map(function(c){return '<option value="'+esc(c.id)+'" '+(String(c.id)===String(selectedId||'')?'selected':'')+'>'+esc(c.center_name)+'</option>';}).join('');
    }
    function openCenter(center) {
        form.reset();
        form.elements.id.value = center ? center.id : '';
        form.elements.center_code.value = center ? center.center_code : '';
        form.elements.center_name.value = center ? center.center_name : '';
        form.elements.center_type.value = center ? center.center_type : 'income';
        form.elements.parent_id.innerHTML = parentOptions(center ? center.id : '', center ? center.parent_id : '');
        form.elements.description.value = center ? (center.description || '') : '';
        form.elements.is_default.checked = center ? Number(center.is_default) === 1 : false;
        form.elements.is_active.checked = center ? Number(center.is_active) === 1 : true;
        var system = center && Number(center.is_system) === 1;
        form.elements.center_code.readOnly = !!system;
        form.elements.center_type.disabled = !!system;
        form.elements.is_active.disabled = !!system;
        document.getElementById('financeCenterModalTitle').textContent = center ? 'Editar centro financiero' : 'Nuevo centro financiero';
        modal.style.display = 'flex'; modal.classList.add('show'); modal.setAttribute('aria-hidden','false'); document.body.classList.add('is-modal-open');
        setTimeout(function(){ form.elements.center_name.focus(); }, 40); icons();
    }
    function closeCenter() {
        modal.classList.remove('show'); modal.style.display = 'none'; modal.setAttribute('aria-hidden','true');
        if (!document.querySelector('.product-modal-backdrop.show')) document.body.classList.remove('is-modal-open');
    }
    async function saveCenter() {
        if (!form.reportValidity()) return;
        var fd = secureFormData(new FormData(form));
        if (form.elements.center_type.disabled) fd.set('center_type', form.elements.center_type.value);
        if (form.elements.is_active.disabled) fd.set('is_active', '1');
        if (!form.elements.is_default.checked) fd.set('is_default','0');
        if (!form.elements.is_active.checked && !form.elements.is_active.disabled) fd.set('is_active','0');
        var button = document.getElementById('saveFinanceCenterBtn'); button.disabled = true;
        try { await request('/modules/admin/finance_center_store_ajax.php',{method:'POST',body:fd}); closeCenter(); centersLoaded=false; await loadCenters(); }
        catch(error){ alert(error.message); }
        finally { button.disabled=false; }
    }
    async function toggleCenter(id) {
        if (!confirm('¿Confirmas el cambio de estado de este centro?')) return;
        var fd = secureFormData(new FormData()); fd.append('action','toggle'); fd.append('id',id);
        try { await request('/modules/admin/finance_center_store_ajax.php',{method:'POST',body:fd}); centersLoaded=false; await loadCenters(); }
        catch(error){ alert(error.message); }
    }

    function assignmentCenterOptions(selected) {
        var list = assignmentData && assignmentData.centers ? assignmentData.centers : [];
        return '<option value="">Sin centro</option>' + list.map(function (center) {
            return '<option value="' + esc(center.id) + '" ' + (String(center.id) === String(selected || '') ? 'selected' : '') + '>' + esc(center.center_code + ' · ' + center.center_name) + '</option>';
        }).join('');
    }
    function assignmentNotice(message, type) {
        var notice = document.getElementById('centerAssignmentNotice');
        if (!notice) return;
        notice.hidden = !message;
        notice.className = 'company-assignment-notice' + (type ? ' is-' + type : '');
        notice.textContent = message || '';
    }
    async function loadAssignment() {
        try {
            var payload = await request('/modules/admin/finance_center_assignment_ajax.php');
            assignmentData = payload.data || {}; assignmentLoaded = true; renderAssignment();
        } catch (error) {
            assignmentNotice(error.message, 'error');
        }
    }
    function renderAssignment() {
        if (!assignmentData) return;
        var settings = assignmentData.settings || {};
        var install = document.getElementById('centerAssignmentInstallNotice');
        install.hidden = Number(settings.installed) === 1;
        install.textContent = Number(settings.installed) === 1 ? '' : 'Falta ejecutar la migración v8.9.1. Puedes revisar las relaciones actuales, pero debes instalarla antes de guardar la política.';
        document.getElementById('centerAssignmentPriority').value = settings.assignment_priority || 'supplier_category_global';
        document.getElementById('centerAssignmentGlobal').innerHTML = assignmentCenterOptions(settings.global_cost_center_id);
        document.getElementById('centerAssignmentManual').checked = Number(settings.auto_apply_manual_costs) === 1;
        document.getElementById('centerAssignmentDte').checked = Number(settings.auto_apply_dte) === 1;
        document.getElementById('centerAssignmentRecurring').checked = Number(settings.auto_apply_recurring) === 1;
        document.getElementById('saveCenterAssignmentBtn').disabled = Number(settings.installed) !== 1;
        document.getElementById('applyCenterAssignmentBtn').disabled = Number(settings.installed) !== 1;

        var coverage = assignmentData.coverage || {};
        var values = [coverage.suppliers_unassigned || 0, coverage.categories_unassigned || 0, coverage.cost_entries_unassigned || 0, coverage.documents_unassigned || 0];
        document.querySelectorAll('#centerAssignmentSummary strong').forEach(function (node, index) { node.textContent = values[index] || 0; });

        var supplierRows = document.getElementById('supplierCenterRows');
        var suppliers = assignmentData.suppliers || [];
        supplierRows.innerHTML = suppliers.length ? suppliers.map(function (row) {
            var search = String((row.display_name || '') + ' ' + (row.customer_tax_id || '')).toLowerCase();
            return '<tr data-assignment-search="' + esc(search) + '"><td><strong>' + esc(row.display_name) + '</strong><small>' + esc(row.customer_tax_id || 'Sin RUT') + '</small></td><td><select class="select" data-supplier-center="' + esc(row.id) + '">' + assignmentCenterOptions(row.finance_center_id) + '</select></td></tr>';
        }).join('') : '<tr><td colspan="2">No hay proveedores activos.</td></tr>';

        var categoryRows = document.getElementById('categoryCenterRows');
        var categories = assignmentData.categories || [];
        categoryRows.innerHTML = categories.length ? categories.map(function (row) {
            var search = String((row.category_code || '') + ' ' + (row.category_name || '')).toLowerCase();
            return '<tr data-assignment-search="' + esc(search) + '"><td><strong>' + esc(row.category_code + ' · ' + row.category_name) + '</strong><small>' + (Number(row.is_active) ? 'Activa' : 'Inactiva') + '</small></td><td><select class="select" data-category-center="' + esc(row.id) + '">' + assignmentCenterOptions(row.finance_center_id) + '</select></td></tr>';
        }).join('') : '<tr><td colspan="2">No hay categorías configuradas.</td></tr>';
        icons();
    }
    async function saveAssignmentSettings() {
        var fd = secureFormData(new FormData());
        fd.append('action', 'save_settings');
        fd.append('assignment_priority', document.getElementById('centerAssignmentPriority').value);
        fd.append('global_cost_center_id', document.getElementById('centerAssignmentGlobal').value);
        fd.append('auto_apply_manual_costs', document.getElementById('centerAssignmentManual').checked ? '1' : '0');
        fd.append('auto_apply_dte', document.getElementById('centerAssignmentDte').checked ? '1' : '0');
        fd.append('auto_apply_recurring', document.getElementById('centerAssignmentRecurring').checked ? '1' : '0');
        var button = document.getElementById('saveCenterAssignmentBtn'); button.disabled = true;
        try { await request('/modules/admin/finance_center_assignment_ajax.php', {method:'POST',body:fd}); assignmentLoaded=false; await loadAssignment(); assignmentNotice('Política de asignación guardada.', 'success'); }
        catch (error) { assignmentNotice(error.message, 'error'); }
        finally { button.disabled = false; }
    }
    async function saveAssignmentMapping(action, idName, id, centerId, select) {
        var fd = secureFormData(new FormData()); fd.append('action', action); fd.append(idName, id); fd.append('finance_center_id', centerId || '');
        select.disabled = true;
        try { await request('/modules/admin/finance_center_assignment_ajax.php', {method:'POST',body:fd}); assignmentLoaded=false; await loadAssignment(); assignmentNotice('Relación actualizada y disponible para los nuevos movimientos.', 'success'); }
        catch (error) { assignmentNotice(error.message, 'error'); assignmentLoaded=false; await loadAssignment(); }
        finally { select.disabled = false; }
    }
    async function applyPendingAssignments() {
        if (!confirm('¿Aplicar la política solo a documentos y movimientos que actualmente no tienen centro?')) return;
        var fd = secureFormData(new FormData()); fd.append('action','apply_pending'); fd.append('period',document.getElementById('centerAssignmentPeriod').value);
        var button = document.getElementById('applyCenterAssignmentBtn'); button.disabled = true;
        try {
            var payload = await request('/modules/admin/finance_center_assignment_ajax.php',{method:'POST',body:fd});
            var result = payload.data || {}; assignmentLoaded=false; await loadAssignment();
            assignmentNotice('Asignación completada: ' + Number(result.documents||0) + ' DTE, ' + Number(result.collections||0) + ' cuentas por pagar, ' + Number(result.cost_entries||0) + ' movimientos y ' + Number(result.recurring_rules||0) + ' recurrencias.', 'success');
        } catch(error) { assignmentNotice(error.message, 'error'); }
        finally { button.disabled=false; }
    }
    function filterAssignmentRows(inputId, rowsId) {
        var input = document.getElementById(inputId); if (!input) return;
        var query = input.value.trim().toLowerCase();
        document.querySelectorAll('#' + rowsId + ' tr[data-assignment-search]').forEach(function (row) { row.hidden = query !== '' && row.getAttribute('data-assignment-search').indexOf(query) === -1; });
    }

    on(document, 'click', function (event) {
        var edit = event.target.closest('[data-edit-center]'); if (edit) { var center=centers.find(function(c){return String(c.id)===String(edit.getAttribute('data-edit-center'));}); openCenter(center||null); return; }
        var toggle = event.target.closest('[data-toggle-center]'); if (toggle) { toggleCenter(toggle.getAttribute('data-toggle-center')); return; }
        var action = event.target.closest('button'); var id = action ? action.id : '';
        if (id === 'newFinanceCenterBtn') openCenter(null);
        if (id === 'closeFinanceCenterModalBtn' || id === 'cancelFinanceCenterBtn') closeCenter();
        if (id === 'saveFinanceCenterBtn') saveCenter();
        if (id === 'saveCenterAssignmentBtn') saveAssignmentSettings();
        if (id === 'applyCenterAssignmentBtn') applyPendingAssignments();
    });
    on(document, 'change', function (event) {
        var supplier = event.target.closest('[data-supplier-center]'); if (supplier) { saveAssignmentMapping('assign_supplier','supplier_id',supplier.getAttribute('data-supplier-center'),supplier.value,supplier); return; }
        var category = event.target.closest('[data-category-center]'); if (category) { saveAssignmentMapping('assign_category','category_id',category.getAttribute('data-category-center'),category.value,category); }
    });
    on(document.getElementById('supplierCenterSearch'), 'input', function () { filterAssignmentRows('supplierCenterSearch','supplierCenterRows'); });
    on(document.getElementById('categoryCenterSearch'), 'input', function () { filterAssignmentRows('categoryCenterSearch','categoryCenterRows'); });
    on(modal, 'pointerdown', function (event) { if (event.target === modal) closeCenter(); });
    on(document, 'keydown', function (event) { if (event.key === 'Escape' && modal.classList.contains('show')) closeCenter(); });

    var requestedTab = new URLSearchParams(window.location.search).get('tab');
    var initial = window.location.hash ? window.location.hash.slice(1) : (requestedTab === 'centros' ? 'tab-centros' : 'tab-empresa');
    activate(initial, false);
    icons();
})();
</script>

<style>
/* ==========================================================================
   ESTRUCTURA APP NATIVA (Sin scroll global)
   ========================================================================== */

/* Bloquear scroll solo en esta pantalla */
#company-settings-main { overflow: hidden !important; }

/* Contenedor flexible principal */
.content-no-scroll {
    display: flex;
    flex-direction: column;
    height: calc(100vh - var(--topbar-height));
    padding-bottom: 0 !important; /* El padding inferior lo dará el área de guardado */
    overflow: hidden;
}

/* Cabeceras y pestañas fijas, no se encogen */
.fixed-header-section {
    flex-shrink: 0;
}

/* El formulario toma el resto del espacio */
.full-height-form {
    flex: 1;
    display: flex;
    flex-direction: column;
    min-height: 0;
    overflow: hidden;
    margin-top: var(--space-4);
    margin-bottom: 0 !important;
}

/* Ventana interna que sí tiene scroll para los campos */
.tabs-scroll-viewport {
    flex: 1;
    min-height: 0;
    overflow-y: auto;
    overflow-x: hidden;
    padding-right: 8px; /* Espacio para que el scroll no toque las cajas */
    padding-bottom: var(--space-4);
}

/* Scrollbar sutil e interno */
.tabs-scroll-viewport::-webkit-scrollbar { width: 6px; }
.tabs-scroll-viewport::-webkit-scrollbar-track { background: transparent; }
.tabs-scroll-viewport::-webkit-scrollbar-thumb { 
    background: var(--border-strong); 
    border-radius: 999px; 
}

/* Zona inferior de guardado anclada a la derecha */
.form-actions-fixed {
    flex-shrink: 0;
    padding: var(--space-4) 0;
    padding-bottom: calc(var(--space-4) + env(safe-area-inset-bottom));
    background: var(--surface-0);
    border-top: 1px solid var(--border-default);
    display: flex;
    justify-content: flex-end;
    align-items: center;
    z-index: 10;
}

/* Diseño interactivo y adaptable de Pestañas */
.tabs-container {
    display: flex;
    flex-wrap: wrap; 
    gap: var(--space-2);
    border-bottom: 1px solid var(--border-default);
}

.tab-trigger {
    background: transparent;
    border: none;
    color: var(--text-secondary);
    padding: var(--space-3) var(--space-4);
    font-size: 0.9rem;
    font-weight: 600;
    cursor: pointer;
    display: inline-flex;
    align-items: center;
    gap: var(--space-2);
    border-radius: var(--radius-md) var(--radius-md) 0 0;
    transition: all var(--motion-fast);
    border-bottom: 2px solid transparent;
    margin-bottom: -1px; 
}

.tab-trigger svg {
    width: 18px;
    height: 18px;
}

.tab-trigger:hover {
    color: var(--text-primary);
    background: var(--surface-2);
}

.tab-trigger.active {
    color: var(--text-inverse); /* Automáticamente se adapta Blanco/Negro al fondo activo */
    background: var(--color-primary); 
    border-bottom: 2px solid var(--color-primary);
}

.tab-panel {
    display: none;
}

.tab-panel.active {
    display: block;
    animation: fadeIn var(--motion-base);
}

@keyframes fadeIn {
    from { opacity: 0; transform: translateY(4px); }
    to { opacity: 1; transform: translateY(0); }
}

/* En teléfonos, el botón de guardado ocupa todo el ancho por facilidad táctil */
@media (max-width: 760px) {
    .form-actions-fixed .btn {
        width: 100%;
        justify-content: center;
    }
}

/* Apariencia operativa homologada con CRM, facturación, costos y tesorería. */
#company-settings-main .content-no-scroll {
    width: min(100%, 1800px);
    max-width: none !important;
    margin: 0 auto;
}

#company-settings-main .page-header-compact {
    margin: 0 0 12px !important;
    padding: 0 !important;
}

#company-settings-main .page-header-content h1 {
    margin: 3px 0 4px !important;
    font-size: clamp(1.55rem, 2vw, 2rem) !important;
    line-height: 1.15 !important;
}

#company-settings-main .page-header-content p {
    margin: 0 !important;
    font-size: 0.86rem !important;
}

#company-settings-main .company-settings-feedback {
    min-height: 40px;
    margin: 0 0 10px;
    padding: 9px 12px;
}

#company-settings-main .company-settings-feedback svg {
    width: 18px;
    height: 18px;
}

#company-settings-main .tabs-container {
    flex-wrap: nowrap;
    gap: 5px;
    width: max-content;
    max-width: 100%;
    padding: 5px;
    overflow-x: auto;
    border: 1px solid var(--border-subtle);
    border-radius: var(--radius-lg);
    background: var(--surface-1);
    scrollbar-width: none;
}

#company-settings-main .tabs-container::-webkit-scrollbar {
    display: none;
}

#company-settings-main .tab-trigger {
    flex: 0 0 auto;
    min-height: 40px;
    margin: 0;
    padding: 9px 13px;
    border: 0;
    border-radius: var(--radius-md);
    color: var(--text-secondary);
    background: transparent;
    font-size: 0.8rem;
    font-weight: 650;
}

#company-settings-main .tab-trigger:hover {
    color: var(--text-primary);
    background: var(--surface-2);
}

#company-settings-main .tab-trigger.active {
    color: var(--text-primary);
    background: var(--surface-3);
    border: 0;
    box-shadow: none;
}

#company-settings-main .tab-trigger.active svg {
    color: var(--color-primary);
}

#company-settings-main .full-height-form {
    margin-top: 12px;
}

#company-settings-main .tabs-scroll-viewport {
    padding-right: 6px;
    padding-bottom: 12px;
}

#company-settings-main .form-card {
    overflow: hidden;
    border-radius: var(--radius-lg);
    box-shadow: none;
}

#company-settings-main .form-card + .form-card {
    margin-top: 12px !important;
}

#company-settings-main .form-card .card-header {
    min-height: 0;
    padding: 14px 16px;
    border-bottom: 1px solid var(--border-subtle);
}

#company-settings-main .form-card .card-header h3 {
    margin: 0;
    font-size: 1rem;
}

#company-settings-main .form-card .card-header p {
    margin: 4px 0 0 !important;
    font-size: 0.74rem;
}

#company-settings-main .form-card .card-body {
    padding: 16px;
}

#company-settings-main .form-grid {
    gap: 13px 16px;
}

#company-settings-main .form-field {
    gap: 5px;
}

#company-settings-main .form-field > .label {
    font-size: 0.7rem;
}

#company-settings-main .input,
#company-settings-main .select {
    min-height: 42px;
}

#company-settings-main textarea.input {
    min-height: 104px;
    height: auto;
    resize: vertical;
}

#company-settings-main .company-commercial-settings {
    display: grid;
    grid-template-columns: repeat(2, minmax(0, 1fr));
    gap: 16px;
}

#company-settings-main .company-document-footer-field {
    margin-top: 16px;
    padding-top: 16px;
    border-top: 1px solid var(--border-subtle);
}

#company-settings-main .form-actions-fixed {
    min-height: 62px;
    padding: 10px 0 calc(10px + env(safe-area-inset-bottom));
    background: color-mix(in srgb, var(--surface-0) 94%, transparent);
    backdrop-filter: blur(10px);
}

#company-settings-main .form-actions-fixed .btn {
    min-height: 42px;
    padding-inline: 16px;
}

@media (max-width: 760px) {
    #company-settings-main .page-header-content p {
        display: none;
    }
    #company-settings-main .company-commercial-settings {
        grid-template-columns: 1fr;
    }
    #company-settings-main .form-card .card-header,
    #company-settings-main .form-card .card-body {
        padding-inline: 13px;
    }
}

.company-centers-card{height:100%;min-height:0;display:flex;flex-direction:column}.company-centers-header{display:flex;align-items:center;justify-content:space-between;gap:16px}.company-centers-body{min-height:0;display:flex;flex-direction:column;gap:14px}.company-centers-summary{display:grid;grid-template-columns:repeat(4,minmax(0,1fr));gap:12px}.company-centers-summary>div{border:1px solid var(--border-subtle);border-radius:16px;padding:14px;background:var(--surface-1)}.company-centers-summary span{display:block;font-size:.72rem;text-transform:uppercase;color:var(--text-muted);font-weight:800}.company-centers-summary strong{display:block;margin-top:6px;font-size:1.25rem}.company-centers-table-wrap{min-height:280px;max-height:52dvh;overflow-y:auto;overflow-x:hidden;border:1px solid var(--border-subtle);border-radius:16px}.company-centers-table{width:100%;table-layout:fixed}.company-centers-table th{position:sticky;top:0;z-index:2;background:var(--surface-1)}.company-centers-table th:nth-child(1){width:14%}.company-centers-table th:nth-child(2){width:22%}.company-centers-table th:nth-child(3){width:12%}.company-centers-table th:nth-child(4){width:14%}.company-centers-table th:nth-child(5){width:12%}.company-centers-table th:nth-child(6){width:10%}.company-centers-table th:nth-child(7){width:16%}.company-centers-table td{overflow:hidden;text-overflow:ellipsis}.company-centers-table td small{display:block;color:var(--text-muted);margin-top:3px}.company-center-actions{display:flex;gap:6px;justify-content:flex-end}.company-center-actions .btn{padding:7px 9px;font-size:.78rem}.company-center-status{display:inline-flex;border-radius:999px;padding:5px 9px;font-size:.75rem;font-weight:800}.company-center-status.is-active{background:#dcfce7;color:#166534}.company-center-status.is-inactive{background:var(--surface-2);color:var(--text-secondary)}.company-settings-modal-box{width:min(760px,calc(100vw - 48px));max-height:calc(100dvh - 80px)}.company-center-check{display:flex;align-items:center;gap:9px;min-height:44px;font-weight:700}.company-center-check input{width:18px;height:18px;accent-color:var(--color-primary)}.form-actions-fixed.is-hidden{display:none!important}
    .company-assignment-card{min-height:0}.company-assignment-body{display:flex;flex-direction:column;gap:18px}.company-assignment-policy{display:grid;grid-template-columns:minmax(230px,1fr) minmax(230px,1fr);gap:14px 18px;padding:16px;border:1px solid var(--border-subtle);border-radius:16px;background:var(--surface-1)}.company-assignment-policy .company-center-check{align-self:end}.company-assignment-summary{display:grid;grid-template-columns:repeat(4,minmax(0,1fr));gap:12px}.company-assignment-summary>div{border:1px solid var(--border-subtle);border-radius:16px;padding:14px;background:var(--surface-1)}.company-assignment-summary span{display:block;color:var(--text-muted);font-size:.72rem;font-weight:800;text-transform:uppercase}.company-assignment-summary strong{display:block;margin-top:6px;font-size:1.25rem}.company-assignment-apply{display:grid;grid-template-columns:minmax(0,1fr) 170px auto;gap:12px;align-items:center;padding:15px;border:1px solid var(--border-subtle);border-radius:16px}.company-assignment-apply small,.company-assignment-list-header small{display:block;margin-top:4px;color:var(--text-muted)}.company-assignment-notice{padding:12px 14px;border-radius:12px;background:var(--surface-2);color:var(--text-secondary)}.company-assignment-notice.is-success{background:#dcfce7;color:#166534}.company-assignment-notice.is-error{background:#fee2e2;color:#991b1b}.company-assignment-columns{display:grid;grid-template-columns:repeat(2,minmax(0,1fr));gap:18px}.company-assignment-columns>section{min-width:0}.company-assignment-list-header{display:flex;justify-content:space-between;align-items:end;gap:12px;margin-bottom:10px}.company-assignment-list-header h4{margin:0}.company-assignment-list-header .input{width:min(220px,42%)}.company-assignment-table-wrap{height:390px;overflow:auto;border:1px solid var(--border-subtle);border-radius:16px}.company-assignment-table-wrap table{width:100%;table-layout:fixed}.company-assignment-table-wrap th{position:sticky;top:0;z-index:2;background:var(--surface-1)}.company-assignment-table-wrap th:first-child{width:48%}.company-assignment-table-wrap td small{display:block;margin-top:3px;color:var(--text-muted)}
@media(max-width:1000px){.company-assignment-columns{grid-template-columns:1fr}.company-assignment-policy{grid-template-columns:1fr 1fr}.company-assignment-summary{grid-template-columns:repeat(2,minmax(0,1fr))}}
@media(max-width:760px){.content-no-scroll{height:calc(100dvh - var(--topbar-height));overflow:hidden}.tabs-container{flex-wrap:nowrap;overflow-x:auto;scrollbar-width:none}.tab-trigger{flex:0 0 auto;padding:10px 12px}.company-centers-header{align-items:stretch;flex-direction:column}.company-centers-summary,.company-assignment-summary{grid-template-columns:repeat(2,minmax(0,1fr))}.company-centers-table-wrap{height:48dvh;min-height:300px;max-height:430px;overflow-x:hidden}.company-centers-table th:nth-child(1),.company-centers-table td:nth-child(1),.company-centers-table th:nth-child(3),.company-centers-table td:nth-child(3),.company-centers-table th:nth-child(4),.company-centers-table td:nth-child(4),.company-centers-table th:nth-child(5),.company-centers-table td:nth-child(5){display:none}.company-centers-table th:nth-child(2){width:auto}.company-centers-table th:nth-child(6){width:82px}.company-centers-table th:nth-child(7){width:64px}.company-center-actions .btn{font-size:0;min-width:42px}.company-center-actions .btn span{display:none}.company-center-actions .btn:not(:first-child){display:none}.company-settings-modal-box{width:calc(100vw - 24px);height:calc(100dvh - 200px);max-height:calc(100dvh - 200px)}.company-settings-modal-box .product-modal-body{overflow-y:auto}.company-centers-summary>div{padding:11px}.company-assignment-policy{grid-template-columns:1fr}.company-assignment-apply{grid-template-columns:1fr}.company-assignment-list-header{align-items:stretch;flex-direction:column}.company-assignment-list-header .input{width:100%}.company-assignment-table-wrap{height:340px}}
</style>

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