<?php
/**
 * SEO Helper Functions - Advanced SEO Analysis
 * Includes validation, scoring, suggestions, and analytics
 */

class SEOHelper {
    
    /**
     * Generate URL-friendly slug from title
     */
    public static function generateSlug($title) {
        // Convert to lowercase
        $slug = strtolower($title);
        
        // Replace spaces with hyphens
        $slug = preg_replace('/\s+/', '-', $slug);
        
        // Remove special characters except hyphens
        $slug = preg_replace('/[^a-z0-9\-]/', '', $slug);
        
        // Replace multiple hyphens with single hyphen
        $slug = preg_replace('/-+/', '-', $slug);
        
        // Remove leading/trailing hyphens
        $slug = trim($slug, '-');
        
        return $slug;
    }
    
    /**
     * Check if keyword exists in content
     */
    public static function checkKeywordInContent($keyword, $content) {
        if (empty($keyword) || empty($content)) {
            return ['exists' => false, 'count' => 0, 'density' => 0];
        }
        
        // Case-insensitive search
        $count = substr_count(strtolower($content), strtolower($keyword));
        $total_words = count(explode(' ', $content));
        $density = $total_words > 0 ? round(($count / $total_words) * 100, 2) : 0;
        
        return [
            'exists' => $count > 0,
            'count' => $count,
            'density' => $density,
            'optimal' => $density > 0.5 && $density < 2.5 // Optimal 0.5-2.5%
        ];
    }
    
    /**
     * Calculate word count and density of specific word
     */
    public static function analyzeContent($content, $focus_keyword = '') {
        if (empty($content)) {
            return ['word_count' => 0, 'character_count' => 0, 'keyword_density' => 0];
        }
        
        // Word count
        $words = preg_split('/\s+/', trim($content), -1, PREG_SPLIT_NO_EMPTY);
        $word_count = count($words);
        
        // Character count (no spaces)
        $character_count = strlen(preg_replace('/\s/', '', $content));
        
        // Keyword density
        $keyword_density = 0;
        if (!empty($focus_keyword) && $word_count > 0) {
            $keyword_count = substr_count(strtolower($content), strtolower($focus_keyword));
            $keyword_density = round(($keyword_count / $word_count) * 100, 2);
        }
        
        // Reading time (average 200 words per minute)
        $reading_time = ceil($word_count / 200);
        
        return [
            'word_count' => $word_count,
            'character_count' => $character_count,
            'keyword_density' => $keyword_density,
            'reading_time' => $reading_time . ' min read',
            'quality' => self::assessContentQuality($word_count)
        ];
    }
    
    /**
     * Assess content quality based on word count
     */
    private static function assessContentQuality($word_count) {
        if ($word_count < 300) {
            return ['status' => 'Poor', 'color' => '#d32f2f', 'suggestion' => 'Add more content (aim for 300+ words)'];
        } elseif ($word_count < 600) {
            return ['status' => 'Good', 'color' => '#f57c00', 'suggestion' => 'Expand to 600+ words for better SEO'];
        } elseif ($word_count >= 600 && $word_count < 1500) {
            return ['status' => 'Excellent', 'color' => '#388e3c', 'suggestion' => 'Great! Well-optimized content length'];
        } else {
            return ['status' => 'Comprehensive', 'color' => '#1565c0', 'suggestion' => 'Very thorough content. Excellent for SEO'];
        }
    }
    
    /**
     * Calculate SEO Score (0-100)
     */
    public static function calculateSEOScore($data) {
        $score = 0;
        $max_score = 100;
        
        // Title optimization (25 points)
        if (!empty($data['title'])) {
            $title_length = strlen($data['title']);
            if ($title_length >= 30 && $title_length <= 60) {
                $score += 25;
            } elseif ($title_length > 0 && $title_length <= 70) {
                $score += 20;
            }
        }
        
        // Meta description optimization (25 points)
        if (!empty($data['meta_description'])) {
            $desc_length = strlen($data['meta_description']);
            if ($desc_length >= 120 && $desc_length <= 160) {
                $score += 25;
            } elseif ($desc_length > 0 && $desc_length <= 180) {
                $score += 20;
            }
        }
        
        // Focus keyword optimization (20 points)
        if (!empty($data['focus_keyword']) && !empty($data['content'])) {
            $keyword_check = self::checkKeywordInContent($data['focus_keyword'], $data['content']);
            if ($keyword_check['exists']) {
                if ($keyword_check['optimal']) {
                    $score += 20;
                } else {
                    $score += 10;
                }
            }
        }
        
        // Slug optimization (10 points)
        if (!empty($data['slug']) && !preg_match('/[^a-z0-9\-]/', $data['slug'])) {
            $score += 10;
        }
        
        // Schema markup (10 points)
        if (!empty($data['schema_markup'])) {
            $score += 10;
        }
        
        // URL structure (5 points)
        if (!empty($data['canonical_url']) && filter_var($data['canonical_url'], FILTER_VALIDATE_URL)) {
            $score += 5;
        }
        
        return min($score, $max_score);
    }
    
    /**
     * Generate SEO improvement suggestions
     */
    public static function generateSuggestions($data) {
        $suggestions = [];
        
        // Title suggestions
        if (empty($data['title'])) {
            $suggestions[] = ['type' => 'error', 'text' => 'SEO Title is missing. Add a title (50-60 chars)'];
        } elseif (strlen($data['title']) < 30) {
            $suggestions[] = ['type' => 'warning', 'text' => 'SEO Title too short. Aim for 50-60 characters'];
        } elseif (strlen($data['title']) > 70) {
            $suggestions[] = ['type' => 'warning', 'text' => 'SEO Title too long. Keep it under 60 characters'];
        } else {
            $suggestions[] = ['type' => 'success', 'text' => '✓ SEO Title is optimized'];
        }
        
        // Meta description suggestions
        if (empty($data['meta_description'])) {
            $suggestions[] = ['type' => 'error', 'text' => 'Meta Description is missing. Add one (120-160 chars)'];
        } elseif (strlen($data['meta_description']) < 120) {
            $suggestions[] = ['type' => 'warning', 'text' => 'Meta Description too short. Aim for 120-160 characters'];
        } elseif (strlen($data['meta_description']) > 180) {
            $suggestions[] = ['type' => 'warning', 'text' => 'Meta Description too long. Keep it under 160 characters'];
        } else {
            $suggestions[] = ['type' => 'success', 'text' => '✓ Meta Description is optimized'];
        }
        
        // Focus keyword suggestions
        if (empty($data['focus_keyword'])) {
            $suggestions[] = ['type' => 'warning', 'text' => 'No focus keyword set. Add your target keyword'];
        } elseif (!empty($data['content'])) {
            $keyword_check = self::checkKeywordInContent($data['focus_keyword'], $data['content']);
            if (!$keyword_check['exists']) {
                $suggestions[] = ['type' => 'error', 'text' => "❌ Keyword '{$data['focus_keyword']}' NOT found in content"];
            } elseif (!$keyword_check['optimal']) {
                $suggestions[] = ['type' => 'warning', 'text' => "⚠ Keyword density {$keyword_check['density']}% - optimal is 0.5-2.5%"];
            } else {
                $suggestions[] = ['type' => 'success', 'text' => "✓ Keyword '{$data['focus_keyword']}' well-placed ({$keyword_check['density']}% density)"];
            }
        }
        
        // Slug suggestions
        if (empty($data['slug'])) {
            $suggestions[] = ['type' => 'warning', 'text' => 'URL slug is not set. Generate from title'];
        } elseif (preg_match('/[^a-z0-9\-]/', $data['slug'])) {
            $suggestions[] = ['type' => 'error', 'text' => 'Slug contains invalid characters. Use only lowercase letters, numbers, and hyphens'];
        } else {
            $suggestions[] = ['type' => 'success', 'text' => '✓ URL slug is optimized'];
        }
        
        // Content quality
        if (!empty($data['content'])) {
            $content_analysis = self::analyzeContent($data['content']);
            if ($content_analysis['word_count'] < 300) {
                $suggestions[] = ['type' => 'warning', 'text' => "Content too short ({$content_analysis['word_count']} words). Add more content (aim for 300+)"];
            } else {
                $suggestions[] = ['type' => 'success', 'text' => "✓ Content length good ({$content_analysis['word_count']} words)"];
            }
        }
        
        // Schema markup
        if (empty($data['schema_markup'])) {
            $suggestions[] = ['type' => 'info', 'text' => 'Consider adding schema markup for better search engine understanding'];
        }
        
        // Open Graph
        if (empty($data['og_title']) || empty($data['og_description'])) {
            $suggestions[] = ['type' => 'info', 'text' => 'Add Open Graph tags for better social media sharing'];
        }
        
        return $suggestions;
    }
    
    /**
     * Get score color
     */
    public static function getScoreColor($score) {
        if ($score >= 80) {
            return ['color' => '#4caf50', 'label' => 'Excellent'];
        } elseif ($score >= 60) {
            return ['color' => '#8bc34a', 'label' => 'Good'];
        } elseif ($score >= 40) {
            return ['color' => '#ff9800', 'label' => 'Fair'];
        } else {
            return ['color' => '#f44336', 'label' => 'Poor'];
        }
    }
}
?>
