<?php
session_start();
header('Content-Type: application/json');

require_once __DIR__ . '/../../includes/auth.php';
require_once __DIR__ . '/../../classes/Database.php';
require_once __DIR__ . '/../../classes/Inventory.php';


if (!isset($_SESSION['user_id']) || !in_array($_SESSION['role'] ?? '', ['admin', 'warehouse', 'branch'], true)) {
    echo json_encode(['success' => false, 'message' => 'Unauthorized']);
    exit;
}

if (!isset($_POST['barcode']) || !isset($_POST['source_branch_id'])) {
    echo json_encode(['success' => false, 'message' => 'Missing parameters.']);
    exit;
}

$barcode = trim($_POST['barcode']);
$sourceBranchId = (int)$_POST['source_branch_id'];

$database = new Database();
$conn = $database->getConnection();
$auth = new Auth($conn);
$inventory = new Inventory($conn);

if (($_SESSION['role'] ?? '') === 'branch' && $auth->getUserBranch($_SESSION['user_id']) != $sourceBranchId) {
    echo json_encode(['success' => false, 'message' => 'You are not authorized to scan from this source branch.']);
    exit;
}

$item = $inventory->getItemByBarcodeOrCode($barcode);

if (!$item) {
    echo json_encode(['success' => false, 'message' => 'No item found with this barcode.']);
    exit;
}

if ($item['current_location_id'] != $sourceBranchId) {
    echo json_encode(['success' => false, 'message' => 'Item is not in the source branch inventory.']);
    exit;
}


if ($item['is_sold']) {
    echo json_encode(['success' => false, 'message' => 'This item has already been sold.']);
    exit;
}

echo json_encode(['success' => true, 'item' => $item]);
?>
