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

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

<main class="app-main" id="company-settings-main">
    <?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 la información legal, de sucursales e instrucciones de transferencias 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 endif; ?>

        <div class="tabs-container fixed-header-section">
            <button type="button" class="tab-trigger active" data-target="tab-empresa">
                <i data-lucide="building-2"></i> <span>Datos de la Empresa</span>
            </button>
            <button type="button" class="tab-trigger" data-target="tab-banco">
                <i data-lucide="landmark"></i> <span>Datos Bancarios</span>
            </button>
            <button type="button" class="tab-trigger" data-target="tab-modulos">
                <i data-lucide="layout-grid"></i> <span>Módulos y Menú</span>
            </button>
        </div>

        <form class="opportunity-form full-height-form" action="/modules/admin/company_settings_store.php" method="POST" enctype="multipart/form-data">
            
            <div class="tabs-scroll-viewport">
                
                <div id="tab-empresa" class="tab-panel active">
                    <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>
                </div>

                <div id="tab-banco" class="tab-panel">
                    <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">
                    <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>

            <div class="form-actions-fixed">
                <button class="btn btn-primary" type="submit">
                    <i data-lucide="save"></i>
                    <span>Guardar Configuración General</span>
                </button>
            </div>
            
        </form>
    </section>
</main>

<script>
(function () {
    var triggers = document.querySelectorAll('.tab-trigger');
    var panels = document.querySelectorAll('.tab-panel');

    triggers.forEach(function (btn) {
        btn.addEventListener('click', function () {
            var targetId = btn.getAttribute('data-target');
            
            triggers.forEach(function (t) { t.classList.remove('active'); });
            panels.forEach(function (p) { p.classList.remove('active'); });

            btn.classList.add('active');
            document.getElementById(targetId).classList.add('active');
        });
    });

    var ruts = document.querySelectorAll('.rut-formatter');
    ruts.forEach(function (input) {
        input.addEventListener('input', function (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, ".");
            var dv = value.slice(-1).toUpperCase();
            e.target.value = body + '-' + dv;
        });
    });
})();
</script>

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

/* Bloquear scroll general del main */
.app-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;
    }
}
</style>

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