<?php
/**
 * Advanced SEO System for Ranking Growth
 * Implements 2025 SEO best practices
 */

class AdvancedSEOSystem {
    private $db;
    private $siteUrl;
    
    public function __construct($database, $siteUrl) {
        $this->db = $database;
        $this->siteUrl = $siteUrl;
    }
    
    /**
     * Generate comprehensive structured data (Schema.org)
     */
    public function generateStructuredData($type, $data) {
        $schemas = [];
        
        switch($type) {
            case 'organization':
                $schemas[] = [
                    "@context" => "https://schema.org",
                    "@type" => "Organization",
                    "name" => $data['name'],
                    "url" => $this->siteUrl,
                    "logo" => $this->siteUrl . '/images/' . $data['logo'],
                    "sameAs" => $data['social_links'] ?? [],
                    "contactPoint" => [
                        "@type" => "ContactPoint",
                        "contactType" => "customer service",
                        "email" => $data['email'] ?? ''
                    ]
                ];
                break;
                
            case 'website':
                $schemas[] = [
                    "@context" => "https://schema.org",
                    "@type" => "WebSite",
                    "name" => $data['name'],
                    "url" => $this->siteUrl,
                    "potentialAction" => [
                        "@type" => "SearchAction",
                        "target" => $this->siteUrl . "/search?q={search_term_string}",
                        "query-input" => "required name=search_term_string"
                    ]
                ];
                break;
                
            case 'breadcrumb':
                $items = [];
                foreach($data['items'] as $index => $item) {
                    $items[] = [
                        "@type" => "ListItem",
                        "position" => $index + 1,
                        "name" => $item['name'],
                        "item" => $item['url']
                    ];
                }
                $schemas[] = [
                    "@context" => "https://schema.org",
                    "@type" => "BreadcrumbList",
                    "itemListElement" => $items
                ];
                break;
                
            case 'article':
                $schemas[] = [
                    "@context" => "https://schema.org",
                    "@type" => "Article",
                    "headline" => $data['title'],
                    "description" => $data['description'],
                    "image" => $data['image'] ?? '',
                    "datePublished" => $data['published'],
                    "dateModified" => $data['modified'] ?? $data['published'],
                    "author" => [
                        "@type" => "Person",
                        "name" => $data['author']
                    ],
                    "publisher" => [
                        "@type" => "Organization",
                        "name" => $data['site_name'],
                        "logo" => [
                            "@type" => "ImageObject",
                            "url" => $data['site_logo']
                        ]
                    ]
                ];
                break;
                
            case 'offer':
                $schemas[] = [
                    "@context" => "https://schema.org",
                    "@type" => "Offer",
                    "name" => $data['title'],
                    "description" => $data['description'],
                    "url" => $data['url'],
                    "priceValidUntil" => $data['valid_until'] ?? '',
                    "availability" => "https://schema.org/InStock",
                    "seller" => [
                        "@type" => "Organization",
                        "name" => $data['store_name']
                    ]
                ];
                break;
                
            case 'faq':
                $questions = [];
                foreach($data['questions'] as $qa) {
                    $questions[] = [
                        "@type" => "Question",
                        "name" => $qa['question'],
                        "acceptedAnswer" => [
                            "@type" => "Answer",
                            "text" => $qa['answer']
                        ]
                    ];
                }
                $schemas[] = [
                    "@context" => "https://schema.org",
                    "@type" => "FAQPage",
                    "mainEntity" => $questions
                ];
                break;
        }
        
        return '<script type="application/ld+json">' . json_encode($schemas, JSON_UNESCAPED_SLASHES | JSON_PRETTY_PRINT) . '</script>';
    }
    
    /**
     * Generate Open Graph tags for social sharing
     */
    public function generateOpenGraphTags($data) {
        $tags = [
            'og:type' => $data['type'] ?? 'website',
            'og:title' => $data['title'],
            'og:description' => $data['description'],
            'og:url' => $data['url'],
            'og:site_name' => $data['site_name'],
            'og:locale' => $data['locale'] ?? 'en_US'
        ];
        
        if (!empty($data['image'])) {
            $tags['og:image'] = $data['image'];
            $tags['og:image:width'] = $data['image_width'] ?? '1200';
            $tags['og:image:height'] = $data['image_height'] ?? '630';
            $tags['og:image:alt'] = $data['image_alt'] ?? $data['title'];
        }
        
        $html = '';
        foreach ($tags as $property => $content) {
            $html .= '<meta property="' . $property . '" content="' . htmlspecialchars($content) . '">' . "\n";
        }
        
        return $html;
    }
    
    /**
     * Generate Twitter Card tags
     */
    public function generateTwitterCardTags($data) {
        $tags = [
            'twitter:card' => $data['card_type'] ?? 'summary_large_image',
            'twitter:title' => $data['title'],
            'twitter:description' => $data['description']
        ];
        
        if (!empty($data['image'])) {
            $tags['twitter:image'] = $data['image'];
            $tags['twitter:image:alt'] = $data['image_alt'] ?? $data['title'];
        }
        
        if (!empty($data['twitter_site'])) {
            $tags['twitter:site'] = $data['twitter_site'];
        }
        
        $html = '';
        foreach ($tags as $name => $content) {
            $html .= '<meta name="' . $name . '" content="' . htmlspecialchars($content) . '">' . "\n";
        }
        
        return $html;
    }
    
    /**
     * Generate canonical URL
     */
    public function generateCanonicalTag($url) {
        return '<link rel="canonical" href="' . htmlspecialchars($url) . '">';
    }
    
    /**
     * Generate hreflang tags for international SEO
     */
    public function generateHreflangTags($urls) {
        $html = '';
        foreach ($urls as $lang => $url) {
            $html .= '<link rel="alternate" hreflang="' . $lang . '" href="' . htmlspecialchars($url) . '">' . "\n";
        }
        return $html;
    }
    
    /**
     * Analyze content for SEO score
     */
    public function analyzeContent($title, $content, $targetKeyword = '') {
        $score = 0;
        $issues = [];
        $recommendations = [];
        
        // Title length check
        $titleLength = strlen($title);
        if ($titleLength >= 50 && $titleLength <= 60) {
            $score += 15;
        } else {
            $issues[] = "Title should be 50-60 characters (current: $titleLength)";
            $recommendations[] = $titleLength < 50 ? "Make title longer" : "Make title shorter";
        }
        
        // Content length check
        $wordCount = str_word_count(strip_tags($content));
        if ($wordCount >= 300) {
            $score += 20;
            if ($wordCount >= 1000) $score += 10;
            if ($wordCount >= 2000) $score += 10;
        } else {
            $issues[] = "Content too short (current: $wordCount words, recommended: 300+)";
            $recommendations[] = "Add more detailed content";
        }
        
        // Keyword density check
        if (!empty($targetKeyword)) {
            $keywordCount = substr_count(strtolower($content), strtolower($targetKeyword));
            $density = ($keywordCount / $wordCount) * 100;
            
            if ($density >= 0.5 && $density <= 2.5) {
                $score += 15;
            } else {
                $issues[] = "Keyword density should be 0.5-2.5% (current: " . number_format($density, 2) . "%)";
                $recommendations[] = $density < 0.5 ? "Use keyword more often" : "Reduce keyword usage";
            }
            
            // Keyword in title
            if (stripos($title, $targetKeyword) !== false) {
                $score += 10;
            } else {
                $issues[] = "Target keyword not in title";
                $recommendations[] = "Include keyword in title";
            }
        }
        
        // Heading structure
        $h1Count = substr_count($content, '<h1');
        $h2Count = substr_count($content, '<h2');
        
        if ($h1Count === 1) {
            $score += 10;
        } else {
            $issues[] = "Should have exactly one H1 tag (current: $h1Count)";
        }
        
        if ($h2Count >= 2) {
            $score += 10;
        } else {
            $issues[] = "Should have at least 2 H2 tags for better structure";
            $recommendations[] = "Add more subheadings";
        }
        
        // Image alt tags
        preg_match_all('/<img[^>]+>/i', $content, $images);
        $imageCount = count($images[0]);
        $altCount = 0;
        
        foreach ($images[0] as $img) {
            if (preg_match('/alt=["\'][^"\']*["\']/', $img)) {
                $altCount++;
            }
        }
        
        if ($imageCount > 0) {
            if ($altCount === $imageCount) {
                $score += 10;
            } else {
                $issues[] = "Not all images have alt tags ($altCount/$imageCount)";
                $recommendations[] = "Add alt text to all images";
            }
        }
        
        // Internal links
        $internalLinks = substr_count($content, 'href="' . $this->siteUrl);
        if ($internalLinks >= 2) {
            $score += 10;
        } else {
            $recommendations[] = "Add more internal links (current: $internalLinks)";
        }
        
        return [
            'score' => min($score, 100),
            'grade' => $this->getGrade($score),
            'issues' => $issues,
            'recommendations' => $recommendations,
            'metrics' => [
                'title_length' => $titleLength,
                'word_count' => $wordCount,
                'keyword_density' => isset($density) ? $density : 0,
                'h1_count' => $h1Count,
                'h2_count' => $h2Count,
                'images_with_alt' => "$altCount/$imageCount",
                'internal_links' => $internalLinks
            ]
        ];
    }
    
    private function getGrade($score) {
        if ($score >= 90) return 'A+';
        if ($score >= 80) return 'A';
        if ($score >= 70) return 'B';
        if ($score >= 60) return 'C';
        if ($score >= 50) return 'D';
        return 'F';
    }
    
    /**
     * Generate meta robots tag
     */
    public function generateRobotsTag($index = true, $follow = true, $additional = []) {
        $directives = [];
        $directives[] = $index ? 'index' : 'noindex';
        $directives[] = $follow ? 'follow' : 'nofollow';
        $directives = array_merge($directives, $additional);
        
        return '<meta name="robots" content="' . implode(', ', $directives) . '">';
    }
    
    /**
     * Generate optimized meta description
     */
    public function generateMetaDescription($content, $maxLength = 160) {
        $description = strip_tags($content);
        $description = preg_replace('/\s+/', ' ', $description);
        $description = trim($description);
        
        if (strlen($description) > $maxLength) {
            $description = substr($description, 0, $maxLength - 3);
            $lastSpace = strrpos($description, ' ');
            if ($lastSpace !== false) {
                $description = substr($description, 0, $lastSpace);
            }
            $description .= '...';
        }
        
        return $description;
    }
    
    /**
     * Track SEO performance
     */
    public function trackSEOMetrics($pageUrl, $metrics) {
        try {
            $stmt = $this->db->prepare("
                INSERT INTO seo_metrics (page_url, score, word_count, keyword_density, tracked_at)
                VALUES (:url, :score, :words, :density, NOW())
                ON DUPLICATE KEY UPDATE 
                    score = :score,
                    word_count = :words,
                    keyword_density = :density,
                    tracked_at = NOW()
            ");
            
            $stmt->execute([
                ':url' => $pageUrl,
                ':score' => $metrics['score'],
                ':words' => $metrics['word_count'],
                ':density' => $metrics['keyword_density']
            ]);
            
            return true;
        } catch (Exception $e) {
            return false;
        }
    }
}
?>
