<?php
/**
 * Gestion SEO - SERVICES-AE
 * Interface pour optimiser les pages du site
 */

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

// Inclure les dépendances
require_once '../config/config.php';
require_once '../config/db.php';
require_once __DIR__ . '/SEOManager.php';

// Initialiser SEOManager
$seoManager = new SEOManager($pdo);

// Vérifier et créer la table si nécessaire
if (!$seoManager->tableExists()) {
    $seoManager->createTable();
}

// Variables pour les messages
$success_message = '';
$error_message = '';

// Traitement des actions
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['action'])) {
    $action = $_POST['action'];
    
    switch ($action) {
        case 'create_or_update':
            $data = [
                'page_name' => trim($_POST['page_name'] ?? ''),
                'page_title' => trim($_POST['page_title'] ?? ''),
                'meta_description' => trim($_POST['meta_description'] ?? ''),
                'meta_keywords' => trim($_POST['meta_keywords'] ?? ''),
                'meta_robots' => $_POST['meta_robots'] ?? 'index,follow',
                'canonical_url' => trim($_POST['canonical_url'] ?? ''),
                'og_title' => trim($_POST['og_title'] ?? ''),
                'og_description' => trim($_POST['og_description'] ?? ''),
                'og_image' => trim($_POST['og_image'] ?? ''),
                'og_type' => $_POST['og_type'] ?? 'website',
                'twitter_card' => $_POST['twitter_card'] ?? 'summary_large_image',
                'twitter_title' => trim($_POST['twitter_title'] ?? ''),
                'twitter_description' => trim($_POST['twitter_description'] ?? ''),
                'twitter_image' => trim($_POST['twitter_image'] ?? ''),
                'schema_type' => $_POST['schema_type'] ?? 'WebPage',
                'custom_head' => trim($_POST['custom_head'] ?? ''),
                'status' => $_POST['status'] ?? 'active'
            ];
            
            // Validation
            if (empty($data['page_name'])) {
                $error_message = "Le nom de la page est obligatoire.";
            } elseif (empty($data['page_title'])) {
                $error_message = "Le titre de la page est obligatoire.";
            } else {
                if ($seoManager->createOrUpdate($data)) {
                    $success_message = "Paramètres SEO mis à jour avec succès pour la page '{$data['page_name']}'.";
                } else {
                    $error_message = "Erreur lors de la mise à jour des paramètres SEO.";
                }
            }
            
            // Réponse AJAX
            if (isset($_POST['ajax'])) {
                header('Content-Type: application/json');
                echo json_encode([
                    'success' => !empty($success_message),
                    'message' => $success_message ?: $error_message
                ]);
                exit;
            }
            break;
            
        case 'delete_page':
            $page_id = (int)($_POST['page_id'] ?? 0);
            
            if ($page_id <= 0) {
                $error_message = "ID de page invalide.";
            } else {
                $page = $seoManager->getById($page_id);
                if (!$page) {
                    $error_message = "Page SEO non trouvée.";
                } else {
                    if ($seoManager->delete($page_id)) {
                        $success_message = "Page SEO '{$page['page_name']}' supprimée avec succès.";
                    } else {
                        $error_message = "Erreur lors de la suppression.";
                    }
                }
            }
            
            // Réponse AJAX
            if (isset($_POST['ajax'])) {
                header('Content-Type: application/json');
                echo json_encode([
                    'success' => !empty($success_message),
                    'message' => $success_message ?: $error_message
                ]);
                exit;
            }
            break;
    }
}

// Routes AJAX additionnelles
if ($_SERVER['REQUEST_METHOD'] === 'GET' && isset($_GET['action'])) {
    $action = $_GET['action'];
    
    switch ($action) {
        case 'get_page':
            $page_id = (int)($_GET['id'] ?? 0);
            if ($page_id > 0) {
                $page = $seoManager->getById($page_id);
                if ($page) {
                    header('Content-Type: application/json');
                    echo json_encode(['success' => true, 'page' => $page]);
                    exit;
                }
            }
            header('Content-Type: application/json');
            echo json_encode(['success' => false, 'message' => 'Page non trouvée']);
            exit;
            
        case 'preview':
            $page_id = (int)($_GET['id'] ?? 0);
            if ($page_id > 0) {
                $page = $seoManager->getById($page_id);
                if ($page) {
                    $preview = [
                        'title' => $page['page_title'],
                        'description' => $page['meta_description'],
                        'url' => $page['canonical_url'],
                        'og_title' => $page['og_title'],
                        'og_description' => $page['og_description'],
                        'og_image' => $page['og_image'],
                        'twitter_title' => $page['twitter_title'],
                        'twitter_description' => $page['twitter_description'],
                        'twitter_image' => $page['twitter_image']
                    ];
                    
                    header('Content-Type: application/json');
                    echo json_encode(['success' => true, 'preview' => $preview]);
                    exit;
                }
            }
            header('Content-Type: application/json');
            echo json_encode(['success' => false, 'message' => 'Page non trouvée']);
            exit;
            
        case 'seo_analysis':
            $page_id = (int)($_GET['id'] ?? 0);
            if ($page_id > 0) {
                $page = $seoManager->getById($page_id);
                if ($page) {
                    $analysis = getSEOAnalysisDetails($page);
                    
                    header('Content-Type: application/json');
                    echo json_encode(['success' => true, 'analysis' => $analysis]);
                    exit;
                }
            }
            header('Content-Type: application/json');
            echo json_encode(['success' => false, 'message' => 'Page non trouvée']);
            exit;
    }
}

// Pagination et recherche
$search = $_GET['search'] ?? '';
$page = max(1, (int)($_GET['page'] ?? 1));
$per_page = 10;
$offset = ($page - 1) * $per_page;

// Obtenir les pages SEO
$total_pages_count = $seoManager->countPages($search);
$seo_pages = $seoManager->getAllPages($search, $offset, $per_page);
$total_pages = ceil($total_pages_count / $per_page);

// Configuration pour le template
$page_title = "Gestion SEO";
$current_page = "seo";

// Fonction helper pour les paramètres de pagination
function buildPaginationParams($search) {
    return !empty($search) ? '&search=' . urlencode($search) : '';
}

/**
 * Calculer le score SEO d'une page (sur 100)
 */
function calculateSEOScore($page) {
    $score = 0;
    $maxScore = 100;
    
    // Titre (25 points max)
    if (!empty($page['page_title'])) {
        $titleLength = strlen($page['page_title']);
        if ($titleLength >= 30 && $titleLength <= 60) {
            $score += 25; // Titre longueur parfaite
        } elseif ($titleLength >= 20 && $titleLength <= 80) {
            $score += 20; // Titre longueur acceptable
        } else {
            $score += 10; // Titre présent mais pas optimal
        }
    }
    
    // Meta description (20 points max)
    if (!empty($page['meta_description'])) {
        $descLength = strlen($page['meta_description']);
        if ($descLength >= 120 && $descLength <= 160) {
            $score += 20; // Description longueur parfaite
        } elseif ($descLength >= 80 && $descLength <= 200) {
            $score += 15; // Description longueur acceptable
        } else {
            $score += 8; // Description présente mais pas optimale
        }
    }
    
    // Mots-clés (15 points max)
    if (!empty($page['meta_keywords'])) {
        $keywordCount = substr_count($page['meta_keywords'], ',') + 1;
        if ($keywordCount >= 3 && $keywordCount <= 10) {
            $score += 15; // Nombre de mots-clés optimal
        } elseif ($keywordCount >= 1 && $keywordCount <= 15) {
            $score += 10; // Nombre acceptable
        } else {
            $score += 5; // Mots-clés présents
        }
    }
    
    // Open Graph (15 points max)
    $ogComplete = 0;
    if (!empty($page['og_title'])) $ogComplete += 5;
    if (!empty($page['og_description'])) $ogComplete += 5;
    if (!empty($page['og_image'])) $ogComplete += 5;
    $score += $ogComplete;
    
    // Twitter Cards (10 points max)
    $twitterComplete = 0;
    if (!empty($page['twitter_title'])) $twitterComplete += 3;
    if (!empty($page['twitter_description'])) $twitterComplete += 3;
    if (!empty($page['twitter_image'])) $twitterComplete += 4;
    $score += $twitterComplete;
    
    // URL canonique (5 points max)
    if (!empty($page['canonical_url'])) {
        $score += 5;
    }
    
    // Meta robots (5 points max)
    if (!empty($page['meta_robots']) && $page['meta_robots'] !== 'noindex,nofollow') {
        $score += 5;
    }
    
    // Schema.org (5 points max)
    if (!empty($page['schema_type']) && $page['schema_type'] !== 'WebPage') {
        $score += 5;
    }
    
    return min($score, $maxScore);
}

/**
 * Obtenir la couleur du badge selon le score
 */
function getSEOScoreBadgeClass($score) {
    if ($score >= 80) return 'bg-success';
    elseif ($score >= 60) return 'bg-warning';
    elseif ($score >= 40) return 'bg-orange';
    else return 'bg-danger';
}

/**
 * Obtenir l'icône selon le score
 */
function getSEOScoreIcon($score) {
    if ($score >= 80) return 'ri-medal-line';
    elseif ($score >= 60) return 'ri-thumb-up-line';
    elseif ($score >= 40) return 'ri-thumb-down-line';
    else return 'ri-error-warning-line';
}

/**
 * Obtenir l'analyse détaillée du SEO
 */
function getSEOAnalysisDetails($page) {
    $analysis = [
        'page_name' => $page['page_name'],
        'total_score' => calculateSEOScore($page),
        'details' => []
    ];
    
    // Analyse du titre
    $titleLength = strlen($page['page_title'] ?? '');
    if (!empty($page['page_title'])) {
        if ($titleLength >= 30 && $titleLength <= 60) {
            $analysis['details']['title'] = ['status' => 'excellent', 'score' => 25, 'message' => "Titre parfait ({$titleLength} caractères)"];
        } elseif ($titleLength >= 20 && $titleLength <= 80) {
            $analysis['details']['title'] = ['status' => 'good', 'score' => 20, 'message' => "Titre correct ({$titleLength} caractères)"];
        } else {
            $analysis['details']['title'] = ['status' => 'warning', 'score' => 10, 'message' => "Titre trop " . ($titleLength < 30 ? 'court' : 'long') . " ({$titleLength} caractères)"];
        }
    } else {
        $analysis['details']['title'] = ['status' => 'error', 'score' => 0, 'message' => 'Titre manquant'];
    }
    
    // Analyse meta description
    $descLength = strlen($page['meta_description'] ?? '');
    if (!empty($page['meta_description'])) {
        if ($descLength >= 120 && $descLength <= 160) {
            $analysis['details']['description'] = ['status' => 'excellent', 'score' => 20, 'message' => "Description parfaite ({$descLength} caractères)"];
        } elseif ($descLength >= 80 && $descLength <= 200) {
            $analysis['details']['description'] = ['status' => 'good', 'score' => 15, 'message' => "Description correcte ({$descLength} caractères)"];
        } else {
            $analysis['details']['description'] = ['status' => 'warning', 'score' => 8, 'message' => "Description trop " . ($descLength < 120 ? 'courte' : 'longue') . " ({$descLength} caractères)"];
        }
    } else {
        $analysis['details']['description'] = ['status' => 'error', 'score' => 0, 'message' => 'Meta description manquante'];
    }
    
    // Analyse mots-clés
    if (!empty($page['meta_keywords'])) {
        $keywordCount = substr_count($page['meta_keywords'], ',') + 1;
        if ($keywordCount >= 3 && $keywordCount <= 10) {
            $analysis['details']['keywords'] = ['status' => 'excellent', 'score' => 15, 'message' => "Nombre optimal de mots-clés ({$keywordCount})"];
        } else {
            $analysis['details']['keywords'] = ['status' => 'warning', 'score' => 10, 'message' => "Ajustez le nombre de mots-clés ({$keywordCount})"];
        }
    } else {
        $analysis['details']['keywords'] = ['status' => 'error', 'score' => 0, 'message' => 'Mots-clés manquants'];
    }
    
    // Open Graph
    $ogScore = 0;
    $ogItems = [];
    if (!empty($page['og_title'])) { $ogScore += 5; $ogItems[] = 'Titre'; }
    if (!empty($page['og_description'])) { $ogScore += 5; $ogItems[] = 'Description'; }
    if (!empty($page['og_image'])) { $ogScore += 5; $ogItems[] = 'Image'; }
    
    if ($ogScore >= 15) {
        $analysis['details']['opengraph'] = ['status' => 'excellent', 'score' => 15, 'message' => 'Open Graph complet'];
    } elseif ($ogScore > 0) {
        $analysis['details']['opengraph'] = ['status' => 'warning', 'score' => $ogScore, 'message' => 'Open Graph partiel (' . implode(', ', $ogItems) . ')'];
    } else {
        $analysis['details']['opengraph'] = ['status' => 'error', 'score' => 0, 'message' => 'Open Graph manquant'];
    }
    
    // Twitter Cards
    $twitterScore = 0;
    if (!empty($page['twitter_title'])) $twitterScore += 3;
    if (!empty($page['twitter_description'])) $twitterScore += 3;
    if (!empty($page['twitter_image'])) $twitterScore += 4;
    
    if ($twitterScore >= 10) {
        $analysis['details']['twitter'] = ['status' => 'excellent', 'score' => 10, 'message' => 'Twitter Cards complet'];
    } elseif ($twitterScore > 0) {
        $analysis['details']['twitter'] = ['status' => 'warning', 'score' => $twitterScore, 'message' => 'Twitter Cards partiel'];
    } else {
        $analysis['details']['twitter'] = ['status' => 'error', 'score' => 0, 'message' => 'Twitter Cards manquant'];
    }
    
    // URL canonique
    if (!empty($page['canonical_url'])) {
        $analysis['details']['canonical'] = ['status' => 'excellent', 'score' => 5, 'message' => 'URL canonique présente'];
    } else {
        $analysis['details']['canonical'] = ['status' => 'error', 'score' => 0, 'message' => 'URL canonique manquante'];
    }
    
    return $analysis;
}

// Configuration pour le contenu de la page
ob_start();
?>

<!-- Messages d'alerte -->
<div id="alertContainer">
    <?php if ($success_message): ?>
        <div class="alert alert-success alert-dismissible fade show" role="alert">
            <i class="ri ri-check-circle-line me-2"></i>
            <?= htmlspecialchars($success_message) ?>
            <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
        </div>
    <?php endif; ?>
    
    <?php if ($error_message): ?>
        <div class="alert alert-danger alert-dismissible fade show" role="alert">
            <i class="ri ri-error-warning-line me-2"></i>
            <?= htmlspecialchars($error_message) ?>
            <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
        </div>
    <?php endif; ?>
</div>

<!-- CSS pour les scores SEO -->
<style>
.bg-orange {
    background-color: #fd7e14 !important;
}
.text-orange {
    color: #fd7e14 !important;
}
.border-orange {
    border-color: #fd7e14 !important;
}
</style>

<!-- Page Content -->
<div class="row">
    <div class="col-12">
        <!-- Page Header -->
        <div class="d-flex justify-content-between align-items-center mb-4">
            <div>
                <h4 class="fw-bold mb-1">
                    <i class="ri ri-search-eye-line me-2 text-primary"></i>Gestion SEO
                </h4>
                <p class="text-muted mb-0">Optimisez le référencement de vos pages</p>
            </div>
            
            <!-- Breadcrumb -->
            <nav aria-label="breadcrumb">
                <ol class="breadcrumb mb-0">
                    <li class="breadcrumb-item"><a href="index.php">Accueil</a></li>
                    <li class="breadcrumb-item active">Gestion SEO</li>
                </ol>
            </nav>
        </div>

        <div class="row">
            <!-- Statistiques -->
            <div class="col-xl-3 col-lg-4 col-md-6 mb-4">
                <div class="card border border-primary">
                    <div class="card-body text-center">
                        <div class="mx-auto mb-3">
                            <i class="ri ri-file-search-line text-primary" style="font-size: 3rem;"></i>
                        </div>
                        <h4 class="fw-bold text-primary"><?= $total_pages_count ?></h4>
                        <p class="mb-0 text-muted">Pages SEO</p>
                    </div>
                </div>
            </div>
            
            <div class="col-xl-3 col-lg-4 col-md-6 mb-4">
                <div class="card border border-success">
                    <div class="card-body text-center">
                        <div class="mx-auto mb-3">
                            <i class="ri ri-checkbox-circle-line text-success" style="font-size: 3rem;"></i>
                        </div>
                        <h4 class="fw-bold text-success">
                            <?php 
                            $active_count = 0;
                            foreach ($seo_pages as $page) {
                                if ($page['status'] === 'active') $active_count++;
                            }
                            echo $active_count;
                            ?>
                        </h4>
                        <p class="mb-0 text-muted">Actives</p>
                    </div>
                </div>
            </div>
            
            <div class="col-xl-3 col-lg-4 col-md-6 mb-4">
                <div class="card border border-warning">
                    <div class="card-body text-center">
                        <div class="mx-auto mb-3">
                            <i class="ri ri-medal-line text-warning" style="font-size: 3rem;"></i>
                        </div>
                        <h4 class="fw-bold text-warning">
                            <?php 
                            $totalScore = 0;
                            $pageCount = count($seo_pages);
                            if ($pageCount > 0) {
                                foreach ($seo_pages as $page) {
                                    $totalScore += calculateSEOScore($page);
                                }
                                $averageScore = round($totalScore / $pageCount);
                                echo $averageScore . '/100';
                            } else {
                                echo '0/100';
                            }
                            ?>
                        </h4>
                        <p class="mb-0 text-muted">Score Moyen</p>
                    </div>
                </div>
            </div>

            <!-- Bouton d'action -->
            <div class="col-xl-3 col-lg-4 col-md-12 mb-4">
                <div class="card border border-info">
                    <div class="card-body d-flex justify-content-between align-items-center">
                        <div>
                            <h6 class="fw-bold text-info mb-1">Nouvelle Page SEO</h6>
                            <p class="mb-0 text-muted">Optimiser une nouvelle page</p>
                        </div>
                        <a href="edit-seo.php" class="btn btn-info">
                            <i class="ri ri-add-line me-2"></i>Créer
                        </a>
                    </div>
                </div>
            </div>
        </div>

        <!-- Recherche -->
        <div class="card border border-info mb-4">
            <div class="card-header">
                <h5 class="mb-0 text-info">
                    <i class="ri ri-search-line me-2"></i>Recherche
                </h5>
            </div>
            <div class="card-body">
                <form method="GET" class="row g-3">
                    <div class="col-md-8">
                        <input type="text" 
                               name="search" 
                               class="form-control" 
                               placeholder="Rechercher par nom de page ou titre..."
                               value="<?= htmlspecialchars($search) ?>">
                    </div>
                    <div class="col-md-2">
                        <button type="submit" class="btn btn-primary w-100">
                            <i class="ri ri-search-line me-2"></i>Rechercher
                        </button>
                    </div>
                    <div class="col-md-2">
                        <?php if ($search): ?>
                            <a href="seo-management.php" class="btn btn-outline-secondary w-100">
                                <i class="ri ri-close-line me-2"></i>Effacer
                            </a>
                        <?php endif; ?>
                    </div>
                </form>
            </div>
        </div>

        <!-- Table des pages SEO -->
        <div class="card border border-warning">
            <div class="card-header">
                <h5 class="mb-0 text-warning">
                    <i class="ri ri-settings-3-line me-2"></i>Pages SEO
                </h5>
            </div>
            
            <div class="card-body p-0">
                <?php if (empty($seo_pages)): ?>
                    <div class="text-center py-5">
                        <div class="mx-auto mb-3">
                            <i class="ri ri-search-eye-line text-muted" style="font-size: 4rem;"></i>
                        </div>
                        <h6 class="text-muted">
                            <?php if ($search): ?>
                                Aucune page SEO trouvée pour "<?= htmlspecialchars($search) ?>"
                            <?php else: ?>
                                Aucune page SEO configurée
                            <?php endif; ?>
                        </h6>
                        <p class="text-muted mb-0">Commencez par créer une nouvelle page SEO</p>
                    </div>
                <?php else: ?>
                    <div class="table-responsive">
                        <table class="table table-hover mb-0">
                            <thead class="table-light">
                                <tr>
                                    <th>Page</th>
                                    <th>Titre</th>
                                    <th>Meta Description</th>
                                    <th>Score SEO</th>
                                    <th>Statut</th>
                                    <th>Modifiée</th>
                                    <th class="text-center">Actions</th>
                                </tr>
                            </thead>
                            <tbody>
                                <?php foreach ($seo_pages as $page): ?>
                                    <tr>
                                        <td class="align-middle">
                                            <span class="badge bg-primary"><?= htmlspecialchars($page['page_name']) ?></span>
                                        </td>
                                        <td class="align-middle">
                                            <span class="fw-medium"><?= htmlspecialchars($page['page_title']) ?></span>
                                        </td>
                                        <td class="align-middle">
                                            <small class="text-muted">
                                                <?= htmlspecialchars(substr($page['meta_description'] ?? '', 0, 100)) ?><?= strlen($page['meta_description'] ?? '') > 100 ? '...' : '' ?>
                                            </small>
                                        </td>
                                        <td class="align-middle">
                                            <?php 
                                            $seoScore = calculateSEOScore($page);
                                            $badgeClass = getSEOScoreBadgeClass($seoScore);
                                            $icon = getSEOScoreIcon($seoScore);
                                            ?>
                                            <span class="badge <?= $badgeClass ?> d-flex align-items-center justify-content-center" 
                                                  style="min-width: 60px; font-size: 0.8rem; cursor: pointer;" 
                                                  title="Cliquez pour voir l'analyse détaillée"
                                                  onclick="showSEOAnalysis(<?= $page['id'] ?>)">
                                                <i class="<?= $icon ?> me-1"></i>
                                                <?= $seoScore ?>/100
                                            </span>
                                            <?php if ($seoScore < 60): ?>
                                                <div class="mt-1">
                                                    <small class="text-warning">
                                                        <i class="ri ri-information-line"></i> Optimisation recommandée
                                                    </small>
                                                </div>
                                            <?php endif; ?>
                                        </td>
                                        <td class="align-middle">
                                            <?php if ($page['status'] === 'active'): ?>
                                                <span class="badge bg-success">
                                                    <i class="ri ri-checkbox-circle-line me-1"></i>Actif
                                                </span>
                                            <?php else: ?>
                                                <span class="badge bg-danger">
                                                    <i class="ri ri-close-circle-line me-1"></i>Inactif
                                                </span>
                                            <?php endif; ?>
                                        </td>
                                        <td class="align-middle">
                                            <small class="text-muted">
                                                <i class="ri ri-time-line me-1"></i>
                                                <?= date('d/m/Y H:i', strtotime($page['updated_at'])) ?>
                                            </small>
                                        </td>
                                        <td class="text-center align-middle">
                                            <div class="dropdown">
                                                <button class="btn btn-sm btn-outline-primary dropdown-toggle" 
                                                        type="button" 
                                                        data-bs-toggle="dropdown">
                                                    <i class="ri ri-more-2-line"></i>
                                                </button>
                                                <ul class="dropdown-menu">
                                                    <li>
                                                        <a class="dropdown-item" 
                                                           href="edit-seo.php?id=<?= $page['id'] ?>">
                                                            <i class="ri ri-edit-line me-2"></i>Modifier
                                                        </a>
                                                    </li>
                                                    <li>
                                                        <button class="dropdown-item text-info" 
                                                                onclick="previewSEO(<?= $page['id'] ?>)">
                                                            <i class="ri ri-eye-line me-2"></i>Aperçu
                                                        </button>
                                                    </li>
                                                    <li><hr class="dropdown-divider"></li>
                                                    <li>
                                                        <button class="dropdown-item text-danger" 
                                                                onclick="deleteSEOPage(<?= $page['id'] ?>, '<?= htmlspecialchars($page['page_name']) ?>')">
                                                            <i class="ri ri-delete-bin-line me-2"></i>Supprimer
                                                        </button>
                                                    </li>
                                                </ul>
                                            </div>
                                        </td>
                                    </tr>
                                <?php endforeach; ?>
                            </tbody>
                        </table>
                    </div>
                <?php endif; ?>
            </div>

            <!-- Pagination -->
            <?php if ($total_pages > 1): ?>
                <div class="card-footer">
                    <nav aria-label="Pagination">
                        <ul class="pagination justify-content-center mb-0">
                            <?php 
                            $paginationParams = buildPaginationParams($search);
                            ?>
                            
                            <?php if ($page > 1): ?>
                                <li class="page-item">
                                    <a class="page-link" href="?page=<?= $page - 1 ?><?= $paginationParams ?>">
                                        <i class="ri ri-arrow-left-s-line"></i>
                                    </a>
                                </li>
                            <?php endif; ?>

                            <?php
                            $start = max(1, $page - 2);
                            $end = min($total_pages, $page + 2);
                            
                            for ($i = $start; $i <= $end; $i++):
                            ?>
                                <li class="page-item <?= $i == $page ? 'active' : '' ?>">
                                    <a class="page-link" href="?page=<?= $i ?><?= $paginationParams ?>">
                                        <?= $i ?>
                                    </a>
                                </li>
                            <?php endfor; ?>

                            <?php if ($page < $total_pages): ?>
                                <li class="page-item">
                                    <a class="page-link" href="?page=<?= $page + 1 ?><?= $paginationParams ?>">
                                        <i class="ri ri-arrow-right-s-line"></i>
                                    </a>
                                </li>
                            <?php endif; ?>
                        </ul>
                    </nav>
                </div>
            <?php endif; ?>
        </div>
    </div>
</div>

<!-- Modal SEO -->
<div class="modal fade" id="seoModal" tabindex="-1">
    <div class="modal-dialog modal-xl">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title">
                    <i class="ri ri-search-eye-line me-2"></i>Configuration SEO
                </h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
            </div>
            
            <form id="seoForm">
                <div class="modal-body">
                    <input type="hidden" id="seoId" name="seo_id">
                    
                    <!-- Onglets -->
                    <ul class="nav nav-tabs mb-4" role="tablist">
                        <li class="nav-item">
                            <button class="nav-link active" id="basic-tab" data-bs-toggle="tab" data-bs-target="#basic" type="button">
                                <i class="ri ri-settings-3-line me-2"></i>Paramètres de Base
                            </button>
                        </li>
                        <li class="nav-item">
                            <button class="nav-link" id="social-tab" data-bs-toggle="tab" data-bs-target="#social" type="button">
                                <i class="ri ri-share-box-line me-2"></i>Réseaux Sociaux
                            </button>
                        </li>
                        <li class="nav-item">
                            <button class="nav-link" id="advanced-tab" data-bs-toggle="tab" data-bs-target="#advanced" type="button">
                                <i class="ri ri-code-s-slash-line me-2"></i>Avancé
                            </button>
                        </li>
                    </ul>
                    
                    <div class="tab-content">
                        <!-- Onglet Paramètres de Base -->
                        <div class="tab-pane fade show active" id="basic" role="tabpanel">
                            <div class="row g-3">
                                <div class="col-md-6">
                                    <label for="pageName" class="form-label">
                                        <i class="ri ri-file-text-line me-2"></i>Nom de la page *
                                    </label>
                                    <input type="text" class="form-control" id="pageName" name="page_name" required 
                                           placeholder="Ex: home, services, contact">
                                    <div class="form-text">Identifiant unique de la page</div>
                                </div>
                                
                                <div class="col-md-6">
                                    <label for="status" class="form-label">
                                        <i class="ri ri-toggle-line me-2"></i>Statut
                                    </label>
                                    <select class="form-select" id="status" name="status">
                                        <option value="active">Actif</option>
                                        <option value="inactive">Inactif</option>
                                    </select>
                                </div>
                                
                                <div class="col-12">
                                    <label for="pageTitle" class="form-label">
                                        <i class="ri ri-h-1 me-2"></i>Titre de la page *
                                    </label>
                                    <input type="text" class="form-control" id="pageTitle" name="page_title" required 
                                           maxlength="60" placeholder="Titre optimisé pour le SEO">
                                    <div class="form-text">Recommandé : 50-60 caractères</div>
                                </div>
                                
                                <div class="col-12">
                                    <label for="seoMetaDesc" class="form-label">
                                        <i class="ri ri-file-text-line me-2"></i>Meta Description
                                    </label>
                                    <textarea class="form-control" id="seoMetaDesc" name="meta_description" 
                                              rows="3" maxlength="160" 
                                              placeholder="Description concise et attrayante de la page"></textarea>
                                    <div class="form-text">Recommandé : 150-160 caractères</div>
                                </div>
                                
                                <div class="col-md-6">
                                    <label for="metaKeywords" class="form-label">
                                        <i class="ri ri-hashtag me-2"></i>Mots-clés
                                    </label>
                                    <input type="text" class="form-control" id="metaKeywords" name="meta_keywords" 
                                           placeholder="mot-clé1, mot-clé2, mot-clé3">
                                    <div class="form-text">Séparés par des virgules</div>
                                </div>
                                
                                <div class="col-md-6">
                                    <label for="canonicalUrl" class="form-label">
                                        <i class="ri ri-links-line me-2"></i>URL Canonique
                                    </label>
                                    <input type="url" class="form-control" id="canonicalUrl" name="canonical_url" 
                                           placeholder="https://example.com/page">
                                    <div class="form-text">URL officielle de la page</div>
                                </div>
                                
                                <div class="col-md-6">
                                    <label for="metaRobots" class="form-label">
                                        <i class="ri ri-robot-line me-2"></i>Meta Robots
                                    </label>
                                    <select class="form-select" id="metaRobots" name="meta_robots">
                                        <option value="index,follow">Index, Follow</option>
                                        <option value="noindex,follow">No Index, Follow</option>
                                        <option value="index,nofollow">Index, No Follow</option>
                                        <option value="noindex,nofollow">No Index, No Follow</option>
                                    </select>
                                </div>
                                
                                <div class="col-md-6">
                                    <label for="schemaType" class="form-label">
                                        <i class="ri ri-code-box-line me-2"></i>Type Schema
                                    </label>
                                    <select class="form-select" id="schemaType" name="schema_type">
                                        <option value="WebPage">WebPage</option>
                                        <option value="Article">Article</option>
                                        <option value="ContactPage">ContactPage</option>
                                        <option value="AboutPage">AboutPage</option>
                                        <option value="Service">Service</option>
                                    </select>
                                </div>
                            </div>
                        </div>
                        
                        <!-- Onglet Réseaux Sociaux -->
                        <div class="tab-pane fade" id="social" role="tabpanel">
                            <div class="row g-3">
                                <div class="col-12">
                                    <h6 class="text-primary mb-3">
                                        <i class="ri ri-facebook-circle-line me-2"></i>Open Graph (Facebook, LinkedIn)
                                    </h6>
                                </div>
                                
                                <div class="col-md-6">
                                    <label for="ogTitle" class="form-label">Titre OG</label>
                                    <input type="text" class="form-control" id="ogTitle" name="og_title" 
                                           maxlength="60" placeholder="Titre pour les réseaux sociaux">
                                </div>
                                
                                <div class="col-md-6">
                                    <label for="ogType" class="form-label">Type OG</label>
                                    <select class="form-select" id="ogType" name="og_type">
                                        <option value="website">Website</option>
                                        <option value="article">Article</option>
                                        <option value="profile">Profile</option>
                                    </select>
                                </div>
                                
                                <div class="col-12">
                                    <label for="ogDescription" class="form-label">Description OG</label>
                                    <textarea class="form-control" id="ogDescription" name="og_description" 
                                              rows="3" maxlength="200" 
                                              placeholder="Description pour les réseaux sociaux"></textarea>
                                </div>
                                
                                <div class="col-12">
                                    <label for="ogImage" class="form-label">Image OG</label>
                                    <input type="url" class="form-control" id="ogImage" name="og_image" 
                                           placeholder="https://example.com/image.jpg">
                                    <div class="form-text">Recommandé : 1200x630 pixels</div>
                                </div>
                                
                                <div class="col-12">
                                    <hr>
                                    <h6 class="text-info mb-3">
                                        <i class="ri ri-twitter-line me-2"></i>Twitter Cards
                                    </h6>
                                </div>
                                
                                <div class="col-md-6">
                                    <label for="twitterCard" class="form-label">Type de carte</label>
                                    <select class="form-select" id="twitterCard" name="twitter_card">
                                        <option value="summary_large_image">Summary Large Image</option>
                                        <option value="summary">Summary</option>
                                        <option value="app">App</option>
                                    </select>
                                </div>
                                
                                <div class="col-md-6">
                                    <label for="twitterTitle" class="form-label">Titre Twitter</label>
                                    <input type="text" class="form-control" id="twitterTitle" name="twitter_title" 
                                           maxlength="70" placeholder="Titre pour Twitter">
                                </div>
                                
                                <div class="col-12">
                                    <label for="twitterDescription" class="form-label">Description Twitter</label>
                                    <textarea class="form-control" id="twitterDescription" name="twitter_description" 
                                              rows="3" maxlength="200" 
                                              placeholder="Description pour Twitter"></textarea>
                                </div>
                                
                                <div class="col-12">
                                    <label for="twitterImage" class="form-label">Image Twitter</label>
                                    <input type="url" class="form-control" id="twitterImage" name="twitter_image" 
                                           placeholder="https://example.com/twitter-image.jpg">
                                    <div class="form-text">Recommandé : 1024x512 pixels</div>
                                </div>
                            </div>
                        </div>
                        
                        <!-- Onglet Avancé -->
                        <div class="tab-pane fade" id="advanced" role="tabpanel">
                            <div class="col-12">
                                <label for="customHead" class="form-label">
                                    <i class="ri ri-code-s-slash-line me-2"></i>Code HTML personnalisé
                                </label>
                                <textarea class="form-control font-monospace" id="customHead" name="custom_head" 
                                          rows="10" 
                                          placeholder="<!-- Code HTML additionnel pour le <head> -->&#10;<script>&#10;// Analytics, pixels de suivi, etc.&#10;</script>"></textarea>
                                <div class="form-text">
                                    Code inséré dans le &lt;head&gt; de la page. Utilisez pour Analytics, pixels de tracking, etc.
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
                
                <div class="modal-footer">
                    <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">
                        <i class="ri ri-close-line me-2"></i>Annuler
                    </button>
                    <button type="submit" class="btn btn-primary">
                        <i class="ri ri-save-line me-2"></i>Enregistrer
                    </button>
                </div>
            </form>
        </div>
    </div>
</div>

<!-- Modal Aperçu SEO -->
<div class="modal fade" id="previewModal" tabindex="-1">
    <div class="modal-dialog modal-lg">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title">
                    <i class="ri ri-eye-line me-2"></i>Aperçu SEO
                </h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
            </div>
            
            <div class="modal-body">
                <div id="seoPreview"></div>
            </div>
        </div>
    </div>
</div>

<!-- Modal Analyse SEO -->
<div class="modal fade" id="seoAnalysisModal" tabindex="-1">
    <div class="modal-dialog modal-lg">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title">
                    <i class="ri ri-bar-chart-line me-2"></i>Analyse SEO Détaillée
                </h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
            </div>
            <div class="modal-body">
                <div id="seoAnalysisContent"></div>
            </div>
        </div>
    </div>
</div>

<script>
// Afficher les alertes
function showAlert(message, type = 'info') {
    const alertContainer = document.getElementById('alertContainer');
    const alertHtml = `
        <div class="alert alert-${type} alert-dismissible fade show" role="alert">
            <i class="ri ${type === 'success' ? 'ri-check-circle-line' : 'ri-error-warning-line'} me-2"></i>
            ${message}
            <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
        </div>
    `;
    alertContainer.innerHTML = alertHtml;
    
    // Auto-hide après 5 secondes
    setTimeout(() => {
        const alert = alertContainer.querySelector('.alert');
        if (alert) {
            alert.remove();
        }
    }, 5000);
}

// Afficher l'analyse SEO détaillée
function showSEOAnalysis(pageId) {
    fetch(`seo-management.php?action=seo_analysis&id=${pageId}`)
        .then(response => response.json())
        .then(data => {
            if (data.success) {
                displaySEOAnalysis(data.analysis);
                const modal = new bootstrap.Modal(document.getElementById('seoAnalysisModal'));
                modal.show();
            } else {
                showAlert('Erreur lors du chargement de l\'analyse SEO', 'danger');
            }
        })
        .catch(error => {
            console.error('Erreur:', error);
            showAlert('Erreur de connexion au serveur.', 'danger');
        });
}

// Afficher les détails de l'analyse SEO
function displaySEOAnalysis(analysis) {
    const content = document.getElementById('seoAnalysisContent');
    
    let html = `
        <div class="row mb-4">
            <div class="col-12">
                <div class="alert alert-info">
                    <h5 class="mb-2">
                        <i class="ri ri-file-text-line me-2"></i>
                        Page: <strong>${analysis.page_name}</strong>
                    </h5>
                    <div class="d-flex align-items-center">
                        <span class="badge bg-primary fs-6 me-2">${analysis.total_score}/100</span>
                        <span class="text-muted">Score SEO Global</span>
                    </div>
                </div>
            </div>
        </div>
        
        <div class="row">
    `;
    
    const statusIcons = {
        'excellent': 'ri-check-circle-fill text-success',
        'good': 'ri-check-line text-info', 
        'warning': 'ri-alert-line text-warning',
        'error': 'ri-close-circle-fill text-danger'
    };
    
    const statusLabels = {
        'excellent': 'Excellent',
        'good': 'Bon',
        'warning': 'À améliorer',
        'error': 'Problème'
    };
    
    Object.entries(analysis.details).forEach(([key, detail]) => {
        const icon = statusIcons[detail.status] || 'ri-information-line';
        const label = statusLabels[detail.status] || 'Inconnu';
        
        html += `
            <div class="col-md-6 mb-3">
                <div class="card h-100">
                    <div class="card-body">
                        <div class="d-flex justify-content-between align-items-start mb-2">
                            <h6 class="card-title mb-0">${getAnalysisTitle(key)}</h6>
                            <span class="badge bg-secondary">${detail.score}pts</span>
                        </div>
                        <div class="d-flex align-items-center mb-2">
                            <i class="${icon} me-2"></i>
                            <span class="fw-medium">${label}</span>
                        </div>
                        <p class="card-text small text-muted mb-0">${detail.message}</p>
                    </div>
                </div>
            </div>
        `;
    });
    
    html += `
        </div>
        <div class="row mt-4">
            <div class="col-12">
                <div class="alert alert-light">
                    <h6><i class="ri ri-lightbulb-line me-2"></i>Recommandations</h6>
                    <ul class="mb-0 small">
                        ${getRecommendations(analysis)}
                    </ul>
                </div>
            </div>
        </div>
    `;
    
    content.innerHTML = html;
}

// Obtenir le titre de chaque section d'analyse
function getAnalysisTitle(key) {
    const titles = {
        'title': 'Titre de la Page',
        'description': 'Meta Description', 
        'keywords': 'Mots-clés',
        'opengraph': 'Open Graph',
        'twitter': 'Twitter Cards',
        'canonical': 'URL Canonique'
    };
    return titles[key] || key;
}

// Générer les recommandations
function getRecommendations(analysis) {
    const recommendations = [];
    
    Object.entries(analysis.details).forEach(([key, detail]) => {
        if (detail.status === 'error' || detail.status === 'warning') {
            switch(key) {
                case 'title':
                    recommendations.push('Optimisez votre titre entre 30-60 caractères');
                    break;
                case 'description':
                    recommendations.push('Rédigez une meta description de 120-160 caractères');
                    break;
                case 'keywords':
                    recommendations.push('Ajoutez 3-10 mots-clés pertinents');
                    break;
                case 'opengraph':
                    recommendations.push('Complétez les données Open Graph pour les réseaux sociaux');
                    break;
                case 'twitter':
                    recommendations.push('Ajoutez les Twitter Cards pour un meilleur partage');
                    break;
                case 'canonical':
                    recommendations.push('Définissez une URL canonique pour éviter le contenu dupliqué');
                    break;
            }
        }
    });
    
    if (recommendations.length === 0) {
        recommendations.push('Excellent travail ! Votre SEO est bien optimisé.');
    }
    
    return recommendations.map(r => `<li>${r}</li>`).join('');
}

// Note: La fonction editSEOPage a été remplacée par une page dédiée edit-seo.php

// Aperçu SEO
function previewSEO(pageId) {
    fetch(`seo-management.php?action=preview&id=${pageId}`)
        .then(response => response.json())
        .then(data => {
            if (data.success) {
                const preview = data.preview;
                document.getElementById('seoPreview').innerHTML = `
                    <div class="row g-4">
                        <div class="col-12">
                            <h6 class="text-primary">Google Search Preview</h6>
                            <div class="border p-3 rounded bg-light">
                                <div class="text-primary fw-bold">${preview.title}</div>
                                <div class="text-success small">${preview.url || 'https://example.com'}</div>
                                <div class="text-muted small">${preview.description}</div>
                            </div>
                        </div>
                        
                        <div class="col-md-6">
                            <h6 class="text-primary">Facebook Preview</h6>
                            <div class="border rounded">
                                ${preview.og_image ? `<img src="${preview.og_image}" class="w-100" style="height: 200px; object-fit: cover;">` : '<div class="bg-light text-center py-5">Aucune image</div>'}
                                <div class="p-3">
                                    <div class="fw-bold">${preview.og_title || preview.title}</div>
                                    <div class="text-muted small">${preview.og_description || preview.description}</div>
                                </div>
                            </div>
                        </div>
                        
                        <div class="col-md-6">
                            <h6 class="text-info">Twitter Preview</h6>
                            <div class="border rounded">
                                ${preview.twitter_image ? `<img src="${preview.twitter_image}" class="w-100" style="height: 200px; object-fit: cover;">` : '<div class="bg-light text-center py-5">Aucune image</div>'}
                                <div class="p-3">
                                    <div class="fw-bold">${preview.twitter_title || preview.title}</div>
                                    <div class="text-muted small">${preview.twitter_description || preview.description}</div>
                                </div>
                            </div>
                        </div>
                    </div>
                `;
                
                const modal = new bootstrap.Modal(document.getElementById('previewModal'));
                modal.show();
            } else {
                showAlert(data.message || 'Erreur lors du chargement de l\'aperçu', 'danger');
            }
        })
        .catch(error => {
            console.error('Erreur:', error);
            showAlert('Erreur de connexion au serveur.', 'danger');
        });
}

// Supprimer une page SEO
function deleteSEOPage(pageId, pageName) {
    if (confirm(`Êtes-vous sûr de vouloir supprimer la page SEO "${pageName}" ?\n\nCette action est irréversible.`)) {
        const formData = new FormData();
        formData.append('action', 'delete_page');
        formData.append('page_id', pageId);
        formData.append('ajax', '1');
        
        fetch('seo-management.php', {
            method: 'POST',
            body: formData
        })
        .then(response => response.json())
        .then(data => {
            if (data.success) {
                showAlert(data.message, 'success');
                
                // Recharger la page après 1 seconde
                setTimeout(() => location.reload(), 1000);
            } else {
                showAlert(data.message, 'danger');
            }
        })
        .catch(error => {
            console.error('Erreur:', error);
            showAlert('Erreur de connexion au serveur.', 'danger');
        });
    }
}

// Auto-complétion des champs sociaux
document.getElementById('pageTitle').addEventListener('input', function() {
    const title = this.value;
    if (!document.getElementById('ogTitle').value) {
        document.getElementById('ogTitle').value = title;
    }
    if (!document.getElementById('twitterTitle').value) {
        document.getElementById('twitterTitle').value = title;
    }
});

// Auto-complétion pour le nouveau champ Meta Description
document.addEventListener('DOMContentLoaded', function() {
    // Attendre que le champ soit disponible (après édition)
    setTimeout(() => {
        const metaDescField = document.getElementById('seoMetaDesc');
        if (metaDescField) {
            metaDescField.addEventListener('input', function() {
                const description = this.value;
                if (!document.getElementById('ogDescription').value) {
                    document.getElementById('ogDescription').value = description;
                }
                if (!document.getElementById('twitterDescription').value) {
                    document.getElementById('twitterDescription').value = description;
                }
            });
        }
    }, 1000);
});
</script>

<?php
// Capturer le contenu
$page_content = ob_get_clean();

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