<?php
// Acciones del módulo de configuración
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']);
    }
}

// Verificar autenticación
if (!isLoggedIn()) {
    http_response_code(401);
    echo json_encode(['success' => false, 'message' => 'No autenticado']);
    exit;
}

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

// Función para actualizar configuración
function updateConfig($pdo, $key, $value) {
    try {
        $stmt = $pdo->prepare("
            INSERT INTO system_config (config_key, config_value, updated_at) 
            VALUES (?, ?, NOW()) 
            ON DUPLICATE KEY UPDATE config_value = VALUES(config_value), updated_at = NOW()
        ");
        return $stmt->execute([$key, $value]);
    } catch (PDOException $e) {
        error_log("Error updating config: " . $e->getMessage());
        return false;
    }
}

// Función para subir archivo de logo
function uploadLogo($file) {
    $uploadDir = '../../public/uploads/';
    
    // Crear directorio si no existe
    if (!is_dir($uploadDir)) {
        mkdir($uploadDir, 0755, true);
    }
    
    // Validar archivo
    $allowedTypes = ['image/jpeg', 'image/png', 'image/gif', 'image/svg+xml'];
    if (!in_array($file['type'], $allowedTypes)) {
        return ['success' => false, 'message' => 'Tipo de archivo no permitido'];
    }
    
    // Validar tamaño (5MB máximo)
    if ($file['size'] > 5 * 1024 * 1024) {
        return ['success' => false, 'message' => 'El archivo es demasiado grande'];
    }
    
    // Generar nombre único
    $extension = pathinfo($file['name'], PATHINFO_EXTENSION);
    $filename = 'logo_' . time() . '.' . $extension;
    $filepath = $uploadDir . $filename;
    
    // Mover archivo
    if (move_uploaded_file($file['tmp_name'], $filepath)) {
        return ['success' => true, 'filename' => $filename];
    } else {
        return ['success' => false, 'message' => 'Error al subir el archivo'];
    }
}

// Procesar acciones
$action = $_POST['action'] ?? '';

// ---- Trading Config: helpers ----
function ensureAccountTypeCurrencyTable($pdo) {
    try {
        $pdo->exec("CREATE TABLE IF NOT EXISTS account_type_currency (
            id INT AUTO_INCREMENT PRIMARY KEY,
            currency VARCHAR(3) NOT NULL,
            account_type VARCHAR(50) NOT NULL,
            is_enabled BOOLEAN DEFAULT TRUE,
            min_deposit DECIMAL(15,2) NULL,
            max_leverage INT NULL,
            commission_rate DECIMAL(5,4) NULL,
            updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
            UNIQUE KEY uniq_currency_type (currency, account_type)
        )");
    } catch (PDOException $e) {
        error_log('ensureAccountTypeCurrencyTable error: ' . $e->getMessage());
    }
}

function getAllowedCurrencies($pdo) {
    try {
        $stmt = $pdo->prepare("SELECT config_value FROM system_config WHERE config_key = 'allowed_currencies' LIMIT 1");
        $stmt->execute();
        $val = $stmt->fetchColumn();
        if ($val) {
            $decoded = json_decode($val, true);
            if (is_array($decoded) && count($decoded) > 0) {
                return array_values(array_unique(array_map(function($c){ return strtoupper(trim($c)); }, $decoded)));
            }
        }
    } catch (Throwable $e) {
        error_log('getAllowedCurrencies error: ' . $e->getMessage());
    }
    return ['USD','EUR','GBP','JPY'];
}

switch ($action) {
    case 'update_general':
        try {
            $configs = [
                'company_name' => $_POST['company_name'] ?? '',
                'system_timezone' => $_POST['system_timezone'] ?? 'America/Mexico_City',
                'system_currency' => $_POST['system_currency'] ?? 'MXN',
                'system_language' => $_POST['system_language'] ?? 'es'
            ];
            
            $success = true;
            foreach ($configs as $key => $value) {
                if (!updateConfig($pdo, $key, $value)) {
                    $success = false;
                    break;
                }
            }
            
            if ($success) {
                // Responder con JSON si es una petición AJAX
                if (!empty($_SERVER['HTTP_X_REQUESTED_WITH']) && strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) == 'xmlhttprequest') {
                    header('Content-Type: application/json');
                    echo json_encode(['success' => true, 'message' => 'Configuración actualizada correctamente']);
                    exit;
                }
                header('Location: index.php?success=general_updated');
            } else {
                // Responder con JSON si es una petición AJAX
                if (!empty($_SERVER['HTTP_X_REQUESTED_WITH']) && strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) == 'xmlhttprequest') {
                    header('Content-Type: application/json');
                    echo json_encode(['success' => false, 'message' => 'Error al actualizar la configuración']);
                    exit;
                }
                header('Location: index.php?error=update_failed');
            }
        } catch (Exception $e) {
            error_log("Error en update_general: " . $e->getMessage());
            header('Location: index.php?error=update_failed');
        }
        break;
        
    case 'update_branding':
        try {
            $success = true;
            
            // Actualizar company_name (incluso si está vacío)
            if (isset($_POST['brand_name'])) {
                if (!updateConfig($pdo, 'company_name', $_POST['brand_name'])) {
                    $success = false;
                }
            }
            
            // Manejar subida de logo si se proporciona
            if (isset($_FILES['company_logo']) && $_FILES['company_logo']['error'] === UPLOAD_ERR_OK) {
                $uploadResult = uploadLogo($_FILES['company_logo']);
                
                if ($uploadResult['success']) {
                    // Eliminar logo anterior si existe
                    $stmt = $pdo->query("SELECT config_value FROM system_config WHERE config_key = 'company_logo'");
                    $oldLogo = $stmt->fetchColumn();
                    
                    if ($oldLogo && file_exists('../../public/uploads/' . $oldLogo)) {
                        unlink('../../public/uploads/' . $oldLogo);
                    }
                    
                    // Actualizar configuración con nuevo logo
                    if (!updateConfig($pdo, 'company_logo', $uploadResult['filename'])) {
                        $success = false;
                    }
                } else {
                    // Responder con JSON si es una petición AJAX
                    if (isset($_SERVER['HTTP_X_REQUESTED_WITH']) && $_SERVER['HTTP_X_REQUESTED_WITH'] === 'XMLHttpRequest') {
                        header('Content-Type: application/json');
                        echo json_encode(['success' => false, 'message' => 'Error al subir el logo']);
                        exit();
                    }
                    header('Location: index.php?error=upload_failed');
                    exit();
                }
            }
            
            // Responder con JSON si es una petición AJAX
            if (isset($_SERVER['HTTP_X_REQUESTED_WITH']) && $_SERVER['HTTP_X_REQUESTED_WITH'] === 'XMLHttpRequest') {
                header('Content-Type: application/json');
                if ($success) {
                    echo json_encode(['success' => true, 'message' => 'Marca actualizada correctamente']);
                } else {
                    echo json_encode(['success' => false, 'message' => 'Error al actualizar la marca']);
                }
                exit();
            }
            
            if ($success) {
                header('Location: index.php?success=branding_updated');
            } else {
                header('Location: index.php?error=update_failed');
            }
        } catch (Exception $e) {
            error_log("Error en update_branding: " . $e->getMessage());
            
            // Responder con JSON si es una petición AJAX
            if (isset($_SERVER['HTTP_X_REQUESTED_WITH']) && $_SERVER['HTTP_X_REQUESTED_WITH'] === 'XMLHttpRequest') {
                header('Content-Type: application/json');
                echo json_encode(['success' => false, 'message' => 'Error interno del servidor']);
                exit();
            }
            
            header('Location: index.php?error=update_failed');
        }
        break;
        
    case 'update_system':
        try {
            $configs = [
                'max_file_size' => intval($_POST['max_file_size'] ?? 10),
                'session_timeout' => intval($_POST['session_timeout'] ?? 3600),
                'backup_frequency' => $_POST['backup_frequency'] ?? 'daily',
                'email_notifications' => isset($_POST['email_notifications']) ? '1' : '0',
                'maintenance_mode' => isset($_POST['maintenance_mode']) ? '1' : '0'
            ];
            
            $success = true;
            foreach ($configs as $key => $value) {
                if (!updateConfig($pdo, $key, $value)) {
                    $success = false;
                    break;
                }
            }
            
            if ($success) {
                header('Location: index.php?success=system_updated');
            } else {
                header('Location: index.php?error=update_failed');
            }
        } catch (Exception $e) {
            error_log("Error en update_system: " . $e->getMessage());
            header('Location: index.php?error=update_failed');
        }
        break;
        
    case 'clear_sessions':
        try {
            // Limpiar todas las sesiones excepto la actual
            $currentSessionId = session_id();
            
            // Eliminar archivos de sesión (esto depende de la configuración de PHP)
            $sessionPath = session_save_path();
            if (empty($sessionPath)) {
                $sessionPath = sys_get_temp_dir();
            }
            
            $sessionFiles = glob($sessionPath . '/sess_*');
            $clearedCount = 0;
            
            foreach ($sessionFiles as $file) {
                $sessionId = substr(basename($file), 5); // Remover 'sess_'
                if ($sessionId !== $currentSessionId) {
                    if (unlink($file)) {
                        $clearedCount++;
                    }
                }
            }
            
            // Log de la acción
            error_log("Sesiones limpiadas por usuario: " . $_SESSION['username'] . " - Total: " . $clearedCount);
            
            echo json_encode([
                'success' => true, 
                'message' => "Se cerraron $clearedCount sesiones",
                'count' => $clearedCount
            ]);
        } catch (Exception $e) {
            error_log("Error al limpiar sesiones: " . $e->getMessage());
            echo json_encode(['success' => false, 'message' => 'Error al cerrar sesiones']);
        }
        break;
        
    case 'get_system_info':
        try {
            $info = [
                'php_version' => PHP_VERSION,
                'server_software' => $_SERVER['SERVER_SOFTWARE'] ?? 'Desconocido',
                'max_execution_time' => ini_get('max_execution_time'),
                'memory_limit' => ini_get('memory_limit'),
                'upload_max_filesize' => ini_get('upload_max_filesize'),
                'post_max_size' => ini_get('post_max_size'),
                'session_save_path' => session_save_path(),
                'timezone' => date_default_timezone_get()
            ];
            
            echo json_encode(['success' => true, 'info' => $info]);
        } catch (Exception $e) {
            error_log("Error al obtener información del sistema: " . $e->getMessage());
            echo json_encode(['success' => false, 'message' => 'Error al obtener información']);
        }
        break;
        
    case 'test_email':
        try {
            $testEmail = $_POST['test_email'] ?? '';
            
            if (empty($testEmail) || !filter_var($testEmail, FILTER_VALIDATE_EMAIL)) {
                echo json_encode(['success' => false, 'message' => 'Email inválido']);
                break;
            }
            
            // Aquí implementarías el envío de email de prueba
            // Por ahora solo simulamos el éxito
            $subject = 'Prueba de Email - ProfixCRM';
            $message = 'Este es un email de prueba desde ProfixCRM.';
            
            // Simular envío exitoso
            $sent = true; // mail($testEmail, $subject, $message);
            
            if ($sent) {
                echo json_encode(['success' => true, 'message' => 'Email de prueba enviado correctamente']);
            } else {
                echo json_encode(['success' => false, 'message' => 'Error al enviar email de prueba']);
            }
        } catch (Exception $e) {
            error_log("Error al enviar email de prueba: " . $e->getMessage());
            echo json_encode(['success' => false, 'message' => 'Error al enviar email']);
        }
        break;
        
    case 'backup_database':
        try {
            // Obtener configuración de la base de datos
            $host = 'localhost'; // Ajustar según tu configuración
            $dbname = 'profixcrm'; // Ajustar según tu configuración
            $username = 'root'; // Ajustar según tu configuración
            $password = ''; // Ajustar según tu configuración
            
            $backupDir = '../../backups/';
            if (!is_dir($backupDir)) {
                mkdir($backupDir, 0755, true);
            }
            
            $filename = 'backup_' . date('Y-m-d_H-i-s') . '.sql';
            $filepath = $backupDir . $filename;
            
            // Comando mysqldump
            $command = "mysqldump --host=$host --user=$username --password=$password $dbname > $filepath";
            
            // Ejecutar comando (en producción, usar métodos más seguros)
            $output = [];
            $returnVar = 0;
            exec($command, $output, $returnVar);
            
            if ($returnVar === 0 && file_exists($filepath)) {
                echo json_encode([
                    'success' => true, 
                    'message' => 'Backup creado correctamente',
                    'filename' => $filename,
                    'size' => filesize($filepath)
                ]);
            } else {
                echo json_encode(['success' => false, 'message' => 'Error al crear backup']);
            }
        } catch (Exception $e) {
            error_log("Error al crear backup: " . $e->getMessage());
            echo json_encode(['success' => false, 'message' => 'Error al crear backup']);
        }
        break;

    // ---- Trading Config: allowed currencies ----
    case 'update_allowed_currencies':
        try {
            $raw = $_POST['allowed_currencies'] ?? [];
            if (!is_array($raw)) {
                // permitir formato CSV
                $raw = array_map('trim', explode(',', (string)$raw));
            }
            $newCur = trim(strtoupper($_POST['new_currency'] ?? ''));
            if ($newCur !== '' && preg_match('/^[A-Z]{3}$/', $newCur)) {
                $raw[] = $newCur;
            }
            $list = [];
            foreach ($raw as $c) {
                $code = strtoupper(trim($c));
                if ($code !== '' && preg_match('/^[A-Z]{3}$/', $code)) {
                    $list[] = $code;
                }
            }
            $list = array_values(array_unique($list));
            if (empty($list)) { $list = ['USD','EUR','GBP','JPY']; }
            $ok = updateConfig($pdo, 'allowed_currencies', json_encode($list));
            if ($ok) {
                echo json_encode(['success' => true, 'allowed_currencies' => $list]);
            } else {
                echo json_encode(['success' => false, 'message' => 'No se pudo guardar divisas permitidas']);
            }
        } catch (Throwable $e) {
            error_log('update_allowed_currencies error: ' . $e->getMessage());
            echo json_encode(['success' => false, 'message' => 'Error interno']);
        }
        break;

    // ---- Trading Config: account types per currency ----
    case 'get_account_types_for_currency':
        try {
            $currency = strtoupper(trim($_POST['currency'] ?? ''));
            if ($currency === '') { echo json_encode(['success' => false, 'message' => 'Divisa requerida']); break; }
            ensureAccountTypeCurrencyTable($pdo);
            $stmt = $pdo->prepare("SELECT at.name, at.display_name, at.description, at.min_deposit, at.max_leverage,
                                          COALESCE(map.is_enabled, 1) AS is_enabled,
                                          COALESCE(map.min_deposit, at.min_deposit) AS eff_min_deposit,
                                          COALESCE(map.max_leverage, at.max_leverage) AS eff_max_leverage
                                     FROM account_types at
                                LEFT JOIN account_type_currency map
                                       ON map.account_type = at.name AND map.currency = ?
                                    WHERE at.is_active = 1
                                 ORDER BY at.min_deposit ASC");
            $stmt->execute([$currency]);
            $rows = $stmt->fetchAll(PDO::FETCH_ASSOC);
            echo json_encode(['success' => true, 'types' => $rows]);
        } catch (Throwable $e) {
            error_log('get_account_types_for_currency error: ' . $e->getMessage());
            echo json_encode(['success' => false, 'message' => 'Error interno']);
        }
        break;

    case 'save_account_types_for_currency':
        try {
            $currency = strtoupper(trim($_POST['currency'] ?? ''));
            $enabledTypes = $_POST['enabled_types'] ?? [];
            if (!is_array($enabledTypes)) { $enabledTypes = []; }
            ensureAccountTypeCurrencyTable($pdo);
            // obtener todos los tipos activos
            $typesStmt = $pdo->query("SELECT name FROM account_types WHERE is_active = 1");
            $allTypes = $typesStmt->fetchAll(PDO::FETCH_COLUMN);
            $pdo->beginTransaction();
            $upsert = $pdo->prepare("INSERT INTO account_type_currency (currency, account_type, is_enabled, updated_at)
                                     VALUES (?, ?, ?, NOW())
                                     ON DUPLICATE KEY UPDATE is_enabled = VALUES(is_enabled), updated_at = NOW()");
            foreach ($allTypes as $t) {
                $enabled = in_array($t, $enabledTypes) ? 1 : 0;
                $upsert->execute([$currency, $t, $enabled]);
            }
            $pdo->commit();
            echo json_encode(['success' => true]);
        } catch (Throwable $e) {
            if ($pdo->inTransaction()) { $pdo->rollBack(); }
            error_log('save_account_types_for_currency error: ' . $e->getMessage());
            echo json_encode(['success' => false, 'message' => 'No se pudo guardar tipos por divisa']);
        }
        break;
        
    default:
        http_response_code(400);
        echo json_encode(['success' => false, 'message' => 'Acción no válida']);
        break;
}
?>