<?php
require_once '../config/connection.php';
checkUserType(['admin']);

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

if ($_SERVER['REQUEST_METHOD'] != 'POST' || !isset($_POST['asset_number'])) {
    echo json_encode(['success' => false, 'message' => 'Invalid request']);
    exit;
}

$asset_number = trim($_POST['asset_number']);

try {
    $stmt = $pdo->prepare("
        SELECT id, asset_number, asset_name, asset_category, description, 
               status_borrower, kondisi, barcode_number, kode_material_sap
        FROM assets 
        WHERE asset_number = ? OR barcode_number = ?
    ");
    $stmt->execute([$asset_number, $asset_number]);
    $asset = $stmt->fetch();
    
    if (!$asset) {
        echo json_encode([
            'success' => false, 
            'message' => "Asset dengan nomor '$asset_number' tidak ditemukan dalam database!"
        ]);
        exit;
    }
    
    // Check if asset is currently in someone's cart for this session
    $stmt = $pdo->prepare("
        SELECT COUNT(*) as count 
        FROM borrow_cart 
        WHERE asset_id = ?
    ");
    $stmt->execute([$asset['id']]);
    $in_cart = $stmt->fetch()['count'] > 0;
    
    if ($in_cart) {
        echo json_encode([
            'success' => false, 
            'message' => "Asset sudah ada dalam keranjang peminjaman!"
        ]);
        exit;
    }
    
    echo json_encode([
        'success' => true,
        'asset' => $asset
    ]);
    
} catch (Exception $e) {
    echo json_encode([
        'success' => false, 
        'message' => 'Terjadi kesalahan: ' . $e->getMessage()
    ]);
}
?>