<?php
// NEXUS Commerce - Magic AI Natural Language Search API
require_once __DIR__ . '/db.php';

header('Content-Type: application/json; charset=utf-8');

$input = json_decode(file_get_contents('php://input'), true);
$query = trim($input['query'] ?? '');

if (empty($query)) {
    echo json_encode(['status' => 'error', 'message' => 'Query prompt cannot be empty.']);
    exit;
}

try {
    // Perform AI analysis simulation on natural language prompt
    $keywords = mb_strtolower($query, 'UTF-8');
    
    // Fetch all products to score relevance
    $stmt = $pdo->query("SELECT p.*, s.store_name, c.name as category_name FROM products p JOIN stores s ON p.store_id = s.id JOIN categories c ON p.category_id = c.id");
    $allProducts = $stmt->fetchAll();

    $results = [];

    foreach ($allProducts as $p) {
        $relevanceScore = 70; // baseline match score
        $reasons = [];

        // Dynamic reasoning based on user's query keywords
        if (strpos($keywords, 'งบ') !== false || strpos($keywords, 'บาท') !== false || preg_match('/\d+/', $keywords)) {
            $reasons[] = "อยู่ในช่วงงบประมาณที่คุณกำหนด (฿" . number_format($p['price'], 0) . ")";
            $relevanceScore += 10;
        }

        if (strpos($keywords, 'เดิน') !== false || strpos($keywords, 'ทำงาน') !== false || strpos($keywords, 'ใส่') !== false) {
            $reasons[] = "เหมาะสำหรับสวมใส่ทำงานและใช้งานลุยยาวนานตลอดวัน";
            $relevanceScore += 10;
        }

        if (strpos($keywords, 'หูฟัง') !== false || strpos($keywords, 'เสียง') !== false || strpos($keywords, 'anc') !== false) {
            if ($p['category_id'] == 1 || $p['category_id'] == 4) {
                $relevanceScore += 25;
                $reasons[] = "ตรงตามหมวดหมู่อุปกรณ์เสียง Noise Cancelling ที่คุณค้นหา";
            }
        }

        if (strpos($keywords, 'คีย์บอร์ด') !== false || strpos($keywords, 'พิมพ์') !== false || strpos($keywords, 'เกม') !== false) {
            if ($p['category_id'] == 5 || $p['category_id'] == 1) {
                $relevanceScore += 25;
                $reasons[] = "สวิตช์ตอบสนองรวดเร็ว เหมาะกับ Gaming & Workspace";
            }
        }

        if (empty($reasons)) {
            $reasons[] = "คะแนนความน่าเชื่อถือสูง (" . $p['trust_score'] . "/100) และได้รับการรีวิวดีเยี่ยมจากผู้ใช้จริง";
        }

        $p['match_percentage'] = min(99, $relevanceScore);
        $p['ai_reasoning'] = "เราเลือกสินค้านี้เพราะ: " . implode(" • ", $reasons);
        $p['gallery'] = json_decode($p['gallery'] ?? '[]');
        $p['specs'] = json_decode($p['specs'] ?? '{}');
        $p['ai_summary'] = json_decode($p['ai_summary'] ?? '{}');

        $results[] = $p;
    }

    // Sort by match percentage
    usort($results, function($a, $b) {
        return $b['match_percentage'] <=> $a['match_percentage'];
    });

    echo json_encode([
        'status' => 'success',
        'query' => $query,
        'ai_analysis' => [
            'perceived_intent' => 'High Intent Shopping Query',
            'extracted_criteria' => ['Optimized Price-Performance', 'High Comfort Rating', 'Verified Seller Trust'],
            'total_matches' => count($results)
        ],
        'data' => array_slice($results, 0, 4)
    ]);

} catch (Exception $e) {
    echo json_encode(['status' => 'error', 'message' => $e->getMessage()]);
}
