<?php
/**
 * Phase 3: Content Optimizer Helper
 * 
 * Provides functions for content expansion, quality improvement,
 * and internal linking optimization
 * 
 * Features:
 * - Content expansion templates
 * - Readability analysis
 * - Internal link recommendations
 * - Content length optimization
 * - Paragraph structure improvement
 * 
 * @version 1.0.0
 * @author SEO Framework
 */

class ContentOptimizer {
    
    /**
     * Expand product description with structured content
     * 
     * @param string $shortDesc Short product description
     * @param string $category Product category
     * @param array $features Product features
     * @return string Expanded description with multiple sections
     */
    public static function expandProductDescription($shortDesc, $category = '', $features = []) {
        $expanded = $shortDesc;
        
        // Add features section if provided
        if (!empty($features)) {
            $expanded .= "\n\n**Key Features:**\n";
            foreach ($features as $feature) {
                $expanded .= "• " . $feature . "\n";
            }
        }
        
        // Add material/care information
        $expanded .= "\n\n**About This Item:**\n";
        $expanded .= "This high-quality " . strtolower($category) . " item combines style with comfort. ";
        $expanded .= "Crafted from premium materials, it's designed to last. ";
        $expanded .= "Perfect for everyday wear or special occasions.\n\n";
        
        // Add care instructions
        $expanded .= "**Care Instructions:**\n";
        $expanded .= "• Machine wash in cold water with similar colors\n";
        $expanded .= "• Use mild detergent and avoid bleach\n";
        $expanded .= "• Tumble dry on low heat or air dry\n";
        $expanded .= "• Iron on medium heat if needed\n\n";
        
        // Add shipping and returns
        $expanded .= "**Shipping & Returns:**\n";
        $expanded .= "Free standard shipping on orders over $50. ";
        $expanded .= "30-day return policy for unworn items in original packaging. ";
        $expanded .= "Fast and easy returns process.\n";
        
        return $expanded;
    }
    
    /**
     * Create blog content outline
     * 
     * @param string $topic Blog post topic
     * @param int $wordCount Target word count
     * @return array Content outline with sections and word count targets
     */
    public static function createContentOutline($topic, $wordCount = 2000) {
        $outline = [
            'title' => $topic,
            'target_words' => $wordCount,
            'sections' => [
                [
                    'heading' => 'Introduction',
                    'target_words' => ceil($wordCount * 0.1),
                    'tips' => 'Hook the reader, mention main topic, set expectations',
                ],
                [
                    'heading' => 'What is ' . $topic . '?',
                    'target_words' => ceil($wordCount * 0.15),
                    'tips' => 'Define the topic, provide context, explain importance',
                ],
                [
                    'heading' => 'Key Benefits',
                    'target_words' => ceil($wordCount * 0.2),
                    'tips' => 'List 3-5 main benefits, explain each one with examples',
                ],
                [
                    'heading' => 'How to ' . $topic,
                    'target_words' => ceil($wordCount * 0.25),
                    'tips' => 'Step-by-step guide, practical tips, real examples',
                ],
                [
                    'heading' => 'Common Mistakes to Avoid',
                    'target_words' => ceil($wordCount * 0.15),
                    'tips' => 'List pitfalls, explain why they\'re problematic, provide solutions',
                ],
                [
                    'heading' => 'Conclusion',
                    'target_words' => ceil($wordCount * 0.15),
                    'tips' => 'Summarize key points, call to action, encourage engagement',
                ],
            ],
        ];
        
        return $outline;
    }
    
    /**
     * Calculate content readability score
     * Based on sentence length, paragraph structure, and complexity
     * 
     * @param string $content Content to analyze
     * @return array Readability metrics
     */
    public static function calculateReadability($content) {
        $sentences = preg_split('/[.!?]+/', $content, -1, PREG_SPLIT_NO_EMPTY);
        $words = str_word_count($content);
        $paragraphs = count(array_filter(explode("\n\n", $content)));
        
        $avgSentenceLength = $words / max(count($sentences), 1);
        $avgWordsPerParagraph = $words / max($paragraphs, 1);
        
        // Flesch Reading Ease approximation (0-100, higher = easier)
        $score = 206.835 - (1.015 * $avgSentenceLength) - (84.6 * 0.001);
        $score = min(100, max(0, $score));
        
        // Determine readability level
        if ($score >= 90) {
            $level = 'Very Easy (5th grade)';
        } elseif ($score >= 80) {
            $level = 'Easy (6th grade)';
        } elseif ($score >= 70) {
            $level = 'Fairly Easy (7th grade)';
        } elseif ($score >= 60) {
            $level = 'Standard (8th-9th grade)';
        } elseif ($score >= 50) {
            $level = 'Fairly Difficult (10th-12th grade)';
        } elseif ($score >= 30) {
            $level = 'Difficult (College)';
        } else {
            $level = 'Very Difficult (College graduate)';
        }
        
        return [
            'score' => round($score, 1),
            'level' => $level,
            'word_count' => $words,
            'sentence_count' => count($sentences),
            'paragraph_count' => $paragraphs,
            'avg_sentence_length' => round($avgSentenceLength, 1),
            'avg_words_per_paragraph' => round($avgWordsPerParagraph, 1),
            'recommendation' => self::getReadabilityRecommendation($score),
        ];
    }
    
    /**
     * Get readability recommendation
     * 
     * @param float $score Readability score
     * @return string Recommendation
     */
    private static function getReadabilityRecommendation($score) {
        if ($score >= 60) {
            return 'Good! Content is easy to understand for most readers.';
        } else {
            return 'Consider breaking paragraphs into shorter chunks and using simpler words.';
        }
    }
    
    /**
     * Get internal link recommendations
     * 
     * @param string $currentPage Current page URL
     * @param array $keywords Keywords to link
     * @return array Recommended internal links
     */
    public static function getInternalLinkRecommendations($currentPage, $keywords = []) {
        // Map keywords to related pages
        $linkMap = [
            'women\'s clothing' => ['category.php?id=1', 'shop.php?cat=women-clothing'],
            'men\'s clothing' => ['category.php?id=2', 'shop.php?cat=men-clothing'],
            'shoes' => ['category.php?id=3', 'shop.php?cat=shoes'],
            'accessories' => ['category.php?id=4', 'shop.php?cat=accessories'],
            'fashion' => ['shop.php', 'index.php'],
            'trending' => ['shop.php?sort=trending', 'index.php'],
            'sale' => ['shop.php?on_sale=1'],
            'new arrivals' => ['shop.php?sort=newest'],
            'best sellers' => ['shop.php?sort=popular'],
        ];
        
        $recommendations = [];
        
        foreach ($keywords as $keyword) {
            $keywordLower = strtolower($keyword);
            foreach ($linkMap as $key => $urls) {
                if (stripos($keywordLower, $key) !== false || stripos($key, $keywordLower) !== false) {
                    foreach ($urls as $url) {
                        if ($url !== $currentPage) {
                            $recommendations[] = [
                                'keyword' => $keyword,
                                'url' => $url,
                                'anchor' => $keyword,
                            ];
                        }
                    }
                }
            }
        }
        
        return array_unique($recommendations, SORT_REGULAR);
    }
    
    /**
     * Format content for better SEO and readability
     * 
     * @param string $content Raw content
     * @param array $headings Heading keywords for proper structure
     * @return string Formatted content with proper structure
     */
    public static function formatContent($content, $headings = []) {
        // Break into paragraphs (max 150 words per paragraph)
        $paragraphs = preg_split('/\n\n+/', trim($content));
        $formatted = '';
        
        foreach ($paragraphs as $index => $para) {
            $para = trim($para);
            if (empty($para)) continue;
            
            // Add heading if available
            if (!empty($headings[$index]) && $index > 0) {
                $formatted .= '<h3>' . htmlspecialchars($headings[$index]) . '</h3>' . "\n";
            }
            
            // Wrap in paragraph
            $formatted .= '<p>' . htmlspecialchars($para) . '</p>' . "\n";
        }
        
        return $formatted;
    }
    
    /**
     * Generate content suggestions for improvement
     * 
     * @param string $content Current content
     * @param string $keyword Target keyword
     * @return array Suggestions for improvement
     */
    public static function getContentSuggestions($content, $keyword) {
        $suggestions = [];
        $wordCount = str_word_count($content);
        $keywordCount = substr_count(strtolower($content), strtolower($keyword));
        
        // Word count suggestion
        if ($wordCount < 300) {
            $suggestions[] = [
                'type' => 'content_length',
                'message' => 'Expand content to at least 300 words for better SEO',
                'current' => $wordCount,
                'recommended' => 300,
            ];
        }
        
        // Keyword density suggestion
        $density = ($keywordCount / max($wordCount, 1)) * 100;
        if ($density < 1) {
            $suggestions[] = [
                'type' => 'keyword_frequency',
                'message' => 'Include the keyword more naturally throughout the content',
                'current' => round($density, 2) . '%',
                'recommended' => '1-2%',
            ];
        } elseif ($density > 3) {
            $suggestions[] = [
                'type' => 'keyword_stuffing',
                'message' => 'Reduce keyword frequency to avoid over-optimization',
                'current' => round($density, 2) . '%',
                'recommended' => '1-2%',
            ];
        }
        
        // Structure suggestion
        if (substr_count($content, "\n") < 3) {
            $suggestions[] = [
                'type' => 'structure',
                'message' => 'Add subheadings to break up content and improve readability',
                'suggestion' => 'Use H2 and H3 tags for better structure',
            ];
        }
        
        return $suggestions;
    }
    
    /**
     * Create content template for product
     * 
     * @param string $productName Product name
     * @param string $category Category
     * @param string $shortDesc Short description
     * @return string Content template
     */
    public static function createProductTemplate($productName, $category, $shortDesc = '') {
        $template = "<!-- Product Content Template -->

<h1>{$productName}</h1>

<h2>Overview</h2>
<p>{$shortDesc}</p>

<h2>Features & Benefits</h2>
<ul>
<li>Premium quality material</li>
<li>Comfortable and durable</li>
<li>Perfect for {$category}</li>
<li>Great value for money</li>
<li>Wide range of sizes available</li>
</ul>

<h2>Product Details</h2>
<p>This {$category} item is carefully selected and quality-tested before shipment. It offers excellent value and durability.</p>

<h2>How to Care</h2>
<ul>
<li>Wash in cold water</li>
<li>Use mild detergent</li>
<li>Air dry or tumble dry on low</li>
<li>Store in cool, dry place</li>
</ul>

<h2>Customer Reviews</h2>
<p>See what our customers say about this product below.</p>";
        
        return $template;
    }
}

?>
