<?php
// NEXUS Commerce - Visual AI Search Endpoint
require_once __DIR__ . '/db.php';

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

try {
    // Fetch products to represent visual search results
    $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");
    $products = $stmt->fetchAll();

    $visualMatches = [];
    $simScores = [96, 92, 88, 84, 79];

    foreach ($products as $index => $p) {
        $p['similarity_score'] = $simScores[$index % count($simScores)];
        $p['match_type'] = ($index === 0) ? 'Identical Style' : (($index === 1) ? 'Higher Quality Alternative' : 'Better Price Alternative');
        $p['gallery'] = json_decode($p['gallery'] ?? '[]');
        $p['specs'] = json_decode($p['specs'] ?? '{}');
        $p['ai_summary'] = json_decode($p['ai_summary'] ?? '{}');
        $visualMatches[] = $p;
    }

    echo json_encode([
        'status' => 'success',
        'image_detected' => [
            'object_type' => 'Consumer Electronics / Cyber Accessories',
            'dominant_colors' => ['Obsidian Black', 'Electric Blue'],
            'estimated_market_val' => '฿1,290 - ฿2,890'
        ],
        'total_found' => count($visualMatches),
        'data' => $visualMatches
    ]);

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