<?php
/**
 * AI-Powered SEO Meta Tag Generator - 2025 Algorithm
 * Ultra-fast processing with intelligent optimization
 */

class SEO_Meta_Generator {
    
    private $connect;
    private $settings;
    
    public function __construct($connect) {
        $this->connect = $connect;
        $this->settings = getSettings($connect);
    }
    
    /**
     * Generate optimized title tag
     */
    public function generate_title($data) {
        $type = $data['type']; // blog, store, category, author
        $title = '';
        $brand = $this->settings['st_sitename'];
        $year = date('Y');
        
        switch ($type) {
            case 'blog':
                // AI-optimized blog title
                $keyword = $this->extract_primary_keyword($data['content']);
                $benefit = $this->extract_benefit($data['title']);
                $title = $data['seo_title'] ?: $data['title'];
                $title = $this->optimize_title_length($title . " | " . $brand . " " . $year);
                break;
                
            case 'store':
                $discount = $this->calculate_max_discount($data['store_id']);
                $title = $data['store_title'] . " Coupons & Deals | Save " . $discount . "% | " . $brand;
                break;
                
            case 'category':
                $count = $this->count_items($data['category_id']);
                $title = $data['category_title'] . " Deals | " . $count . "+ Coupons | " . $brand . " " . $year;
                break;
                
            case 'author':
                $post_count = $this->count_author_posts($data['author_id']);
                $title = $data['author_name'] . " | " . $post_count . " Expert Articles | " . $brand;
                break;
                
            default:
                $title = $data['title'] . " | " . $brand;
        }
        
        return $this->sanitize_title($title);
    }
    
    /**
     * Generate optimized meta description
     */
    public function generate_description($data) {
        $type = $data['type'];
        $description = '';
        
        switch ($type) {
            case 'blog':
                $description = $data['seo_description'] ?: $this->auto_generate_description($data);
                break;
                
            case 'store':
                $count = $this->count_store_coupons($data['store_id']);
                $description = "Get " . $data['store_title'] . " coupons! " . $count . "+ verified promo codes and deals. Save up to " . $this->calculate_max_discount($data['store_id']) . "%. Updated daily. Shop now!";
                break;
                
            case 'category':
                $count = $this->count_items($data['category_id']);
                $description = "Browse " . $count . "+ " . $data['category_title'] . " deals! Find the best coupons, promo codes, and exclusive discounts. Updated daily. Start saving money today!";
                break;
                
            case 'author':
                $post_count = $this->count_author_posts($data['author_id']);
                $description = "Read articles by " . $data['author_name'] . ". " . $post_count . "+ expert guides, reviews, and tips. Follow for the latest updates and insights!";
                break;
        }
        
        return $this->optimize_description_length($description);
    }
    
    /**
     * Auto-generate description from content
     */
    private function auto_generate_description($data) {
        $content = strip_tags($data['content']);
        $excerpt = substr($content, 0, 300);
        
        // Find first complete sentence
        $sentences = preg_split('/(?<=[.?!])\s+/', $excerpt, -1, PREG_SPLIT_NO_EMPTY);
        $description = '';
        $length = 0;
        
        foreach ($sentences as $sentence) {
            if ($length + strlen($sentence) <= 155) {
                $description .= $sentence . ' ';
                $length += strlen($sentence) + 1;
            } else {
                break;
            }
        }
        
        // Add call-to-action
        $ctas = ['Read more →', 'Learn more →', 'Discover now →', 'Get started →'];
        $description = trim($description) . ' ' . $ctas[array_rand($ctas)];
        
        return $description;
    }
    
    /**
     * Extract primary keyword using AI logic
     */
    private function extract_primary_keyword($content) {
        $words = str_word_count(strtolower(strip_tags($content)), 1);
        $stopWords = ['the', 'is', 'at', 'which', 'on', 'a', 'an', 'and', 'or', 'but', 'in', 'with', 'to', 'for', 'of', 'as', 'by'];
        
        // Remove stop words
        $words = array_diff($words, $stopWords);
        
        // Count word frequency
        $frequency = array_count_values($words);
        arsort($frequency);
        
        // Get top keyword
        $keywords = array_slice(array_keys($frequency), 0, 3);
        return implode(' ', $keywords);
    }
    
    /**
     * Extract benefit from title
     */
    private function extract_benefit($title) {
        $benefits = [
            'save' => 'Save Money',
            'best' => 'Best Deals',
            'free' => 'Free Shipping',
            'discount' => 'Huge Discounts',
            'coupon' => 'Exclusive Coupons',
            'deal' => 'Hot Deals',
            'offer' => 'Special Offers'
        ];
        
        foreach ($benefits as $keyword => $benefit) {
            if (stripos($title, $keyword) !== false) {
                return $benefit;
            }
        }
        
        return 'Great Value';
    }
    
    /**
     * Optimize title length (50-60 characters)
     */
    private function optimize_title_length($title) {
        if (strlen($title) > 60) {
            $title = substr($title, 0, 57) . '...';
        }
        return $title;
    }
    
    /**
     * Optimize description length (150-160 characters)
     */
    private function optimize_description_length($description) {
        if (strlen($description) > 160) {
            $description = substr($description, 0, 157) . '...';
        }
        return $description;
    }
    
    /**
     * Sanitize title
     */
    private function sanitize_title($title) {
        return htmlspecialchars($title, ENT_QUOTES, 'UTF-8');
    }
    
    /**
     * Calculate maximum discount for store
     */
    private function calculate_max_discount($store_id) {
        $stmt = $this->connect->prepare("SELECT MAX(CAST(SUBSTRING_INDEX(coupon_code, '%', 1) AS UNSIGNED)) as max_discount 
                                         FROM coupons 
                                         WHERE coupon_store = :store_id 
                                         AND coupon_status = 1 
                                         AND coupon_code LIKE '%OFF%'");
        $stmt->execute([':store_id' => $store_id]);
        $result = $stmt->fetch(PDO::FETCH_ASSOC);
        return $result['max_discount'] ?: 50;
    }
    
    /**
     * Count store coupons
     */
    private function count_store_coupons($store_id) {
        $stmt = $this->connect->prepare("SELECT COUNT(*) as count FROM coupons WHERE coupon_store = :store_id AND coupon_status = 1");
        $stmt->execute([':store_id' => $store_id]);
        $result = $stmt->fetch(PDO::FETCH_ASSOC);
        return $result['count'];
    }
    
    /**
     * Count category items
     */
    private function count_items($category_id) {
        $stmt = $this->connect->prepare("SELECT COUNT(*) as count FROM coupons WHERE coupon_category = :category_id AND coupon_status = 1");
        $stmt->execute([':category_id' => $category_id]);
        $result = $stmt->fetch(PDO::FETCH_ASSOC);
        return $result['count'];
    }
    
    /**
     * Count author posts
     */
    private function count_author_posts($author_id) {
        $stmt = $this->connect->prepare("SELECT COUNT(*) as count FROM blog_posts WHERE post_author = :author_id AND post_status = 'published'");
        $stmt->execute([':author_id' => $author_id]);
        $result = $stmt->fetch(PDO::FETCH_ASSOC);
        return $result['count'];
    }
    
    /**
     * Generate complete meta tags HTML
     */
    public function generate_meta_tags($data) {
        $title = $this->generate_title($data);
        $description = $this->generate_description($data);
        $url = $data['url'];
        $image = $data['image'] ?: SITE_URL . '/images/default-og.jpg';
        $type = $data['og_type'] ?: 'website';
        
        $meta = '';
        
        // Core Meta Tags
        $meta .= '<title>' . $title . '</title>' . "\n";
        $meta .= '<meta name="description" content="' . $description . '">' . "\n";
        
        if (!empty($data['keywords'])) {
            $meta .= '<meta name="keywords" content="' . htmlspecialchars($data['keywords']) . '">' . "\n";
        }
        
        // Robots
        $meta .= '<meta name="robots" content="index, follow, max-snippet:-1, max-image-preview:large, max-video-preview:-1">' . "\n";
        $meta .= '<meta name="googlebot" content="index, follow, max-snippet:-1, max-image-preview:large, max-video-preview:-1">' . "\n";
        
        // Canonical
        $meta .= '<link rel="canonical" href="' . $url . '">' . "\n";
        
        // Open Graph
        $meta .= '<meta property="og:type" content="' . $type . '">' . "\n";
        $meta .= '<meta property="og:site_name" content="' . $this->settings['st_sitename'] . '">' . "\n";
        $meta .= '<meta property="og:title" content="' . $title . '">' . "\n";
        $meta .= '<meta property="og:description" content="' . $description . '">' . "\n";
        $meta .= '<meta property="og:url" content="' . $url . '">' . "\n";
        $meta .= '<meta property="og:image" content="' . $image . '">' . "\n";
        $meta .= '<meta property="og:image:width" content="1200">' . "\n";
        $meta .= '<meta property="og:image:height" content="630">' . "\n";
        
        // Twitter Card
        $meta .= '<meta name="twitter:card" content="summary_large_image">' . "\n";
        $meta .= '<meta name="twitter:title" content="' . $title . '">' . "\n";
        $meta .= '<meta name="twitter:description" content="' . $description . '">' . "\n";
        $meta .= '<meta name="twitter:image" content="' . $image . '">' . "\n";
        
        // Advanced 2025 Tags
        $meta .= '<meta name="AI-search-optimized" content="true">' . "\n";
        $meta .= '<meta name="content-type" content="' . $data['type'] . '">' . "\n";
        
        if ($data['type'] == 'blog') {
            $meta .= '<meta name="article:published_time" content="' . date('c', strtotime($data['published_at'])) . '">' . "\n";
            $meta .= '<meta name="article:modified_time" content="' . date('c', strtotime($data['updated_at'])) . '">' . "\n";
            $meta .= '<meta name="article:author" content="' . $data['author_name'] . '">' . "\n";
        }
        
        return $meta;
    }
    
    /**
     * Score meta tags (0-100)
     */
    public function score_meta_tags($title, $description) {
        $score = 0;
        
        // Title scoring
        $titleLen = strlen($title);
        if ($titleLen >= 50 && $titleLen <= 60) $score += 20;
        elseif ($titleLen >= 40 && $titleLen < 70) $score += 15;
        else $score += 5;
        
        // Description scoring
        $descLen = strlen($description);
        if ($descLen >= 150 && $descLen <= 160) $score += 20;
        elseif ($descLen >= 130 && $descLen < 170) $score += 15;
        else $score += 5;
        
        // Keyword in title
        if (preg_match('/\b(best|top|guide|how|what|why)\b/i', $title)) $score += 15;
        
        // Year in title
        if (strpos($title, date('Y')) !== false) $score += 10;
        
        // CTA in description
        if (preg_match('/\b(now|today|start|get|learn|discover|read)\b/i', $description)) $score += 15;
        
        // Numbers in content
        if (preg_match('/\d+/', $title . $description)) $score += 10;
        
        // Brand mention
        if (stripos($title, $this->settings['st_sitename']) !== false) $score += 10;
        
        return min($score, 100);
    }
}

// Helper function
function generate_seo_meta($connect, $data) {
    $generator = new SEO_Meta_Generator($connect);
    return $generator->generate_meta_tags($data);
}
?>
