<?php
/**
 * ZLO Platform - Search Controller
 */

declare(strict_types=1);

require_once __DIR__ . '/../core/Router.php';

class SearchController
{
    private Database $db;
    
    public function __construct()
    {
        $this->db = new Database();
    }
    
    /**
     * Global search across all content
     */
    public function search(array $params): array
    {
        $query = Router::getQuery();
        $q = $query['q'] ?? '';
        $type = $query['type'] ?? 'all';
        $limit = (int) ($query['limit'] ?? 10);
        
        if (empty($q) || strlen($q) < 2) {
            http_response_code(400);
            return ['error' => 'Search query must be at least 2 characters'];
        }
        
        $results = [];
        $searchTerm = "%{$q}%";
        
        // Search solutions
        if ($type === 'all' || $type === 'solutions') {
            $solutions = $this->db->fetchAll(
                "SELECT id, title, slug, short_description as excerpt, 'solution' as type, icon, preview_image as image 
                 FROM solutions 
                 WHERE status = 'active' AND (title LIKE ? OR short_description LIKE ? OR full_description LIKE ?) 
                 LIMIT ?",
                [$searchTerm, $searchTerm, $searchTerm, $limit]
            );
            $results = array_merge($results, $solutions);
        }
        
        // Search blog posts
        if ($type === 'all' || $type === 'blog') {
            $posts = $this->db->fetchAll(
                "SELECT bp.id, bp.title, bp.slug, bp.excerpt, 'blog' as type, bp.featured_image as image, bc.name as category 
                 FROM blog_posts bp 
                 LEFT JOIN blog_categories bc ON bp.category_id = bc.id 
                 WHERE bp.status = 'published' AND (bp.title LIKE ? OR bp.excerpt LIKE ? OR bp.content LIKE ?) 
                 LIMIT ?",
                [$searchTerm, $searchTerm, $searchTerm, $limit]
            );
            $results = array_merge($results, $posts);
        }
        
        // Search pages
        if ($type === 'all' || $type === 'pages') {
            $pages = $this->db->fetchAll(
                "SELECT id, title, slug, SUBSTRING(content, 1, 200) as excerpt, 'page' as type 
                 FROM pages 
                 WHERE status = 'active' AND (title LIKE ? OR content LIKE ?) 
                 LIMIT ?",
                [$searchTerm, $searchTerm, $limit]
            );
            $results = array_merge($results, $pages);
        }
        
        // Search case studies
        if ($type === 'all' || $type === 'case-studies') {
            $cases = $this->db->fetchAll(
                "SELECT id, title, slug, problem as excerpt, 'case-study' as type, image 
                 FROM case_studies 
                 WHERE published = 1 AND (title LIKE ? OR problem LIKE ? OR solution LIKE ?) 
                 LIMIT ?",
                [$searchTerm, $searchTerm, $searchTerm, $limit]
            );
            $results = array_merge($results, $cases);
        }
        
        // Search FAQs
        if ($type === 'all' || $type === 'faqs') {
            $faqs = $this->db->fetchAll(
                "SELECT id, question as title, answer as excerpt, 'faq' as type 
                 FROM faqs 
                 WHERE status = 'active' AND (question LIKE ? OR answer LIKE ?) 
                 LIMIT ?",
                [$searchTerm, $searchTerm, $limit]
            );
            $results = array_merge($results, $faqs);
        }
        
        // Sort by relevance (simple - title match gets priority)
        usort($results, function($a, $b) use ($q) {
            $aTitleMatch = stripos($a['title'], $q) !== false;
            $bTitleMatch = stripos($b['title'], $q) !== false;
            
            if ($aTitleMatch && !$bTitleMatch) return -1;
            if (!$aTitleMatch && $bTitleMatch) return 1;
            return 0;
        });
        
        // Limit total results
        $results = array_slice($results, 0, $limit);
        
        return [
            'query' => $q,
            'type' => $type,
            'count' => count($results),
            'results' => $results
        ];
    }
    
    /**
     * Search suggestions (autocomplete)
     */
    public function suggestions(array $params): array
    {
        $query = Router::getQuery();
        $q = $query['q'] ?? '';
        $limit = (int) ($query['limit'] ?? 5);
        
        if (empty($q) || strlen($q) < 2) {
            return ['suggestions' => []];
        }
        
        $searchTerm = "%{$q}%";
        $suggestions = [];
        
        // Solutions suggestions
        $solutions = $this->db->fetchAll(
            "SELECT title, slug, 'solution' as type, icon 
             FROM solutions 
             WHERE status = 'active' AND title LIKE ? 
             LIMIT ?",
            [$searchTerm, $limit]
        );
        $suggestions = array_merge($suggestions, $solutions);
        
        // Blog suggestions
        $posts = $this->db->fetchAll(
            "SELECT bp.title, bp.slug, 'blog' as type, bc.name as category 
             FROM blog_posts bp 
             LEFT JOIN blog_categories bc ON bp.category_id = bc.id 
             WHERE bp.status = 'published' AND bp.title LIKE ? 
             LIMIT ?",
            [$searchTerm, $limit]
        );
        $suggestions = array_merge($suggestions, $posts);
        
        // Limit suggestions
        $suggestions = array_slice($suggestions, 0, $limit);
        
        return ['suggestions' => $suggestions];
    }
    
    /**
     * Get popular searches
     */
    public function popular(array $params): array
    {
        // In production, this would come from analytics
        // For now, return static popular terms
        return [
            'popular_searches' => [
                'fleet management',
                'e-commerce',
                'school transport',
                'AI automation',
                'mobile payment',
                'logistics',
                'GPS tracking'
            ]
        ];
    }
}
