<?php
// get/search_by_barcode.php
require_once '../config/config.php';

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

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

 $barcode = $_POST['barcode'] ?? '';

if (empty($barcode)) {
    echo json_encode(['status' => 'error', 'msg' => 'Barcode empty']);
    exit;
}

try {
    // Cari berdasarkan part_number
    $stmt = $pdo->prepare("
        SELECT s.*, c.name as category_name, l.name as location_name,
               (SELECT image_path FROM sparepart_images WHERE sparepart_id = s.id LIMIT 1) as image_path
        FROM spareparts s
        LEFT JOIN category c ON s.category_id = c.id
        LEFT JOIN locations l ON s.location_id = l.id
        WHERE s.part_number = ?
    ");
    $stmt->execute([$barcode]);
    $data = $stmt->fetch(PDO::FETCH_ASSOC);

    if ($data) {
        echo json_encode([
            'status' => 'success',
            'data' => $data
        ]);
    } else {
        echo json_encode(['status' => 'error', 'msg' => 'Not found']);
    }
} catch (PDOException $e) {
    echo json_encode(['status' => 'error', 'msg' => 'DB Error']);
}
?>