<?php
// API for AI search suggestions
header('Content-Type: application/json');
require_once '../config/config.php';
require_once '../classes/Database.php';
require_once '../classes/Auth.php';

$db = Database::getInstance();
$auth = new Auth($db);

if (!$auth->isLoggedIn()) {
    echo json_encode(['suggestions' => []]);
    exit();
}

$currentUser = $auth->getCurrentUser();
$userId = $currentUser['id'];
$searchType = $_GET['type'] ?? 'mobile'; // 'mobile' or 'aadhaar'
$query = trim($_GET['query'] ?? '');

if (empty($query) || strlen($query) < 2) {
    echo json_encode(['suggestions' => []]);
    exit();
}

try {
    // Get recent searches matching the query
    $sql = "SELECT DISTINCT query FROM search_logs 
            WHERE user_id = $userId AND type = '$searchType' AND query LIKE '%$query%'
            ORDER BY created_at DESC LIMIT 8";
    
    $recentSearches = $db->fetchAll($sql) ?: [];
    
    // Generate smart suggestions
    $suggestions = [];
    
    foreach ($recentSearches as $search) {
        $suggestions[] = $search['query'];
    }
    
    // If not enough from history, suggest patterns
    if (count($suggestions) < 5) {
        if ($searchType === 'mobile' && preg_match('/^[6-9]/', $query)) {
            // Suggest common mobile patterns
            $digit = substr($query, 0, 1);
            for ($i = 0; $i < 3; $i++) {
                $pattern = $digit . str_repeat('8', strlen($query) - 1 + $i);
                if (!in_array($pattern, $suggestions)) {
                    $suggestions[] = $pattern;
                }
            }
        }
    }
    
    echo json_encode([
        'suggestions' => array_slice($suggestions, 0, 8),
        'query' => $query
    ]);
    
} catch (Exception $e) {
    echo json_encode(['suggestions' => [], 'error' => $e->getMessage()]);
}
?>
