<?php
/**
 * Helper SEO - Intégration des métadonnées SEO dans les pages - SERVICES-AE
 */

// Inclure uniquement si pas déjà inclus
if (!function_exists('getSEOData')) {
    
    /**
     * Obtenir les données SEO d'une page
     */
    function getSEOData($pageName) {
        static $pdo_instance = null;
        
        try {
            // Initialiser la connexion une seule fois
            if ($pdo_instance === null) {
                // Configuration de la base de données
                $dsn = "mysql:host=localhost;dbname=serv;charset=utf8mb4";
                $options = [
                    PDO::ATTR_ERRMODE            => PDO::ERRMODE_EXCEPTION,
                    PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC,
                    PDO::ATTR_EMULATE_PREPARES   => false,
                    PDO::MYSQL_ATTR_INIT_COMMAND => "SET NAMES utf8mb4"
                ];
                
                $pdo_instance = new PDO($dsn, 'root', '', $options);
            }
            
            $stmt = $pdo_instance->prepare("SELECT * FROM seo_pages WHERE page_name = ? AND status = 'active'");
            $stmt->execute([$pageName]);
            return $stmt->fetch(PDO::FETCH_ASSOC);
            
        } catch (Exception $e) {
            error_log("getSEOData Error: " . $e->getMessage());
            return false;
        }
    }
    
    /**
     * Générer les balises SEO HTML pour une page
     */
    function generateSEOTags($pageName, $defaultTitle = 'SERVICES-AE', $defaultDescription = '') {
        $seoData = getSEOData($pageName);
        
        // Utiliser les données SEO ou les valeurs par défaut
        $title = $seoData['page_title'] ?? $defaultTitle;
        $description = $seoData['meta_description'] ?? $defaultDescription;
        $keywords = $seoData['meta_keywords'] ?? '';
        $robots = $seoData['meta_robots'] ?? 'index,follow';
        $canonical = $seoData['canonical_url'] ?? '';
        
        // Open Graph
        $ogTitle = $seoData['og_title'] ?? $title;
        $ogDescription = $seoData['og_description'] ?? $description;
        $ogImage = $seoData['og_image'] ?? '';
        $ogType = $seoData['og_type'] ?? 'website';
        
        // Twitter
        $twitterCard = $seoData['twitter_card'] ?? 'summary_large_image';
        $twitterTitle = $seoData['twitter_title'] ?? $title;
        $twitterDescription = $seoData['twitter_description'] ?? $description;
        $twitterImage = $seoData['twitter_image'] ?? '';
        
        // Custom Head
        $customHead = $seoData['custom_head'] ?? '';
        
        // Générer le HTML
        $html = [];
        
        // Title
        $html[] = '<title>' . htmlspecialchars($title) . '</title>';
        
        // Meta tags de base
        if ($description) {
            $html[] = '<meta name="description" content="' . htmlspecialchars($description) . '">';
        }
        
        if ($keywords) {
            $html[] = '<meta name="keywords" content="' . htmlspecialchars($keywords) . '">';
        }
        
        $html[] = '<meta name="robots" content="' . htmlspecialchars($robots) . '">';
        
        if ($canonical) {
            $html[] = '<link rel="canonical" href="' . htmlspecialchars($canonical) . '">';
        }
        
        // Open Graph
        $html[] = '<meta property="og:title" content="' . htmlspecialchars($ogTitle) . '">';
        if ($ogDescription) {
            $html[] = '<meta property="og:description" content="' . htmlspecialchars($ogDescription) . '">';
        }
        $html[] = '<meta property="og:type" content="' . htmlspecialchars($ogType) . '">';
        if ($ogImage) {
            $html[] = '<meta property="og:image" content="' . htmlspecialchars($ogImage) . '">';
        }
        
        // Twitter
        $html[] = '<meta name="twitter:card" content="' . htmlspecialchars($twitterCard) . '">';
        $html[] = '<meta name="twitter:title" content="' . htmlspecialchars($twitterTitle) . '">';
        if ($twitterDescription) {
            $html[] = '<meta name="twitter:description" content="' . htmlspecialchars($twitterDescription) . '">';
        }
        if ($twitterImage) {
            $html[] = '<meta name="twitter:image" content="' . htmlspecialchars($twitterImage) . '">';
        }
        
        // Custom head code
        if ($customHead) {
            $html[] = $customHead;
        }
        
        return implode("\n", $html);
    }
    
    /**
     * Afficher les balises SEO (echo directement)
     */
    function displaySEOTags($pageName, $defaultTitle = 'SERVICES-AE', $defaultDescription = '') {
        echo generateSEOTags($pageName, $defaultTitle, $defaultDescription);
    }
    
    /**
     * Obtenir uniquement le titre SEO d'une page
     */
    function getSEOTitle($pageName, $defaultTitle = 'SERVICES-AE') {
        $seoData = getSEOData($pageName);
        return $seoData['page_title'] ?? $defaultTitle;
    }
    
    /**
     * Obtenir uniquement la description SEO d'une page
     */
    function getSEODescription($pageName, $defaultDescription = '') {
        $seoData = getSEOData($pageName);
        return $seoData['meta_description'] ?? $defaultDescription;
    }
    
    /**
     * Vérifier si une page a des données SEO configurées
     */
    function hasSEOData($pageName) {
        $seoData = getSEOData($pageName);
        return $seoData !== false;
    }
    
    /**
     * Obtenir toutes les pages SEO actives (pour sitemap par exemple)
     */
    function getAllActiveSEOPages() {
        try {
            require_once __DIR__ . '/config/db.php';
            
            $stmt = $pdo->prepare("SELECT page_name, page_title, canonical_url, updated_at FROM seo_pages WHERE status = 'active' ORDER BY page_name");
            $stmt->execute();
            return $stmt->fetchAll(PDO::FETCH_ASSOC);
            
        } catch (Exception $e) {
            error_log("getAllActiveSEOPages Error: " . $e->getMessage());
            return [];
        }
    }
}
?>