<?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 = ["i.Status = 'Active'"];

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.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['location']) && !empty($_GET['location'])) {
    $locationId = (int)$_GET['location'];
    $whereConditions[] = "i.LocationID = $locationId";
}

if (isset($_GET['stockStatus']) && !empty($_GET['stockStatus'])) {
    $stockStatus = $_GET['stockStatus'];
    switch($stockStatus) {
        case 'low':
            $whereConditions[] = "i.CurrentStock <= i.AlertQuantity AND i.CurrentStock > 0";
            break;
        case 'out':
            $whereConditions[] = "i.CurrentStock = 0";
            break;
        case 'sufficient':
            $whereConditions[] = "i.CurrentStock > i.AlertQuantity";
            break;
    }
}

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

// Fetch items with stock information
$query = "SELECT 
          i.ID,
          i.ItemCode,
          i.ItemName,
          i.ItemNameTamil,
          i.SKU,
          i.Barcode,
          i.HSN,
          i.CurrentStock,
          i.AlertQuantity,
          i.OpeningStock,
          i.PurchasePrice,
          i.SalesPrice,
          i.ShopRate,
          i.WholesaleRate,
          i.MRP,
          i.Status,
          b.BrandName,
          c.CategoryName,
          u.UnitName,
          u.UnitSymbol,
          l.LocationName,
          r.RackName,
          s.SupplierName,
          (i.CurrentStock * i.PurchasePrice) as StockValue,
          CASE 
              WHEN i.CurrentStock = 0 THEN 'Out of Stock'
              WHEN i.CurrentStock <= i.AlertQuantity THEN 'Low Stock'
              ELSE 'In Stock'
          END as StockStatus
          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 tbllocations l ON i.LocationID = l.ID
          LEFT JOIN tblracks r ON i.RackID = r.ID
          LEFT JOIN tblsuppliers s ON i.SupplierID = s.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 = [];
$totalStock = 0;
$totalValue = 0;

while ($row = mysqli_fetch_assoc($result)) {
    // Calculate totals
    $totalStock += $row['CurrentStock'];
    $totalValue += $row['StockValue'];
    
    $items[] = [
        'id' => $row['ID'],
        'itemCode' => $row['ItemCode'],
        'itemName' => $row['ItemName'],
        'itemNameTamil' => $row['ItemNameTamil'],
        'category' => $row['CategoryName'] ?? 'N/A',
        'brand' => $row['BrandName'] ?? 'N/A',
        'unit' => $row['UnitName'] ?? 'N/A',
        'unitSymbol' => $row['UnitSymbol'] ?? '',
        'location' => $row['LocationName'] ?? 'N/A',
        'rack' => $row['RackName'] ?? 'N/A',
        'sku' => $row['SKU'],
        'barcode' => $row['Barcode'],
        'hsn' => $row['HSN'],
        'currentStock' => number_format($row['CurrentStock'], 2, '.', ''),
        'alertQuantity' => number_format($row['AlertQuantity'], 2, '.', ''),
        'openingStock' => number_format($row['OpeningStock'], 2, '.', ''),
        'purchasePrice' => number_format($row['PurchasePrice'], 2, '.', ''),
        'salesPrice' => number_format($row['SalesPrice'], 2, '.', ''),
        'shopRate' => number_format($row['ShopRate'], 2, '.', ''),
        'wholesaleRate' => number_format($row['WholesaleRate'], 2, '.', ''),
        'mrp' => number_format($row['MRP'], 2, '.', ''),
        'stockValue' => number_format($row['StockValue'], 2, '.', ''),
        'stockStatus' => $row['StockStatus'],
        'status' => $row['Status']
    ];
}

echo json_encode([
    'success' => true,
    'items' => $items,
    'count' => count($items),
    'totals' => [
        'totalStock' => number_format($totalStock, 2, '.', ''),
        'totalValue' => number_format($totalValue, 2, '.', '')
    ]
]);
?>
