<?php
/**
 * SEO Schema Markup Generator
 * Generates structured data (JSON-LD) for SEO
 */

class SchemaMarkupGenerator {
    
    /**
     * Generate schema markup based on type
     */
    public static function generateSchema($type, $data) {
        switch ($type) {
            case 'article':
                return self::generateArticleSchema($data);
            case 'product':
                return self::generateProductSchema($data);
            case 'organization':
                return self::generateOrganizationSchema($data);
            case 'blog':
                return self::generateBlogPostingSchema($data);
            case 'faq':
                return self::generateFAQSchema($data);
            case 'breadcrumb':
                return self::generateBreadcrumbSchema($data);
            case 'localbusiness':
                return self::generateLocalBusinessSchema($data);
            default:
                return null;
        }
    }
    
    /**
     * Generate Article Schema
     */
    private static function generateArticleSchema($data) {
        $schema = [
            '@context' => 'https://schema.org',
            '@type' => 'NewsArticle',
            'headline' => $data['title'] ?? '',
            'description' => $data['description'] ?? '',
            'image' => $data['image'] ?? '',
            'datePublished' => $data['published_date'] ?? date('Y-m-d'),
            'dateModified' => $data['modified_date'] ?? date('Y-m-d'),
            'author' => [
                '@type' => 'Person',
                'name' => $data['author'] ?? 'Admin'
            ],
            'mainEntityOfPage' => [
                '@type' => 'WebPage',
                '@id' => $data['url'] ?? ''
            ]
        ];
        
        if (!empty($data['publisher'])) {
            $schema['publisher'] = [
                '@type' => 'Organization',
                'name' => $data['publisher'],
                'logo' => [
                    '@type' => 'ImageObject',
                    'url' => $data['publisher_logo'] ?? ''
                ]
            ];
        }
        
        return $schema;
    }
    
    /**
     * Generate Product Schema
     */
    private static function generateProductSchema($data) {
        $schema = [
            '@context' => 'https://schema.org',
            '@type' => 'Product',
            'name' => $data['name'] ?? '',
            'description' => $data['description'] ?? '',
            'image' => $data['image'] ?? '',
            'url' => $data['url'] ?? ''
        ];
        
        // Add price and availability if provided
        if (!empty($data['price'])) {
            $schema['offers'] = [
                '@type' => 'Offer',
                'price' => $data['price'],
                'priceCurrency' => $data['currency'] ?? 'USD',
                'availability' => 'https://schema.org/' . ($data['availability'] ?? 'InStock'),
                'url' => $data['url'] ?? ''
            ];
        }
        
        // Add rating if provided
        if (!empty($data['rating'])) {
            $schema['aggregateRating'] = [
                '@type' => 'AggregateRating',
                'ratingValue' => $data['rating'],
                'ratingCount' => $data['rating_count'] ?? 1,
                'bestRating' => 5,
                'worstRating' => 1
            ];
        }
        
        return $schema;
    }
    
    /**
     * Generate Organization Schema
     */
    private static function generateOrganizationSchema($data) {
        $schema = [
            '@context' => 'https://schema.org',
            '@type' => 'Organization',
            'name' => $data['name'] ?? '',
            'url' => $data['url'] ?? '',
            'logo' => $data['logo'] ?? ''
        ];
        
        if (!empty($data['description'])) {
            $schema['description'] = $data['description'];
        }
        
        if (!empty($data['phone'])) {
            $schema['telephone'] = $data['phone'];
        }
        
        if (!empty($data['email'])) {
            $schema['email'] = $data['email'];
        }
        
        if (!empty($data['address'])) {
            $schema['address'] = [
                '@type' => 'PostalAddress',
                'streetAddress' => $data['address']['street'] ?? '',
                'addressLocality' => $data['address']['city'] ?? '',
                'addressRegion' => $data['address']['state'] ?? '',
                'postalCode' => $data['address']['zip'] ?? '',
                'addressCountry' => $data['address']['country'] ?? ''
            ];
        }
        
        if (!empty($data['social_profiles'])) {
            $schema['sameAs'] = $data['social_profiles'];
        }
        
        return $schema;
    }
    
    /**
     * Generate Blog Posting Schema
     */
    private static function generateBlogPostingSchema($data) {
        $schema = [
            '@context' => 'https://schema.org',
            '@type' => 'BlogPosting',
            'headline' => $data['title'] ?? '',
            'description' => $data['description'] ?? '',
            'image' => $data['image'] ?? '',
            'datePublished' => $data['published_date'] ?? date('Y-m-d'),
            'dateModified' => $data['modified_date'] ?? date('Y-m-d'),
            'author' => [
                '@type' => 'Person',
                'name' => $data['author'] ?? 'Admin'
            ],
            'mainEntityOfPage' => [
                '@type' => 'WebPage',
                '@id' => $data['url'] ?? ''
            ]
        ];
        
        if (!empty($data['keywords'])) {
            $schema['keywords'] = is_array($data['keywords']) ? implode(',', $data['keywords']) : $data['keywords'];
        }
        
        return $schema;
    }
    
    /**
     * Generate FAQ Schema
     */
    private static function generateFAQSchema($data) {
        $schema = [
            '@context' => 'https://schema.org',
            '@type' => 'FAQPage',
            'mainEntity' => []
        ];
        
        if (!empty($data['faqs']) && is_array($data['faqs'])) {
            foreach ($data['faqs'] as $faq) {
                $schema['mainEntity'][] = [
                    '@type' => 'Question',
                    'name' => $faq['question'] ?? '',
                    'acceptedAnswer' => [
                        '@type' => 'Answer',
                        'text' => $faq['answer'] ?? ''
                    ]
                ];
            }
        }
        
        return $schema;
    }
    
    /**
     * Generate Breadcrumb Schema
     */
    private static function generateBreadcrumbSchema($data) {
        $schema = [
            '@context' => 'https://schema.org',
            '@type' => 'BreadcrumbList',
            'itemListElement' => []
        ];
        
        if (!empty($data['breadcrumbs']) && is_array($data['breadcrumbs'])) {
            $position = 1;
            foreach ($data['breadcrumbs'] as $breadcrumb) {
                $schema['itemListElement'][] = [
                    '@type' => 'ListItem',
                    'position' => $position,
                    'name' => $breadcrumb['name'] ?? '',
                    'item' => $breadcrumb['url'] ?? ''
                ];
                $position++;
            }
        }
        
        return $schema;
    }
    
    /**
     * Generate Local Business Schema
     */
    private static function generateLocalBusinessSchema($data) {
        $schema = [
            '@context' => 'https://schema.org',
            '@type' => 'LocalBusiness',
            'name' => $data['name'] ?? '',
            'url' => $data['url'] ?? '',
            'telephone' => $data['phone'] ?? '',
            'address' => [
                '@type' => 'PostalAddress',
                'streetAddress' => $data['address']['street'] ?? '',
                'addressLocality' => $data['address']['city'] ?? '',
                'addressRegion' => $data['address']['state'] ?? '',
                'postalCode' => $data['address']['zip'] ?? '',
                'addressCountry' => $data['address']['country'] ?? ''
            ]
        ];
        
        if (!empty($data['hours'])) {
            $schema['openingHoursSpecification'] = $data['hours'];
        }
        
        if (!empty($data['rating'])) {
            $schema['aggregateRating'] = [
                '@type' => 'AggregateRating',
                'ratingValue' => $data['rating'],
                'ratingCount' => $data['rating_count'] ?? 1
            ];
        }
        
        return $schema;
    }
    
    /**
     * Convert schema to JSON-LD format
     */
    public static function toJSON($schema) {
        if (!is_array($schema)) {
            return null;
        }
        
        return '<script type="application/ld+json">' . json_encode($schema, JSON_PRETTY_PRINT | JSON_UNESCAPED_SLASHES) . '</script>';
    }
    
    /**
     * Validate schema structure
     */
    public static function validateSchema($schema) {
        $errors = [];
        
        if (!isset($schema['@context'])) {
            $errors[] = 'Missing @context property';
        }
        
        if (!isset($schema['@type'])) {
            $errors[] = 'Missing @type property';
        }
        
        if (empty($errors)) {
            // Validate required fields based on type
            $type = $schema['@type'] ?? '';
            $required = self::getRequiredFields($type);
            
            foreach ($required as $field) {
                if (empty($schema[$field])) {
                    $errors[] = "Missing required field: $field";
                }
            }
        }
        
        return [
            'valid' => empty($errors),
            'errors' => $errors
        ];
    }
    
    /**
     * Get required fields for schema type
     */
    private static function getRequiredFields($type) {
        $required_fields = [
            'NewsArticle' => ['headline', 'description', 'image'],
            'Product' => ['name', 'description'],
            'Organization' => ['name', 'url'],
            'BlogPosting' => ['headline', 'datePublished', 'author'],
            'FAQPage' => ['mainEntity'],
            'BreadcrumbList' => ['itemListElement'],
            'LocalBusiness' => ['name', 'address']
        ];
        
        return $required_fields[$type] ?? [];
    }
    
    /**
     * Generate schema suggestions
     */
    public static function getSchemaSuggestions() {
        return [
            [
                'type' => 'Organization',
                'description' => 'Define your business organization',
                'use_case' => 'Homepage and about pages'
            ],
            [
                'type' => 'BlogPosting',
                'description' => 'Mark up blog posts with publication dates and authors',
                'use_case' => 'Blog pages'
            ],
            [
                'type' => 'Product',
                'description' => 'Add product information with prices and ratings',
                'use_case' => 'Product pages'
            ],
            [
                'type' => 'BreadcrumbList',
                'description' => 'Show site hierarchy with breadcrumbs',
                'use_case' => 'All content pages'
            ],
            [
                'type' => 'FAQPage',
                'description' => 'Display frequently asked questions',
                'use_case' => 'FAQ pages'
            ],
            [
                'type' => 'LocalBusiness',
                'description' => 'Mark up local business information',
                'use_case' => 'Local business pages'
            ]
        ];
    }
}
?>
