<?php
// views/admin/dashboard.php
if (!isset($_SESSION['user']['role']) || !in_array($_SESSION['user']['role'], ['admin', 'moderator'])) {
    flash('error', 'Acceso denegado');
    redirect('dashboard');
    exit;
}
?>



<!-- Restored Admin Styles -->
<style>

        :root {
            --bg: #0b0c10;
            --panel: #12141a;
            --card: #0e1016;
            --card-hover: #151820;
            --border: #21242c;
            --border-light: #2a2e3a;
            --text: #e9eaf1;
            --muted: #a7acb9;
            --accent: #7cd1ff;
            --accent2: #b99cff;
            --accent3: #ff9cf2;
            --success: #4dff88;
            --warning: #ffc44d;
            --error: #ff4d4d;
            --radius: 16px;
            --radius-sm: 10px;
            --shadow: 0 8px 24px rgba(0, 0, 0, 0.2);
            --transition: all 0.3s ease;
        }

        * {
            box-sizing: border-box;
            margin: 0;
            padding: 0;
            font-family: 'Segoe UI', system-ui, -apple-system, sans-serif;
        }

        body {
            background: linear-gradient(180deg, var(--bg) 0%, var(--panel) 100%);
            color: var(--text);
            line-height: 1.6;
            min-height: 100vh;
            padding: 20px;
        }

        .admin-header {
            background: linear-gradient(135deg, rgba(124,209,255,0.1), rgba(185,156,255,0.1));
            border-radius: var(--radius);
            padding: 24px;
            margin-bottom: 24px;
            border: 1px solid var(--border);
            position: relative;
            overflow: hidden;
        }

        .admin-header::before {
            content: '';
            position: absolute;
            top: 0;
            left: 0;
            right: 0;
            height: 4px;
            background: linear-gradient(90deg, var(--accent), var(--accent2), var(--accent3));
        }

        .stats-grid {
            display: grid;
            grid-template-columns: repeat(auto-fit, minmax(280px, 1fr));
            gap: 20px;
            margin-bottom: 24px;
        }

        .stat-card {
            background: var(--card);
            border: 1px solid var(--border);
            border-radius: var(--radius);
            padding: 20px;
            transition: var(--transition);
            position: relative;
            overflow: hidden;
        }

        .stat-card:hover {
            border-color: var(--border-light);
            transform: translateY(-5px);
        }

        .stat-card::before {
            content: '';
            position: absolute;
            top: 0;
            left: 0;
            right: 0;
            height: 4px;
            background: var(--accent);
            opacity: 0.7;
        }

        .stat-value {
            font-size: 2.5rem;
            font-weight: bold;
            margin: 10px 0;
            background: linear-gradient(135deg, var(--accent), var(--accent2));
            -webkit-background-clip: text;
            background-clip: text;
            color: transparent;
        }

        .stat-label {
            color: var(--muted);
            font-size: 0.9rem;
        }

        .stat-icon {
            width: 48px;
            height: 48px;
            border-radius: 12px;
            display: flex;
            align-items: center;
            justify-content: center;
            font-size: 1.5rem;
            margin-bottom: 12px;
        }

        .quick-actions {
            display: grid;
            grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
            gap: 16px;
            margin-bottom: 24px;
        }

        .action-btn {
            background: var(--card);
            border: 1px solid var(--border);
            border-radius: var(--radius-sm);
            padding: 20px;
            text-align: center;
            text-decoration: none;
            color: var(--text);
            transition: var(--transition);
            display: flex;
            flex-direction: column;
            align-items: center;
            gap: 12px;
        }

        .action-btn:hover {
            border-color: var(--accent);
            background: rgba(124, 209, 255, 0.05);
            transform: translateY(-3px);
        }

        .action-icon {
            width: 48px;
            height: 48px;
            border-radius: 12px;
            display: flex;
            align-items: center;
            justify-content: center;
            font-size: 1.5rem;
            background: linear-gradient(135deg, var(--accent), var(--accent2));
            color: white;
        }

        .grid-2col {
            display: grid;
            grid-template-columns: 1fr 1fr;
            gap: 24px;
        }

        .activity-list {
            max-height: 400px;
            overflow-y: auto;
        }

        .activity-item {
            padding: 16px;
            border-bottom: 1px solid var(--border);
            display: flex;
            align-items: flex-start;
            gap: 12px;
        }

        .activity-item:last-child {
            border-bottom: none;
        }

        .activity-icon {
            width: 32px;
            height: 32px;
            border-radius: 8px;
            display: flex;
            align-items: center;
            justify-content: center;
            flex-shrink: 0;
        }

        .severity-high { background: rgba(255, 77, 77, 0.2); color: var(--error); }
        .severity-medium { background: rgba(255, 196, 77, 0.2); color: var(--warning); }
        .severity-low { background: rgba(77, 255, 136, 0.2); color: var(--success); }

        .update-alert {
            background: linear-gradient(135deg, rgba(255, 196, 77, 0.1), rgba(255, 156, 242, 0.1));
            border: 1px solid var(--warning);
            border-radius: var(--radius);
            padding: 16px;
            margin-bottom: 24px;
            display: flex;
            align-items: center;
            gap: 12px;
        }

        @media (max-width: 768px) {
            .grid-2col {
                grid-template-columns: 1fr;
            }
            
            .stats-grid {
                grid-template-columns: 1fr;
            }
            
            .quick-actions {
                grid-template-columns: repeat(auto-fit, minmax(150px, 1fr));
            }
        }

        .system-health {
            display: flex;
            align-items: center;
            gap: 8px;
            padding: 8px 12px;
            border-radius: 20px;
            background: rgba(77, 255, 136, 0.1);
            color: var(--success);
            font-size: 0.9rem;
            font-weight: 500;
        }

        .health-warning {
            background: rgba(255, 196, 77, 0.1);
            color: var(--warning);
        }

        .health-critical {
            background: rgba(255, 77, 77, 0.1);
            color: var(--error);
        }

        .btn {
            padding: 12px 22px;
            border-radius: var(--radius-sm);
            border: 1px solid var(--border);
            background: transparent;
            color: var(--text);
            cursor: pointer;
            display: inline-flex;
            align-items: center;
            gap: 8px;
            transition: var(--transition);
            font-weight: 500;
            text-decoration: none;
        }

        .btn:hover {
            background: rgba(255, 255, 255, 0.05);
            border-color: var(--border-light);
            transform: translateY(-2px);
        }

        .card {
            background: var(--card);
            border: 1px solid var(--border);
            border-radius: var(--radius);
            padding: 28px;
            transition: var(--transition);
            box-shadow: var(--shadow);
            position: relative;
            overflow: hidden;
        }

        .muted {
            color: var(--muted);
            font-size: 0.9rem;
        }

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

        .fade-in {
            animation: fadeInUp 0.6s ease-out forwards;
            opacity: 0;
        }
    
</style>
<div class="admin-header">
        <div style="display: flex; justify-content: space-between; align-items: center; margin-bottom: 16px;">
            <div>
                <h1 style="margin: 0 0 8px 0; display: flex; align-items: center; gap: 12px;">
                    <i class="fas fa-shield-alt" style="color: var(--accent);"></i>
                    Panel de Administración
                </h1>
                <p class="muted" style="margin: 0;">Gestión completa del sistema Thirty</p>
            </div>
            <div class="system-health">
                <i class="fas fa-circle-check"></i>
                Sistema Operativo
            </div>
        </div>
        
        <div style="display: flex; gap: 16px; flex-wrap: wrap;">
            <a href="./?r=admin/dashboard" class="btn" style="background: rgba(124, 209, 255, 0.1); border-color: var(--accent);">
                <i class="fas fa-gauge-high"></i> Dashboard
            </a>
            <a href="./?r=admin/users" class="btn">
                <i class="fas fa-users"></i> Usuarios
            </a>
            <a href="./?r=admin/posts" class="btn">
                <i class="fas fa-image"></i> Publicaciones
            </a>
            <a href="./?r=admin/ads" class="btn">
                <i class="fas fa-ad"></i> Anuncios
            </a>
            <a href="./?r=admin/reports" class="btn">
                <i class="fas fa-flag"></i> Reportes
            </a>
            <a href="./?r=admin/control-panel" class="btn">
                <i class="fas fa-cogs"></i> Control Panel
            </a>
        </div>
    </div>

    <?php if ($system_updates['available']): ?>
    <div class="update-alert">
        <i class="fas fa-exclamation-triangle" style="color: var(--warning); font-size: 1.5rem;"></i>
        <div>
            <strong>Actualización de seguridad disponible</strong>
            <p style="margin: 4px 0 0 0; color: var(--muted);">Versión <?= h($system_updates['version']) ?> - Se recomienda actualizar</p>
        </div>
    </div>
    <?php endif; ?>

    <!-- Estadísticas rápidas -->
    <div class="stats-grid">
        <div class="stat-card fade-in" style="animation-delay: 0.1s">
            <div class="stat-icon" style="background: rgba(124, 209, 255, 0.2); color: var(--accent);">
                <i class="fas fa-users"></i>
            </div>
            <div class="stat-value"><?= h($quick_stats['new_users_week'] ?? 0) ?></div>
            <div class="stat-label">Nuevos usuarios (7 días)</div>
        </div>

        <div class="stat-card fade-in" style="animation-delay: 0.2s">
            <div class="stat-icon" style="background: rgba(185, 156, 255, 0.2); color: var(--accent2);">
                <i class="fas fa-image"></i>
            </div>
            <div class="stat-value"><?= h($quick_stats['new_posts_week'] ?? 0) ?></div>
            <div class="stat-label">Nuevas publicaciones (7 días)</div>
        </div>

        <div class="stat-card fade-in" style="animation-delay: 0.3s">
            <div class="stat-icon" style="background: rgba(255, 196, 77, 0.2); color: var(--warning);">
                <i class="fas fa-flag"></i>
            </div>
            <div class="stat-value"><?= h($quick_stats['pending_reports'] ?? 0) ?></div>
            <div class="stat-label">Reportes pendientes</div>
        </div>

        <div class="stat-card fade-in" style="animation-delay: 0.4s">
            <div class="stat-icon" style="background: rgba(255, 77, 77, 0.2); color: var(--error);">
                <i class="fas fa-lock"></i>
            </div>
            <div class="stat-value"><?= h($quick_stats['locked_accounts'] ?? 0) ?></div>
            <div class="stat-label">Cuentas bloqueadas</div>
        </div>

        <div class="stat-card fade-in" style="animation-delay: 0.5s">
            <div class="stat-icon" style="background: rgba(77, 255, 136, 0.2); color: var(--success);">
                <i class="fas fa-ad"></i>
            </div>
            <div class="stat-value"><?= h($quick_stats['active_ads'] ?? 0) ?></div>
            <div class="stat-label">Anuncios activos</div>
        </div>

        <div class="stat-card fade-in" style="animation-delay: 0.6s">
            <div class="stat-icon" style="background: rgba(255, 156, 242, 0.2); color: var(--accent3);">
                <i class="fas fa-chart-bar"></i>
            </div>
            <div class="stat-value"><?= h($ad_stats['ctr'] ?? '0.00') ?>%</div>
            <div class="stat-label">CTR de anuncios</div>
        </div>
    </div>

    <!-- Acciones rápidas -->
    <div class="quick-actions">
        <a href="./?r=admin/users" class="action-btn fade-in" style="animation-delay: 0.1s">
            <div class="action-icon">
                <i class="fas fa-user-cog"></i>
            </div>
            <span>Gestión de Usuarios</span>
            <small class="muted">Administrar usuarios y permisos</small>
        </a>

        <a href="./?r=admin/posts" class="action-btn fade-in" style="animation-delay: 0.2s">
            <div class="action-icon">
                <i class="fas fa-modx"></i>
            </div>
            <span>Moderar Contenido</span>
            <small class="muted">Revisar publicaciones y comentarios</small>
        </a>

        <a href="./?r=admin/ads" class="action-btn fade-in" style="animation-delay: 0.3s">
            <div class="action-icon">
                <i class="fas fa-chart-line"></i>
            </div>
            <span>Anuncios</span>
            <small class="muted">Gestionar campañas publicitarias</small>
        </a>

        <a href="./?r=admin/system-settings" class="action-btn fade-in" style="animation-delay: 0.4s">
            <div class="action-icon">
                <i class="fas fa-sliders"></i>
            </div>
            <span>Configuración</span>
            <small class="muted">Ajustes del sistema</small>
        </a>

        <a href="./?r=admin/backup" class="action-btn fade-in" style="animation-delay: 0.5s">
            <div class="action-icon">
                <i class="fas fa-database"></i>
            </div>
            <span>Backup</span>
            <small class="muted">Copias de seguridad</small>
        </a>

        <a href="./?r=admin/logs" class="action-btn fade-in" style="animation-delay: 0.6s">
            <div class="action-icon">
                <i class="fas fa-clipboard-list"></i>
            </div>
            <span>Logs del Sistema</span>
            <small class="muted">Registros de actividad</small>
        </a>
    </div>

    <!-- Contenido principal en dos columnas -->
    <div class="grid-2col">
        <!-- Actividad reciente -->
        <div class="card fade-in" style="animation-delay: 0.3s">
            <h3 style="margin: 0 0 16px 0; display: flex; align-items: center; gap: 8px;">
                <i class="fas fa-clock-rotate-left"></i>
                Actividad Reciente
            </h3>
            <div class="activity-list">
                <?php if (!empty($recent_activity)): ?>
                    <?php foreach ($recent_activity as $activity): ?>
                        <div class="activity-item">
                            <div class="activity-icon severity-<?= h($activity['severity'] ?? 'low') ?>">
                                <i class="fas fa-<?= h($activity['action'] === 'login_success' ? 'sign-in-alt' : 
                                                ($activity['action'] === 'login_failed' ? 'exclamation-triangle' : 
                                                ($activity['action'] === 'user_blocked' ? 'ban' : 'info-circle'))) ?>"></i>
                            </div>
                            <div style="flex: 1;">
                                <div style="font-weight: 500;"><?= h($activity['details']) ?></div>
                                <div class="muted" style="font-size: 0.85rem; margin-top: 4px;">
                                    <?= h($activity['username'] ?? 'Sistema') ?> • 
                                    <?= h(fdt_madrid($activity['created_at'])) ?>
                                </div>
                            </div>
                        </div>
                    <?php endforeach; ?>
                <?php else: ?>
                    <div style="text-align: center; padding: 40px 20px; color: var(--muted);">
                        <i class="fas fa-inbox" style="font-size: 3rem; margin-bottom: 12px;"></i>
                        <p>No hay actividad reciente</p>
                    </div>
                <?php endif; ?>
            </div>
        </div>

        <!-- Información del sistema -->
        <div class="card fade-in" style="animation-delay: 0.4s">
            <h3 style="margin: 0 0 16px 0; display: flex; align-items: center; gap: 8px;">
                <i class="fas fa-server"></i>
                Estado del Sistema
            </h3>
            
            <div style="display: flex; flex-direction: column; gap: 16px;">
                <div>
                    <label class="muted">Uso de Base de Datos</label>
                    <div style="font-weight: 500; font-size: 1.2rem;"><?= h($system_usage['db_size'] ?? '0') ?> MB</div>
                </div>

                <div>
                    <label class="muted">Usuarios Activos (24h)</label>
                    <div style="font-weight: 500; font-size: 1.2rem;"><?= h($system_usage['active_users_24h'] ?? 0) ?></div>
                </div>

                <div>
                    <label class="muted">Versión PHP</label>
                    <div style="font-weight: 500; font-size: 1.2rem;"><?= h($system_usage['php_version'] ?? 'N/A') ?></div>
                </div>

                <div>
                    <label class="muted">Hora del Servidor</label>
                    <div style="font-weight: 500; font-size: 1.1rem;"><?= h($system_usage['server_time'] ?? gmdate('Y-m-d H:i:s')) ?></div>
                </div>

                <!-- Estadísticas de anuncios -->
                <?php if (!empty($ad_stats)): ?>
                <div style="border-top: 1px solid var(--border); padding-top: 16px;">
                    <h4 style="margin: 0 0 12px 0; color: var(--accent);">
                        <i class="fas fa-chart-simple"></i> Estadísticas de Anuncios
                    </h4>
                    <div style="display: grid; grid-template-columns: 1fr 1fr; gap: 12px;">
                        <div>
                            <div class="muted">Impresiones</div>
                            <div style="font-weight: 500;"><?= h($ad_stats['total_impressions'] ?? 0) ?></div>
                        </div>
                        <div>
                            <div class="muted">Clics</div>
                            <div style="font-weight: 500;"><?= h($ad_stats['total_clicks'] ?? 0) ?></div>
                        </div>
                        <div>
                            <div class="muted">CTR</div>
                            <div style="font-weight: 500;"><?= h($ad_stats['ctr'] ?? '0.00') ?>%</div>
                        </div>
                        <div>
                            <div class="muted">Presupuesto</div>
                            <div style="font-weight: 500;">€<?= h(number_format($ad_stats['total_budget'] ?? 0, 2)) ?></div>
                        </div>
                    </div>
                </div>
                <?php endif; ?>
            </div>
        </div>
    </div>

    <script>
    // Actualización automática cada 30 segundos
    setInterval(() => {
        fetch('./?r=admin/refresh-stats')
            .then(response => response.json())
            .then(data => {
                if (data.success) {
                    // Actualizar contadores en tiempo real
                    const statValues = document.querySelectorAll('.stat-value');
                    if (statValues[0]) statValues[0].textContent = data.new_users_week;
                    if (statValues[1]) statValues[1].textContent = data.new_posts_week;
                    if (statValues[2]) statValues[2].textContent = data.pending_reports;
                    if (statValues[3]) statValues[3].textContent = data.locked_accounts;
                    if (statValues[4]) statValues[4].textContent = data.active_ads;
                }
            })
            .catch(error => console.error('Error actualizando stats:', error));
    }, 30000);

    // Efectos visuales para las tarjetas
    document.addEventListener('DOMContentLoaded', function() {
        const cards = document.querySelectorAll('.fade-in');
        cards.forEach((card, index) => {
            card.style.animationDelay = (index * 0.1) + 's';
        });
    });
    </script>
