<?php
date_default_timezone_set('UTC');
// index.php
require_once __DIR__ . '/src/config.php';
require_once __DIR__ . '/src/Database.php';
require_once __DIR__ . '/src/helpers.php';

// Iniciar sesión segura
secure_session_start();

// Configuración
$CONFIG = include __DIR__ . '/src/config.php';

// Conexión a la base de datos
try {
    $db = Database::getConnection($CONFIG);
} catch (Exception $e) {
    die("Error de conexión a la base de datos: " . $e->getMessage());
}

// Generar token CSRF si no existe
if (empty($_SESSION['csrf'])) {
    $_SESSION['csrf'] = bin2hex(random_bytes(32));
}

// Cargar controladores
require_once __DIR__ . '/src/controllers/HomeController.php';
require_once __DIR__ . '/src/controllers/AuthController.php';
require_once __DIR__ . '/src/controllers/FriendsController.php';
require_once __DIR__ . '/src/controllers/PostController.php';
require_once __DIR__ . '/src/controllers/InviteController.php';
require_once __DIR__ . '/src/controllers/NotificationsController.php';
require_once __DIR__ . '/src/controllers/ProfileController.php';
require_once __DIR__ . '/src/controllers/RankingController.php';
require_once __DIR__ . '/src/controllers/ReportController.php';
require_once __DIR__ . '/src/controllers/AdminController.php';
require_once __DIR__ . '/src/controllers/ReportAdminController.php';
require_once __DIR__ . '/src/controllers/AnonymousController.php';

// Cargar helpers de seguridad
require_once __DIR__ . '/src/helpers/SecurityHelper.php';

// Sanitizar entradas
$_GET = sanitize_input($_GET);
$_POST = sanitize_input($_POST);

// Verificar modo mantenimiento (excepto para rutas específicas)
$route = $_GET['r'] ?? 'landing';
$allowed_maintenance_routes = ['login', 'auth/forgot-password', 'auth/reset-password', 'admin/dashboard', 'admin/control-panel', 'admin/system-settings', 'admin/maintenance', 'admin/policies', 'admin/cache', 'admin/backup', 'admin/users', 'admin/logs', 'admin/login-attempts', 'admin/posts', 'admin/comments', 'admin/reports', 'admin/ads'];

try {
    // Verificar si el sitio está en mantenimiento
    $config_stmt = $db->prepare("SELECT maintenance_mode, maintenance_message FROM system_config WHERE id = 1");
    $config_stmt->execute();
    $system_config = $config_stmt->fetch();
    
    if ($system_config && $system_config['maintenance_mode'] && 
        !in_array($route, $allowed_maintenance_routes) && 
        empty($_SESSION['user']['role'])) {
        
        // Mostrar página de mantenimiento
        http_response_code(503);
        echo '<!DOCTYPE html>
        <html lang="es">
        <head>
            <meta charset="UTF-8">
            <meta name="viewport" content="width=device-width, initial-scale=1.0">
            <title>Sitio en Mantenimiento - Thirty</title>
            <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css">
            <style>
                body { 
                    font-family: "Segoe UI", system-ui, sans-serif; 
                    background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
                    color: white; 
                    margin: 0; 
                    padding: 0;
                    min-height: 100vh;
                    display: flex;
                    align-items: center;
                    justify-content: center;
                    text-align: center;
                }
                .maintenance-container { 
                    max-width: 600px;
                    padding: 40px;
                    background: rgba(255, 255, 255, 0.1);
                    backdrop-filter: blur(10px);
                    border-radius: 20px;
                    border: 1px solid rgba(255, 255, 255, 0.2);
                }
                .maintenance-icon { 
                    font-size: 4rem; 
                    margin-bottom: 1rem;
                    color: #ffd166;
                }
                .maintenance-title { 
                    font-size: 2.5rem; 
                    margin-bottom: 1rem;
                    font-weight: 800;
                }
                .maintenance-message { 
                    font-size: 1.2rem; 
                    margin-bottom: 2rem;
                    line-height: 1.6;
                    opacity: 0.9;
                }
                .admin-login {
                    margin-top: 2rem;
                    padding-top: 2rem;
                    border-top: 1px solid rgba(255, 255, 255, 0.2);
                }
                .admin-login a {
                    color: #7cd1ff;
                    text-decoration: none;
                    font-weight: 600;
                }
                .admin-login a:hover {
                    text-decoration: underline;
                }
            </style>
        </head>
        <body>
            <div class="maintenance-container">
                <div class="maintenance-icon">
                    <i class="fas fa-screwdriver-wrench"></i>
                </div>
                <h1 class="maintenance-title">Sitio en Mantenimiento</h1>
                <div class="maintenance-message">';
        
        echo $system_config['maintenance_message'] ?: 'Estamos realizando tareas de mantenimiento para mejorar tu experiencia. Vuelve pronto.';
        
        echo '</div>
                <p><i class="fas fa-clock"></i> Estaremos de vuelta pronto</p>';
        
        // Mostrar enlace de login para administradores
        echo '<div class="admin-login">
                    <p><i class="fas fa-shield-alt"></i> ¿Eres administrador? <a href="./?r=login">Inicia sesión aquí</a></p>
                </div>
            </div>
        </body>
        </html>';
        exit;
    }
} catch (Exception $e) {
    // Continuar si hay error al verificar mantenimiento
    error_log("Error verificando modo mantenimiento: " . $e->getMessage());
}

// Actualizar estados de anuncios automáticamente en cada carga
try {
    error_log("🔄 Index.php - Actualizando estados de anuncios automáticamente...");
    $result = updateAdStatusAutomatically($db);
    if ($result) {
        error_log("✅ Estados de anuncios actualizados correctamente");
    } else {
        error_log("⚠️ Estados de anuncios no se pudieron actualizar");
    }
} catch (Exception $e) {
    error_log("❌ Error actualizando estados de anuncios en index.php: " . $e->getMessage());
}

// Routing
$route = $_GET['r'] ?? 'landing';

try {
    switch ($route) {
        case 'landing':
            HomeController::landing();
            break;
        case 'dashboard':
            HomeController::dashboard($db);
            break;
        case 'ranking':
            RankingController::index($db);
            break;
        case 'ranking/refresh':
            RankingController::refresh($db);
            break;
        case 'login':
            AuthController::login($db);
            break;
        case 'register':
            AuthController::register($db);
            break;
        case 'logout':
            AuthController::logout();
            break;
        case 'friends':
            FriendsController::index($db);
            break;
        case 'friends/add':
            FriendsController::add($db);
            break;
        case 'friends/accept':
            FriendsController::accept($db);
            break;
        case 'friends/reject':
            FriendsController::reject($db);
            break;
        case 'friends/remove':
            FriendsController::remove($db);
            break;
        case 'friends/search':
            FriendsController::search($db);
            break;
        case 'posts':
            PostController::list($db);
            break;
        case 'posts/new':
        case 'posts/create':
            PostController::create($db);
            break;
        case 'posts/view':
            PostController::view($db);
            break;
        case 'posts/comment': // compat: comment form posts here
            PostController::view($db);
            break;
        
            PostController::view($db);
            break;
        case 'posts/delete':
            PostController::delete($db);
            break;
        case 'posts/like':
            PostController::like($db);
            break;
        case 'posts/tag/delete':
            PostController::deleteTag($db);
            break;
        case 'posts/deleteComment':
            PostController::deleteComment($db);
            break;
        case 'invites':
            InviteController::index($db);
            break;
        case 'notifications':
            NotificationsController::index($db);
            break;
        case 'notifications/list':
            NotificationsController::listApi($db);
            break;
        case 'notifications/count':
            NotificationsController::countApi($db);
            break;
        case 'notifications/delete-read':
            NotificationsController::deleteRead($db);
            break;
        case 'notifications/delete':
            NotificationsController::delete($db);
            break;
        case 'notifications/mark-read':
            NotificationsController::markRead($db);
            break;
        case 'notifications/mark-all-read':
            NotificationsController::markAllRead($db);
            break;
        case 'profile':
            ProfileController::view($db);
            break;
        case 'profile/update':
            ProfileController::update($db);
            break;
        case 'profile/avatar':
        case 'profile/updateAvatar':
            ProfileController::updateAvatar($db);
            break;
        case 'profile/friend':
            ProfileController::viewFriend($db);
            break;
        case 'auth/verify-email':
            AuthController::verifyEmail($db);
            break;
        case 'auth/resend-verification':
            AuthController::resendVerification($db);
            break;
        case 'auth/forgot-password':
            AuthController::forgotPassword($db);
            break;
        case 'auth/reset-password':
            AuthController::resetPassword($db);
            break;
            
        // ===== RUTAS DE ADMINISTRACIÓN UNIFICADAS =====
        case 'admin/dashboard':
            AdminController::dashboard($db);
            break;
        case 'admin/control-panel':
            AdminController::controlPanel($db);
            break;
        case 'admin/users':
            AdminController::users($db);
            break;
        case 'admin/logs':
            AdminController::logs($db);
            break;
        case 'admin/login-attempts':
            AdminController::loginAttempts($db);
            break;
        case 'admin/block-user':
            AdminController::blockUser($db);
            break;
        case 'admin/unblock-user':
            AdminController::unblockUser($db);
            break;
        case 'admin/update-user':
            AdminController::updateUser($db);
            break;
        case 'admin/posts':
            AdminController::posts($db);
            break;
        case 'admin/delete-post':
            AdminController::deletePost($db);
            break;
        case 'admin/comments':
            AdminController::comments($db);
            break;
        case 'admin/delete-comment':
            AdminController::deleteComment($db);
            break;
        case 'admin/reports':
            AdminController::reports($db);
            break;
        case 'admin/report-detail':
            ReportAdminController::detail($db);
            break;
        case 'admin/update-report':
            AdminController::updateReport($db);
            break;
        case 'admin/update-report-status':
            ReportAdminController::updateStatus($db);
            break;
        case 'admin/take-action':
            ReportAdminController::takeAction($db);
            break;
            
        // ===== NUEVAS RUTAS DE CONTROL DEL SISTEMA =====
        case 'admin/system-settings':
            AdminController::systemSettings($db);
            break;
        case 'admin/maintenance':
            AdminController::maintenance($db);
            break;
        case 'admin/policies':
            AdminController::policies($db);
            break;
        case 'admin/cache':
            AdminController::cache($db);
            break;
        case 'admin/backup':
            AdminController::backup($db);
            break;
            
        // ===== RUTAS DE ANUNCIOS MEJORADAS =====
        case 'admin/ads':
            AdminController::ads($db);
            break;
        case 'admin/create-ad':
            AdminController::createAd($db);
            break;
        case 'admin/edit-ad':
            AdminController::editAd($db);
            break;
        case 'admin/update-ad':
            AdminController::updateAd($db);
            break;
        case 'admin/update-ad-status':
            AdminController::updateAdStatus($db);
            break;
        case 'admin/delete-ad':
            AdminController::deleteAd($db);
            break;
        case 'admin/refresh-ads':
            AdminController::forceRefreshAdStatuses($db);
            flash('success', 'Estados de anuncios actualizados manualmente');
            redirect('admin/ads');
            break;
            
        // ===== RUTAS DE ANUNCIOS PÚBLICAS (ANONYMOUS) =====
        case 'ad-click':
            error_log("🎯 Ruta ad-click llamada - ID: " . ($_GET['id'] ?? 'N/A'));
            AnonymousController::trackAdClick();
            break;
        case 'track-ad-click':
            error_log("🎯 Ruta track-ad-click llamada - ID: " . ($_POST['id'] ?? $_GET['id'] ?? 'N/A'));
            AnonymousController::trackAdClickPost();
            break;
        case 'refresh-ad-statuses':
            error_log("🔄 Ruta refresh-ad-statuses llamada");
            AnonymousController::refreshAdStatuses();
            break;
            
        // ===== RUTAS DE REPORTES (usuarios normales) =====
        case 'reports':
            ReportController::index($db);
            break;
        case 'reports/create':
            ReportController::create($db);
            break;
        case 'reports/update':
            ReportController::update($db);
            break;
        case 'reports/form':
            ReportController::getReportForm($db);
            break;
            
        // ===== RUTA DE DEBUG PARA ANUNCIOS =====
        default:
            // Intentar cargar una vista directa si existe
            $viewPath = __DIR__ . '/src/views/' . $route . '.php';
            if (file_exists($viewPath)) {
                view($route);
            } else {
                http_response_code(404);
                echo '<!DOCTYPE html>
                <html lang="es">
                <head>
                    <meta charset="UTF-8">
                    <meta name="viewport" content="width=device-width, initial-scale=1.0">
                    <title>Página no encontrada - Thirty</title>
                    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css">
                    <style>
                        body { 
                            font-family: "Segoe UI", system-ui, sans-serif; 
                            background: linear-gradient(180deg, #0b0c10 0%, #12141a 100%);
                            color: #e9eaf1; 
                            margin: 0; 
                            padding: 20px;
                            min-height: 100vh;
                            display: flex;
                            align-items: center;
                            justify-content: center;
                        }
                        .error-container { 
                            text-align: center; 
                            max-width: 500px;
                        }
                        .error-icon { 
                            font-size: 4rem; 
                            color: #ff4d4d; 
                            margin-bottom: 1rem;
                        }
                        .error-title { 
                            font-size: 2rem; 
                            margin-bottom: 1rem;
                            background: linear-gradient(135deg, #7cd1ff, #b99cff);
                            -webkit-background-clip: text;
                            -webkit-text-fill-color: transparent;
                        }
                        .error-message { 
                            color: #a7acb9; 
                            margin-bottom: 2rem;
                            line-height: 1.6;
                        }
                        .btn { 
                            display: inline-block;
                            padding: 12px 24px;
                            background: linear-gradient(135deg, #7cd1ff, #b99cff);
                            color: #0b0c10;
                            text-decoration: none;
                            border-radius: 10px;
                            font-weight: 600;
                            transition: transform 0.3s ease;
                        }
                        .btn:hover {
                            transform: translateY(-2px);
                        }
                    </style>
                </head>
                <body>
                    <div class="error-container">
                        <div class="error-icon">
                            <i class="fas fa-exclamation-triangle"></i>
                        </div>
                        <h1 class="error-title">Página no encontrada</h1>
                        <p class="error-message">
                            La página que buscas no existe o ha sido movida a otra ubicación.
                        </p>
                        <a href="./" class="btn">
                            <i class="fas fa-home"></i> Volver al inicio
                        </a>
                    </div>
                </body>
                </html>';
            }
            break;
    }
} catch (Exception $e) {
    // Log del error
    error_log("❌ Error crítico en ruta $route: " . $e->getMessage());
    error_log("📋 Stack trace: " . $e->getTraceAsString());
    
    // Registrar evento de seguridad
    if (isset($db)) {
        SecurityHelper::logSecurityEvent($db, 'system_error', "Error en ruta $route: " . $e->getMessage(), $_SESSION['user']['id'] ?? null);
    }
    
    // Mostrar error amigable
    http_response_code(500);
    echo '<!DOCTYPE html>
    <html lang="es">
    <head>
        <meta charset="UTF-8">
        <meta name="viewport" content="width=device-width, initial-scale=1.0">
        <title>Error del Sistema - Thirty</title>
        <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css">
        <style>
            body { 
                font-family: "Segoe UI", system-ui, sans-serif; 
                background: linear-gradient(180deg, #0b0c10 0%, #12141a 100%);
                color: #e9eaf1; 
                margin: 0; 
                padding: 20px;
                min-height: 100vh;
                display: flex;
                align-items: center;
                justify-content: center;
            }
            .error-container { 
                text-align: center; 
                max-width: 600px;
                background: rgba(14, 16, 22, 0.8);
                padding: 40px;
                border-radius: 16px;
                border: 1px solid #21242c;
            }
            .error-icon { 
                font-size: 4rem; 
                color: #ff4d4d; 
                margin-bottom: 1rem;
            }
            .error-title { 
                font-size: 1.8rem; 
                margin-bottom: 1rem;
                color: #e9eaf1;
            }
            .error-message { 
                color: #a7acb9; 
                margin-bottom: 2rem;
                line-height: 1.6;
            }
            .btn { 
                display: inline-block;
                padding: 12px 24px;
                background: linear-gradient(135deg, #7cd1ff, #b99cff);
                color: #0b0c10;
                text-decoration: none;
                border-radius: 10px;
                font-weight: 600;
                margin: 5px;
                transition: transform 0.3s ease;
            }
            .btn:hover {
                transform: translateY(-2px);
            }
            .debug-info {
                background: rgba(255, 77, 77, 0.1);
                padding: 15px;
                border-radius: 8px;
                margin-top: 20px;
                text-align: left;
                font-size: 0.9rem;
                display: ' . (isset($CONFIG['debug']) && $CONFIG['debug'] ? 'block' : 'none') . ';
            }
        </style>
    </head>
    <body>
        <div class="error-container">
            <div class="error-icon">
                <i class="fas fa-bug"></i>
            </div>
            <h1 class="error-title">Error del sistema</h1>
            <p class="error-message">
                Ha ocurrido un error inesperado. Por favor, intenta nuevamente más tarde.
            </p>
            <div>
                <a href="./" class="btn">
                    <i class="fas fa-home"></i> Volver al inicio
                </a>';

    // Mostrar detalles en desarrollo
    if (isset($CONFIG['debug']) && $CONFIG['debug']) {
        echo '<div class="debug-info">
                <h4 style="margin-top:0; color:#ff4d4d;">Detalles del error:</h4>
                <pre style="color:#ff4d4d; white-space: pre-wrap; font-size:0.8rem;">' . 
                htmlspecialchars($e->getMessage()) . '</pre>
                <p style="color:#a7acb9; font-size:0.8rem; margin-top:8px;">
                    <strong>Archivo:</strong> ' . htmlspecialchars($e->getFile()) . ':' . htmlspecialchars($e->getLine()) . '<br>
                    <strong>Ruta:</strong> ' . htmlspecialchars($route) . '<br>
                    <strong>Hora:</strong> ' . gmdate('Y-m-d H:i:s') . '
                </p>
            </div>';
    }
    
    echo '</div>
    </body>
    </html>';
}

// Funciones auxiliares para el router
if (!function_exists('not_found')) { 
    function not_found(){ 
        http_response_code(404); 
        echo '404'; 
    } 
}

if (!function_exists('redirect')) { 
    function redirect($path, $params = []) {
        if ($path === '/') {
            $url = './';
        } else {
            $url = './?r=' . urlencode($path);
            
            // Agregar parámetros adicionales
            if (!empty($params)) {
                foreach ($params as $key => $value) {
                    $url .= '&' . urlencode($key) . '=' . urlencode($value);
                }
            }
        }
        header("Location: $url");
        exit;
    } 
}

// Función para cargar vista si no existe
if (!function_exists('view')) {
    function view($name, $data = []) {
        extract($data);
        $viewPath = __DIR__ . "/src/views/$name.php";
        if (file_exists($viewPath)) {
            // Incluir header si existe
            $headerPath = __DIR__ . "/src/views/_header.php";
            if (file_exists($headerPath)) {
                include $headerPath;
            }
            
            include $viewPath;
            
            // Incluir footer si existe
            $footerPath = __DIR__ . "/src/views/_footer.php";
            if (file_exists($footerPath)) {
                include $footerPath;
            }
        } else {
            http_response_code(404);
            echo "Vista no encontrada: $name";
        }
    }
}
?>