<?php
session_start();
include_once('../../includes/config.php');

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

if (!isset($_SESSION['uid'])) {
    echo json_encode(['success' => false, 'message' => 'Unauthorized']);
    exit();
}

if (!isset($_GET['id'])) {
    echo json_encode(['success' => false, 'message' => 'Item ID not provided']);
    exit();
}

$itemId = (int)$_GET['id'];

// Fetch item details
$itemQuery = "SELECT i.*, 
              b.BrandName, 
              c.CategoryName, 
              u.UnitName, 
              t.TaxName, t.TaxRate,
              l.LocationName,
              r.RackName
              FROM tblitems i
              LEFT JOIN tblbrands b ON i.BrandID = b.ID
              LEFT JOIN tblcategories c ON i.CategoryID = c.ID
              LEFT JOIN tblunits u ON i.UnitID = u.ID
              LEFT JOIN tbltaxtypes t ON i.TaxID = t.ID
              LEFT JOIN tbllocations l ON i.LocationID = l.ID
              LEFT JOIN tblracks r ON i.RackID = r.ID
              WHERE i.ID = $itemId";

$itemResult = mysqli_query($con, $itemQuery);

if (!$itemResult || mysqli_num_rows($itemResult) == 0) {
    echo json_encode(['success' => false, 'message' => 'Item not found']);
    exit();
}

$item = mysqli_fetch_assoc($itemResult);

// Fetch variants if item has variants
$variants = [];
if ($item['ItemGroup'] == 'Variant') {
    $variantQuery = "SELECT v.*, 
                     l.LocationName,
                     r.RackName
                     FROM tblitemvariants v
                     LEFT JOIN tbllocations l ON v.LocationID = l.ID
                     LEFT JOIN tblracks r ON v.RackID = r.ID
                     WHERE v.ItemID = $itemId
                     ORDER BY v.VariantName";
    
    $variantResult = mysqli_query($con, $variantQuery);
    
    if ($variantResult) {
        while ($row = mysqli_fetch_assoc($variantResult)) {
            $variants[] = $row;
        }
    }
}

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