<?php
/**
 * SEO Schema Markup Generator
 * Auto-generates JSON-LD schema and BreadcrumbList
 */

class SchemaMarkupGenerator {
    
    /**
     * Generate schema based on type
     */
    public static function generateSchema($type, $data) {
        switch ($type) {
            case 'product':
                return self::generateProductSchema($data);
            case 'article':
                return self::generateArticleSchema($data);
            case 'blog':
                return self::generateBlogPostSchema($data);
            case 'breadcrumb':
                return self::generateBreadcrumbSchema($data);
            case 'organization':
                return self::generateOrganizationSchema($data);
            case 'faq':
                return self::generateFAQSchema($data);
            case 'localbusiness':
                return self::generateLocalBusinessSchema($data);
            default:
                return null;
        }
    }
    
    /**
     * Generate Product Schema
     */
    private static function generateProductSchema($data) {
        $schema = [
            '@context' => 'https://schema.org/',
            '@type' => 'Product',
            'name' => $data['name'] ?? 'Product',
            'description' => $data['description'] ?? '',
            'url' => $data['url'] ?? '',
            'sku' => $data['sku'] ?? '',
        ];
        
        // Add image if provided
        if (isset($data['image'])) {
            $schema['image'] = is_array($data['image']) ? $data['image'] : [$data['image']];
        }
        
        // Add brand
        if (isset($data['brand'])) {
            $schema['brand'] = [
                '@type' => 'Brand',
                'name' => $data['brand']
            ];
        }
        
        // Add offers
        if (isset($data['price'])) {
            $schema['offers'] = [
                '@type' => 'Offer',
                'priceCurrency' => $data['currency'] ?? 'USD',
                'price' => $data['price'],
                'availability' => $data['availability'] ?? 'https://schema.org/InStock',
                'url' => $data['url'] ?? ''
            ];
        }
        
        // Add rating if provided
        if (isset($data['rating'])) {
            $schema['aggregateRating'] = [
                '@type' => 'AggregateRating',
                'ratingValue' => $data['rating'],
                'reviewCount' => $data['review_count'] ?? 1,
                'ratingCount' => $data['rating_count'] ?? 1
            ];
        }
        
        return json_encode($schema, JSON_PRETTY_PRINT | JSON_UNESCAPED_SLASHES);
    }
    
    /**
     * Generate Article Schema
     */
    private static function generateArticleSchema($data) {
        $schema = [
            '@context' => 'https://schema.org',
            '@type' => 'Article',
            'headline' => $data['title'] ?? 'Article',
            'description' => $data['description'] ?? '',
            'url' => $data['url'] ?? '',
            'author' => [
                '@type' => 'Person',
                'name' => $data['author'] ?? 'Unknown',
                'url' => $data['author_url'] ?? ''
            ],
            'datePublished' => $data['date_published'] ?? date('Y-m-d'),
            'dateModified' => $data['date_modified'] ?? date('Y-m-d'),
            'image' => isset($data['image']) ? [$data['image']] : [],
            'publisher' => [
                '@type' => 'Organization',
                'name' => $data['publisher'] ?? 'Your Site',
                'logo' => [
                    '@type' => 'ImageObject',
                    'url' => $data['logo'] ?? ''
                ]
            ]
        ];
        
        // Add keywords
        if (isset($data['keywords'])) {
            $schema['keywords'] = $data['keywords'];
        }
        
        return json_encode($schema, JSON_PRETTY_PRINT | JSON_UNESCAPED_SLASHES);
    }
    
    /**
     * Generate Blog Post Schema
     */
    private static function generateBlogPostSchema($data) {
        $schema = [
            '@context' => 'https://schema.org',
            '@type' => 'BlogPosting',
            'headline' => $data['title'] ?? 'Blog Post',
            'description' => $data['description'] ?? '',
            'url' => $data['url'] ?? '',
            'author' => [
                '@type' => 'Person',
                'name' => $data['author'] ?? 'Unknown'
            ],
            'datePublished' => $data['date_published'] ?? date('Y-m-d'),
            'dateModified' => $data['date_modified'] ?? date('Y-m-d'),
            'image' => isset($data['image']) ? [$data['image']] : [],
            'articleBody' => $data['content'] ?? '',
            'publisher' => [
                '@type' => 'Organization',
                'name' => $data['publisher'] ?? 'Your Site'
            ]
        ];
        
        return json_encode($schema, JSON_PRETTY_PRINT | JSON_UNESCAPED_SLASHES);
    }
    
    /**
     * Generate Breadcrumb Schema
     */
    public static function generateBreadcrumbSchema($breadcrumbs) {
        if (!is_array($breadcrumbs) || empty($breadcrumbs)) {
            return null;
        }
        
        $itemListElement = [];
        foreach ($breadcrumbs as $index => $crumb) {
            $itemListElement[] = [
                '@type' => 'ListItem',
                'position' => $index + 1,
                'name' => $crumb['name'] ?? '',
                'item' => $crumb['url'] ?? ''
            ];
        }
        
        $schema = [
            '@context' => 'https://schema.org',
            '@type' => 'BreadcrumbList',
            'itemListElement' => $itemListElement
        ];
        
        return json_encode($schema, JSON_PRETTY_PRINT | JSON_UNESCAPED_SLASHES);
    }
    
    /**
     * Generate Organization Schema
     */
    private static function generateOrganizationSchema($data) {
        $schema = [
            '@context' => 'https://schema.org',
            '@type' => 'Organization',
            'name' => $data['name'] ?? 'Organization',
            'url' => $data['url'] ?? '',
            'logo' => $data['logo'] ?? '',
            'description' => $data['description'] ?? '',
            'contactPoint' => [
                '@type' => 'ContactPoint',
                'contactType' => $data['contact_type'] ?? 'Customer Service',
                'telephone' => $data['phone'] ?? '',
                'email' => $data['email'] ?? ''
            ]
        ];
        
        // Add social profiles
        if (isset($data['social_profiles'])) {
            $schema['sameAs'] = $data['social_profiles'];
        }
        
        return json_encode($schema, JSON_PRETTY_PRINT | JSON_UNESCAPED_SLASHES);
    }
    
    /**
     * Generate FAQ Schema
     */
    private static function generateFAQSchema($faqs) {
        if (!is_array($faqs) || empty($faqs)) {
            return null;
        }
        
        $mainEntity = [];
        foreach ($faqs as $faq) {
            $mainEntity[] = [
                '@type' => 'Question',
                'name' => $faq['question'] ?? '',
                'acceptedAnswer' => [
                    '@type' => 'Answer',
                    'text' => $faq['answer'] ?? ''
                ]
            ];
        }
        
        $schema = [
            '@context' => 'https://schema.org',
            '@type' => 'FAQPage',
            'mainEntity' => $mainEntity
        ];
        
        return json_encode($schema, JSON_PRETTY_PRINT | JSON_UNESCAPED_SLASHES);
    }
    
    /**
     * Generate Local Business Schema
     */
    private static function generateLocalBusinessSchema($data) {
        $schema = [
            '@context' => 'https://schema.org',
            '@type' => 'LocalBusiness',
            'name' => $data['name'] ?? 'Business',
            'url' => $data['url'] ?? '',
            'telephone' => $data['phone'] ?? '',
            'address' => [
                '@type' => 'PostalAddress',
                'streetAddress' => $data['street'] ?? '',
                'addressLocality' => $data['city'] ?? '',
                'addressRegion' => $data['state'] ?? '',
                'postalCode' => $data['zip'] ?? '',
                'addressCountry' => $data['country'] ?? 'US'
            ],
            'priceRange' => $data['price_range'] ?? '$$'
        ];
        
        // Add hours if provided
        if (isset($data['hours'])) {
            $schema['openingHoursSpecification'] = $data['hours'];
        }
        
        return json_encode($schema, JSON_PRETTY_PRINT | JSON_UNESCAPED_SLASHES);
    }
    
    /**
     * Generate HTML script tag with schema
     */
    public static function generateScriptTag($schema) {
        if (!$schema) {
            return '';
        }
        
        return sprintf(
            '<script type="application/ld+json">%s</script>',
            $schema
        );
    }
    
    /**
     * Auto-generate schema from database record
     */
    public static function autoGenerateSchema($db, $entity_type, $entity_id) {
        // Fetch entity data
        switch ($entity_type) {
            case 'product':
                $query = "SELECT * FROM products WHERE id = ?";
                $schema_type = 'product';
                break;
            case 'blog':
                $query = "SELECT * FROM blogs WHERE id = ?";
                $schema_type = 'blog';
                break;
            case 'page':
                $query = "SELECT * FROM pages WHERE id = ?";
                $schema_type = 'article';
                break;
            default:
                return null;
        }
        
        $stmt = $db->prepare($query);
        $stmt->bind_param('i', $entity_id);
        $stmt->execute();
        $result = $stmt->get_result();
        
        if ($result && $result->num_rows > 0) {
            $entity = $result->fetch_assoc();
            $data = self::prepareSchemaData($entity, $entity_type);
            return self::generateSchema($schema_type, $data);
        }
        
        return null;
    }
    
    /**
     * Prepare entity data for schema generation
     */
    private static function prepareSchemaData($entity, $entity_type) {
        $base_url = 'http://' . $_SERVER['HTTP_HOST'];
        
        switch ($entity_type) {
            case 'product':
                return [
                    'name' => $entity['product_name'] ?? $entity['name'] ?? '',
                    'description' => $entity['description'] ?? '',
                    'url' => $base_url . '/product.php?id=' . $entity['id'],
                    'image' => $base_url . '/images/' . ($entity['image'] ?? ''),
                    'price' => $entity['price'] ?? 0,
                    'currency' => 'USD',
                    'sku' => $entity['sku'] ?? $entity['id'],
                    'brand' => $_SERVER['HTTP_HOST']
                ];
            
            case 'blog':
                return [
                    'title' => $entity['title'] ?? '',
                    'description' => $entity['excerpt'] ?? $entity['description'] ?? '',
                    'url' => $base_url . '/blog.php?id=' . $entity['id'],
                    'author' => $entity['author'] ?? 'Admin',
                    'date_published' => $entity['created_at'] ?? date('Y-m-d'),
                    'date_modified' => $entity['updated_at'] ?? date('Y-m-d'),
                    'image' => $base_url . '/images/' . ($entity['image'] ?? ''),
                    'content' => strip_tags($entity['content'] ?? ''),
                    'publisher' => $_SERVER['HTTP_HOST']
                ];
            
            case 'page':
                return [
                    'title' => $entity['title'] ?? '',
                    'description' => $entity['description'] ?? '',
                    'url' => $base_url . '/page.php?id=' . $entity['id'],
                    'author' => $entity['author'] ?? 'Admin',
                    'date_published' => $entity['created_at'] ?? date('Y-m-d'),
                    'date_modified' => $entity['updated_at'] ?? date('Y-m-d'),
                    'image' => $base_url . '/images/' . ($entity['image'] ?? '')
                ];
        }
        
        return [];
    }
}

// AJAX handler
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['action'])) {
    header('Content-Type: application/json');
    
    switch ($_POST['action']) {
        case 'generate_product_schema':
            $schema = SchemaMarkupGenerator::generateSchema('product', $_POST);
            echo json_encode(['success' => true, 'schema' => $schema]);
            break;
            
        case 'generate_article_schema':
            $schema = SchemaMarkupGenerator::generateSchema('article', $_POST);
            echo json_encode(['success' => true, 'schema' => $schema]);
            break;
            
        case 'generate_blog_schema':
            $schema = SchemaMarkupGenerator::generateSchema('blog', $_POST);
            echo json_encode(['success' => true, 'schema' => $schema]);
            break;
            
        case 'generate_breadcrumb':
            $breadcrumbs = json_decode($_POST['breadcrumbs'], true);
            $schema = SchemaMarkupGenerator::generateBreadcrumbSchema($breadcrumbs);
            echo json_encode(['success' => true, 'schema' => $schema]);
            break;
            
        default:
            echo json_encode(['success' => false, 'message' => 'Invalid action']);
    }
    exit;
}
?>
