<?php
/**
 * Page d'accueil moderne du panel admin - SERVICES-AE
 * Vue d'ensemble complète avec accès rapide aux fonctionnalités
 */

// Protection d'authentification
require_once __DIR__ . '/auth-check.php';

require_once '../config/config.php';
require_once '../config/db.php';

// Configuration de la page
$page_title = 'Panel Administration - SERVICES-AE';
$current_page = 'home';
$include_charts = true;

// Statistiques rapides pour la page d'accueil
try {
    // Statistiques du jour
    $today_visits = fetchOne("SELECT COUNT(*) as count FROM site_analytics WHERE DATE(visit_date) = CURDATE()")['count'];
    $today_events = fetchOne("SELECT COUNT(*) as count FROM site_events WHERE DATE(event_date) = CURDATE()")['count'];
    
    // Témoignages en attente
    $pending_testimonials = fetchOne("SELECT COUNT(*) as count FROM testimonials WHERE approuve = 0")['count'];
    $total_testimonials = fetchOne("SELECT COUNT(*) as count FROM testimonials")['count'];
    
    // Visiteurs uniques cette semaine
    $week_visitors = fetchOne("SELECT COUNT(DISTINCT visitor_ip) as count FROM site_analytics WHERE visit_date >= DATE_SUB(NOW(), INTERVAL 7 DAY)")['count'];
    
    // Performance moyenne
    $avg_performance = fetchOne("
        SELECT AVG(load_time) as avg_load_time 
        FROM page_performance 
        WHERE measurement_date >= DATE_SUB(NOW(), INTERVAL 24 HOUR)
    ")['avg_load_time'] ?? 0;
    
    // Dernières activités
    $recent_testimonials = fetchAll("
        SELECT nom_client, service_utilise, note, date_creation,
               DATE_FORMAT(date_creation, '%d/%m à %H:%i') as date_fmt
        FROM testimonials 
        ORDER BY date_creation DESC 
        LIMIT 5
    ");
    
    $recent_visits = fetchAll("
        SELECT page_title, visitor_ip, browser, country,
               DATE_FORMAT(visit_date, '%d/%m à %H:%i') as date_fmt
        FROM site_analytics 
        WHERE DATE(visit_date) = CURDATE()
        ORDER BY visit_date DESC 
        LIMIT 8
    ");
    
    // Top services cette semaine
    $top_services = fetchAll("
        SELECT service_utilise, COUNT(*) as count
        FROM testimonials 
        WHERE date_creation >= DATE_SUB(NOW(), INTERVAL 7 DAY)
        GROUP BY service_utilise
        ORDER BY count DESC
        LIMIT 5
    ");
    
    // Système info
    $system_info = [
        'php_version' => phpversion(),
        'mysql_version' => fetchOne("SELECT VERSION() as version")['version'],
        'server_time' => date('Y-m-d H:i:s'),
        'disk_free' => function_exists('disk_free_space') ? round(disk_free_space('.') / 1024 / 1024 / 1024, 2) . ' GB' : 'N/A',
        'memory_limit' => ini_get('memory_limit')
    ];
    
} catch (Exception $e) {
    $error_message = "Erreur lors du chargement des données : " . $e->getMessage();
}

// Contenu de la page
ob_start();
?>

<?php if (isset($error_message)): ?>
<div class="alert alert-warning alert-dismissible fade show" role="alert">
    <i class="ri-error-warning-line me-2"></i>
    <?php echo $error_message; ?>
    <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
</div>
<?php endif; ?>

<!-- Welcome Hero -->
<div class="row mb-6">
    <div class="col-12">
        <div class="card border-start border-4 border-primary shadow-lg overflow-hidden">
            <div class="card-body p-4">
                <div class="row align-items-center">
                    <div class="col-lg-8">
                        <div class="d-flex align-items-center mb-3">
                            <div class="avatar me-3">
                                <div class="avatar-initial bg-label-primary rounded">
                                    <i class="ri-shield-user-line ri-2x text-primary"></i>
                                </div>
                            </div>
                            <div>
                                <h3 class="text-primary mb-0"><i class="ri-hand-heart-line me-2"></i>Bienvenue, Administrateur</h3>
                                <p class="text-muted mb-0">Panel de gestion SERVICES-AE - Tableau de bord complet</p>
                            </div>
                        </div>
                        
                        <div class="row text-center g-3">
                            <div class="col-md-3">
                                <div class="bg-light border rounded p-3">
                                    <h4 class="text-primary mb-1"><?php echo number_format($today_visits); ?></h4>
                                    <small class="text-muted">Visites Aujourd'hui</small>
                                </div>
                            </div>
                            <div class="col-md-3">
                                <div class="bg-light border rounded p-3">
                                    <h4 class="text-success mb-1"><?php echo number_format($week_visitors); ?></h4>
                                    <small class="text-muted">Visiteurs/Semaine</small>
                                </div>
                            </div>
                            <div class="col-md-3">
                                <div class="bg-light border rounded p-3">
                                    <h4 class="<?php echo $pending_testimonials > 0 ? 'text-warning' : 'text-info'; ?> mb-1">
                                        <?php echo $pending_testimonials; ?>
                                        <?php if ($pending_testimonials > 0): ?>
                                        <span class="badge bg-warning ms-1">!</span>
                                        <?php endif; ?>
                                    </h4>
                                    <small class="text-muted">Avis en Attente</small>
                                </div>
                            </div>
                            <div class="col-md-3">
                                <div class="bg-light border rounded p-3">
                                    <h4 class="text-dark mb-1"><?php echo round($avg_performance); ?>ms</h4>
                                    <small class="text-muted">Perf. Moyenne</small>
                                </div>
                            </div>
                        </div>
                    </div>
                    
                    <div class="col-lg-4 text-end d-none d-lg-block">
                        <div class="position-relative">
                            <i class="ri-dashboard-3-line text-white" style="font-size: 120px; opacity: 0.2;"></i>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>
</div>

<!-- Actions rapides -->
<div class="row mb-6">
    <div class="col-12">
        <div class="card">
            <div class="card-header">
                <h5 class="mb-0">
                    <i class="ri-rocket-line me-2 text-primary"></i>
                    Actions Rapides
                </h5>
            </div>
            <div class="card-body">
                <div class="row g-4">
                    <!-- Analytics -->
                    <div class="col-lg-3 col-md-6">
                        <div class="card h-100 border-start border-4 border-danger">
                            <div class="card-body text-center">
                                <div class="mb-3">
                                    <i class="ri ri-line-chart-line text-danger" style="font-size: 3rem;"></i>
                                </div>
                                <h6 class="text-danger mb-2">Analytics Live</h6>
                                <p class="small text-muted mb-3">Statistiques temps réel, graphiques interactifs</p>
                                <a href="dashboard-stats.php" class="btn btn-danger btn-sm">
                                    <i class="ri-external-link-line me-1"></i>
                                    Accéder
                                </a>
                            </div>
                        </div>
                    </div>
                    
                    <!-- Témoignages -->
                    <div class="col-lg-3 col-md-6">
                        <div class="card h-100 border-start border-4 border-success">
                            <div class="card-body text-center">
                                <div class="mb-3">
                                    <i class="ri ri-chat-quote-line text-success" style="font-size: 3rem;"></i>
                                </div>
                                <h6 class="text-success mb-2">Témoignages</h6>
                                <p class="small text-muted mb-3">Interface moderne avec filtres avancés</p>
                                <a href="admin-testimonials.php" class="btn btn-success btn-sm">
                                    <i class="ri-external-link-line me-1"></i>
                                    Gérer
                                </a>
                            </div>
                        </div>
                    </div>
                    
                    <!-- Ajouter Témoignage -->
                    <div class="col-lg-3 col-md-6">
                        <div class="card h-100 border-start border-4 border-warning">
                            <div class="card-body text-center">
                                <div class="mb-3">
                                    <i class="ri ri-add-circle-line text-warning" style="font-size: 3rem;"></i>
                                </div>
                                <h6 class="text-warning mb-2">Nouveau Témoignage</h6>
                                <p class="small text-muted mb-3">Ajouter un avis client rapidement</p>
                                <a href="../add-testimonial.php" class="btn btn-warning btn-sm">
                                    <i class="ri-add-line me-1"></i>
                                    Ajouter
                                </a>
                            </div>
                        </div>
                    </div>
                    
                    <!-- Vue Site -->
                    <div class="col-lg-3 col-md-6">
                        <div class="card h-100 border-start border-4 border-info">
                            <div class="card-body text-center">
                                <div class="mb-3">
                                    <i class="ri ri-global-line text-info" style="font-size: 3rem;"></i>
                                </div>
                                <h6 class="text-info mb-2">Voir le Site</h6>
                                <p class="small text-muted mb-3">Accès direct au site public</p>
                                <a href="../index.php" target="_blank" class="btn btn-info btn-sm">
                                    <i class="ri-external-link-line me-1"></i>
                                    Visiter
                                </a>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>
</div>

<!-- Activité récente et statistiques -->
<div class="row">
    <!-- Activité récente -->
    <div class="col-lg-8 mb-4">
        <div class="card h-100">
            <div class="card-header d-flex align-items-center justify-content-between">
                <h5 class="mb-0">
                    <i class="ri-pulse-line me-2 text-success"></i>
                    Activité Récente
                </h5>
                <div class="btn-group" role="group" aria-label="Filtres">
                    <input type="radio" class="btn-check" name="activity-filter" id="filter-all" checked>
                    <label class="btn btn-sm btn-outline-primary" for="filter-all">Tout</label>
                    
                    <input type="radio" class="btn-check" name="activity-filter" id="filter-testimonials">
                    <label class="btn btn-sm btn-outline-primary" for="filter-testimonials">Avis</label>
                    
                    <input type="radio" class="btn-check" name="activity-filter" id="filter-visits">
                    <label class="btn btn-sm btn-outline-primary" for="filter-visits">Visites</label>
                </div>
            </div>
            <div class="card-body">
                <div class="activity-feed">
                    <?php 
                    // Combiner témoignages et visites
                    $all_activity = [];
                    
                    foreach ($recent_testimonials as $testimonial) {
                        $all_activity[] = [
                            'type' => 'testimonial',
                            'time' => $testimonial['date_creation'],
                            'time_fmt' => $testimonial['date_fmt'],
                            'data' => $testimonial
                        ];
                    }
                    
                    foreach ($recent_visits as $visit) {
                        $all_activity[] = [
                            'type' => 'visit',
                            'time' => $visit['date_fmt'],
                            'time_fmt' => $visit['date_fmt'],
                            'data' => $visit
                        ];
                    }
                    
                    // Trier par date
                    usort($all_activity, function($a, $b) {
                        return strtotime($b['time']) - strtotime($a['time']);
                    });
                    
                    $activity_shown = 0;
                    foreach ($all_activity as $activity): 
                        if ($activity_shown >= 12) break;
                        $activity_shown++;
                    ?>
                    
                    <div class="activity-item mb-3 <?php echo $activity['type']; ?>-activity" data-type="<?php echo $activity['type']; ?>">
                        <div class="d-flex align-items-start">
                            <div class="avatar avatar-sm me-3">
                                <div class="avatar-initial bg-label-<?php echo $activity['type'] === 'testimonial' ? 'success' : 'primary'; ?> rounded">
                                    <i class="ri-<?php echo $activity['type'] === 'testimonial' ? 'chat-quote' : 'eye'; ?>-line text-<?php echo $activity['type'] === 'testimonial' ? 'success' : 'primary'; ?>"></i>
                                </div>
                            </div>
                            <div class="flex-grow-1">
                                <?php if ($activity['type'] === 'testimonial'): ?>
                                <div class="mb-1">
                                    <strong><?php echo htmlspecialchars($activity['data']['nom_client']); ?></strong> 
                                    a laissé un avis <?php echo $activity['data']['note']; ?>/5 ⭐
                                </div>
                                <div class="text-muted small mb-1">
                                    Service: <?php echo htmlspecialchars($activity['data']['service_utilise']); ?>
                                </div>
                                <?php else: ?>
                                <div class="mb-1">
                                    <strong>Nouvelle visite</strong> 
                                    <?php echo htmlspecialchars($activity['data']['page_title'] ?: 'Page sans titre'); ?>
                                </div>
                                <div class="text-muted small mb-1">
                                    <?php echo htmlspecialchars($activity['data']['browser']); ?>
                                    <?php if ($activity['data']['country']): ?>
                                    - <?php echo htmlspecialchars($activity['data']['country']); ?>
                                    <?php endif; ?>
                                </div>
                                <?php endif; ?>
                                <small class="text-muted"><?php echo $activity['time_fmt']; ?></small>
                            </div>
                        </div>
                    </div>
                    
                    <?php endforeach; ?>
                    
                    <?php if (empty($all_activity)): ?>
                    <div class="text-center py-4 text-muted">
                        <i class="ri-inbox-line ri-3x mb-3 d-block"></i>
                        <p>Aucune activité récente</p>
                    </div>
                    <?php endif; ?>
                </div>
            </div>
        </div>
    </div>
    
    <!-- Sidebar avec infos système et services -->
    <div class="col-lg-4">
        <!-- Top Services -->
        <div class="card mb-4">
            <div class="card-header">
                <h6 class="mb-0">
                    <i class="ri-service-line me-2 text-warning"></i>
                    Top Services (7j)
                </h6>
            </div>
            <div class="card-body">
                <?php if (!empty($top_services)): ?>
                <div class="d-flex flex-column gap-3">
                    <?php 
                    $max_count = max(array_column($top_services, 'count'));
                    foreach ($top_services as $service): 
                        $percentage = $max_count > 0 ? ($service['count'] / $max_count) * 100 : 0;
                    ?>
                    <div>
                        <div class="d-flex justify-content-between mb-1">
                            <span class="fw-medium"><?php echo htmlspecialchars($service['service_utilise']); ?></span>
                            <span class="text-muted"><?php echo $service['count']; ?></span>
                        </div>
                        <div class="progress" style="height: 6px;">
                            <div class="progress-bar bg-warning" style="width: <?php echo $percentage; ?>%"></div>
                        </div>
                    </div>
                    <?php endforeach; ?>
                </div>
                <?php else: ?>
                <div class="text-center py-3 text-muted">
                    <i class="ri-service-line ri-2x mb-2 d-block text-muted"></i>
                    <small>Aucune donnée cette semaine</small>
                </div>
                <?php endif; ?>
            </div>
        </div>
        
        <!-- Infos système -->
        <div class="card">
            <div class="card-header">
                <h6 class="mb-0">
                    <i class="ri-computer-line me-2 text-secondary"></i>
                    Informations Système
                </h6>
            </div>
            <div class="card-body">
                <div class="list-group list-group-flush">
                    <div class="list-group-item d-flex justify-content-between px-0">
                        <small class="text-muted">PHP</small>
                        <small class="fw-medium"><?php echo $system_info['php_version']; ?></small>
                    </div>
                    <div class="list-group-item d-flex justify-content-between px-0">
                        <small class="text-muted">MySQL</small>
                        <small class="fw-medium"><?php echo explode('-', $system_info['mysql_version'])[0]; ?></small>
                    </div>
                    <div class="list-group-item d-flex justify-content-between px-0">
                        <small class="text-muted">Heure Serveur</small>
                        <small class="fw-medium"><?php echo date('H:i:s'); ?></small>
                    </div>
                    <div class="list-group-item d-flex justify-content-between px-0">
                        <small class="text-muted">Mémoire</small>
                        <small class="fw-medium"><?php echo $system_info['memory_limit']; ?></small>
                    </div>
                    <div class="list-group-item d-flex justify-content-between px-0">
                        <small class="text-muted">Espace Libre</small>
                        <small class="fw-medium"><?php echo $system_info['disk_free']; ?></small>
                    </div>
                </div>
            </div>
        </div>
    </div>
</div>

<?php
$page_content = ob_get_clean();

// JavaScript pour les interactions
$page_js = '
document.addEventListener("DOMContentLoaded", function() {
    // Filtres d\'activité
    const filterBtns = document.querySelectorAll(\'input[name="activity-filter"]\');
    const activityItems = document.querySelectorAll(\'.activity-item\');
    
    filterBtns.forEach(btn => {
        btn.addEventListener(\'change\', function() {
            const filter = this.id.replace(\'filter-\', \'\');
            
            activityItems.forEach(item => {
                if (filter === \'all\' || item.dataset.type === filter) {
                    item.style.display = \'block\';
                    item.classList.add(\'fadeIn\');
                } else {
                    item.style.display = \'none\';
                }
            });
        });
    });
    
    // Auto-refresh des stats toutes les 2 minutes
    setInterval(refreshStats, 120000);
});

async function refreshStats() {
    try {
        const response = await fetch("../api-analytics.php?action=quick_stats");
        const data = await response.json();
        
        if (!data.error && data.stats) {
            // Mettre à jour les stats si nécessaire
            console.log("Stats updated:", data.stats);
        }
    } catch (error) {
        console.error("Erreur refresh stats:", error);
    }
}
';

// Inclure le template
include 'template.php';
?>