<?php
/**
 * Tableau de bord principal - SERVICES-AE Admin
 * Utilise le template moderne Materio
 */

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

// Authentification admin
session_start();
$admin_logged = isset($_SESSION['admin_logged']) && $_SESSION['admin_logged'] === true;

if (!$admin_logged) {
    if ($_SERVER['REQUEST_METHOD'] === 'POST') {
        $username = $_POST['username'] ?? '';
        $password = $_POST['password'] ?? '';
        
        if ($username === 'admin' && $password === 'services2024') {
            $_SESSION['admin_logged'] = true;
            header('Location: admin-dashboard.php');
            exit;
        } else {
            $login_error = "Identifiants incorrects";
        }
    }
}

if (isset($_GET['logout'])) {
    session_destroy();
    header('Location: admin-dashboard.php');
    exit;
}

// Configuration de la page
$page_title = 'Tableau de Bord';
$current_page = 'dashboard';
$include_charts = true;

// Statistiques pour le dashboard
if ($admin_logged) {
    try {
        // Témoignages
        $total_testimonials = fetchOne("SELECT COUNT(*) as count FROM testimonials")['count'];
        $pending_testimonials = fetchOne("SELECT COUNT(*) as count FROM testimonials WHERE approuve = 0")['count'];
        $approved_testimonials = fetchOne("SELECT COUNT(*) as count FROM testimonials WHERE approuve = 1")['count'];
        
        // Analytics
        $total_visits = 0;
        $today_visits = 0;
        $total_events = 0;
        $unique_visitors = 0;
        try {
            $total_visits = fetchOne("SELECT COUNT(*) as count FROM site_analytics")['count'];
            $today_visits = fetchOne("SELECT COUNT(*) as count FROM site_analytics WHERE DATE(visit_date) = CURDATE()")['count'];
            $total_events = fetchOne("SELECT COUNT(*) as count FROM site_events")['count'];
            $unique_visitors = fetchOne("SELECT COUNT(DISTINCT visitor_ip) as count FROM site_analytics WHERE DATE(visit_date) = CURDATE()")['count'];
        } catch (Exception $e) {
            // Tables analytics pas encore créées
        }
        
        // Activité récente
        $recent_testimonials = fetchAll("SELECT nom_client, entreprise, note, DATE_FORMAT(date_creation, '%d/%m/%Y %H:%i') as date_fmt FROM testimonials ORDER BY date_creation DESC LIMIT 5");
        
        // Statistiques par navigateur (si disponible)
        $browser_stats = [];
        try {
            $browser_stats = fetchAll("
                SELECT browser, COUNT(*) as count 
                FROM site_analytics 
                WHERE DATE(visit_date) = CURDATE() AND browser != '' 
                GROUP BY browser 
                ORDER BY count DESC 
                LIMIT 5
            ");
        } catch (Exception $e) {
            // Pas de données
        }
        
    } catch (Exception $e) {
        $error_message = "Erreur lors du chargement des statistiques : " . $e->getMessage();
    }
}

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

<?php if (!$admin_logged): ?>
<!-- Page de connexion avec design moderne -->
<div class="row justify-content-center">
    <div class="col-md-6">
        <div class="card shadow-lg border-0">
            <div class="card-header bg-primary text-center py-4">
                <h3 class="text-white mb-1">
                    <i class="ri-lock-line me-2"></i>
                    Connexion Administrateur
                </h3>
                <p class="text-white-50 mb-0">Panel d'administration SERVICES-AE</p>
            </div>
            <div class="card-body p-5">
                <?php if (isset($login_error)): ?>
                    <div class="alert alert-danger alert-dismissible" role="alert">
                        <i class="ri-error-warning-line me-2"></i>
                        <?php echo $login_error; ?>
                        <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
                    </div>
                <?php endif; ?>
                
                <form method="POST">
                    <div class="form-floating mb-4">
                        <input type="text" name="username" class="form-control" id="username" placeholder="Nom d'utilisateur" required>
                        <label for="username">Nom d'utilisateur</label>
                    </div>
                    <div class="form-floating mb-4">
                        <input type="password" name="password" class="form-control" id="password" placeholder="Mot de passe" required>
                        <label for="password">Mot de passe</label>
                    </div>
                    <button type="submit" class="btn btn-primary w-100 py-3">
                        <i class="ri-login-box-line me-2"></i>
                        Se connecter
                    </button>
                </form>
                
                <div class="mt-4 text-center">
                    <small class="text-muted">
                        <i class="ri-shield-check-line me-1"></i>
                        Accès sécurisé - SERVICES-AE
                    </small>
                </div>
            </div>
        </div>
    </div>
</div>

<?php else: ?>

<!-- Cartes de statistiques principales -->
<div class="row mb-6">
    <div class="col-lg-3 col-md-6 mb-4">
        <div class="card bg-primary h-100">
            <div class="card-body text-center">
                <div class="avatar mx-auto mb-3">
                    <div class="avatar-initial bg-white bg-opacity-25 rounded">
                        <i class="ri-eye-line ri-2x text-white"></i>
                    </div>
                </div>
                <h3 class="card-title text-white mb-2"><?php echo number_format($total_visits); ?></h3>
                <p class="text-white-75 mb-0">Visites Totales</p>
                <small class="text-white-50">Depuis le début</small>
            </div>
        </div>
    </div>
    
    <div class="col-lg-3 col-md-6 mb-4">
        <div class="card bg-success h-100">
            <div class="card-body text-center">
                <div class="avatar mx-auto mb-3">
                    <div class="avatar-initial bg-white bg-opacity-25 rounded">
                        <i class="ri-calendar-line ri-2x text-white"></i>
                    </div>
                </div>
                <h3 class="card-title text-white mb-2"><?php echo number_format($today_visits); ?></h3>
                <p class="text-white-75 mb-0">Visites Aujourd'hui</p>
                <small class="text-white-50"><?php echo number_format($unique_visitors); ?> visiteurs uniques</small>
            </div>
        </div>
    </div>
    
    <div class="col-lg-3 col-md-6 mb-4">
        <div class="card bg-info h-100">
            <div class="card-body text-center">
                <div class="avatar mx-auto mb-3">
                    <div class="avatar-initial bg-white bg-opacity-25 rounded">
                        <i class="ri-chat-quote-line ri-2x text-white"></i>
                    </div>
                </div>
                <h3 class="card-title text-white mb-2"><?php echo number_format($total_testimonials); ?></h3>
                <p class="text-white-75 mb-0">Témoignages</p>
                <small class="text-white-50"><?php echo $approved_testimonials; ?> approuvés</small>
            </div>
        </div>
    </div>
    
    <div class="col-lg-3 col-md-6 mb-4">
        <div class="card <?php echo $pending_testimonials > 0 ? 'bg-warning' : 'bg-secondary'; ?> h-100">
            <div class="card-body text-center">
                <div class="avatar mx-auto mb-3">
                    <div class="avatar-initial bg-white bg-opacity-25 rounded">
                        <i class="ri-time-line ri-2x text-white"></i>
                    </div>
                </div>
                <h3 class="card-title text-white mb-2"><?php echo number_format($pending_testimonials); ?></h3>
                <p class="text-white-75 mb-0">En Attente</p>
                <?php if ($pending_testimonials > 0): ?>
                    <small class="text-white-50">
                        <a href="admin-testimonials.php" class="text-white text-decoration-underline">
                            Voir maintenant
                        </a>
                    </small>
                <?php else: ?>
                    <small class="text-white-50">Tout traité !</small>
                <?php endif; ?>
            </div>
        </div>
    </div>
</div>

<!-- Actions rapides -->
<div class="row mb-6">
    <div class="col-12">
        <div class="card">
            <div class="card-header d-flex align-items-center">
                <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">
                    <div class="col-md-4">
                        <div class="d-grid">
                            <a href="dashboard-stats.php" class="btn btn-outline-primary btn-lg">
                                <i class="ri-line-chart-line me-2"></i>
                                Analytics Détaillés
                            </a>
                        </div>
                    </div>
                    <div class="col-md-4">
                        <div class="d-grid">
                            <a href="admin-testimonials.php" class="btn btn-outline-success btn-lg">
                                <i class="ri-chat-settings-line me-2"></i>
                                Gérer Témoignages
                            </a>
                        </div>
                    </div>
                    <div class="col-md-4">
                        <div class="d-grid">
                            <a href="../test-analytics.html" class="btn btn-outline-info btn-lg" target="_blank">
                                <i class="ri-flask-line me-2"></i>
                                Tester Système
                            </a>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>
</div>

<!-- Graphiques et données -->
<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">
                <h5 class="mb-0">
                    <i class="ri-history-line me-2 text-success"></i>
                    Témoignages Récents
                </h5>
                <a href="admin-testimonials.php" class="btn btn-sm btn-outline-primary ms-auto">
                    Voir tout
                </a>
            </div>
            <div class="card-body">
                <?php if (!empty($recent_testimonials)): ?>
                <div class="table-responsive">
                    <table class="table table-hover">
                        <thead class="table-light">
                            <tr>
                                <th>Client</th>
                                <th>Entreprise</th>
                                <th>Note</th>
                                <th>Date</th>
                            </tr>
                        </thead>
                        <tbody>
                            <?php foreach ($recent_testimonials as $testimonial): ?>
                            <tr>
                                <td>
                                    <strong><?php echo htmlspecialchars($testimonial['nom_client']); ?></strong>
                                </td>
                                <td>
                                    <span class="text-muted"><?php echo htmlspecialchars($testimonial['entreprise'] ?? 'Non spécifiée'); ?></span>
                                </td>
                                <td>
                                    <div class="d-flex align-items-center">
                                        <?php for ($i = 1; $i <= 5; $i++): ?>
                                            <i class="ri-star-<?php echo $i <= $testimonial['note'] ? 'fill' : 'line'; ?> text-warning"></i>
                                        <?php endfor; ?>
                                        <span class="ms-2 small text-muted"><?php echo $testimonial['note']; ?>/5</span>
                                    </div>
                                </td>
                                <td>
                                    <small class="text-muted"><?php echo $testimonial['date_fmt']; ?></small>
                                </td>
                            </tr>
                            <?php endforeach; ?>
                        </tbody>
                    </table>
                </div>
                <?php else: ?>
                <div class="text-center py-4">
                    <i class="ri-inbox-line ri-3x text-muted mb-3 d-block"></i>
                    <p class="text-muted">Aucun témoignage pour le moment</p>
                    <a href="../add-testimonial.php" class="btn btn-primary">Ajouter le premier</a>
                </div>
                <?php endif; ?>
            </div>
        </div>
    </div>
    
    <!-- Statistiques navigateurs -->
    <div class="col-lg-4 mb-4">
        <div class="card h-100">
            <div class="card-header">
                <h5 class="mb-0">
                    <i class="ri-global-line me-2 text-info"></i>
                    Navigateurs Populaires
                </h5>
            </div>
            <div class="card-body">
                <?php if (!empty($browser_stats)): ?>
                <div class="d-flex flex-column gap-3">
                    <?php 
                    $total_browser_visits = array_sum(array_column($browser_stats, 'count'));
                    foreach ($browser_stats as $browser): 
                        $percentage = $total_browser_visits > 0 ? round(($browser['count'] / $total_browser_visits) * 100) : 0;
                    ?>
                    <div class="d-flex align-items-center">
                        <div class="flex-grow-1">
                            <div class="d-flex justify-content-between mb-1">
                                <span class="fw-medium"><?php echo htmlspecialchars($browser['browser']); ?></span>
                                <span class="text-muted"><?php echo $percentage; ?>%</span>
                            </div>
                            <div class="progress" style="height: 6px;">
                                <div class="progress-bar bg-primary" style="width: <?php echo $percentage; ?>%"></div>
                            </div>
                        </div>
                        <div class="ms-3">
                            <span class="badge bg-label-secondary"><?php echo $browser['count']; ?></span>
                        </div>
                    </div>
                    <?php endforeach; ?>
                </div>
                <?php else: ?>
                <div class="text-center py-4">
                    <i class="ri-bar-chart-line ri-3x text-muted mb-3 d-block"></i>
                    <p class="text-muted mb-0">Pas de données disponibles</p>
                    <small class="text-muted">Les statistiques apparaîtront ici</small>
                </div>
                <?php endif; ?>
            </div>
        </div>
    </div>
</div>

<!-- Outils système -->
<div class="row">
    <div class="col-12">
        <div class="card">
            <div class="card-header">
                <h5 class="mb-0">
                    <i class="ri-settings-line me-2 text-secondary"></i>
                    Outils Système
                </h5>
            </div>
            <div class="card-body">
                <div class="row g-3">
                    <div class="col-md-3">
                        <a href="../install-analytics.php" class="btn btn-outline-secondary w-100" target="_blank">
                            <i class="ri-database-line d-block mb-2"></i>
                            <small>Installer Analytics</small>
                        </a>
                    </div>
                    <div class="col-md-3">
                        <a href="../generate-test-data.php" class="btn btn-outline-secondary w-100" target="_blank">
                            <i class="ri-file-add-line d-block mb-2"></i>
                            <small>Données de Test</small>
                        </a>
                    </div>
                    <div class="col-md-3">
                        <a href="../verify-analytics.php" class="btn btn-outline-secondary w-100" target="_blank">
                            <i class="ri-shield-check-line d-block mb-2"></i>
                            <small>Vérifier Système</small>
                        </a>
                    </div>
                    <div class="col-md-3">
                        <a href="../ANALYTICS-DOCUMENTATION.md" class="btn btn-outline-secondary w-100" target="_blank">
                            <i class="ri-book-open-line d-block mb-2"></i>
                            <small>Documentation</small>
                        </a>
                    </div>
                </div>
            </div>
        </div>
    </div>
</div>

<?php if (isset($error_message)): ?>
<div class="alert alert-warning mt-4">
    <i class="ri-error-warning-line me-2"></i>
    <?php echo $error_message; ?>
</div>
<?php endif; ?>

<?php endif; ?>

<?php
$page_content = ob_get_clean();

// JavaScript personnalisé pour la page
$page_js = '
// Animation des cartes au chargement
document.addEventListener("DOMContentLoaded", function() {
    const cards = document.querySelectorAll(".card");
    cards.forEach((card, index) => {
        card.style.opacity = "0";
        card.style.transform = "translateY(20px)";
        setTimeout(() => {
            card.style.transition = "all 0.5s ease";
            card.style.opacity = "1";
            card.style.transform = "translateY(0)";
        }, index * 100);
    });
    
    // Mise à jour du temps en temps réel
    function updateCurrentTime() {
        const now = new Date();
        const timeString = now.toLocaleTimeString("fr-FR");
        const timeElements = document.querySelectorAll(".current-time");
        timeElements.forEach(el => el.textContent = timeString);
    }
    
    updateCurrentTime();
    setInterval(updateCurrentTime, 1000);
});
';

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