<?php
/**
 * SEO Helper Class
 * Handles SEO-related functions like canonical tags, meta descriptions, structured data, etc.
 * Place in: /classes/SEOHelper.php
 */

class SEOHelper {
    
    private $baseURL;
    private $currentPage;
    
    public function __construct() {
        $protocol = (isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] === 'on') ? 'https' : 'http';
        $this->baseURL = $protocol . '://' . $_SERVER['SERVER_NAME'];
        $this->currentPage = $_SERVER['REQUEST_URI'];
    }
    
    /**
     * Generate canonical URL tag
     * Prevents duplicate content issues
     */
    public function getCanonicalTag($url = null) {
        if ($url === null) {
            $url = $this->baseURL . $this->currentPage;
        }
        // Remove query parameters for cleaner canonical URLs
        $url = strtok($url, '?');
        return '<link rel="canonical" href="' . htmlspecialchars($url) . '">' . "\n";
    }
    
    /**
     * Generate meta description tag
     */
    public function getMetaDescription($description) {
        if (strlen($description) > 160) {
            $description = substr($description, 0, 157) . '...';
        }
        return '<meta name="description" content="' . htmlspecialchars($description) . '">' . "\n";
    }
    
    /**
     * Generate meta keywords tag
     */
    public function getMetaKeywords($keywords) {
        if (is_array($keywords)) {
            $keywords = implode(', ', $keywords);
        }
        return '<meta name="keywords" content="' . htmlspecialchars($keywords) . '">' . "\n";
    }
    
    /**
     * Generate Open Graph meta tags for social sharing
     */
    public function getOpenGraphTags($data = []) {
        $defaults = [
            'title' => $_SERVER['SERVER_NAME'],
            'description' => 'Premium fashion products',
            'image' => $this->baseURL . '/pics_ecom/logo.png',
            'url' => $this->baseURL . $this->currentPage,
            'type' => 'website'
        ];
        
        $data = array_merge($defaults, $data);
        
        $tags = '';
        $tags .= '<meta property="og:title" content="' . htmlspecialchars($data['title']) . '">' . "\n";
        $tags .= '<meta property="og:description" content="' . htmlspecialchars($data['description']) . '">' . "\n";
        $tags .= '<meta property="og:image" content="' . htmlspecialchars($data['image']) . '">' . "\n";
        $tags .= '<meta property="og:url" content="' . htmlspecialchars($data['url']) . '">' . "\n";
        $tags .= '<meta property="og:type" content="' . htmlspecialchars($data['type']) . '">' . "\n";
        
        return $tags;
    }
    
    /**
     * Generate Twitter Card meta tags
     */
    public function getTwitterCardTags($data = []) {
        $defaults = [
            'card' => 'summary_large_image',
            'title' => $_SERVER['SERVER_NAME'],
            'description' => 'Premium fashion products',
            'image' => $this->baseURL . '/pics_ecom/logo.png',
            'creator' => '@yourhandle' // Update with your Twitter handle
        ];
        
        $data = array_merge($defaults, $data);
        
        $tags = '';
        $tags .= '<meta name="twitter:card" content="' . htmlspecialchars($data['card']) . '">' . "\n";
        $tags .= '<meta name="twitter:title" content="' . htmlspecialchars($data['title']) . '">' . "\n";
        $tags .= '<meta name="twitter:description" content="' . htmlspecialchars($data['description']) . '">' . "\n";
        $tags .= '<meta name="twitter:image" content="' . htmlspecialchars($data['image']) . '">' . "\n";
        if (!empty($data['creator'])) {
            $tags .= '<meta name="twitter:creator" content="' . htmlspecialchars($data['creator']) . '">' . "\n";
        }
        
        return $tags;
    }
    
    /**
     * Generate JSON-LD Structured Data
     */
    public function getStructuredData($type, $data = []) {
        $structuredData = [];
        
        switch ($type) {
            case 'product':
                $structuredData = $this->getProductSchema($data);
                break;
            case 'article':
                $structuredData = $this->getArticleSchema($data);
                break;
            case 'organization':
                $structuredData = $this->getOrganizationSchema($data);
                break;
            case 'breadcrumb':
                $structuredData = $this->getBreadcrumbSchema($data);
                break;
            case 'review':
                $structuredData = $this->getReviewSchema($data);
                break;
        }
        
        return '<script type="application/ld+json">' . "\n" . 
               json_encode($structuredData, JSON_UNESCAPED_SLASHES | JSON_PRETTY_PRINT) . 
               "\n" . '</script>' . "\n";
    }
    
    /**
     * Product Schema for e-commerce
     */
    private function getProductSchema($data) {
        return [
            '@context' => 'https://schema.org/',
            '@type' => 'Product',
            'name' => $data['name'] ?? 'Product',
            'description' => $data['description'] ?? '',
            'image' => $data['image'] ?? ($this->baseURL . '/pic-placeholder.jpg'),
            'brand' => [
                '@type' => 'Brand',
                'name' => $data['brand'] ?? 'Esa\'s Fashion'
            ],
            'offers' => [
                '@type' => 'Offer',
                'url' => $data['url'] ?? $this->baseURL,
                'priceCurrency' => $data['currency'] ?? 'USD',
                'price' => $data['price'] ?? '0',
                'availability' => $data['availability'] ?? 'https://schema.org/InStock',
                'seller' => [
                    '@type' => 'Organization',
                    'name' => 'Esa\'s Fashion'
                ]
            ],
            'aggregateRating' => isset($data['rating']) ? [
                '@type' => 'AggregateRating',
                'ratingValue' => $data['rating'],
                'reviewCount' => $data['reviewCount'] ?? 0
            ] : null
        ];
    }
    
    /**
     * Article/Blog Schema
     */
    private function getArticleSchema($data) {
        return [
            '@context' => 'https://schema.org',
            '@type' => 'BlogPosting',
            'headline' => $data['title'] ?? 'Article',
            'description' => $data['description'] ?? '',
            'image' => $data['image'] ?? ($this->baseURL . '/pic-placeholder.jpg'),
            'datePublished' => $data['datePublished'] ?? date('c'),
            'dateModified' => $data['dateModified'] ?? date('c'),
            'author' => [
                '@type' => 'Person',
                'name' => $data['author'] ?? 'Esa\'s Fashion'
            ],
            'publisher' => [
                '@type' => 'Organization',
                'name' => 'Esa\'s Fashion',
                'logo' => [
                    '@type' => 'ImageObject',
                    'url' => $this->baseURL . '/pics_ecom/logo.png'
                ]
            ]
        ];
    }
    
    /**
     * Organization Schema
     */
    private function getOrganizationSchema($data = []) {
        return [
            '@context' => 'https://schema.org',
            '@type' => 'Organization',
            'name' => 'Esa\'s Fashion',
            'url' => $this->baseURL,
            'logo' => $this->baseURL . '/pics_ecom/logo.png',
            'description' => 'Premium fashion products for women',
            'sameAs' => [
                'https://www.facebook.com/yourpage',
                'https://www.instagram.com/yourpage',
                'https://www.twitter.com/yourpage'
            ],
            'contact' => [
                '@type' => 'ContactPoint',
                'telephone' => '+1-XXX-XXX-XXXX',
                'contactType' => 'Customer Service'
            ]
        ];
    }
    
    /**
     * Breadcrumb Schema
     */
    private function getBreadcrumbSchema($breadcrumbs = []) {
        $itemListElement = [];
        foreach ($breadcrumbs as $index => $item) {
            $itemListElement[] = [
                '@type' => 'ListItem',
                'position' => $index + 1,
                'name' => $item['name'],
                'item' => $item['url']
            ];
        }
        
        return [
            '@context' => 'https://schema.org',
            '@type' => 'BreadcrumbList',
            'itemListElement' => $itemListElement
        ];
    }
    
    /**
     * Review Schema
     */
    private function getReviewSchema($data) {
        return [
            '@context' => 'https://schema.org/',
            '@type' => 'Review',
            'reviewRating' => [
                '@type' => 'Rating',
                'ratingValue' => $data['rating'] ?? '5'
            ],
            'author' => [
                '@type' => 'Person',
                'name' => $data['author'] ?? 'Customer'
            ],
            'reviewBody' => $data['body'] ?? '',
            'datePublished' => $data['date'] ?? date('c')
        ];
    }
    
    /**
     * Generate alt text from filename or provided text
     */
    public function generateAltText($filename, $customAlt = null) {
        if ($customAlt) {
            return htmlspecialchars($customAlt);
        }
        
        // Extract filename without extension
        $name = pathinfo($filename, PATHINFO_FILENAME);
        // Replace hyphens and underscores with spaces
        $alt = str_replace(['-', '_'], ' ', $name);
        // Capitalize words
        $alt = ucwords($alt);
        
        return htmlspecialchars($alt);
    }
    
    /**
     * Get current page title
     */
    public function getPageTitle($title, $siteName = "Esa's Fashion") {
        if ($title === null || $title === '') {
            return htmlspecialchars($siteName);
        }
        return htmlspecialchars($title . ' - ' . $siteName);
    }
    
    /**
     * Generate breadcrumb HTML
     */
    public function generateBreadcrumb($items = []) {
        if (empty($items)) {
            return '';
        }
        
        $html = '<nav aria-label="breadcrumb"><ol class="breadcrumb">' . "\n";
        
        foreach ($items as $index => $item) {
            $isLast = ($index === count($items) - 1);
            
            if ($isLast) {
                $html .= '<li class="breadcrumb-item active" aria-current="page">' . 
                         htmlspecialchars($item['name']) . '</li>' . "\n";
            } else {
                $html .= '<li class="breadcrumb-item"><a href="' . htmlspecialchars($item['url']) . '">' . 
                         htmlspecialchars($item['name']) . '</a></li>' . "\n";
            }
        }
        
        $html .= '</ol></nav>' . "\n";
        
        return $html;
    }
    
    /**
     * Cleanup text for SEO (remove special chars, etc)
     */
    public function cleanText($text) {
        $text = strip_tags($text);
        $text = html_entity_decode($text);
        $text = trim($text);
        return htmlspecialchars($text);
    }
    
    /**
     * Generate slug from text (for URLs)
     */
    public function slugify($text) {
        $text = strtolower($text);
        $text = preg_replace('/[^a-z0-9\s-]/', '', $text);
        $text = preg_replace('/[\s-]+/', '-', $text);
        $text = trim($text, '-');
        return $text;
    }
    
    /**
     * Mobile-friendly viewport meta tag
     */
    public function getViewportTag() {
        return '<meta name="viewport" content="width=device-width, initial-scale=1.0, viewport-fit=cover">' . "\n";
    }
    
    /**
     * Charset meta tag
     */
    public function getCharsetTag() {
        return '<meta charset="UTF-8">' . "\n";
    }
}

// Initialize globally if needed
if (!isset($seoHelper)) {
    $seoHelper = new SEOHelper();
}
?>
