<?php
// get/search_by_image.php
require_once '../config/config.php';
require_once '../assets/php/ImageHasher.php';

header('Content-Type: application/json');

if (!isset($_SESSION['user_id'])) {
    echo json_encode(['status' => 'error', 'msg' => 'Unauthorized']);
    exit;
}

if (!isset($_FILES['search_image']) || $_FILES['search_image']['error'] !== 0) {
    echo json_encode(['status' => 'error', 'msg' => 'No image uploaded']);
    exit;
}

// 1. Proses Upload Sementara
 $tmpName = $_FILES['search_image']['tmp_name'];
 $uploadDir = '../assets/img/product/tmp/';
if (!is_dir($uploadDir)) mkdir($uploadDir, 0777, true);
 $tempFile = $uploadDir . 'scan_' . time() . '.jpg';

if (!move_uploaded_file($tmpName, $tempFile)) {
    echo json_encode(['status' => 'error', 'msg' => 'Failed to move file']);
    exit;
}

// 2. Generate Hash dari Foto User
 $userHash = ImageHasher::generateHash($tempFile);

if (!$userHash) {
    unlink($tempFile);
    echo json_encode(['status' => 'error', 'msg' => 'Cannot read image']);
    exit;
}

// 3. Ambil semua hash dari DB
 $stmt = $pdo->query("SELECT si.image_hash, si.image_path, s.id, s.name, s.part_number, s.stock, s.unit, c.name as category_name
                     FROM sparepart_images si
                     JOIN spareparts s ON si.sparepart_id = s.id
                     LEFT JOIN category c ON s.category_id = c.id
                     WHERE si.image_hash IS NOT NULL");
 $images = $stmt->fetchAll(PDO::FETCH_ASSOC);

// 4. Bandingkan Hash (Brute Force - cocok untuk <5000 gambar)
 $results = [];
foreach ($images as $img) {
    $distance = ImageHasher::compareHash($userHash, $img['image_hash']);
    
    // Threshold: 10 (boleh mirip), 0 (identik)
    if ($distance <= 12) { 
        $results[] = [
            'id' => $img['id'],
            'name' => $img['name'],
            'part_number' => $img['part_number'],
            'stock' => $img['stock'],
            'unit' => $img['unit'],
            'category_name' => $img['category_name'],
            'image_path' => $img['image_path'],
            'distance' => $distance // Untuk sorting
        ];
    }
}

// 5. Sortir berdasarkan kemiripan terbaik (distance terkecil)
usort($results, function($a, $b) {
    return $a['distance'] <=> $b['distance'];
});

// Hapus file temp
unlink($tempFile);

echo json_encode([
    'status' => 'success',
    'count' => count($results),
    'data' => array_slice($results, 0, 5) // Ambil 5 teratas
]);
?>