<?php
/**
 * Classe SEOManager - Gestion des optimisations SEO - SERVICES-AE
 */

class SEOManager {
    private $pdo;
    private $table = 'seo_pages';
    
    public function __construct($pdo) {
        $this->pdo = $pdo;
    }
    
    /**
     * Créer la table SEO si elle n'existe pas
     */
    public function createTable() {
        $sql = "CREATE TABLE IF NOT EXISTS `{$this->table}` (
          `id` int(11) NOT NULL AUTO_INCREMENT,
          `page_name` varchar(100) NOT NULL UNIQUE,
          `page_title` varchar(255) NOT NULL,
          `meta_description` text,
          `meta_keywords` text,
          `meta_robots` varchar(50) DEFAULT 'index,follow',
          `canonical_url` varchar(255),
          `og_title` varchar(255),
          `og_description` text,
          `og_image` varchar(255),
          `og_type` varchar(50) DEFAULT 'website',
          `twitter_card` varchar(50) DEFAULT 'summary_large_image',
          `twitter_title` varchar(255),
          `twitter_description` text,
          `twitter_image` varchar(255),
          `schema_type` varchar(50) DEFAULT 'WebPage',
          `custom_head` text,
          `status` enum('active','inactive') NOT NULL DEFAULT 'active',
          `created_at` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP,
          `updated_at` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
          PRIMARY KEY (`id`),
          KEY `page_name` (`page_name`),
          KEY `status` (`status`)
        ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci";
        
        try {
            $this->pdo->exec($sql);
            
            // Insérer des données par défaut
            $this->insertDefaultPages();
            
            return true;
        } catch (PDOException $e) {
            error_log("SEOManager::createTable Error: " . $e->getMessage());
            return false;
        }
    }
    
    /**
     * Insérer les pages par défaut
     */
    private function insertDefaultPages() {
        $defaultPages = [
            [
                'page_name' => 'home',
                'page_title' => 'SERVICES-AE - Services Informatiques Professionnels',
                'meta_description' => 'SERVICES-AE offre des services informatiques professionnels : réparation d\'ordinateurs, récupération de données, support technique et solutions réseau.',
                'meta_keywords' => 'services informatiques, réparation ordinateur, récupération données, support technique, solutions réseau',
                'og_title' => 'SERVICES-AE - Votre Expert Informatique',
                'og_description' => 'Solutions informatiques complètes pour particuliers et entreprises. Réparation, maintenance et support technique professionnel.',
            ],
            [
                'page_name' => 'services',
                'page_title' => 'Nos Services - SERVICES-AE',
                'meta_description' => 'Découvrez nos services : réparation d\'ordinateurs, récupération de données, maintenance, support technique et solutions réseau personnalisées.',
                'meta_keywords' => 'réparation ordinateur, maintenance informatique, récupération données, support technique, installation logiciel',
            ],
            [
                'page_name' => 'contact',
                'page_title' => 'Contactez-nous - SERVICES-AE',
                'meta_description' => 'Contactez SERVICES-AE pour vos besoins informatiques. Devis gratuit, intervention rapide et support professionnel.',
                'meta_keywords' => 'contact, devis informatique, intervention rapide, support client, services-ae',
            ],
            [
                'page_name' => 'about',
                'page_title' => 'À Propos - SERVICES-AE',
                'meta_description' => 'SERVICES-AE, votre partenaire informatique de confiance. Expertise, professionnalisme et solutions sur mesure depuis plusieurs années.',
                'meta_keywords' => 'à propos, expertise informatique, partenaire informatique, professionnalisme, services-ae',
            ]
        ];
        
        foreach ($defaultPages as $page) {
            $stmt = $this->pdo->prepare("INSERT IGNORE INTO {$this->table} (page_name, page_title, meta_description, meta_keywords, og_title, og_description) VALUES (?, ?, ?, ?, ?, ?)");
            $stmt->execute([
                $page['page_name'],
                $page['page_title'],
                $page['meta_description'],
                $page['meta_keywords'],
                $page['og_title'] ?? $page['page_title'],
                $page['og_description'] ?? $page['meta_description']
            ]);
        }
    }
    
    /**
     * Obtenir toutes les pages SEO
     */
    public function getAllPages($search = '', $offset = 0, $limit = 10) {
        try {
            $where = '';
            $params = [];
            
            if (!empty($search)) {
                $where = "WHERE page_name LIKE ? OR page_title LIKE ?";
                $searchTerm = '%' . $search . '%';
                $params = [$searchTerm, $searchTerm];
            }
            
            $sql = "SELECT * FROM {$this->table} {$where} ORDER BY page_name ASC LIMIT {$limit} OFFSET {$offset}";
            $stmt = $this->pdo->prepare($sql);
            $stmt->execute($params);
            return $stmt->fetchAll(PDO::FETCH_ASSOC);
            
        } catch (PDOException $e) {
            error_log("SEOManager::getAllPages Error: " . $e->getMessage());
            return [];
        }
    }
    
    /**
     * Compter le nombre total de pages
     */
    public function countPages($search = '') {
        try {
            $where = '';
            $params = [];
            
            if (!empty($search)) {
                $where = "WHERE page_name LIKE ? OR page_title LIKE ?";
                $searchTerm = '%' . $search . '%';
                $params = [$searchTerm, $searchTerm];
            }
            
            $sql = "SELECT COUNT(*) FROM {$this->table} {$where}";
            $stmt = $this->pdo->prepare($sql);
            $stmt->execute($params);
            return $stmt->fetchColumn();
            
        } catch (PDOException $e) {
            error_log("SEOManager::countPages Error: " . $e->getMessage());
            return 0;
        }
    }
    
    /**
     * Obtenir une page par ID
     */
    public function getById($id) {
        try {
            $stmt = $this->pdo->prepare("SELECT * FROM {$this->table} WHERE id = ?");
            $stmt->execute([$id]);
            return $stmt->fetch(PDO::FETCH_ASSOC);
        } catch (PDOException $e) {
            error_log("SEOManager::getById Error: " . $e->getMessage());
            return false;
        }
    }
    
    /**
     * Obtenir une page par nom
     */
    public function getByPageName($pageName) {
        try {
            $stmt = $this->pdo->prepare("SELECT * FROM {$this->table} WHERE page_name = ?");
            $stmt->execute([$pageName]);
            return $stmt->fetch(PDO::FETCH_ASSOC);
        } catch (PDOException $e) {
            error_log("SEOManager::getByPageName Error: " . $e->getMessage());
            return false;
        }
    }
    
    /**
     * Créer ou mettre à jour une page SEO
     */
    public function createOrUpdate($data) {
        try {
            // Vérifier si la page existe
            $existing = $this->getByPageName($data['page_name']);
            
            if ($existing) {
                // Mettre à jour
                $sql = "UPDATE {$this->table} SET 
                        page_title = ?, meta_description = ?, meta_keywords = ?, 
                        meta_robots = ?, canonical_url = ?, og_title = ?, 
                        og_description = ?, og_image = ?, og_type = ?, 
                        twitter_card = ?, twitter_title = ?, twitter_description = ?, 
                        twitter_image = ?, schema_type = ?, custom_head = ?, 
                        status = ?, updated_at = NOW() 
                        WHERE page_name = ?";
                        
                $params = [
                    $data['page_title'], $data['meta_description'], $data['meta_keywords'],
                    $data['meta_robots'], $data['canonical_url'], $data['og_title'],
                    $data['og_description'], $data['og_image'], $data['og_type'],
                    $data['twitter_card'], $data['twitter_title'], $data['twitter_description'],
                    $data['twitter_image'], $data['schema_type'], $data['custom_head'],
                    $data['status'], $data['page_name']
                ];
            } else {
                // Créer
                $sql = "INSERT INTO {$this->table} 
                        (page_name, page_title, meta_description, meta_keywords, 
                         meta_robots, canonical_url, og_title, og_description, 
                         og_image, og_type, twitter_card, twitter_title, 
                         twitter_description, twitter_image, schema_type, 
                         custom_head, status) 
                        VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)";
                        
                $params = [
                    $data['page_name'], $data['page_title'], $data['meta_description'], $data['meta_keywords'],
                    $data['meta_robots'], $data['canonical_url'], $data['og_title'], $data['og_description'],
                    $data['og_image'], $data['og_type'], $data['twitter_card'], $data['twitter_title'],
                    $data['twitter_description'], $data['twitter_image'], $data['schema_type'],
                    $data['custom_head'], $data['status']
                ];
            }
            
            $stmt = $this->pdo->prepare($sql);
            return $stmt->execute($params);
            
        } catch (PDOException $e) {
            error_log("SEOManager::createOrUpdate Error: " . $e->getMessage());
            return false;
        }
    }
    
    /**
     * Supprimer une page SEO
     */
    public function delete($id) {
        try {
            $stmt = $this->pdo->prepare("DELETE FROM {$this->table} WHERE id = ?");
            return $stmt->execute([$id]);
        } catch (PDOException $e) {
            error_log("SEOManager::delete Error: " . $e->getMessage());
            return false;
        }
    }
    
    /**
     * Vérifier si la table existe
     */
    public function tableExists() {
        try {
            $stmt = $this->pdo->prepare("SELECT 1 FROM {$this->table} LIMIT 1");
            $stmt->execute();
            return true;
        } catch (PDOException $e) {
            return false;
        }
    }
    
    /**
     * Générer le code HTML SEO pour une page
     */
    public function generateSEOHtml($pageName) {
        $page = $this->getByPageName($pageName);
        if (!$page || $page['status'] !== 'active') {
            return '';
        }
        
        $html = [];
        
        // Title
        if ($page['page_title']) {
            $html[] = '<title>' . htmlspecialchars($page['page_title']) . '</title>';
        }
        
        // Meta description
        if ($page['meta_description']) {
            $html[] = '<meta name="description" content="' . htmlspecialchars($page['meta_description']) . '">';
        }
        
        // Meta keywords
        if ($page['meta_keywords']) {
            $html[] = '<meta name="keywords" content="' . htmlspecialchars($page['meta_keywords']) . '">';
        }
        
        // Meta robots
        if ($page['meta_robots']) {
            $html[] = '<meta name="robots" content="' . htmlspecialchars($page['meta_robots']) . '">';
        }
        
        // Canonical URL
        if ($page['canonical_url']) {
            $html[] = '<link rel="canonical" href="' . htmlspecialchars($page['canonical_url']) . '">';
        }
        
        // Open Graph
        if ($page['og_title']) {
            $html[] = '<meta property="og:title" content="' . htmlspecialchars($page['og_title']) . '">';
        }
        if ($page['og_description']) {
            $html[] = '<meta property="og:description" content="' . htmlspecialchars($page['og_description']) . '">';
        }
        if ($page['og_image']) {
            $html[] = '<meta property="og:image" content="' . htmlspecialchars($page['og_image']) . '">';
        }
        if ($page['og_type']) {
            $html[] = '<meta property="og:type" content="' . htmlspecialchars($page['og_type']) . '">';
        }
        
        // Twitter Cards
        if ($page['twitter_card']) {
            $html[] = '<meta name="twitter:card" content="' . htmlspecialchars($page['twitter_card']) . '">';
        }
        if ($page['twitter_title']) {
            $html[] = '<meta name="twitter:title" content="' . htmlspecialchars($page['twitter_title']) . '">';
        }
        if ($page['twitter_description']) {
            $html[] = '<meta name="twitter:description" content="' . htmlspecialchars($page['twitter_description']) . '">';
        }
        if ($page['twitter_image']) {
            $html[] = '<meta name="twitter:image" content="' . htmlspecialchars($page['twitter_image']) . '">';
        }
        
        // Custom head
        if ($page['custom_head']) {
            $html[] = $page['custom_head'];
        }
        
        return implode("\n", $html);
    }
}
?>