<?php
/**
 * Internal Linking Engine for AloneDeals.com
 * Automatically suggests and creates internal links for better SEO
 */

class InternalLinkingEngine {
    private $siteUrl = 'https://alonedeals.com';
    private $db;
    private $maxLinksPerPage = 5;
    
    public function __construct($database) {
        $this->db = $database;
    }
    
    /**
     * Find related content based on keywords
     */
    public function findRelatedContent($currentId, $currentType, $keywords, $limit = 5) {
        $related = [];
        
        // Extract important keywords
        $keywordArray = $this->extractKeywords($keywords);
        
        if (empty($keywordArray)) {
            return $related;
        }
        
        // Build keyword search
        $keywordSearch = implode('|', array_map('preg_quote', $keywordArray));
        
        // Find related blog posts
        if ($currentType !== 'blog') {
            $stmt = $this->db->prepare("
                SELECT post_id, post_title, post_slug, post_excerpt 
                FROM blog_posts 
                WHERE post_status = 'published' 
                AND (post_title REGEXP :keywords OR post_content REGEXP :keywords)
                ORDER BY published_at DESC 
                LIMIT :limit
            ");
            $stmt->bindValue(':keywords', $keywordSearch, PDO::PARAM_STR);
            $stmt->bindValue(':limit', $limit, PDO::PARAM_INT);
            $stmt->execute();
            
            while ($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
                $related[] = [
                    'type' => 'blog',
                    'title' => $row['post_title'],
                    'url' => $this->siteUrl . '/Post/' . $row['post_slug'],
                    'excerpt' => $row['post_excerpt']
                ];
            }
        }
        
        // Find related stores
        if ($currentType !== 'store' && count($related) < $limit) {
            $stmt = $this->db->prepare("
                SELECT store_id, store_title, store_slug, store_description 
                FROM stores 
                WHERE store_status = 1 
                AND (store_title REGEXP :keywords OR store_description REGEXP :keywords)
                LIMIT :limit
            ");
            $stmt->bindValue(':keywords', $keywordSearch, PDO::PARAM_STR);
            $stmt->bindValue(':limit', $limit - count($related), PDO::PARAM_INT);
            $stmt->execute();
            
            while ($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
                $related[] = [
                    'type' => 'store',
                    'title' => $row['store_title'],
                    'url' => $this->siteUrl . '/store/' . $row['store_slug'],
                    'excerpt' => substr($row['store_description'], 0, 150)
                ];
            }
        }
        
        // Find related categories
        if ($currentType !== 'category' && count($related) < $limit) {
            $stmt = $this->db->prepare("
                SELECT category_id, category_title, category_slug 
                FROM categories 
                WHERE category_status = 1 
                AND category_title REGEXP :keywords
                LIMIT :limit
            ");
            $stmt->bindValue(':keywords', $keywordSearch, PDO::PARAM_STR);
            $stmt->bindValue(':limit', $limit - count($related), PDO::PARAM_INT);
            $stmt->execute();
            
            while ($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
                $related[] = [
                    'type' => 'category',
                    'title' => $row['category_title'],
                    'url' => $this->siteUrl . '/category/' . $row['category_slug'],
                    'excerpt' => ''
                ];
            }
        }
        
        return $related;
    }
    
    /**
     * Extract important keywords from text
     */
    private function extractKeywords($text, $limit = 10) {
        // Remove HTML tags
        $text = strip_tags($text);
        
        // Convert to lowercase
        $text = strtolower($text);
        
        // Remove common words
        $stopWords = ['the', 'a', 'an', 'and', 'or', 'but', 'in', 'on', 'at', 'to', 'for', 'of', 'with', 'by', 'from', 'as', 'is', 'was', 'are', 'been', 'be', 'have', 'has', 'had', 'do', 'does', 'did', 'will', 'would', 'could', 'should', 'may', 'might', 'can', 'this', 'that', 'these', 'those'];
        
        // Split into words
        $words = preg_split('/\s+/', $text);
        
        // Count word frequency
        $wordCount = [];
        foreach ($words as $word) {
            $word = preg_replace('/[^a-z0-9]/', '', $word);
            if (strlen($word) > 3 && !in_array($word, $stopWords)) {
                $wordCount[$word] = ($wordCount[$word] ?? 0) + 1;
            }
        }
        
        // Sort by frequency
        arsort($wordCount);
        
        // Return top keywords
        return array_slice(array_keys($wordCount), 0, $limit);
    }
    
    /**
     * Auto-insert internal links into content
     */
    public function autoInsertLinks($content, $currentId, $currentType) {
        // Extract keywords from content
        $keywords = $this->extractKeywords($content, 20);
        
        // Find related content
        $related = $this->findRelatedContent($currentId, $currentType, implode(' ', $keywords), 10);
        
        if (empty($related)) {
            return $content;
        }
        
        $linksAdded = 0;
        $maxLinks = $this->maxLinksPerPage;
        
        // Try to insert links for each related item
        foreach ($related as $item) {
            if ($linksAdded >= $maxLinks) {
                break;
            }
            
            // Find the first occurrence of the title in content (case-insensitive)
            $title = $item['title'];
            $pattern = '/\b(' . preg_quote($title, '/') . ')\b/i';
            
            // Check if link already exists
            if (stripos($content, 'href="' . $item['url'] . '"') !== false) {
                continue;
            }
            
            // Replace first occurrence with link
            $replacement = '<a href="' . $item['url'] . '" title="' . htmlspecialchars($title) . '">$1</a>';
            $newContent = preg_replace($pattern, $replacement, $content, 1, $count);
            
            if ($count > 0) {
                $content = $newContent;
                $linksAdded++;
            }
        }
        
        return $content;
    }
    
    /**
     * Generate related content widget HTML
     */
    public function generateRelatedWidget($currentId, $currentType, $keywords) {
        $related = $this->findRelatedContent($currentId, $currentType, $keywords, 4);
        
        if (empty($related)) {
            return '';
        }
        
        $html = '<div class="related-content-widget">';
        $html .= '<h3 class="related-title">Related Content</h3>';
        $html .= '<div class="related-items">';
        
        foreach ($related as $item) {
            $icon = $this->getTypeIcon($item['type']);
            $html .= '<div class="related-item">';
            $html .= '<a href="' . $item['url'] . '" class="related-link">';
            $html .= '<span class="related-icon">' . $icon . '</span>';
            $html .= '<span class="related-text">';
            $html .= '<strong>' . htmlspecialchars($item['title']) . '</strong>';
            if (!empty($item['excerpt'])) {
                $html .= '<small>' . htmlspecialchars(substr($item['excerpt'], 0, 80)) . '...</small>';
            }
            $html .= '</span>';
            $html .= '</a>';
            $html .= '</div>';
        }
        
        $html .= '</div>';
        $html .= '</div>';
        
        return $html;
    }
    
    /**
     * Get icon for content type
     */
    private function getTypeIcon($type) {
        $icons = [
            'blog' => '📝',
            'store' => '🏪',
            'category' => '📂',
            'coupon' => '🎫'
        ];
        
        return $icons[$type] ?? '🔗';
    }
    
    /**
     * Analyze internal linking structure
     */
    public function analyzeLinkingStructure() {
        $analysis = [
            'total_pages' => 0,
            'pages_with_links' => 0,
            'pages_without_links' => 0,
            'avg_links_per_page' => 0,
            'orphan_pages' => []
        ];
        
        // Analyze blog posts
        $posts = $this->db->query("SELECT post_id, post_title, post_content FROM blog_posts WHERE post_status = 'published'")->fetchAll(PDO::FETCH_ASSOC);
        
        $totalLinks = 0;
        foreach ($posts as $post) {
            $analysis['total_pages']++;
            
            // Count internal links
            $linkCount = substr_count($post['post_content'], $this->siteUrl);
            
            if ($linkCount > 0) {
                $analysis['pages_with_links']++;
                $totalLinks += $linkCount;
            } else {
                $analysis['pages_without_links']++;
                $analysis['orphan_pages'][] = [
                    'id' => $post['post_id'],
                    'title' => $post['post_title'],
                    'type' => 'blog'
                ];
            }
        }
        
        if ($analysis['total_pages'] > 0) {
            $analysis['avg_links_per_page'] = round($totalLinks / $analysis['total_pages'], 2);
        }
        
        return $analysis;
    }
}
?>
