<?php
/**
 * Phase 3: FAQ Schema Helper
 * 
 * Generates FAQ schema markup and displays FAQ sections
 * with automatic JSON-LD schema generation for search engines
 * 
 * Features:
 * - FAQ schema markup generation
 * - Expandable FAQ display
 * - Question answering for SEO
 * - FAQ rich snippet support
 * 
 * @version 1.0.0
 * @author SEO Framework
 */

class FAQHelper {
    
    /**
     * FAQs database for common product questions
     */
    private static $productFAQs = [
        'women-clothing' => [
            [
                'question' => 'What sizes do you offer?',
                'answer' => 'We offer a wide range of sizes from XS to XXL for women\'s clothing. Each product page displays the complete size chart with measurements to help you find the perfect fit.'
            ],
            [
                'question' => 'What is your return policy?',
                'answer' => 'We offer free returns within 30 days of purchase. Items must be in original condition with tags attached. Simply initiate a return through your account or contact our customer service.'
            ],
            [
                'question' => 'How long does shipping take?',
                'answer' => 'Standard shipping typically takes 3-7 business days. Express shipping (1-2 days) is also available. Orders are usually processed within 24 hours.'
            ],
            [
                'question' => 'Are your products made from quality materials?',
                'answer' => 'Yes! All our women\'s clothing is made from premium, durable materials. We conduct quality checks on every item before shipping to ensure you receive the best products.'
            ],
            [
                'question' => 'Do you offer international shipping?',
                'answer' => 'Yes, we ship to most countries worldwide. Shipping costs and delivery times vary by location. Customs and duties may apply for international orders.'
            ],
        ],
        'men-clothing' => [
            [
                'question' => 'What sizes do you have in stock?',
                'answer' => 'We carry men\'s clothing in sizes XS to XXXL. All products include detailed size charts on the product page to ensure proper fit.'
            ],
            [
                'question' => 'What\'s your return policy?',
                'answer' => 'Returns are free within 30 days of purchase for items in original condition. Contact our customer service team to initiate a return.'
            ],
            [
                'question' => 'How fast can you deliver?',
                'answer' => 'We offer multiple shipping options: Standard (3-7 days) and Express (1-2 days). Most orders ship within 24 hours.'
            ],
            [
                'question' => 'Are these quality products?',
                'answer' => 'Absolutely! All our men\'s clothing is made from high-quality materials and undergoes rigorous quality checks before shipping.'
            ],
            [
                'question' => 'Do you ship internationally?',
                'answer' => 'Yes, we ship worldwide. International shipping costs and delivery times vary by location. Please check shipping rates at checkout.'
            ],
        ],
        'shoes' => [
            [
                'question' => 'How do I know my shoe size?',
                'answer' => 'Each shoe product includes a detailed size chart with US, EU, and UK sizing. We also provide a sizing guide to help you find your perfect fit.'
            ],
            [
                'question' => 'Can I return shoes if I\'ve tried them on?',
                'answer' => 'Yes, as long as the shoes are in original condition with tags attached, you can return them within 30 days for a full refund.'
            ],
            [
                'question' => 'What brands do you carry?',
                'answer' => 'We offer a wide selection of both premium and affordable shoe brands. Browse our collection to find your favorite brands.'
            ],
            [
                'question' => 'Are your shoes comfortable?',
                'answer' => 'All our shoes are selected for both style and comfort. Read customer reviews on each product page to see what others say about fit and comfort.'
            ],
            [
                'question' => 'Do you offer custom shoe fitting?',
                'answer' => 'While we don\'t offer in-store fitting, our detailed size charts and customer reviews help you find the perfect fit online.'
            ],
        ],
        'accessories' => [
            [
                'question' => 'What accessories are in stock?',
                'answer' => 'We offer a wide range of fashion accessories including bags, belts, scarves, jewelry, hats, and more. Browse our full collection online.'
            ],
            [
                'question' => 'Can I return accessories?',
                'answer' => 'Yes, accessories can be returned within 30 days if unused and in original packaging. Simply initiate a return through your account.'
            ],
            [
                'question' => 'Are your accessories real/authentic?',
                'answer' => 'All our fashion accessories are authentic and high-quality. We source from trusted suppliers and verify authenticity for premium items.'
            ],
            [
                'question' => 'How do I care for my accessories?',
                'answer' => 'Each product comes with care instructions. We also provide general care guides for different materials like leather, metal, and fabric accessories.'
            ],
            [
                'question' => 'Can accessories be gift wrapped?',
                'answer' => 'Yes! We offer gift wrapping services for accessories. Select the gift wrap option at checkout and include a personalized message.'
            ],
        ],
    ];
    
    /**
     * Get FAQs for a category
     * 
     * @param string $category Product category
     * @return array FAQ questions and answers
     */
    public static function getFAQs($category = 'women-clothing') {
        $category = strtolower(str_replace(' ', '-', $category));
        
        if (isset(self::$productFAQs[$category])) {
            return self::$productFAQs[$category];
        }
        
        // Default FAQs
        return self::$productFAQs['women-clothing'];
    }
    
    /**
     * Output FAQ schema markup (JSON-LD)
     * 
     * @param array $faqs FAQ array with 'question' and 'answer' keys
     * @return string JSON-LD schema markup
     */
    public static function outputFAQSchema($faqs) {
        if (empty($faqs)) {
            return '';
        }
        
        $schema = [
            '@context' => 'https://schema.org',
            '@type' => 'FAQPage',
            'mainEntity' => []
        ];
        
        foreach ($faqs as $faq) {
            $schema['mainEntity'][] = [
                '@type' => 'Question',
                'name' => htmlspecialchars($faq['question']),
                'acceptedAnswer' => [
                    '@type' => 'Answer',
                    'text' => htmlspecialchars($faq['answer'])
                ]
            ];
        }
        
        return '<script type="application/ld+json">' . json_encode($schema, JSON_UNESCAPED_SLASHES | JSON_PRETTY_PRINT) . '</script>' . "\n";
    }
    
    /**
     * Display FAQ accordion HTML
     * 
     * @param array $faqs FAQ array with 'question' and 'answer' keys
     * @param string $id Unique ID for accordion
     * @return string HTML for FAQ accordion
     */
    public static function displayFAQAccordion($faqs, $id = 'faq-accordion') {
        if (empty($faqs)) {
            return '';
        }
        
        $html = '<div class="faq-accordion" id="' . htmlspecialchars($id) . '">' . "\n";
        
        foreach ($faqs as $index => $faq) {
            $itemId = $id . '-' . ($index + 1);
            $html .= self::getFAQItem($faq, $itemId);
        }
        
        $html .= '</div>' . "\n";
        
        return $html;
    }
    
    /**
     * Get single FAQ item HTML
     * 
     * @param array $faq Question and answer
     * @param string $id Unique item ID
     * @return string HTML for one FAQ item
     */
    private static function getFAQItem($faq, $id) {
        return '
  <div class="faq-item">
    <button class="faq-question" onclick="toggleFAQ(\''. htmlspecialchars($id) .'\')">
      <span class="question-text">' . htmlspecialchars($faq['question']) . '</span>
      <span class="faq-toggle">+</span>
    </button>
    <div class="faq-answer" id="' . htmlspecialchars($id) . '" style="display:none;">
      <p>' . htmlspecialchars($faq['answer']) . '</p>
    </div>
  </div>' . "\n";
    }
    
    /**
     * Get FAQs with schema for a page
     * Returns both HTML display and schema markup
     * 
     * @param string $category Product category
     * @param string $accordionId Unique accordion ID
     * @return array ['schema' => html, 'accordion' => html]
     */
    public static function getFAQsWithSchema($category = 'women-clothing', $accordionId = 'faq-accordion') {
        $faqs = self::getFAQs($category);
        
        return [
            'schema' => self::outputFAQSchema($faqs),
            'accordion' => self::displayFAQAccordion($faqs, $accordionId),
            'count' => count($faqs),
        ];
    }
    
    /**
     * Add custom FAQ to category
     * 
     * @param string $category Category to add FAQ to
     * @param string $question FAQ question
     * @param string $answer FAQ answer
     */
    public static function addCustomFAQ($category, $question, $answer) {
        $category = strtolower(str_replace(' ', '-', $category));
        
        if (!isset(self::$productFAQs[$category])) {
            self::$productFAQs[$category] = [];
        }
        
        self::$productFAQs[$category][] = [
            'question' => $question,
            'answer' => $answer,
        ];
    }
    
    /**
     * Get specific FAQ by index
     * 
     * @param string $category Category
     * @param int $index FAQ index (0-based)
     * @return array|null FAQ item or null if not found
     */
    public static function getFAQByIndex($category, $index) {
        $faqs = self::getFAQs($category);
        
        if (isset($faqs[$index])) {
            return $faqs[$index];
        }
        
        return null;
    }
    
    /**
     * Search FAQs by keyword
     * 
     * @param string $keyword Search keyword
     * @param string $category Optional: limit to category
     * @return array Matching FAQs
     */
    public static function searchFAQs($keyword, $category = null) {
        $results = [];
        $keyword = strtolower($keyword);
        
        if ($category) {
            $faqs = self::getFAQs($category);
            $categories = [$category];
        } else {
            $categories = array_keys(self::$productFAQs);
        }
        
        foreach ($categories as $cat) {
            $faqs = self::getFAQs($cat);
            foreach ($faqs as $faq) {
                if (stripos($faq['question'], $keyword) !== false || 
                    stripos($faq['answer'], $keyword) !== false) {
                    $results[] = array_merge($faq, ['category' => $cat]);
                }
            }
        }
        
        return $results;
    }
    
    /**
     * Get FAQ stats
     * 
     * @return array Statistics about FAQs
     */
    public static function getFAQStats() {
        $stats = [
            'total_categories' => count(self::$productFAQs),
            'total_faqs' => 0,
            'by_category' => [],
        ];
        
        foreach (self::$productFAQs as $category => $faqs) {
            $count = count($faqs);
            $stats['total_faqs'] += $count;
            $stats['by_category'][$category] = $count;
        }
        
        return $stats;
    }
}

?>
