<?php
// Configuración del Sistema
if (session_status() === PHP_SESSION_NONE) { session_start(); }
if (!defined('BASE_PATH')) { define('BASE_PATH', dirname(dirname(__DIR__))); }
require_once BASE_PATH . '/database/config.php';
require_once BASE_PATH . '/database/connection.php';

// Función de autenticación (definida si no existe)
if (!function_exists('isLoggedIn')) {
    function isLoggedIn() {
        return isset($_SESSION['user_id']) && !empty($_SESSION['user_id']);
    }
}

// Función de permisos (definida si no existe)
if (!function_exists('userHasPermissionByName')) {
    function userHasPermissionByName($pdo, $permName, $userId) {
        if (empty($userId)) return false;
        $stmt = $pdo->prepare("SELECT 1 FROM role_permissions rp INNER JOIN permissions p ON rp.permission_id = p.id INNER JOIN user_roles ur ON rp.role_id = ur.role_id WHERE ur.user_id = ? AND p.name = ? LIMIT 1");
        $stmt->execute([$userId, $permName]);
        return (bool)$stmt->fetchColumn();
    }
}

// Verificar si el usuario está logueado
if (!isLoggedIn()) {
    header('Location: /index.php?module=auth&action=login');
    exit;
}

// Variables para el layout
$current_module = 'config';
$current_action = 'index';

$db = getDB();
$pdo = $db->getConnection();

// Procesar acciones POST
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    require_once 'actions.php';
}

// Obtener configuraciones del sistema
try {
    $stmt = $pdo->prepare("SELECT config_key, config_value FROM system_config");
    $stmt->execute();
    $config_rows = $stmt->fetchAll(PDO::FETCH_ASSOC);
    
    $config = [];
    foreach ($config_rows as $row) {
        $config[$row['config_key']] = $row['config_value'];
    }
} catch (PDOException $e) {
    $config = [];
    error_log("Error loading system config: " . $e->getMessage());
}

// Valores por defecto si no existen
$defaults = [
    'company_name' => 'ProfixCRM Business Suite',
    'brand_name' => 'ProfixCRM Business Suite',
    'company_logo' => '',
    'timezone' => 'America/Mexico_City',
    'system_timezone' => 'America/Mexico_City',
    'currency' => 'USD',
    'system_currency' => 'MXN',
    'language' => 'es',
    'system_language' => 'es',
    'email_notifications' => '1',
    'maintenance_mode' => '0',
    'max_file_size' => '10',
    'session_timeout' => '3600',
    'backup_frequency' => 'daily',
    'smtp_host' => '',
    'smtp_port' => '587',
    'smtp_username' => '',
    'smtp_password' => '',
    'smtp_encryption' => 'tls',
    'password_min_length' => '8',
    'login_attempts_limit' => '5',
    'auto_logout_time' => '30'
];

$configs = array_merge($defaults, $config);

// Divisas permitidas desde configuración
$allowedCurrenciesRaw = isset($config['allowed_currencies']) ? json_decode($config['allowed_currencies'], true) : [];
if (!is_array($allowedCurrenciesRaw)) { $allowedCurrenciesRaw = []; }
$allowedCurrencies = array_values(array_unique(array_map(function($c){ return strtoupper(trim($c)); }, $allowedCurrenciesRaw)));
$defaultCurrencyOptions = ['USD','EUR','GBP','JPY','MXN','AUD','CAD','CHF'];
$currencyOptions = array_values(array_unique(array_merge($defaultCurrencyOptions, $allowedCurrencies)));

// Obtener información del sistema
$system_info = [
    'php_version' => phpversion(),
    'server_software' => $_SERVER['SERVER_SOFTWARE'] ?? 'Unknown',
    'memory_limit' => ini_get('memory_limit'),
    'max_execution_time' => ini_get('max_execution_time'),
    'upload_max_filesize' => ini_get('upload_max_filesize'),
    'post_max_size' => ini_get('post_max_size')
];
?>

<!DOCTYPE html>
<html lang="es">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Configuración del Sistema - <?php echo htmlspecialchars($configs['company_name']); ?></title>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css" rel="stylesheet">
    <link href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.0.0/css/all.min.css" rel="stylesheet">
    <?php $appBase = dirname($_SERVER['SCRIPT_NAME']); $appBase = $appBase === '/' ? '' : $appBase; ?>
    <link href="<?php echo $appBase; ?>/public/style.css" rel="stylesheet">
    <style>
        .config-section {
            background: var(--bs-body-bg);
            border-radius: 12px;
            padding: 2rem;
            margin-bottom: 2rem;
            border: 1px solid var(--bs-border-color);
            box-shadow: 0 2px 4px rgba(0,0,0,0.05);
        }
        .config-section h5 {
            color: var(--primary-color);
            margin-bottom: 1.5rem;
            font-weight: 600;
        }
        .form-group {
            margin-bottom: 1rem;
        }
        
        .form-label {
            font-weight: 500;
            color: #333;
            margin-bottom: 0.5rem;
        }
        
        .form-control {
            border: 1px solid #ddd;
            border-radius: 4px;
            padding: 0.75rem;
            font-size: 0.9rem;
        }
        
        .form-control:focus {
            border-color: #007bff;
            box-shadow: 0 0 0 0.2rem rgba(0, 123, 255, 0.25);
        }
        
        .config-section .row {
            margin-bottom: 1.5rem;
        }
        
        .config-section .row .col-md-6 {
            margin-bottom: 1rem;
        }
        
        .logo-preview {
            max-width: 200px;
            max-height: 100px;
            border: 2px dashed var(--bs-border-color);
            border-radius: 8px;
            padding: 1rem;
            text-align: center;
            background: var(--bs-light);
        }
        .logo-preview img {
            max-width: 100%;
            max-height: 80px;
        }
        .system-info-card {
            background: linear-gradient(135deg, var(--primary-color), var(--secondary-color));
            color: white;
            border-radius: 12px;
            padding: 1.5rem;
        }
        .info-item {
            display: flex;
            justify-content: space-between;
            padding: 0.5rem 0;
            border-bottom: 1px solid rgba(255,255,255,0.1);
        }
        .info-item:last-child {
            border-bottom: none;
        }
        .security-actions .btn {
            margin: 0.25rem;
        }
    </style>
    <?php if (!isset($appBase)) { $appBase = dirname($_SERVER['SCRIPT_NAME']); $appBase = $appBase === '/' ? '' : $appBase; } ?>
    <script src="<?php echo $appBase; ?>/public/basepath.js"></script>
</head>
<body>
    <!-- Sidebar Overlay para móvil -->
    <div class="sidebar-overlay" id="sidebarOverlay"></div>

    <!-- Main Wrapper -->
    <div class="main-wrapper">
        <!-- Sidebar -->
        <?php include BASE_PATH . '/modules/shared/sidebar.php'; ?>

        <!-- Content Wrapper -->
        <div class="content-wrapper">
            <!-- Page Header -->
            <div class="roles-header">
                <div class="header-left">
                    <h1 class="page-title">
                        <svg class="title-icon" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
                            <circle cx="12" cy="12" r="3"/>
                            <path d="M12 1v6m0 6v6m11-7h-6m-6 0H1m15.5-3.5L19 4l-1.5 1.5M5 20l-1.5-1.5L5 17"/>
                        </svg>
                        Configuración del Sistema
                    </h1>
                    <p class="page-subtitle">Personaliza la apariencia y configuración general del sistema.</p>
                </div>
                <button class="btn btn-outline-primary d-lg-none" id="sidebarToggle">
                    <i class="fas fa-bars"></i>
                </button>
            </div>

            <!-- Status Messages -->
            <?php if (isset($_SESSION['success_message'])): ?>
                <div class="alert alert-success alert-dismissible fade show" role="alert">
                    <i class="fas fa-check-circle"></i> <?php echo $_SESSION['success_message']; unset($_SESSION['success_message']); ?>
                    <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
                </div>
            <?php endif; ?>

            <?php if (isset($_SESSION['error_message'])): ?>
                <div class="alert alert-danger alert-dismissible fade show" role="alert">
                    <i class="fas fa-exclamation-circle"></i> <?php echo $_SESSION['error_message']; unset($_SESSION['error_message']); ?>
                    <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
                </div>
            <?php endif; ?>

            <!-- Configuration Tabs -->
            <div class="card">
                <div class="card-header">
                    <ul class="nav nav-tabs card-header-tabs" id="configTabs" role="tablist">
                        <li class="nav-item" role="presentation">
                            <button class="nav-link active" id="general-tab" data-bs-toggle="tab" data-bs-target="#general" type="button" role="tab">
                                <i class="fas fa-cog"></i> General
                            </button>
                        </li>
                        <li class="nav-item" role="presentation">
                            <button class="nav-link" id="branding-tab" data-bs-toggle="tab" data-bs-target="#branding" type="button" role="tab">
                                <i class="fas fa-palette"></i> Marca y Logo
                            </button>
                        </li>
                        <li class="nav-item" role="presentation">
                            <button class="nav-link" id="system-tab" data-bs-toggle="tab" data-bs-target="#system" type="button" role="tab">
                                <i class="fas fa-server"></i> Sistema
                            </button>
                        </li>
                        <li class="nav-item" role="presentation">
                            <button class="nav-link" id="trading-tab" data-bs-toggle="tab" data-bs-target="#trading" type="button" role="tab">
                                <i class="fas fa-coins"></i> Trading
                            </button>
                        </li>
                        <li class="nav-item" role="presentation">
                            <button class="nav-link" id="security-tab" data-bs-toggle="tab" data-bs-target="#security" type="button" role="tab">
                                <i class="fas fa-shield-alt"></i> Seguridad
                            </button>
                        </li>
                    </ul>
                </div>

                <div class="card-body">
                    <div class="tab-content" id="configTabsContent">
                        <!-- Tab: Configuración General -->
                        <div class="tab-pane fade show active" id="general" role="tabpanel">
                            <div class="config-section">
                                <h5><i class="fas fa-cog"></i> Configuración General</h5>
                                <p class="text-muted">Configuración básica del sistema</p>
                                
                                <form method="POST" action="" id="generalConfigForm">
                                    <input type="hidden" name="action" value="update_general">
                                    
                                    <div class="row">
                                        <div class="col-md-6">
                                            <div class="form-group">
                                                <label class="form-label" for="company_name">Nombre de la Empresa</label>
                                                <input type="text" class="form-control" id="company_name" name="company_name" 
                                                       value="<?php echo htmlspecialchars($configs['company_name']); ?>">
                                            </div>
                                        </div>
                                        <div class="col-md-6">
                                            <div class="form-group">
                                                <label class="form-label" for="timezone">Zona Horaria</label>
                                                <select class="form-control" id="timezone" name="timezone">
                                                    <option value="America/New_York" <?php echo $configs['timezone'] === 'America/New_York' ? 'selected' : ''; ?>>ET (GMT-5)</option>
                                                    <option value="America/Chicago" <?php echo $configs['timezone'] === 'America/Chicago' ? 'selected' : ''; ?>>CT (GMT-6)</option>
                                                    <option value="America/Denver" <?php echo $configs['timezone'] === 'America/Denver' ? 'selected' : ''; ?>>MT (GMT-7)</option>
                                                    <option value="America/Los_Angeles" <?php echo $configs['timezone'] === 'America/Los_Angeles' ? 'selected' : ''; ?>>PT (GMT-8)</option>
                                                    <option value="Europe/London" <?php echo $configs['timezone'] === 'Europe/London' ? 'selected' : ''; ?>>GMT (GMT+0)</option>
                                                    <option value="Europe/Madrid" <?php echo $configs['timezone'] === 'Europe/Madrid' ? 'selected' : ''; ?>>CET (GMT+1)</option>
                                                </select>
                                            </div>
                                        </div>
                                    </div>
                                    
                                    <div class="row">
                                        <div class="col-md-6">
                                            <div class="form-group">
                                                <label class="form-label" for="currency">Moneda</label>
                                                <select class="form-control" id="currency" name="currency">
                                                    <option value="USD" <?php echo $configs['currency'] === 'USD' ? 'selected' : ''; ?>>USD ($)</option>
                                                    <option value="EUR" <?php echo $configs['currency'] === 'EUR' ? 'selected' : ''; ?>>EUR (€)</option>
                                                    <option value="GBP" <?php echo $configs['currency'] === 'GBP' ? 'selected' : ''; ?>>GBP (£)</option>
                                                    <option value="JPY" <?php echo $configs['currency'] === 'JPY' ? 'selected' : ''; ?>>JPY (¥)</option>
                                                </select>
                                            </div>
                                        </div>
                                        <div class="col-md-6">
                                            <div class="form-group">
                                                <label class="form-label" for="language">Idioma</label>
                                                <select class="form-control" id="language" name="language">
                                                    <option value="es" <?php echo $configs['language'] === 'es' ? 'selected' : ''; ?>>Español</option>
                                                    <option value="en" <?php echo $configs['language'] === 'en' ? 'selected' : ''; ?>>English</option>
                                                    <option value="fr" <?php echo $configs['language'] === 'fr' ? 'selected' : ''; ?>>Français</option>
                                                </select>
                                            </div>
                                        </div>
                                    </div>
                                    
                                    <div class="row">
                                        <div class="col-md-6">
                                            <div class="form-check form-switch mb-3">
                                                <input class="form-check-input" type="checkbox" id="email_notifications" name="email_notifications" 
                                                       <?php echo $configs['email_notifications'] ? 'checked' : ''; ?>>
                                                <label class="form-check-label" for="email_notifications">
                                                    Notificaciones por Email
                                                </label>
                                            </div>
                                        </div>
                                        <div class="col-md-6">
                                            <div class="form-check form-switch mb-3">
                                                <input class="form-check-input" type="checkbox" id="maintenance_mode" name="maintenance_mode" 
                                                       <?php echo $configs['maintenance_mode'] ? 'checked' : ''; ?>>
                                                <label class="form-check-label" for="maintenance_mode">
                                                    Modo de Mantenimiento
                                                </label>
                                            </div>
                                        </div>
                                    </div>
                                    
                                    <div class="d-flex justify-content-end">
                                        <button type="submit" class="btn btn-primary" id="saveGeneralConfig">
                                            <i class="fas fa-save"></i> Guardar Configuración
                                        </button>
                                    </div>
                                </form>
                            </div>
                        </div>

                        <!-- Tab: Marca y Logo -->
                        <div class="tab-pane fade" id="branding" role="tabpanel">
                            <div class="config-section">
                                <h5><i class="fas fa-palette"></i> Marca y Logo</h5>
                                <p class="text-muted">Personaliza la identidad visual de tu sistema</p>
                                
                                <form method="POST" action="" enctype="multipart/form-data" id="brandingForm">
                                    <input type="hidden" name="action" value="update_branding">
                                    
                                    <div class="row">
                                        <div class="col-md-8">
                                            <div class="form-group">
                                                <label class="form-label" for="brand_name">Nombre de la Empresa</label>
                                                <input type="text" class="form-control" id="brand_name" name="brand_name" 
                                                       value="<?php echo htmlspecialchars($configs['company_name']); ?>">
                                            </div>
                                            
                                            <div class="form-group">
                                                <label class="form-label" for="company_logo">Logo de la Empresa</label>
                                                <input type="file" class="form-control" id="company_logo" name="company_logo" 
                                                       accept="image/*" onchange="previewLogo(this)">
                                                <div class="form-text">Formatos soportados: JPG, PNG, SVG. Tamaño máximo: 2MB</div>
                                            </div>
                                        </div>
                                        <div class="col-md-4">
                                            <div class="logo-preview" id="logoPreview">
                                                <?php if (!empty($configs['company_logo']) && file_exists('../../uploads/logos/' . $configs['company_logo'])): ?>
                                                    <img src="../../uploads/logos/<?php echo htmlspecialchars($configs['company_logo']); ?>" alt="Logo actual">
                                                <?php else: ?>
                                                    <i class="fas fa-image fa-3x text-muted"></i>
                                                    <p class="text-muted mt-2">Vista Previa del Logo</p>
                                                <?php endif; ?>
                                            </div>
                                        </div>
                                    </div>
                                    
                                    <div class="d-flex justify-content-end">
                                        <button type="submit" class="btn btn-primary" id="saveBrandingBtn">
                                            <i class="fas fa-save"></i> Actualizar Marca
                                        </button>
                                    </div>
                                </form>
                            </div>
                        </div>

                        <!-- Tab: Sistema -->
                        <div class="tab-pane fade" id="system" role="tabpanel">
                            <div class="row">
                                <div class="col-md-8">
                                    <div class="config-section">
                                        <h5><i class="fas fa-server"></i> Configuración del Sistema</h5>
                                        <p class="text-muted">Parámetros técnicos y de rendimiento</p>
                                        
                                        <form method="POST" action="">
                                            <input type="hidden" name="action" value="update_system">
                                            
                                            <div class="row">
                                                <div class="col-md-6">
                                                    <div class="form-group">
                                                        <label class="form-label" for="max_file_size">Tamaño Máximo de Archivo (MB)</label>
                                                        <input type="number" class="form-control" id="max_file_size" name="max_file_size" 
                                                               value="<?php echo htmlspecialchars($configs['max_file_size']); ?>" min="1" max="100">
                                                    </div>
                                                </div>
                                                <div class="col-md-6">
                                                    <div class="form-group">
                                                        <label class="form-label" for="session_timeout">Tiempo de Sesión (segundos)</label>
                                                        <input type="number" class="form-control" id="session_timeout" name="session_timeout" 
                                                               value="<?php echo htmlspecialchars($configs['session_timeout']); ?>" min="300" max="86400">
                                                    </div>
                                                </div>
                                            </div>
                                            
                                            <div class="row">
                                                <div class="col-md-6">
                                                    <div class="form-group">
                                                        <label class="form-label" for="backup_frequency">Frecuencia de Respaldos</label>
                                                        <select class="form-control" id="backup_frequency" name="backup_frequency">
                                                            <option value="daily" <?php echo $configs['backup_frequency'] === 'daily' ? 'selected' : ''; ?>>Diario</option>
                                                            <option value="weekly" <?php echo $configs['backup_frequency'] === 'weekly' ? 'selected' : ''; ?>>Semanal</option>
                                                            <option value="monthly" <?php echo $configs['backup_frequency'] === 'monthly' ? 'selected' : ''; ?>>Mensual</option>
                                                            <option value="manual" <?php echo $configs['backup_frequency'] === 'manual' ? 'selected' : ''; ?>>Manual</option>
                                                        </select>
                                                    </div>
                                                </div>
                                                <div class="col-md-6">
                                                    <div class="form-group">
                                                        <label class="form-label" for="auto_logout_time">Auto-logout (minutos)</label>
                                                        <input type="number" class="form-control" id="auto_logout_time" name="auto_logout_time" 
                                                               value="<?php echo htmlspecialchars($configs['auto_logout_time']); ?>" min="5" max="120">
                                                    </div>
                                                </div>
                                            </div>
                                            
                                            <div class="d-flex justify-content-end">
                                                <button type="submit" class="btn btn-primary">
                                                    <i class="fas fa-save"></i> Guardar Sistema
                                                </button>
                                            </div>
                                        </form>
                                    </div>
                                </div>
                                
                                <div class="col-md-4">
                                    <div class="system-info-card">
                                        <h6><i class="fas fa-info-circle"></i> Información del Sistema</h6>
                                        <div class="info-item">
                                            <span>PHP Version:</span>
                                            <span><?php echo $system_info['php_version']; ?></span>
                                        </div>
                                        <div class="info-item">
                                            <span>Servidor:</span>
                                            <span><?php echo $system_info['server_software']; ?></span>
                                        </div>
                                        <div class="info-item">
                                            <span>Memoria:</span>
                                            <span><?php echo $system_info['memory_limit']; ?></span>
                                        </div>
                                        <div class="info-item">
                                            <span>Max Upload:</span>
                                            <span><?php echo $system_info['upload_max_filesize']; ?></span>
                                        </div>
                                        <div class="info-item">
                                            <span>Post Max:</span>
                                            <span><?php echo $system_info['post_max_size']; ?></span>
                                        </div>
                                    </div>
                                </div>
                            </div>
                        </div>

                        <!-- Tab: Trading -->
                        <div class="tab-pane fade" id="trading" role="tabpanel">
                            <div class="config-section">
                                <h5><i class="fas fa-coins"></i> Trading: Divisas y Tipos de Cuenta</h5>
                                <p class="text-muted">Configura qué divisas están permitidas y qué tipos de cuenta se ofrecen por cada divisa.</p>

                                <div class="mb-4">
                                    <h6 class="mb-2"><i class="fas fa-money-bill-wave"></i> Divisas permitidas</h6>
                                    <form id="allowedCurrenciesForm" method="POST" action="">
                                        <input type="hidden" name="action" value="update_allowed_currencies">
                                        <div class="d-flex flex-wrap gap-3">
                                            <?php foreach ($currencyOptions as $code): ?>
                                                <div class="form-check form-check-inline">
                                                    <input class="form-check-input" type="checkbox" id="currency_<?php echo $code; ?>" name="allowed_currencies[]" value="<?php echo $code; ?>" <?php echo in_array($code, $allowedCurrencies) ? 'checked' : ''; ?>>
                                                    <label class="form-check-label" for="currency_<?php echo $code; ?>"><?php echo $code; ?></label>
                                                </div>
                                            <?php endforeach; ?>
                                        </div>
                                        <div class="row mt-3">
                                            <div class="col-md-4">
                                                <div class="input-group">
                                                    <span class="input-group-text">Nueva divisa</span>
                                                    <input type="text" class="form-control" id="new_currency" name="new_currency" placeholder="Ej: MXN" maxlength="3">
                                                    <button type="submit" class="btn btn-primary">
                                                        <i class="fas fa-save"></i> Guardar divisas
                                                    </button>
                                                </div>
                                                <div class="form-text">Usa códigos ISO de 3 letras, p.e. USD, EUR, MXN.</div>
                                            </div>
                                        </div>
                                    </form>
                                </div>

                                <div>
                                    <h6 class="mb-2"><i class="fas fa-list"></i> Tipos de cuenta por divisa</h6>
                                    <div class="row align-items-end">
                                        <div class="col-md-4">
                                            <label class="form-label" for="trading_currency_select">Divisa</label>
                                            <select class="form-control" id="trading_currency_select">
                                                <?php $selectCurrencies = !empty($allowedCurrencies) ? $allowedCurrencies : $currencyOptions; ?>
                                                <?php foreach ($selectCurrencies as $code): ?>
                                                    <option value="<?php echo $code; ?>"><?php echo $code; ?></option>
                                                <?php endforeach; ?>
                                            </select>
                                        </div>
                                        <div class="col-md-8 text-end">
                                            <button type="button" class="btn btn-primary" id="saveTypesBtn">
                                                <i class="fas fa-save"></i> Guardar tipos para divisa
                                            </button>
                                        </div>
                                    </div>

                                    <div class="mt-3" id="accountTypesForCurrency">
                                        <div class="alert alert-info"><i class="fas fa-info-circle"></i> Selecciona una divisa para cargar los tipos de cuenta.</div>
                                    </div>
                                </div>
                            </div>
                        </div>

                        <!-- Tab: Seguridad -->
                        <div class="tab-pane fade" id="security" role="tabpanel">
                            <div class="config-section">
                                <h5><i class="fas fa-shield-alt"></i> Configuración de Seguridad</h5>
                                <p class="text-muted">Parámetros de seguridad y acceso</p>
                                
                                <form method="POST" action="">
                                    <input type="hidden" name="action" value="update_security">
                                    
                                    <div class="row">
                                        <div class="col-md-6">
                                            <div class="form-group">
                                                <label class="form-label" for="password_min_length">Longitud Mínima de Contraseña</label>
                                                <input type="number" class="form-control" id="password_min_length" name="password_min_length" 
                                                       value="<?php echo htmlspecialchars($configs['password_min_length']); ?>" min="6" max="20">
                                            </div>
                                        </div>
                                        <div class="col-md-6">
                                            <div class="form-group">
                                                <label class="form-label" for="login_attempts_limit">Límite de Intentos de Login</label>
                                                <input type="number" class="form-control" id="login_attempts_limit" name="login_attempts_limit" 
                                                       value="<?php echo htmlspecialchars($configs['login_attempts_limit']); ?>" min="3" max="10">
                                            </div>
                                        </div>
                                    </div>
                                    
                                    <div class="security-actions mt-4">
                                        <h6>Acciones de Seguridad</h6>
                                        <div class="d-flex flex-wrap gap-2">
                                            <button type="button" class="btn btn-warning" onclick="clearAllSessions()">
                                                <i class="fas fa-users-slash"></i> Cerrar Todas las Sesiones
                                            </button>
                                            <button type="button" class="btn btn-info" onclick="viewSystemLogs()">
                                                <i class="fas fa-file-alt"></i> Ver Logs del Sistema
                                            </button>
                                            <button type="button" class="btn btn-success" onclick="testEmailConfig()">
                                                <i class="fas fa-envelope"></i> Probar Email
                                            </button>
                                            <button type="button" class="btn btn-secondary" onclick="createBackup()">
                                                <i class="fas fa-database"></i> Crear Respaldo
                                            </button>
                                        </div>
                                    </div>
                                    
                                    <div class="d-flex justify-content-end mt-4">
                                        <button type="submit" class="btn btn-primary">
                                            <i class="fas fa-save"></i> Guardar Seguridad
                                        </button>
                                    </div>
                                </form>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>

    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/js/bootstrap.bundle.min.js"></script>
    <script src="/public/script.js"></script>
    <script>
        // Preview logo function
        function previewLogo(input) {
            const preview = document.getElementById('logoPreview');
            if (input.files && input.files[0]) {
                const reader = new FileReader();
                reader.onload = function(e) {
                    preview.innerHTML = '<img src="' + e.target.result + '" alt="Vista previa" style="max-width: 100%; max-height: 80px;">';
                };
                reader.readAsDataURL(input.files[0]);
            }
        }

        // Security actions
        function clearAllSessions() {
            if (confirm('¿Estás seguro de que quieres cerrar todas las sesiones activas?')) {
                fetch('/modules/config/actions.php', {
                    method: 'POST',
                    headers: {'Content-Type': 'application/x-www-form-urlencoded'},
                    body: 'action=clear_sessions'
                })
                .then(response => response.json())
                .then(data => {
                    if (data.success) {
                        alert('Todas las sesiones han sido cerradas');
                    } else {
                        alert('Error: ' + data.message);
                    }
                });
            }
        }

        function viewSystemLogs() {
            window.open('modules/config/actions.php?action=view_logs', '_blank');
        }

        function testEmailConfig() {
            fetch('/modules/config/actions.php', {
                method: 'POST',
                headers: {'Content-Type': 'application/x-www-form-urlencoded'},
                body: 'action=test_email'
            })
            .then(response => response.json())
            .then(data => {
                if (data.success) {
                    alert('Email de prueba enviado correctamente');
                } else {
                    alert('Error al enviar email: ' + data.message);
                }
            });
        }

        function createBackup() {
            if (confirm('¿Crear un respaldo de la base de datos?')) {
                fetch('/modules/config/actions.php', {
                    method: 'POST',
                    headers: {'Content-Type': 'application/x-www-form-urlencoded'},
                    body: 'action=create_backup'
                })
                .then(response => response.json())
                .then(data => {
                    if (data.success) {
                        alert('Respaldo creado exitosamente');
                    } else {
                        alert('Error al crear respaldo: ' + data.message);
                    }
                });
            }
        }

        // Initialize sidebar functionality
        document.addEventListener('DOMContentLoaded', function() {
            initializeSidebar();
            
            // Manejar envío del formulario de configuración general con AJAX
            const generalForm = document.getElementById('generalConfigForm');
            if (generalForm) {
                generalForm.addEventListener('submit', function(e) {
                    e.preventDefault();
                    
                    const formData = new FormData(this);
                    const companyName = formData.get('company_name');
                    
                    fetch('/modules/config/actions.php', {
                         method: 'POST',
                         headers: {
                             'X-Requested-With': 'XMLHttpRequest'
                         },
                         body: formData
                     })
                     .then(response => response.json())
                     .then(data => {
                         if (data.success) {
                             // Actualizar el nombre de la empresa en el sidebar en tiempo real
                             updateCompanyNameInSidebar(companyName);
                             
                             // Mostrar mensaje de éxito
                             showSuccessMessage('Configuración actualizada correctamente');
                         } else {
                             showErrorMessage(data.message || 'Error al actualizar la configuración');
                         }
                     })
                     .catch(error => {
                         console.error('Error:', error);
                         showErrorMessage('Error de conexión');
                     });
                });
            }
            
            // Manejar envío del formulario de marca y logo con AJAX
            const brandingForm = document.getElementById('brandingForm');
            if (brandingForm) {
                brandingForm.addEventListener('submit', function(e) {
                    e.preventDefault();
                    
                    const formData = new FormData(this);
                    const brandName = formData.get('brand_name');
                    
                    fetch('/modules/config/actions.php', {
                         method: 'POST',
                         headers: {
                             'X-Requested-With': 'XMLHttpRequest'
                         },
                         body: formData
                     })
                     .then(response => response.json())
                     .then(data => {
                         if (data.success) {
                             // Actualizar el nombre de la empresa en el sidebar en tiempo real
                             updateCompanyNameInSidebar(brandName);
                             
                             // Mostrar mensaje de éxito
                             showSuccessMessage('Marca actualizada correctamente');
                         } else {
                             showErrorMessage(data.message || 'Error al actualizar la marca');
                         }
                     })
                     .catch(error => {
                         console.error('Error:', error);
                         showErrorMessage('Error de conexión');
                     });
                });
            }
        });
        
        // --- Trading Tab JS ---
        document.addEventListener('DOMContentLoaded', function() {
            const tradingTabBtn = document.getElementById('trading-tab');
            const currencySelect = document.getElementById('trading_currency_select');
            const typesContainer = document.getElementById('accountTypesForCurrency');
            const saveTypesBtn = document.getElementById('saveTypesBtn');
            const allowedCurrenciesForm = document.getElementById('allowedCurrenciesForm');

            if (tradingTabBtn) {
                tradingTabBtn.addEventListener('shown.bs.tab', function() {
                    if (currencySelect && currencySelect.value) {
                        loadAccountTypes(currencySelect.value);
                    }
                });
            }

            if (currencySelect) {
                currencySelect.addEventListener('change', function() {
                    loadAccountTypes(this.value);
                });
            }

            if (allowedCurrenciesForm) {
                allowedCurrenciesForm.addEventListener('submit', function(e) {
                    e.preventDefault();
                    const params = new URLSearchParams();
                    params.set('action','update_allowed_currencies');
                    const checked = Array.from(allowedCurrenciesForm.querySelectorAll('input[name="allowed_currencies[]"]:checked')).map(i=>i.value);
                    checked.forEach(v => params.append('allowed_currencies[]', v));
                    const newCurInput = document.getElementById('new_currency');
                    const newCur = newCurInput ? newCurInput.value.trim().toUpperCase() : '';
                    if (newCur) { params.set('new_currency', newCur); }

                    fetch('/modules/config/actions.php', {
                        method: 'POST',
                        headers: {'Content-Type': 'application/x-www-form-urlencoded'},
                        body: params.toString()
                    })
                    .then(r => r.json())
                    .then(data => {
                        if (data.success) {
                            showSuccessMessage('Divisas permitidas actualizadas');
                            // Actualizar opciones del selector de divisa para tipos
                            if (currencySelect && Array.isArray(data.allowed_currencies)) {
                                const current = currencySelect.value;
                                currencySelect.innerHTML = '';
                                data.allowed_currencies.forEach(c => {
                                    const opt = document.createElement('option');
                                    opt.value = c; opt.textContent = c;
                                    currencySelect.appendChild(opt);
                                });
                                // Mantener selección si existe
                                if (data.allowed_currencies.includes(current)) {
                                    currencySelect.value = current;
                                }
                            }
                        } else {
                            showErrorMessage(data.message || 'No se pudo guardar divisas');
                        }
                    })
                    .catch(err => {
                        console.error(err);
                        showErrorMessage('Error de conexión');
                    });
                });
            }

            if (saveTypesBtn) {
                saveTypesBtn.addEventListener('click', function() {
                    const currency = currencySelect ? currencySelect.value : '';
                    if (!currency) { showErrorMessage('Selecciona una divisa'); return; }
                    const enabled = Array.from(typesContainer.querySelectorAll('input[name="enabled_type"]:checked')).map(i=>i.value);
                    const params = new URLSearchParams();
                    params.set('action','save_account_types_for_currency');
                    params.set('currency', currency);
                    enabled.forEach(v => params.append('enabled_types[]', v));

                    fetch('/modules/config/actions.php', {
                        method: 'POST',
                        headers: {'Content-Type': 'application/x-www-form-urlencoded'},
                        body: params.toString()
                    })
                    .then(r => r.json())
                    .then(data => {
                        if (data.success) {
                            showSuccessMessage('Tipos de cuenta guardados para ' + currency);
                        } else {
                            showErrorMessage(data.message || 'No se pudo guardar tipos');
                        }
                    })
                    .catch(err => {
                        console.error(err);
                        showErrorMessage('Error de conexión');
                    });
                });
            }

            function loadAccountTypes(currency) {
                const params = new URLSearchParams();
                params.set('action','get_account_types_for_currency');
                params.set('currency', currency);
                typesContainer.innerHTML = '<div class="text-center py-3"><div class="spinner-border" role="status"></div></div>';
                fetch('/modules/config/actions.php', {
                    method: 'POST',
                    headers: {'Content-Type': 'application/x-www-form-urlencoded'},
                    body: params.toString()
                })
                .then(r => r.json())
                .then(data => {
                    if (data.success) {
                        renderAccountTypes(data.types || []);
                    } else {
                        typesContainer.innerHTML = '<div class="alert alert-danger">' + (data.message || 'Error al cargar tipos') + '</div>';
                    }
                })
                .catch(err => {
                    console.error(err);
                    typesContainer.innerHTML = '<div class="alert alert-danger">Error de conexión</div>';
                });
            }

            function renderAccountTypes(types) {
                if (!types || types.length === 0) {
                    typesContainer.innerHTML = '<div class="alert alert-warning"><i class="fas fa-exclamation-triangle"></i> No hay tipos de cuenta activos.</div>';
                    return;
                }
                let html = '<div class="list-group">';
                types.forEach(t => {
                    const enabled = parseInt(t.is_enabled) === 1;
                    const display = t.display_name || t.name;
                    const desc = t.description || '';
                    const minDep = t.eff_min_deposit || t.min_deposit || '';
                    const maxLev = t.eff_max_leverage || t.max_leverage || '';
                    html += `
<label class="list-group-item d-flex align-items-center justify-content-between">
  <div class="d-flex align-items-start">
    <input class="form-check-input me-3" type="checkbox" name="enabled_type" value="${t.name}" ${enabled ? 'checked' : ''}>
    <div>
      <div><strong>${display}</strong></div>
      <div class="small text-muted">${desc}</div>
    </div>
  </div>
  <div class="text-end small">
    ${minDep ? `<div>Depósito mínimo: ${minDep}</div>` : ''}
    ${maxLev ? `<div>Leverage máx: ${maxLev}</div>` : ''}
  </div>
</label>`;
                });
                html += '</div>';
                typesContainer.innerHTML = html;
            }
        });
        
        // Función para actualizar el nombre de la empresa en el sidebar
        function updateCompanyNameInSidebar(newCompanyName) {
            const logoTitle = document.querySelector('.sidebar .logo-title');
            const logoSubtitle = document.querySelector('.sidebar .logo-subtitle');
            
            if (logoTitle) {
                // Si el campo está vacío, mostrar texto vacío
                logoTitle.textContent = newCompanyName.trim() || '';
            }
            
            // También actualizar el subtitle si está vacío el company_name
            if (logoSubtitle && !newCompanyName.trim()) {
                logoSubtitle.textContent = '';
            }
        }
        
        // Función para mostrar mensaje de éxito
        function showSuccessMessage(message) {
            // Crear elemento de alerta
            const alertDiv = document.createElement('div');
            alertDiv.className = 'alert alert-success alert-dismissible fade show';
            alertDiv.innerHTML = `
                <i class="fas fa-check-circle"></i> ${message}
                <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
            `;
            
            // Insertar antes del contenido principal
            const contentWrapper = document.querySelector('.content-wrapper');
            const firstChild = contentWrapper.querySelector('.roles-header').nextElementSibling;
            contentWrapper.insertBefore(alertDiv, firstChild);
        }
        
        // Función para mostrar mensaje de error
        function showErrorMessage(message) {
            const alertDiv = document.createElement('div');
            alertDiv.className = 'alert alert-danger alert-dismissible fade show';
            alertDiv.innerHTML = `
                <i class="fas fa-exclamation-circle"></i> ${message}
                <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
            `;
            
            const contentWrapper = document.querySelector('.content-wrapper');
            const firstChild = contentWrapper.querySelector('.roles-header').nextElementSibling;
            contentWrapper.insertBefore(alertDiv, firstChild);
        }
    </script>
</body>
</html>