<?php
/**
 * Schema Markup Helper
 * Generates JSON-LD structured data for rich snippets
 * Place in: /helpers/schema_helper.php
 */

class SchemaHelper {
    
    private static $baseUrl = '';
    private static $organization = [
        'name' => 'Esa\'s Fashion',
        'url' => '',
        'logo' => '',
        'contact' => '+1-800-000-0000',
        'email' => 'info@esasfashion.com'
    ];
    
    /**
     * Initialize schema helper
     */
    public static function init($config = []) {
        self::$baseUrl = $config['baseUrl'] ?? 'https://example.com';
        
        if (isset($config['organization'])) {
            self::$organization = array_merge(self::$organization, $config['organization']);
        }
    }
    
    /**
     * Generate Product schema
     */
    public static function generateProductSchema($product = []) {
        $schema = [
            '@context' => 'https://schema.org',
            '@type' => 'Product',
            'name' => $product['name'] ?? '',
            'description' => $product['description'] ?? '',
            'image' => $product['image'] ?? '',
            'sku' => $product['sku'] ?? '',
            'url' => self::$baseUrl . '/product/' . ($product['id'] ?? ''),
            'brand' => [
                '@type' => 'Brand',
                'name' => self::$organization['name']
            ],
            'offers' => [
                '@type' => 'Offer',
                'url' => self::$baseUrl . '/product/' . ($product['id'] ?? ''),
                'priceCurrency' => $product['currency'] ?? 'USD',
                'price' => $product['price'] ?? '0',
                'availability' => $product['in_stock'] ?? true ? 'InStock' : 'OutOfStock',
                'itemCondition' => 'NewCondition'
            ]
        ];
        
        // Add rating if available
        if (isset($product['rating'], $product['ratingCount'])) {
            $schema['aggregateRating'] = [
                '@type' => 'AggregateRating',
                'ratingValue' => $product['rating'],
                'ratingCount' => $product['ratingCount'],
                'bestRating' => 5,
                'worstRating' => 1
            ];
        }
        
        // Add reviews if available
        if (isset($product['reviews']) && !empty($product['reviews'])) {
            $schema['review'] = array_map(function($review) {
                return [
                    '@type' => 'Review',
                    'reviewRating' => [
                        '@type' => 'Rating',
                        'ratingValue' => $review['rating'] ?? 5,
                        'bestRating' => 5,
                        'worstRating' => 1
                    ],
                    'reviewBody' => $review['text'] ?? '',
                    'author' => [
                        '@type' => 'Person',
                        'name' => $review['author'] ?? 'Anonymous'
                    ]
                ];
            }, $product['reviews']);
        }
        
        return json_encode($schema);
    }
    
    /**
     * Generate Article/BlogPost schema
     */
    public static function generateArticleSchema($article = []) {
        $schema = [
            '@context' => 'https://schema.org',
            '@type' => 'BlogPosting',
            'headline' => $article['title'] ?? '',
            'description' => $article['excerpt'] ?? '',
            'image' => $article['featured_image'] ?? '',
            'datePublished' => $article['published_date'] ?? date('Y-m-d'),
            'dateModified' => $article['modified_date'] ?? date('Y-m-d'),
            'author' => [
                '@type' => 'Person',
                'name' => $article['author'] ?? 'Admin'
            ],
            'publisher' => [
                '@type' => 'Organization',
                'name' => self::$organization['name'],
                'logo' => [
                    '@type' => 'ImageObject',
                    'url' => self::$organization['logo']
                ]
            ],
            'mainEntityOfPage' => [
                '@type' => 'WebPage',
                '@id' => self::$baseUrl . '/blog/' . ($article['slug'] ?? '')
            ]
        ];
        
        // Add article body if very long content
        if (isset($article['content']) && strlen($article['content']) > 500) {
            $schema['articleBody'] = strip_tags($article['content']);
        }
        
        return json_encode($schema);
    }
    
    /**
     * Generate Breadcrumb schema
     */
    public static function generateBreadcrumbSchema($breadcrumbs = []) {
        $items = [];
        
        foreach ($breadcrumbs as $index => $crumb) {
            $items[] = [
                '@type' => 'ListItem',
                'position' => $index + 1,
                'name' => $crumb['title'] ?? '',
                'item' => self::$baseUrl . ($crumb['url'] ?? '')
            ];
        }
        
        $schema = [
            '@context' => 'https://schema.org',
            '@type' => 'BreadcrumbList',
            'itemListElement' => $items
        ];
        
        return json_encode($schema);
    }
    
    /**
     * Generate Organization schema
     */
    public static function generateOrganizationSchema() {
        $schema = [
            '@context' => 'https://schema.org',
            '@type' => 'Organization',
            'name' => self::$organization['name'],
            'url' => self::$organization['url'] ?? self::$baseUrl,
            'logo' => self::$organization['logo'] ?? '',
            'description' => 'Fashion store with latest trends and styles',
            'contactPoint' => [
                '@type' => 'ContactPoint',
                'telephone' => self::$organization['contact'] ?? '',
                'contactType' => 'Customer Service',
                'email' => self::$organization['email'] ?? ''
            ],
            'sameAs' => [
                'https://www.facebook.com/esasfashion',
                'https://www.instagram.com/esasfashion',
                'https://www.twitter.com/esasfashion'
            ]
        ];
        
        return json_encode($schema);
    }
    
    /**
     * Generate LocalBusiness schema
     */
    public static function generateLocalBusinessSchema($business = []) {
        $schema = [
            '@context' => 'https://schema.org',
            '@type' => 'LocalBusiness',
            'name' => $business['name'] ?? self::$organization['name'],
            'description' => $business['description'] ?? 'Fashion store',
            'address' => [
                '@type' => 'PostalAddress',
                'streetAddress' => $business['street'] ?? '',
                'addressLocality' => $business['city'] ?? '',
                'addressRegion' => $business['state'] ?? '',
                'postalCode' => $business['zip'] ?? '',
                'addressCountry' => $business['country'] ?? 'US'
            ],
            'telephone' => $business['phone'] ?? '',
            'url' => self::$baseUrl,
            'priceRange' => $business['priceRange'] ?? '$$'
        ];
        
        // Add opening hours if provided
        if (isset($business['hours'])) {
            $schema['openingHoursSpecification'] = array_map(function($hour) {
                return [
                    '@type' => 'OpeningHoursSpecification',
                    'dayOfWeek' => $hour['day'] ?? '',
                    'opens' => $hour['open'] ?? '',
                    'closes' => $hour['close'] ?? ''
                ];
            }, $business['hours']);
        }
        
        return json_encode($schema);
    }
    
    /**
     * Generate FAQ schema
     */
    public static function generateFAQSchema($faqs = []) {
        if (empty($faqs)) {
            return '';
        }
        
        $mainEntity = array_map(function($faq) {
            return [
                '@type' => 'Question',
                'name' => $faq['question'] ?? '',
                'acceptedAnswer' => [
                    '@type' => 'Answer',
                    'text' => $faq['answer'] ?? ''
                ]
            ];
        }, $faqs);
        
        $schema = [
            '@context' => 'https://schema.org',
            '@type' => 'FAQPage',
            'mainEntity' => $mainEntity
        ];
        
        return json_encode($schema);
    }
    
    /**
     * Generate ReviewRating schema
     */
    public static function generateReviewSchema($review = []) {
        $schema = [
            '@context' => 'https://schema.org',
            '@type' => 'Review',
            'reviewRating' => [
                '@type' => 'Rating',
                'ratingValue' => $review['rating'] ?? 5,
                'bestRating' => 5,
                'worstRating' => 1
            ],
            'author' => [
                '@type' => 'Person',
                'name' => $review['author'] ?? 'Anonymous'
            ],
            'reviewBody' => $review['text'] ?? '',
            'datePublished' => $review['date'] ?? date('Y-m-d'),
            'reviewedItem' => [
                '@type' => 'Product',
                'name' => $review['product'] ?? ''
            ]
        ];
        
        return json_encode($schema);
    }
    
    /**
     * Output schema as <script> tag
     */
    public static function outputSchema($schema, $type = 'json-ld') {
        if (is_array($schema)) {
            $schema = json_encode($schema);
        }
        
        return '<script type="application/' . $type . '">' . "\n" .
               $schema . "\n" .
               '</script>' . "\n";
    }
    
    /**
     * Generate E-E-A-T schema (Experience, Expertise, Authority, Trustworthiness)
     */
    public static function generateEEATSchema($content = []) {
        $schema = [
            '@context' => 'https://schema.org',
            '@type' => 'Article',
            'author' => [
                '@type' => 'Person',
                'name' => $content['author'] ?? 'Admin',
                'jobTitle' => $content['author_title'] ?? 'Content Creator',
                'description' => $content['author_bio'] ?? ''
            ],
            'datePublished' => $content['published'] ?? date('Y-m-d'),
            'dateModified' => $content['modified'] ?? date('Y-m-d'),
            'reviewedBy' => [
                '@type' => 'Person',
                'name' => $content['reviewer'] ?? self::$organization['name']
            ]
        ];
        
        return json_encode($schema);
    }
}

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

/**
 * Quick helper functions
 */
function output_product_schema($product) {
    return SchemaHelper::outputSchema(
        SchemaHelper::generateProductSchema($product)
    );
}

function output_article_schema($article) {
    return SchemaHelper::outputSchema(
        SchemaHelper::generateArticleSchema($article)
    );
}

function output_breadcrumb_schema($breadcrumbs) {
    return SchemaHelper::outputSchema(
        SchemaHelper::generateBreadcrumbSchema($breadcrumbs)
    );
}

function output_organization_schema() {
    return SchemaHelper::outputSchema(
        SchemaHelper::generateOrganizationSchema()
    );
}

function output_faq_schema($faqs) {
    return SchemaHelper::outputSchema(
        SchemaHelper::generateFAQSchema($faqs)
    );
}

function get_product_schema($product) {
    return SchemaHelper::generateProductSchema($product);
}

function get_article_schema($article) {
    return SchemaHelper::generateArticleSchema($article);
}
?>
