<?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();
}

// Build query with optional filters
$whereConditions = ['1=1'];
$searchTerm = '';

if (isset($_GET['search']) && !empty($_GET['search'])) {
    $searchTerm = mysqli_real_escape_string($con, $_GET['search']);
    $whereConditions[] = "(i.ItemName LIKE '%$searchTerm%' 
                           OR i.ItemCode LIKE '%$searchTerm%' 
                           OR i.ItemSearchName LIKE '%$searchTerm%'
                           OR i.SKU LIKE '%$searchTerm%' 
                           OR i.Barcode LIKE '%$searchTerm%')";
}

if (isset($_GET['category']) && !empty($_GET['category'])) {
    $categoryId = (int)$_GET['category'];
    $whereConditions[] = "i.CategoryID = $categoryId";
}

if (isset($_GET['brand']) && !empty($_GET['brand'])) {
    $brandId = (int)$_GET['brand'];
    $whereConditions[] = "i.BrandID = $brandId";
}

if (isset($_GET['status']) && !empty($_GET['status'])) {
    $status = mysqli_real_escape_string($con, $_GET['status']);
    $whereConditions[] = "i.Status = '$status'";
}

if (isset($_GET['itemGroup']) && !empty($_GET['itemGroup'])) {
    $itemGroup = mysqli_real_escape_string($con, $_GET['itemGroup']);
    $whereConditions[] = "i.ItemGroup = '$itemGroup'";
}

$whereClause = implode(' AND ', $whereConditions);

// Fetch items
$query = "SELECT i.*, 
          b.BrandName, 
          c.CategoryName, 
          u.UnitName, u.UnitSymbol,
          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 $whereClause
          ORDER BY i.ItemName";

$result = mysqli_query($con, $query);

if (!$result) {
    echo json_encode(['success' => false, 'message' => 'Query error: ' . mysqli_error($con)]);
    exit();
}

$items = [];
while ($row = mysqli_fetch_assoc($result)) {
    // Fetch variants if item has variants
    $variants = [];
    if ($row['ItemGroup'] == 'Variant') {
        $itemId = $row['ID'];
        $variantQuery = "SELECT COUNT(*) as variant_count FROM tblitemvariants WHERE ItemID = $itemId";
        $variantResult = mysqli_query($con, $variantQuery);
        if ($variantResult) {
            $variantData = mysqli_fetch_assoc($variantResult);
            $row['variant_count'] = $variantData['variant_count'];
        }
    }
    
    $items[] = $row;
}

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