<?php

ob_start();

session_start();


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


function sendItemLookupJson(array $payload, int $statusCode = 200): void
{
    while (ob_get_level() > 0) {
        ob_end_clean();
    }

    http_response_code($statusCode);
    header('Content-Type: application/json; charset=utf-8');
    echo json_encode($payload);
    exit();
}


if (!isset($_SESSION['user_id'])) {
    sendItemLookupJson(['success' => false, 'message' => 'User not authenticated'], 401);
}


try {
    $database = new Database();
    $conn = $database->getConnection();

    if (!$conn) {
        throw new Exception("Database connection failed");
    }

    $inventory = new Inventory($conn);
    $auth = new Auth($conn);

} catch (Exception $e) {
    error_log("Database initialization error: " . $e->getMessage());
    sendItemLookupJson(['success' => false, 'message' => 'Database connection error'], 500);
}


$branchId = $auth->getUserBranch($_SESSION['user_id']);
if (!$branchId) {
    sendItemLookupJson(['success' => false, 'message' => 'User not assigned to any branch'], 403);
}


if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
    sendItemLookupJson(['success' => false, 'message' => 'Only POST method allowed'], 405);
}

$item = null;
$lookupMethod = '';

try {

    if (isset($_POST['barcode_data']) && !empty(trim($_POST['barcode_data']))) {
        $barcodeData = trim($_POST['barcode_data']);
        $lookupMethod = 'barcode';

        error_log("Looking up item by barcode: " . $barcodeData);


        $item = $inventory->getItemByBarcodeData($barcodeData);

        if (!$item) {

            $item = $inventory->getItemByUniqueCode($barcodeData);
            if ($item) {
                error_log("Item found by unique_code fallback for barcode: " . $barcodeData);
            }
        }

    }

    elseif (isset($_POST['unique_code']) && !empty(trim($_POST['unique_code']))) {
        $uniqueCode = trim($_POST['unique_code']);
        $lookupMethod = 'unique_code';

        error_log("Looking up item by unique_code: " . $uniqueCode);


        $item = $inventory->getItemByUniqueCode($uniqueCode);

    }

    elseif (isset($_POST['item_name']) && !empty(trim($_POST['item_name']))) {
        $itemName = trim($_POST['item_name']);
        $lookupMethod = 'item_name';

        error_log("Looking up items by item_name: " . $itemName);


        $availableItems = $inventory->getAvailableItemsByName('%' . $itemName . '%', $branchId);

        if (empty($availableItems)) {
            sendItemLookupJson([
                'success' => false,
                'message' => "No available items found matching name: " . $itemName,
                'lookup_method' => $lookupMethod
            ], 404);
        }


        $randomIndex = array_rand($availableItems);
        $item = $availableItems[$randomIndex];

        error_log("Randomly selected item: " . $item['unique_code'] . " from " . count($availableItems) . " available items");

    } else {
        sendItemLookupJson(['success' => false, 'message' => 'Missing required parameter: unique_code, barcode_data, or item_name'], 400);
    }


    if (!$item) {
        $searchTerm = $lookupMethod === 'barcode' ? $barcodeData : $uniqueCode;
        error_log("Item not found for {$lookupMethod}: " . $searchTerm);

        sendItemLookupJson([
            'success' => false,
            'message' => "Item not found with {$lookupMethod}: " . $searchTerm,
            'lookup_method' => $lookupMethod
        ], 404);
    }

    require_once __DIR__ . '/../../classes/Sales.php';
    $sales = new Sales($conn);

    $soldItem = $sales->isItemSold($item['unique_code']);
    if ($soldItem) {
        error_log("Item {$item['unique_code']} has already been sold");

        sendItemLookupJson([
            'success' => false,
            'message' => 'This code has already been sold on ' . date('Y-m-d H:i', strtotime($soldItem['sold_at'])),
            'status' => 'sold',
            'sold_date' => $soldItem['sold_at']
        ], 409);
    }

    if ($item['current_location_id'] != $branchId) {
        error_log("Item {$item['unique_code']} is not in user's branch. Item location: {$item['current_location_id']}, User branch: {$branchId}");

        $branchStmt = $conn->prepare("SELECT branch_name FROM branches WHERE branch_id = ?");
        $branchStmt->execute([$item['current_location_id']]);
        $itemBranchName = $branchStmt->fetchColumn();
        $locationName = $itemBranchName ?: 'another branch';

        sendItemLookupJson([
            'success' => false,
            'message' => 'This code has been transferred to ' . $locationName . ' and cannot be sold from your branch.',
            'status' => 'transferred',
            'item_location' => $item['current_location_id'],
            'item_location_name' => $itemBranchName,
            'user_branch' => $branchId
        ], 403);
    }


    error_log("Item found successfully: " . $item['unique_code'] . " - " . $item['item_name']);

    // The sales screen must use the tax group assigned to this exact stock item.
    // Do not resolve it from product mappings or other fallback tables.
    $taxRateId = strtoupper(trim((string)($item['tax_rate_id'] ?? '')));

    sendItemLookupJson([
        'success' => true,
        'item' => [
            'item_id' => $item['item_id'],
            'unique_code' => $item['unique_code'],
            'item_name' => $item['item_name'],
            'item_details' => $item['item_details'] ?? '',
            'unit_price' => $item['unit_price'],
            'description' => $item['description'] ?? '',
            'condition_status' => $item['condition_status'] ?? 'NEW',
            'brand' => $item['brand'] ?? '',
            'model' => $item['model'] ?? '',
            'serial_number' => $item['serial_number'] ?? '',
            'warranty_months' => $item['warranty_months'] ?? 0,
            'technical_specs' => $item['technical_specs'] ?? '',
            'barcode_data' => $item['barcode_data'] ?? '',
            'barcode_image_path' => $item['barcode_image_path'] ?? '',
            'tax_rate_id' => $taxRateId
        ],
        'lookup_method' => $lookupMethod
    ]);

} catch (PDOException $e) {
    error_log("Database error in get_item_details.php: " . $e->getMessage());
    sendItemLookupJson(['success' => false, 'message' => 'Database error occurred'], 500);

} catch (Exception $e) {
    error_log("General error in get_item_details.php: " . $e->getMessage());
    sendItemLookupJson(['success' => false, 'message' => 'An error occurred while processing your request'], 500);
}
?>
