<?php
/**
 * Meta Tags Optimization Helper
 * Generates and manages meta tags for each page
 * Place in: /helpers/meta_tags_helper.php
 */

class MetaTagsHelper {
    
    private static $config = [];
    
    /**
     * Initialize with configuration
     */
    public static function init($config = []) {
        self::$config = array_merge([
            'site_name' => 'Esa\'s Fashion',
            'site_url' => 'https://esasfashion.com',
            'default_description' => 'Fashion store with latest trending styles',
            'default_keywords' => 'fashion, clothing, style, trends',
            'twitter_handle' => '@esasfashion',
            'facebook_page' => 'https://facebook.com/esasfashion',
            'og_image' => '/images/og-image.jpg'
        ], $config);
    }
    
    /**
     * Generate title tag (50-60 characters ideal)
     */
    public static function generateTitle($primary, $secondary = '', $maxLength = 60) {
        $title = $primary;
        
        if ($secondary) {
            $title .= ' | ' . $secondary;
        } else {
            $title .= ' | ' . self::$config['site_name'];
        }
        
        // Trim if too long
        if (strlen($title) > $maxLength) {
            $title = substr($title, 0, $maxLength - 3) . '...';
        }
        
        return htmlspecialchars($title, ENT_QUOTES, 'UTF-8');
    }
    
    /**
     * Generate meta description (150-160 characters ideal)
     */
    public static function generateDescription($text, $maxLength = 160) {
        // Clean up text
        $text = strip_tags($text);
        $text = str_replace(['\n', '\r', '\t'], ' ', $text);
        $text = preg_replace('/\s+/', ' ', $text);
        
        // Trim if too long
        if (strlen($text) > $maxLength) {
            $text = substr($text, 0, $maxLength - 3) . '...';
        }
        
        return htmlspecialchars($text, ENT_QUOTES, 'UTF-8');
    }
    
    /**
     * Generate meta keywords (5-7 keywords ideal)
     */
    public static function generateKeywords($keywords = []) {
        if (is_string($keywords)) {
            $keywords = array_map('trim', explode(',', $keywords));
        }
        
        // Limit to 7 keywords
        $keywords = array_slice($keywords, 0, 7);
        
        $keywordString = implode(', ', array_map(function($k) {
            return htmlspecialchars($k, ENT_QUOTES, 'UTF-8');
        }, $keywords));
        
        return $keywordString;
    }
    
    /**
     * Generate canonical tag to prevent duplicate content
     */
    public static function generateCanonical($url = '') {
        if (!$url) {
            $url = self::getCurrentUrl();
        }
        
        $canonical = rtrim($url, '/');
        
        return '<link rel="canonical" href="' . htmlspecialchars($canonical, ENT_QUOTES, 'UTF-8') . '" />' . "\n";
    }
    
    /**
     * Generate Open Graph meta tags for social sharing
     */
    public static function generateOpenGraph($data = []) {
        $defaults = [
            'title' => self::$config['site_name'],
            'description' => self::$config['default_description'],
            'type' => 'website',
            'url' => self::getCurrentUrl(),
            'image' => self::$config['og_image'],
            'site_name' => self::$config['site_name']
        ];
        
        $data = array_merge($defaults, $data);
        
        $html = '';
        foreach ($data as $property => $content) {
            if ($content) {
                $html .= '<meta property="og:' . htmlspecialchars($property) . '" ' .
                        'content="' . htmlspecialchars($content, ENT_QUOTES, 'UTF-8') . '" />' . "\n";
            }
        }
        
        return $html;
    }
    
    /**
     * Generate Twitter Card meta tags
     */
    public static function generateTwitterCard($data = []) {
        $defaults = [
            'card' => 'summary_large_image',
            'title' => self::$config['site_name'],
            'description' => self::$config['default_description'],
            'image' => self::$config['og_image'],
            'creator' => self::$config['twitter_handle']
        ];
        
        $data = array_merge($defaults, $data);
        
        $html = '';
        foreach ($data as $name => $content) {
            if ($content) {
                $html .= '<meta name="twitter:' . htmlspecialchars($name) . '" ' .
                        'content="' . htmlspecialchars($content, ENT_QUOTES, 'UTF-8') . '" />' . "\n";
            }
        }
        
        return $html;
    }
    
    /**
     * Generate all SEO meta tags for a page
     */
    public static function generateComplete($config = []) {
        $html = '';
        
        // Character set
        $html .= '<meta charset="UTF-8" />' . "\n";
        
        // Viewport for responsive design
        $html .= '<meta name="viewport" content="width=device-width, initial-scale=1.0" />' . "\n";
        
        // X-UA-Compatible
        $html .= '<meta http-equiv="X-UA-Compatible" content="ie=edge" />' . "\n";
        
        // Title
        if (isset($config['title'])) {
            $html .= '<title>' . self::generateTitle($config['title'], 
                isset($config['title_secondary']) ? $config['title_secondary'] : '') . '</title>' . "\n";
        }
        
        // Description
        if (isset($config['description'])) {
            $html .= '<meta name="description" content="' . 
                    self::generateDescription($config['description']) . '" />' . "\n";
        }
        
        // Keywords
        if (isset($config['keywords'])) {
            $html .= '<meta name="keywords" content="' . 
                    self::generateKeywords($config['keywords']) . '" />' . "\n";
        }
        
        // Author
        if (isset($config['author'])) {
            $html .= '<meta name="author" content="' . htmlspecialchars($config['author']) . '" />' . "\n";
        }
        
        // Canonical
        if (isset($config['canonical'])) {
            $html .= self::generateCanonical($config['canonical']);
        }
        
        // Open Graph
        if (isset($config['og'])) {
            $html .= self::generateOpenGraph($config['og']);
        }
        
        // Twitter Card
        if (isset($config['twitter'])) {
            $html .= self::generateTwitterCard($config['twitter']);
        }
        
        // Language
        if (isset($config['language'])) {
            $html .= '<meta name="language" content="' . htmlspecialchars($config['language']) . '" />' . "\n";
        }
        
        // Robots meta tag
        if (isset($config['robots'])) {
            $html .= '<meta name="robots" content="' . htmlspecialchars($config['robots']) . '" />' . "\n";
        } else {
            $html .= '<meta name="robots" content="index, follow, max-snippet:-1, max-image-preview:large, max-video-preview:-1" />' . "\n";
        }
        
        return $html;
    }
    
    /**
     * Get current page URL
     */
    private static function getCurrentUrl() {
        $protocol = isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] === 'on' ? 'https' : 'http';
        $host = isset($_SERVER['HTTP_HOST']) ? $_SERVER['HTTP_HOST'] : 'localhost';
        $path = isset($_SERVER['REQUEST_URI']) ? $_SERVER['REQUEST_URI'] : '/';
        
        // Remove query string
        $path = strtok($path, '?');
        
        return rtrim($protocol . '://' . $host . $path, '/');
    }
    
    /**
     * Generate page-specific meta tags configuration
     */
    public static function getPageConfig($pageType, $data = []) {
        $configs = [
            'home' => [
                'title' => 'Home - Fashion Store',
                'description' => 'Welcome to Esa\'s Fashion. Shop the latest trends in women\'s and men\'s fashion.',
                'keywords' => ['fashion', 'clothing', 'style', 'trends', 'online shopping'],
                'robots' => 'index, follow'
            ],
            'product' => [
                'title' => isset($data['name']) ? $data['name'] . ' - Buy Online' : 'Product',
                'description' => isset($data['description']) ? substr($data['description'], 0, 160) : '',
                'keywords' => isset($data['category']) ? [$data['category'], 'buy', 'online', $data['name'] ?? ''] : [],
                'robots' => 'index, follow'
            ],
            'blog' => [
                'title' => isset($data['title']) ? $data['title'] . ' - Blog' : 'Blog Post',
                'description' => isset($data['excerpt']) ? $data['excerpt'] : '',
                'keywords' => isset($data['tags']) ? (is_array($data['tags']) ? $data['tags'] : explode(',', $data['tags'])) : [],
                'robots' => 'index, follow'
            ],
            'category' => [
                'title' => isset($data['name']) ? $data['name'] . ' - Shop' : 'Category',
                'description' => isset($data['description']) ? $data['description'] : '',
                'keywords' => isset($data['name']) ? [$data['name'], 'shop', 'buy'] : [],
                'robots' => 'index, follow'
            ],
            'shop' => [
                'title' => 'Shop - Browse All Products',
                'description' => 'Browse and shop our complete collection of fashion items.',
                'keywords' => ['shop', 'browse', 'products', 'fashion', 'clothing'],
                'robots' => 'index, follow'
            ]
        ];
        
        return isset($configs[$pageType]) ? array_merge($configs[$pageType], $data) : $data;
    }
}

// Initialize with defaults
MetaTagsHelper::init();

/**
 * Quick helper functions
 */
function seo_title($primary, $secondary = '') {
    return MetaTagsHelper::generateTitle($primary, $secondary);
}

function seo_description($text) {
    return MetaTagsHelper::generateDescription($text);
}

function seo_keywords($keywords) {
    return MetaTagsHelper::generateKeywords($keywords);
}

function seo_canonical($url = '') {
    return MetaTagsHelper::generateCanonical($url);
}

function seo_og_tags($data = []) {
    return MetaTagsHelper::generateOpenGraph($data);
}

function seo_twitter_tags($data = []) {
    return MetaTagsHelper::generateTwitterCard($data);
}

function seo_all_meta_tags($config = []) {
    return MetaTagsHelper::generateComplete($config);
}

function get_page_seo_config($pageType, $data = []) {
    return MetaTagsHelper::getPageConfig($pageType, $data);
}
?>
