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

if (!isset($_SESSION['uid'])) {
    header('location:../logout.php');
    exit();
}

$currentUserId = $_SESSION['uid'];
$userType = $_SESSION['usertype'];

// Handle AJAX requests
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['ajax']) && $_POST['ajax'] == '1') {
    header('Content-Type: application/json');
    
    $action = $_POST['action'];
    
    if ($action == 'create' || $action == 'update') {
        $itemName = mysqli_real_escape_string($con, $_POST['itemName']);
        $itemSearchName = mysqli_real_escape_string($con, $_POST['itemSearchName']);
        $itemDescription = mysqli_real_escape_string($con, $_POST['itemDescription']);
        $brandID = !empty($_POST['brandID']) ? (int)$_POST['brandID'] : null;
        $categoryID = !empty($_POST['categoryID']) ? (int)$_POST['categoryID'] : null;
        $supplierID = !empty($_POST['supplierID']) ? (int)$_POST['supplierID'] : null;
        $unitID = !empty($_POST['unitID']) ? (int)$_POST['unitID'] : null;
        $hsn = mysqli_real_escape_string($con, $_POST['hsn']);
        $alertQuantity = !empty($_POST['alertQuantity']) ? (float)$_POST['alertQuantity'] : 0;
        $barcode = mysqli_real_escape_string($con, $_POST['barcode']);
        $taxabilityType = mysqli_real_escape_string($con, $_POST['taxabilityType']);
        $taxID = !empty($_POST['taxID']) ? (int)$_POST['taxID'] : null;
        $purchasePrice = !empty($_POST['purchasePrice']) ? (float)$_POST['purchasePrice'] : 0;
        $profitMarginPercent = !empty($_POST['profitMarginPercent']) ? (float)$_POST['profitMarginPercent'] : 0;
        $salesPrice = !empty($_POST['salesPrice']) ? (float)$_POST['salesPrice'] : 0;
        $shopRate = !empty($_POST['shopRate']) ? (float)$_POST['shopRate'] : 0;
        $wholesaleRate = !empty($_POST['wholesaleRate']) ? (float)$_POST['wholesaleRate'] : 0;
        $mrp = !empty($_POST['mrp']) ? (float)$_POST['mrp'] : 0;
        $locationID = !empty($_POST['locationID']) ? (int)$_POST['locationID'] : null;
        $rackID = !empty($_POST['rackID']) ? (int)$_POST['rackID'] : null;
        $openingStock = !empty($_POST['openingStock']) ? (float)$_POST['openingStock'] : 0;
        $status = mysqli_real_escape_string($con, $_POST['status']);
        
        // Handle image upload
        $itemImage = '';
        if (isset($_FILES['itemImage']) && $_FILES['itemImage']['error'] == 0) {
            $uploadDir = '../uploads/items/';
            if (!file_exists($uploadDir)) {
                mkdir($uploadDir, 0777, true);
            }
            
            $fileName = time() . '_' . basename($_FILES['itemImage']['name']);
            $targetFile = $uploadDir . $fileName;
            
            if (move_uploaded_file($_FILES['itemImage']['tmp_name'], $targetFile)) {
                $itemImage = $fileName;
            }
        }
        
        if ($action == 'update' && isset($_POST['itemId'])) {
            // Update existing item
            $itemId = (int)$_POST['itemId'];
            
            $updateQuery = "UPDATE tblitems SET 
                ItemName = '$itemName',
                ItemSearchName = '$itemSearchName',
                ItemDescription2 = '$itemDescription',
                BrandID = " . ($brandID ? $brandID : 'NULL') . ",
                CategoryID = " . ($categoryID ? $categoryID : 'NULL') . ",
                SupplierID = " . ($supplierID ? $supplierID : 'NULL') . ",
                UnitID = " . ($unitID ? $unitID : 'NULL') . ",
                HSN = '$hsn',
                AlertQuantity = $alertQuantity,
                Barcode = '$barcode',
                " . ($itemImage ? "ItemImage = '$itemImage'," : "") . "
                TaxabilityType = '$taxabilityType',
                TaxID = " . ($taxID ? $taxID : 'NULL') . ",
                PurchasePrice = $purchasePrice,
                ProfitMarginPercent = $profitMarginPercent,
                SalesPrice = $salesPrice,
                ShopRate = $shopRate,
                WholesaleRate = $wholesaleRate,
                MRP = $mrp,
                LocationID = " . ($locationID ? $locationID : 'NULL') . ",
                RackID = " . ($rackID ? $rackID : 'NULL') . ",
                OpeningStock = $openingStock,
                Status = '$status'
            WHERE ID = $itemId";
            
            if (mysqli_query($con, $updateQuery)) {
                // Fetch updated item data
                $getItem = "SELECT i.ID, i.ItemCode, i.ItemName, i.SalesPrice, i.PurchasePrice, i.CurrentStock, i.Status, i.ItemImage, c.CategoryName 
                           FROM tblitems i 
                           LEFT JOIN tblcategories c ON i.CategoryID = c.ID 
                           WHERE i.ID = $itemId";
                $itemResult = mysqli_query($con, $getItem);
                $itemData = mysqli_fetch_assoc($itemResult);
                
                echo json_encode(['success' => true, 'message' => 'Item updated successfully!', 'data' => $itemData]);
            } else {
                echo json_encode(['success' => false, 'message' => 'Error updating item: ' . mysqli_error($con)]);
            }
            exit();
        } else {
            // Create new item
            $query = "SELECT ItemCode FROM tblitems ORDER BY ID DESC LIMIT 1";
            $result = mysqli_query($con, $query);
            
            if ($result && mysqli_num_rows($result) > 0) {
                $row = mysqli_fetch_assoc($result);
                $lastCode = $row['ItemCode'];
                $number = (int)substr($lastCode, 4);
                $newNumber = $number + 1;
                $itemCode = 'ITEM' . str_pad($newNumber, 6, '0', STR_PAD_LEFT);
            } else {
                $itemCode = 'ITEM000001';
            }
            
            $insertQuery = "INSERT INTO tblitems (
                ItemCode, ItemName, ItemSearchName, ItemDescription2, BrandID, CategoryID, SupplierID, UnitID, 
                HSN, AlertQuantity, Barcode, ItemImage,
                TaxabilityType, TaxID,
                PurchasePrice, ProfitMarginPercent,
                SalesPrice, ShopRate, WholesaleRate, MRP, LocationID, RackID, OpeningStock, 
                CurrentStock, Status
            ) VALUES (
                '$itemCode', '$itemName', '$itemSearchName', '$itemDescription', " . ($brandID ? $brandID : 'NULL') . ", 
                " . ($categoryID ? $categoryID : 'NULL') . ", " . ($supplierID ? $supplierID : 'NULL') . ", 
                " . ($unitID ? $unitID : 'NULL') . ",
                '$hsn', $alertQuantity, '$barcode', '$itemImage',
                '$taxabilityType', " . ($taxID ? $taxID : 'NULL') . ",
                $purchasePrice, $profitMarginPercent,
                $salesPrice, $shopRate, $wholesaleRate, $mrp, " . ($locationID ? $locationID : 'NULL') . ", 
                " . ($rackID ? $rackID : 'NULL') . ", $openingStock, $openingStock, '$status'
            )";
            
            if (mysqli_query($con, $insertQuery)) {
                $newItemId = mysqli_insert_id($con);
                
                // Fetch the newly created item
                $getItem = "SELECT i.ID, i.ItemCode, i.ItemName, i.SalesPrice, i.PurchasePrice, i.CurrentStock, i.Status, i.ItemImage, c.CategoryName 
                           FROM tblitems i 
                           LEFT JOIN tblcategories c ON i.CategoryID = c.ID 
                           WHERE i.ID = $newItemId";
                $itemResult = mysqli_query($con, $getItem);
                $itemData = mysqli_fetch_assoc($itemResult);
                
                echo json_encode(['success' => true, 'message' => 'Item added successfully!', 'data' => $itemData]);
            } else {
                echo json_encode(['success' => false, 'message' => 'Error adding item: ' . mysqli_error($con)]);
            }
            exit();
        }
    }
}

// Handle form submissions (non-AJAX fallback)
if ($_POST && isset($_POST['action'])) {
    $action = $_POST['action'];
    
    if ($action == 'create' || $action == 'update') {
        $itemName = mysqli_real_escape_string($con, $_POST['itemName']);
        $itemSearchName = mysqli_real_escape_string($con, $_POST['itemSearchName']);
        $itemDescription = mysqli_real_escape_string($con, $_POST['itemDescription']);
        $brandID = !empty($_POST['brandID']) ? (int)$_POST['brandID'] : null;
        $categoryID = !empty($_POST['categoryID']) ? (int)$_POST['categoryID'] : null;
        $supplierID = !empty($_POST['supplierID']) ? (int)$_POST['supplierID'] : null;
        $unitID = !empty($_POST['unitID']) ? (int)$_POST['unitID'] : null;
        $hsn = mysqli_real_escape_string($con, $_POST['hsn']);
        $alertQuantity = !empty($_POST['alertQuantity']) ? (float)$_POST['alertQuantity'] : 0;
        $barcode = mysqli_real_escape_string($con, $_POST['barcode']);
        $taxabilityType = mysqli_real_escape_string($con, $_POST['taxabilityType']);
        $taxID = !empty($_POST['taxID']) ? (int)$_POST['taxID'] : null;
        $purchasePrice = !empty($_POST['purchasePrice']) ? (float)$_POST['purchasePrice'] : 0;
        $profitMarginPercent = !empty($_POST['profitMarginPercent']) ? (float)$_POST['profitMarginPercent'] : 0;
        $salesPrice = !empty($_POST['salesPrice']) ? (float)$_POST['salesPrice'] : 0;
        $shopRate = !empty($_POST['shopRate']) ? (float)$_POST['shopRate'] : 0;
        $wholesaleRate = !empty($_POST['wholesaleRate']) ? (float)$_POST['wholesaleRate'] : 0;
        $mrp = !empty($_POST['mrp']) ? (float)$_POST['mrp'] : 0;
        $locationID = !empty($_POST['locationID']) ? (int)$_POST['locationID'] : null;
        $rackID = !empty($_POST['rackID']) ? (int)$_POST['rackID'] : null;
        $openingStock = !empty($_POST['openingStock']) ? (float)$_POST['openingStock'] : 0;
        $status = mysqli_real_escape_string($con, $_POST['status']);
        
        // Handle image upload
        $itemImage = '';
        if (isset($_FILES['itemImage']) && $_FILES['itemImage']['error'] == 0) {
            $uploadDir = '../uploads/items/';
            if (!file_exists($uploadDir)) {
                mkdir($uploadDir, 0777, true);
            }
            
            $fileName = time() . '_' . basename($_FILES['itemImage']['name']);
            $targetFile = $uploadDir . $fileName;
            
            if (move_uploaded_file($_FILES['itemImage']['tmp_name'], $targetFile)) {
                $itemImage = $fileName;
            }
        }
        
        if ($action == 'update' && isset($_POST['itemId'])) {
            // Update existing item
            $itemId = (int)$_POST['itemId'];
            
            $updateQuery = "UPDATE tblitems SET 
                ItemName = '$itemName',
                ItemSearchName = '$itemSearchName',
                ItemDescription2 = '$itemDescription',
                BrandID = " . ($brandID ? $brandID : 'NULL') . ",
                CategoryID = " . ($categoryID ? $categoryID : 'NULL') . ",
                SupplierID = " . ($supplierID ? $supplierID : 'NULL') . ",
                UnitID = " . ($unitID ? $unitID : 'NULL') . ",
                HSN = '$hsn',
                AlertQuantity = $alertQuantity,
                Barcode = '$barcode',
                " . ($itemImage ? "ItemImage = '$itemImage'," : "") . "
                TaxabilityType = '$taxabilityType',
                TaxID = " . ($taxID ? $taxID : 'NULL') . ",
                PurchasePrice = $purchasePrice,
                ProfitMarginPercent = $profitMarginPercent,
                SalesPrice = $salesPrice,
                ShopRate = $shopRate,
                WholesaleRate = $wholesaleRate,
                MRP = $mrp,
                LocationID = " . ($locationID ? $locationID : 'NULL') . ",
                RackID = " . ($rackID ? $rackID : 'NULL') . ",
                OpeningStock = $openingStock,
                Status = '$status'
            WHERE ID = $itemId";
            
            if (mysqli_query($con, $updateQuery)) {
                $_SESSION['success'] = "Item updated successfully!";
                header("Location: add-item.php");
                exit();
            } else {
                $error = "Error updating item: " . mysqli_error($con);
            }
        } else {
            // Create new item
            // Generate Item Code
            $query = "SELECT ItemCode FROM tblitems ORDER BY ID DESC LIMIT 1";
            $result = mysqli_query($con, $query);
            
            if ($result && mysqli_num_rows($result) > 0) {
                $row = mysqli_fetch_assoc($result);
                $lastCode = $row['ItemCode'];
                $number = (int)substr($lastCode, 4);
                $newNumber = $number + 1;
                $itemCode = 'ITEM' . str_pad($newNumber, 6, '0', STR_PAD_LEFT);
            } else {
                $itemCode = 'ITEM000001';
            }
            
            $insertQuery = "INSERT INTO tblitems (
                ItemCode, ItemName, ItemSearchName, ItemDescription2, BrandID, CategoryID, SupplierID, UnitID, 
                HSN, AlertQuantity, Barcode, ItemImage,
                TaxabilityType, TaxID,
                PurchasePrice, ProfitMarginPercent,
                SalesPrice, ShopRate, WholesaleRate, MRP, LocationID, RackID, OpeningStock, 
                CurrentStock, Status
            ) VALUES (
                '$itemCode', '$itemName', '$itemSearchName', '$itemDescription', " . ($brandID ? $brandID : 'NULL') . ", 
                " . ($categoryID ? $categoryID : 'NULL') . ", " . ($supplierID ? $supplierID : 'NULL') . ", 
                " . ($unitID ? $unitID : 'NULL') . ",
                '$hsn', $alertQuantity, '$barcode', '$itemImage',
                '$taxabilityType', " . ($taxID ? $taxID : 'NULL') . ",
                $purchasePrice, $profitMarginPercent,
                $salesPrice, $shopRate, $wholesaleRate, $mrp, " . ($locationID ? $locationID : 'NULL') . ", 
                " . ($rackID ? $rackID : 'NULL') . ", $openingStock, $openingStock, '$status'
            )";
            
            if (mysqli_query($con, $insertQuery)) {
                if (isset($_POST['saveAndContinue']) && $_POST['saveAndContinue'] == '1') {
                    $_SESSION['success'] = "Item added successfully! Add another item.";
                    header("Location: add-item.php");
                } else {
                    $_SESSION['success'] = "Item added successfully!";
                    header("Location: item-management.php");
                }
                exit();
            } else {
                $error = "Error adding item: " . mysqli_error($con);
            }
        }
    }
}

// Fetch dropdown data
function fetchData($con, $table, $orderBy) {
    $query = "SELECT * FROM $table WHERE Status = 'Active' ORDER BY $orderBy";
    $result = mysqli_query($con, $query);
    $data = [];
    if ($result) {
        while ($row = mysqli_fetch_assoc($result)) {
            $data[] = $row;
        }
    }
    return $data;
}

$brands = fetchData($con, 'tblbrands', 'BrandName');
$categories = fetchData($con, 'tblcategories', 'CategoryName');
$suppliers = fetchData($con, 'tblsuppliers', 'SupplierName');
$units = fetchData($con, 'tblunits', 'UnitName');
$taxes = fetchData($con, 'tbltaxtypes', 'TaxName');
$locations = fetchData($con, 'tbllocations', 'LocationName');
$racks = fetchData($con, 'tblracks', 'RackName');

// Fetch items for product list
$itemsQuery = "SELECT i.ID, i.ItemCode, i.ItemName, i.SalesPrice, i.PurchasePrice, i.CurrentStock, i.Status, i.ItemImage, c.CategoryName 
               FROM tblitems i 
               LEFT JOIN tblcategories c ON i.CategoryID = c.ID 
               ORDER BY i.ID DESC LIMIT 50";
$itemsResult = mysqli_query($con, $itemsQuery);
$items = [];
if ($itemsResult) {
    while ($row = mysqli_fetch_assoc($itemsResult)) {
        $items[] = $row;
    }
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="utf-8">
    <title>Add New Item | UZRS Inventory</title>
    <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
    <link href="../vendor/fontawesome-free/css/all.min.css" rel="stylesheet" type="text/css">
    <link href="../css/sb-admin-2.min.css" rel="stylesheet">
    <link href="../css/modern-messagebox.css" rel="stylesheet">
    <link href="https://cdn.jsdelivr.net/npm/select2@4.1.0-rc.0/dist/css/select2.min.css" rel="stylesheet" />
    <link href="css/add-item.css" rel="stylesheet">
    <link href="../Sales/css/barcode-scanner.css" rel="stylesheet">
    
    <!-- html5-qrcode for QR and barcode scanning -->
    <script src="https://unpkg.com/html5-qrcode"></script>
</head>
<body class="standalone-page">
                <div class="container-fluid p-0">
                    <div class="two-column-layout">
                        <!-- Left Column: Form -->
                        <div class="left-column">
                    <div class="add-item-container">
                        <div class="form-header">
                            <div class="header-left">
                                <a href="../Sales/index.php" class="btn-back" title="Back to Sales">
                                    <i class="fas fa-arrow-left"></i>
                                </a>
                                <h5>Add New Item</h5>
                            </div>
                            <div class="header-right">
                                <button type="button" id="languageToggleBtn" class="btn-language-toggle" onclick="toggleLanguage()" title="Switch to Tamil">
                                    <i class="fas fa-language"></i> த
                                </button>
                            </div>
                        </div>

                        <form method="POST" id="itemForm" enctype="multipart/form-data">
                            <input type="hidden" name="action" value="create">
                            <input type="hidden" id="saveAndContinue" name="saveAndContinue" value="0">

                            <div class="form-content">
                                <!-- Row 1: Basic Information Only (Left) -->
                                <div class="form-sections-row single-section">
                                    <!-- Basic Information -->
                                    <div class="form-section">
                                        <div class="section-header">Basic Information</div>
                                        <div class="form-row">
                                            <div class="form-group full-width">
                                                <label>Item Name <span class="required">*</span></label>
                                                <input type="text" name="itemName" class="form-control" required>
                                            </div>
                                        </div>
                                        <div class="form-row">
                                            <div class="form-group full-width">
                                                <label>Item Search Name</label>
                                                <input type="text" name="itemSearchName" class="form-control" placeholder="Alternative search name">
                                            </div>
                                        </div>
                                        <div class="form-row">
                                            <div class="form-group full-width">
                                                <label>Description</label>
                                                <textarea name="itemDescription" class="form-control" rows="3" placeholder="Enter item description"></textarea>
                                            </div>
                                        </div>
                                        <div class="form-row">
                                            <div class="form-group">
                                                <label>Category</label>
                                                <div class="input-with-btn">
                                                    <select name="categoryID" id="categoryID" class="form-control select2">
                                                        <option value="">Select Category</option>
                                                        <?php foreach($categories as $cat): ?>
                                                        <option value="<?php echo $cat['ID']; ?>"><?php echo htmlspecialchars($cat['CategoryName']); ?></option>
                                                        <?php endforeach; ?>
                                                    </select>
                                                    <button type="button" class="btn-add-master" onclick="openQuickAdd('category')" title="Add Category">
                                                        <i class="fas fa-plus"></i>
                                                    </button>
                                                </div>
                                            </div>
                                            <div class="form-group">
                                                <label>Brand</label>
                                                <div class="input-with-btn">
                                                    <select name="brandID" id="brandID" class="form-control select2">
                                                        <option value="">Select Brand</option>
                                                        <?php foreach($brands as $brand): ?>
                                                        <option value="<?php echo $brand['ID']; ?>"><?php echo htmlspecialchars($brand['BrandName']); ?></option>
                                                        <?php endforeach; ?>
                                                    </select>
                                                    <button type="button" class="btn-add-master" onclick="openQuickAdd('brand')" title="Add Brand">
                                                        <i class="fas fa-plus"></i>
                                                    </button>
                                                </div>
                                            </div>
                                        </div>
                                        <div class="form-row">
                                            <div class="form-group">
                                                <label>Supplier</label>
                                                <div class="input-with-btn">
                                                    <select name="supplierID" id="supplierID" class="form-control select2">
                                                        <option value="">Select Supplier</option>
                                                        <?php foreach($suppliers as $supplier): ?>
                                                        <option value="<?php echo $supplier['ID']; ?>"><?php echo htmlspecialchars($supplier['SupplierName']); ?></option>
                                                        <?php endforeach; ?>
                                                    </select>
                                                    <button type="button" class="btn-add-master" onclick="openQuickAdd('supplier')" title="Add Supplier">
                                                        <i class="fas fa-plus"></i>
                                                    </button>
                                                </div>
                                            </div>
                                            <div class="form-group">
                                                <label>Unit</label>
                                                <div class="input-with-btn">
                                                    <select name="unitID" id="unitID" class="form-control select2">
                                                        <option value="">Select Unit</option>
                                                        <?php foreach($units as $unit): ?>
                                                        <option value="<?php echo $unit['ID']; ?>"><?php echo htmlspecialchars($unit['UnitName']); ?></option>
                                                        <?php endforeach; ?>
                                                    </select>
                                                    <button type="button" class="btn-add-master" onclick="openQuickAdd('unit')" title="Add Unit">
                                                        <i class="fas fa-plus"></i>
                                                    </button>
                                                </div>
                                            </div>
                                        </div>
                                        <div class="form-row">
                                            <div class="form-group">
                                                <label>HSN Code</label>
                                                <input type="text" name="hsn" class="form-control">
                                            </div>
                                            <div class="form-group">
                                                <label>Barcode</label>
                                                <div class="input-with-btn">
                                                    <input type="text" name="barcode" id="barcodeInput" class="form-control" placeholder="Enter or scan barcode">
                                                    <button type="button" class="btn-add-master" id="scanBarcodeBtn" title="Scan Barcode/QR Code">
                                                        <i class="fas fa-camera"></i>
                                                    </button>
                                                </div>
                                            </div>
                                        </div>
                                        <div class="form-row">
                                            <div class="form-group compact">
                                                <label>Alert Qty</label>
                                                <input type="number" step="0.01" name="alertQuantity" class="form-control" value="0">
                                            </div>
                                            <div class="form-group">
                                                <label>Item Image</label>
                                                <input type="file" name="itemImage" class="form-control" accept="image/*">
                                            </div>
                                            <div class="form-group compact">
                                                <label>Status</label>
                                                <select name="status" class="form-control">
                                                    <option value="Active">Active</option>
                                                    <option value="Inactive">Inactive</option>
                                                </select>
                                            </div>
                                        </div>
                                    </div>

                                    <!-- Right Side: Pricing + Tax + Stock -->
                                    <div class="form-section-group">
                                        <!-- Pricing Information -->
                                        <div class="form-section">
                                            <div class="section-header">Pricing Information</div>
                                            <div class="form-row pricing-row">
                                                <div class="form-group">
                                                    <label>Purchase Price (₹)</label>
                                                    <input type="number" step="0.01" name="purchasePrice" id="purchasePrice" class="form-control" value="0">
                                                </div>
                                                <div class="form-group">
                                                    <label>Profit Margin %</label>
                                                    <input type="number" step="0.01" name="profitMarginPercent" id="profitMarginPercent" class="form-control" value="0">
                                                </div>
                                                <div class="form-group">
                                                    <label>Sales Price (₹)</label>
                                                    <input type="number" step="0.01" name="salesPrice" id="salesPrice" class="form-control" value="0">
                                                </div>
                                            </div>
                                            <div class="form-row pricing-row">
                                                <div class="form-group">
                                                    <label>Shop Rate (₹)</label>
                                                    <input type="number" step="0.01" name="shopRate" class="form-control" value="0">
                                                </div>
                                                <div class="form-group">
                                                    <label>Wholesale Rate (₹)</label>
                                                    <input type="number" step="0.01" name="wholesaleRate" class="form-control" value="0">
                                                </div>
                                                <div class="form-group">
                                                    <label>MRP (₹)</label>
                                                    <input type="number" step="0.01" name="mrp" class="form-control" value="0">
                                                </div>
                                            </div>
                                        </div>

                                        <!-- Tax Information -->
                                        <div class="form-section">
                                            <div class="section-header">Tax Information</div>
                                            <div class="form-row">
                                                <div class="form-group">
                                                    <label>Taxability Type</label>
                                                    <select name="taxabilityType" class="form-control">
                                                        <option value="Taxable">Taxable</option>
                                                        <option value="Non-Taxable">Non-Taxable</option>
                                                    </select>
                                                </div>
                                                <div class="form-group">
                                                    <label>Tax</label>
                                                    <div class="input-with-btn">
                                                        <select name="taxID" id="taxID" class="form-control select2">
                                                            <option value="">Select Tax</option>
                                                            <?php foreach($taxes as $tax): ?>
                                                            <option value="<?php echo $tax['ID']; ?>"><?php echo htmlspecialchars($tax['TaxName']); ?> (<?php echo $tax['TaxRate']; ?>%)</option>
                                                            <?php endforeach; ?>
                                                        </select>
                                                        <button type="button" class="btn-add-master" onclick="openQuickAdd('tax')" title="Add Tax">
                                                            <i class="fas fa-plus"></i>
                                                        </button>
                                                    </div>
                                                </div>
                                            </div>
                                        </div>

                                        <!-- Stock & Location -->
                                        <div class="form-section">
                                            <div class="section-header">Stock & Location</div>
                                            <div class="form-row">
                                                <div class="form-group">
                                                    <label>Location</label>
                                                    <div class="input-with-btn">
                                                        <select name="locationID" id="locationID" class="form-control select2">
                                                            <option value="">Select Location</option>
                                                            <?php foreach($locations as $location): ?>
                                                            <option value="<?php echo $location['ID']; ?>"><?php echo htmlspecialchars($location['LocationName']); ?></option>
                                                            <?php endforeach; ?>
                                                        </select>
                                                        <button type="button" class="btn-add-master" onclick="openQuickAdd('location')" title="Add Location">
                                                            <i class="fas fa-plus"></i>
                                                        </button>
                                                    </div>
                                                </div>
                                                <div class="form-group">
                                                    <label>Rack</label>
                                                    <div class="input-with-btn">
                                                        <select name="rackID" id="rackID" class="form-control select2">
                                                            <option value="">Select Rack</option>
                                                            <?php foreach($racks as $rack): ?>
                                                            <option value="<?php echo $rack['ID']; ?>"><?php echo htmlspecialchars($rack['RackName']); ?></option>
                                                            <?php endforeach; ?>
                                                        </select>
                                                        <button type="button" class="btn-add-master" onclick="openQuickAdd('rack')" title="Add Rack">
                                                            <i class="fas fa-plus"></i>
                                                        </button>
                                                    </div>
                                                </div>
                                            </div>
                                            <div class="form-row">
                                                <div class="form-group compact">
                                                    <label>Opening Stock</label>
                                                    <input type="number" step="0.01" name="openingStock" class="form-control" value="0">
                                                </div>
                                            </div>
                                        </div>
                                    </div>
                                </div>
                            </div>
                            
                            <!-- Save Button at Bottom -->
                            <div class="form-actions">
                                <button type="submit" class="btn-save-bottom">
                                    <i class="fas fa-save"></i> Save Item
                                </button>
                            </div>
                        </form>
                    </div>
                        </div>

                        <!-- Right Column: Product List -->
                        <div class="right-column">
                            <div class="product-list-container">
                                <div class="product-list-header">
                                    <h5><i class="fas fa-boxes"></i> Product List</h5>
                                    <div class="search-box">
                                        <input type="text" id="searchProduct" class="form-control form-control-sm" placeholder="Search products...">
                                        <i class="fas fa-search"></i>
                                    </div>
                                </div>
                                <div class="product-grid" id="productGrid">
                                    <?php if (count($items) > 0): ?>
                                        <?php foreach($items as $item): ?>
                                        <?php 
                                            $stockValue = $item['PurchasePrice'] * $item['CurrentStock'];
                                        ?>
                                        <div class="product-card" 
                                             data-id="<?php echo $item['ID']; ?>"
                                             data-category="<?php echo htmlspecialchars($item['CategoryName'] ?? 'N/A'); ?>"
                                             data-purchase-price="<?php echo number_format($item['PurchasePrice'], 2); ?>"
                                             data-stock="<?php echo number_format($item['CurrentStock'], 2); ?>"
                                             data-stock-value="<?php echo number_format($stockValue, 2); ?>">
                                            <div class="product-card-header">
                                                <div class="product-info">
                                                    <div class="product-name"><?php echo htmlspecialchars($item['ItemName']); ?></div>
                                                    <div class="product-price">₹<?php echo number_format($item['SalesPrice'], 2); ?></div>
                                                </div>
                                                <button class="btn-delete-icon" title="Delete">
                                                    <i class="fas fa-trash"></i>
                                                </button>
                                            </div>
                                        </div>
                                        <?php endforeach; ?>
                                    <?php else: ?>
                                        <div class="no-products">
                                            <i class="fas fa-box-open"></i>
                                            <p>No products found</p>
                                        </div>
                                    <?php endif; ?>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>

    <!-- Quick Add Master Modal -->
    <div class="modal fade" id="quickAddModal" tabindex="-1">
        <div class="modal-dialog modal-sm">
            <div class="modal-content">
                <div class="modal-header">
                    <h5 class="modal-title" id="quickAddTitle">Add New</h5>
                    <button type="button" class="close" data-dismiss="modal">
                        <span>&times;</span>
                    </button>
                </div>
                <div class="modal-body" id="quickAddBody">
                    <!-- Dynamic content will be loaded here -->
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-secondary btn-sm" data-dismiss="modal">Cancel</button>
                    <button type="button" class="btn btn-primary btn-sm" id="saveQuickAdd">Save</button>
                </div>
            </div>
        </div>
    </div>
    
    <!-- Toast Notification -->
    <div id="toastNotification" class="toast-notification"></div>

    <script src="../vendor/jquery/jquery.min.js"></script>
    <script src="../vendor/bootstrap/js/bootstrap.bundle.min.js"></script>
    <script src="../js/modern-messagebox.js"></script>
    <script src="../js/messagebox-wrapper.js"></script>
    <script src="https://cdn.jsdelivr.net/npm/select2@4.1.0-rc.0/dist/js/select2.min.js"></script>
    <script src="js/tamil-translation.js"></script>
    
    <!-- Barcode Scanner Script - Using html5-qrcode -->
    <script>
        // Use html5-qrcode for QR and barcode scanning
        function startBarcodeScanner() {
            // Modal setup
            const modal = document.createElement('div');
            modal.style.cssText = `
                position: fixed; top: 0; left: 0; width: 100vw; height: 100vh;
                background: rgba(0,0,0,0.9); z-index: 9999; display: flex;
                align-items: center; justify-content: center; flex-direction: column;
            `;

            const content = document.createElement('div');
            content.style.cssText = `
                background: white; padding: 20px; border-radius: 10px;
                text-align: center; max-width: 90vw; max-height: 90vh;
            `;

            const title = document.createElement('h4');
            title.textContent = 'Scan QR Code or Barcode';
            title.style.marginBottom = '15px';

            const qrReaderDiv = document.createElement('div');
            qrReaderDiv.id = 'qr-reader';
            qrReaderDiv.style.cssText = 'width: 100% !important; max-width: 400px; margin: 0 auto;';

            const controlsDiv = document.createElement('div');
            controlsDiv.style.cssText = 'margin-top: 15px;';

            const flashBtn = document.createElement('button');
            flashBtn.innerHTML = '<i class="fas fa-lightbulb"></i> Flash: ON';
            flashBtn.className = 'btn btn-warning mr-2';
            flashBtn.id = 'flashToggle';

            const closeBtn = document.createElement('button');
            closeBtn.innerHTML = '<i class="fas fa-times"></i> Close Scanner';
            closeBtn.className = 'btn btn-danger';

            controlsDiv.appendChild(flashBtn);
            controlsDiv.appendChild(closeBtn);

            content.appendChild(title);
            content.appendChild(qrReaderDiv);
            content.appendChild(controlsDiv);
            modal.appendChild(content);
            document.body.appendChild(modal);

            const html5QrCode = new Html5Qrcode("qr-reader");
            let isScanning = true;
            let isFlashOn = false;

            async function toggleFlash() {
                try {
                    if (html5QrCode.getState() === Html5QrcodeScannerState.SCANNING) {
                        if (isFlashOn) {
                            await html5QrCode.applyVideoConstraints({
                                advanced: [{ torch: false }]
                            });
                            flashBtn.innerHTML = '<i class="fas fa-lightbulb"></i> Flash: OFF';
                            flashBtn.className = 'btn btn-secondary mr-2';
                            isFlashOn = false;
                        } else {
                            await html5QrCode.applyVideoConstraints({
                                advanced: [{ torch: true }]
                            });
                            flashBtn.innerHTML = '<i class="fas fa-lightbulb"></i> Flash: ON';
                            flashBtn.className = 'btn btn-warning mr-2';
                            isFlashOn = true;
                        }
                    }
                } catch (err) {
                    console.log('Flash control not supported:', err);
                }
            }

            function stopScanner() {
                if (isScanning) {
                    isScanning = false;
                    html5QrCode.stop().then(() => {
                        if (modal.parentNode) document.body.removeChild(modal);
                    }).catch(() => {
                        if (modal.parentNode) document.body.removeChild(modal);
                    });
                }
            }

            flashBtn.onclick = toggleFlash;
            closeBtn.onclick = stopScanner;
            modal.onclick = (e) => {
                if (e.target === modal) stopScanner();
            };

            const onScanSuccess = (decodedText, decodedResult) => {
                if (!isScanning) return;
                
                // Set value in barcode input
                const barcodeInput = document.querySelector('input[name="barcode"]');
                if (barcodeInput) {
                    barcodeInput.value = decodedText;
                    
                    // Show success message
                    if (typeof MsgBox !== 'undefined') {
                        MsgBox.success('Barcode scanned: ' + decodedText);
                    } else {
                        alert('Barcode scanned: ' + decodedText);
                    }
                }
                
                // Stop the scanner
                stopScanner();
            };

            html5QrCode.start(
                { facingMode: "environment" },
                {
                    fps: 10,
                    qrbox: 250,
                    formatsToSupport: [
                        Html5QrcodeSupportedFormats.QR_CODE,
                        Html5QrcodeSupportedFormats.CODE_128,
                        Html5QrcodeSupportedFormats.EAN_13,
                        Html5QrcodeSupportedFormats.EAN_8,
                        Html5QrcodeSupportedFormats.UPC_A,
                        Html5QrcodeSupportedFormats.UPC_E,
                        Html5QrcodeSupportedFormats.CODE_39,
                        Html5QrcodeSupportedFormats.CODE_93,
                        Html5QrcodeSupportedFormats.CODABAR
                    ]
                },
                onScanSuccess,
                (errorMessage) => {
                    // ignore scan errors, keep frame open
                }
            ).then(() => {
                // Automatically turn on flashlight when camera starts
                setTimeout(async () => {
                    try {
                        await html5QrCode.applyVideoConstraints({
                            advanced: [{ torch: true }]
                        });
                        flashBtn.innerHTML = '<i class="fas fa-lightbulb"></i> Flash: ON';
                        flashBtn.className = 'btn btn-warning mr-2';
                        isFlashOn = true;
                    } catch (err) {
                        console.log('Auto-flash not supported:', err);
                        flashBtn.style.display = 'none';
                    }
                }, 1000);
            }).catch(err => {
                alert('Camera initialization failed: ' + err);
                stopScanner();
            });
        }
    </script>
    
    <script src="js/add-item.js"></script>
</body>
</html>
