<?php
ob_start();
include 'db.php';
include 'auth.php';
require_right('Item List');
include 'layout.php';

// Fetch categories, tax rates, and UOMs for the modal
$categories = $conn->query("SELECT * FROM categories");
$tax_rates = $conn->query("SELECT * FROM tax_rates");

// Fetch grouped UOMs
$uom_groups = [];
$uoms = $conn->query("SELECT uoms.*, uom_groups.name AS group_name FROM uoms
                      JOIN uom_groups ON uoms.group_id = uom_groups.id
                      ORDER BY uom_groups.id, uoms.name");
foreach ($uoms as $uom) {
    $uom_groups[$uom['group_name']][] = $uom;
}
?>

<div class="page-wrapper">
    <div class="content">
        <div class="page-header">
            <div class="page-title">
                <h4>Item List</h4>
                <h6>Manage your items</h6>
                <div class="row mb-3">
                    <div class="col-md-6">
                        <input type="text" id="itemSearch" class="form-control" placeholder="Search by Item Code or Name">
                    </div>
                </div>

                <div class="page-btn d-flex justify-content-end gap-2">
                    <button class="btn btn-added" data-bs-toggle="modal" data-bs-target="#addItemModal">
                        <i class="fa fa-plus"></i> Add Item
                    </button>
                    <button class="btn btn-added" data-bs-toggle="modal" data-bs-target="#importModal">
                        <i class="fa fa-upload"></i> Import Items
                    </button>
                </div>

                <div class="card">
                    <div class="table-responsive" style="overflow-x: auto;">
                        <table class="table datatable">
                            <thead>
                                <tr>
                                    <th>ID</th>
                                    <th>Image</th>
                                    <th>Item Code</th>
                                    <th>SKU</th>
                                    <th>Item Role</th>
                                    <th>Name</th>
                                    <th>Category</th>
                                    <th>Sub-Category</th>
                                    <th>Retail Price</th>
                                    <th>Cost Price</th>
                                    <th>Tax Type</th>
                                    <th>Tax Rate (%)</th>
                                    <th class="text-end">Action</th>
                                </tr>
                            </thead>
                            <tbody>
                                <?php
                                $result = $conn->query("SELECT items.*, tax_rates.rate AS tax_rate, categories.name AS category_name, sub_categories.name AS sub_category_name
                                                        FROM items
                                                        LEFT JOIN tax_rates ON items.tax_rate_id = tax_rates.id
                                                        LEFT JOIN categories ON items.category_id = categories.id
                                                        LEFT JOIN sub_categories ON items.sub_category_id = sub_categories.id
                                                        ORDER BY items.id DESC");
                                while ($row = $result->fetch_assoc()):
                                ?>
                                <tr>
                                    <td><?= $row['id'] ?></td>
                                    <td>
                                        <?php
                                        $img = !empty($row['product_image']) ? $row['product_image'] : 'default.png';
                                        $img_path = "assets/img/products/" . htmlspecialchars($img);
                                        ?>
                                        <img src="<?= $img_path ?>" alt="Product" class="img-thumbnail" style="width: 50px;" onerror="this.onerror=null;this.src='assets/img/products/default.png';">
                                    </td>
                                    <td><?= $row['item_code'] ?></td>
                                    <td><?= $row['sku_number'] ?></td>
                                    <td><?= htmlspecialchars($row['item_role']) ?></td>
                                    <td><?= $row['name'] ?></td>
                                    <td><?= $row['category_name'] ?? '' ?></td>
                                    <td><?= $row['sub_category_name'] ?? '' ?></td>
                                    <td><?= $row['retail_price'] ?></td>
                                    <td><?= $row['cost_price'] ?></td>
                                    <td><?= $row['tax_type'] ?></td>
                                    <td><?= $row['tax_rate'] ?? 'N/A' ?></td>
                                    <td class="text-end">
                                        <a href="edit_item.php?id=<?= $row['id'] ?>" class="btn btn-sm btn-outline-warning"><i class="fa fa-edit"></i></a>
                                        <a href="delete_item.php?id=<?= $row['id'] ?>" onclick="return confirm('Delete this item?')" class="btn btn-sm btn-outline-danger"><i class="fa fa-trash"></i></a>
                                        <a href="#" class="btn btn-sm btn-outline-info" data-bs-toggle="modal" data-bs-target="#printModal" onclick="setPrintItemCode('<?= $row['item_code'] ?>')">
                                            <i class="fa fa-barcode"></i> Print
                                        </a>
                                        <?php if ($row['item_role'] === 'stock'): ?>
                                            <a href="#" class="btn btn-sm btn-outline-success" data-bs-toggle="modal"
                                               data-bs-target="#bomModal" onclick="loadBOM(<?= $row['id'] ?>, '<?= htmlspecialchars($row['name']) ?>')">
                                               <i class="fa fa-cogs"></i> BOM
                                            </a>
                                        <?php endif; ?>
                                    </td>
                                </tr>
                                <?php endwhile; ?>
                            </tbody>
                        </table>
                    </div>
                </div>
            </div>
        </div>
    </div>
</div>

<!-- BOM Modal -->
<div class="modal fade" id="bomModal" tabindex="-1">
    <div class="modal-dialog modal-lg">
        <form id="bomForm" class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title">Build BOM for <span id="bomItemName"></span></h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
            </div>
            <div class="modal-body">
                <input type="hidden" name="item_id" id="bomItemId">
                <table class="table table-bordered" id="bomTable">
                    <thead>
                        <tr>
                            <th>Material Item</th>
                            <th>Quantity</th>
                            <th>Unit Cost</th>
                            <th><button type="button" class="btn btn-sm btn-primary" onclick="addBOMRow()">+</button></th>
                        </tr>
                    </thead>
                    <tbody></tbody>
                </table>
                <div class="text-end mt-3">
    <strong>Total BOM Cost: Rs <span id="bomTotalCost">0.00</span></strong>
</div>

            </div>
            
            <div class="modal-footer">
                <button type="submit" class="btn btn-primary">Save BOM</button>
                <button class="btn btn-secondary" data-bs-dismiss="modal">Cancel</button>
            </div>
        </form>
    </div>
</div>
<script>
function loadBOM(itemId, itemName) {
    $('#bomItemId').val(itemId);
    $('#bomItemName').text(itemName);
    $('#bomTable tbody').empty();

    // Step 1: Load BOM components
    $.get('fetch_bom.php', { item_id: itemId }, function (res) {
        const data = JSON.parse(res);

        // Build rows
        const bomRows = () => {
            if (data.length === 0) {
                addBOMRow();
            } else {
                data.forEach(row => {
                    addBOMRow(row.component_item_id, row.quantity);
                });
            }
        };

        // Step 2: Load item cost map first
        $.get('fetch_item_costs.php', function (costsRes) {
            try {
                window.itemCostMap = JSON.parse(costsRes);
                bomRows();
                updateBOMTotalCost();
            } catch (e) {
                console.error('Failed to parse item costs:', e);
                bomRows(); // Still show BOM rows
            }
        });

        // Step 3: Update cost in DB too
        updateCostPriceFromBOM(itemId);
    });
}

function addBOMRow(selectedId = '', qty = '') {
    $.get('fetch_material_items.php', function (res) {
        let options = '<option value="">Select Material</option>';
        const items = JSON.parse(res);
        items.forEach(i => {
            options += `<option value="${i.id}" ${i.id == selectedId ? 'selected' : ''}>${i.name}</option>`;
        });

      $('#bomTable tbody').append(`
    <tr>
        <td><select name="component_item_id[]" class="form-select">${options}</select></td>
        <td><input type="number" name="quantity[]" class="form-control" step="0.01" value="${qty}" required></td>
        <td><input type="text" class="form-control unit-cost" readonly value="0.00"></td>
        <td><button type="button" class="btn btn-sm btn-danger" onclick="$(this).closest('tr').remove(); updateBOMTotalCost();">&times;</button></td>
    </tr>
`);
updateBOMTotalCost();

    });
}
function updateBOMTotalCost() {
    let total = 0;
    $('#bomTable tbody tr').each(function () {
        const componentId = $(this).find('select[name="component_item_id[]"]').val();
        const qty = parseFloat($(this).find('input[name="quantity[]"]').val()) || 0;
        const unitCost = window.itemCostMap?.[componentId] || 0;

        // Show unit cost
        $(this).find('.unit-cost').val(unitCost.toFixed(2));

        total += qty * unitCost;
    });

    $('#bomTotalCost').text(total.toFixed(2));
}


function updateCostPriceFromBOM(itemId) {
    $.get('update_cost_from_bom.php', { item_id: itemId }, function (res) {
        try {
            const data = JSON.parse(res);
            if (data.status === 'ok') {
                $('#bomTotalCost').text(parseFloat(data.cost_price).toFixed(2));
            }
        } catch (err) {
            console.error('Invalid JSON from update_cost_from_bom.php');
        }
    });
}

$('#bomForm').on('submit', function (e) {
    e.preventDefault();
    $.post('save_bom.php', $(this).serialize(), function () {
        Swal.fire({
            icon: 'success',
            title: 'Saved!',
            text: 'BOM updated successfully.',
            timer: 1500,
            showConfirmButton: false
        });
        $('#bomModal').modal('hide');
    });
});

// Update cost if user changes qty or component
$(document).on('change', 'select[name="component_item_id[]"], input[name="quantity[]"]', updateBOMTotalCost);
</script>


<!-- Add Item Modal -->
<div class="modal fade" id="addItemModal" tabindex="-1">
    <div class="modal-dialog modal-lg">
        <form method="POST" action="add_item.php" enctype="multipart/form-data" class="modal-content" id="itemForm">

            <div class="modal-header">
                <h5 class="modal-title">Add New Item</h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
            </div>

            <div class="modal-body row g-3">
                <div class="col-md-6">
                    <label>Item Code</label>
                    <input type="text" name="item_code" class="form-control" required>
                </div>

                <div class="col-md-6">
                    <label>SKU Number</label>
                    <input type="text" name="sku_number" class="form-control" required>
                </div>
                <div class="col-md-12">
    <label>Item Role</label>
    <select name="item_role" class="form-control" required>
        <option value="">Select Role</option>
        <option value="stock">Stock Item (Sold Product)</option>
        <option value="material">Material Item (Raw/Ingredient)</option>
    </select>
</div>

                <div class="col-md-12">
                    <label>Name</label>
                    <input type="text" name="name" class="form-control" required>
                </div>
                <div class="col-md-6">
                    <label>Category</label>
                    <select name="category_id" id="category_id" class="form-control" required>
                        <option value="">Select</option>
                        <?php foreach ($categories as $cat): ?>
                        <option value="<?= $cat['id'] ?>"><?= $cat['name'] ?></option>
                        <?php endforeach; ?>
                    </select>
                </div>
                <div class="col-md-6">
                    <label>Sub Category</label>
                    <select name="sub_category_id" id="sub_category_id" class="form-control">
                        <option value="">Select</option>
                    </select>
                </div>
                <div class="col-md-6">
                    <label>Retail Price</label>
                    <input type="number" step="0.01" name="retail_price" class="form-control" required>
                </div>
                <div class="col-md-6">
                    <label>Cost Price</label>
                    <input type="number" step="0.01" name="cost_price" class="form-control" required>
                </div>
                <div class="col-md-6">
                    <label>Reorder Qty</label>
                    <input type="number" name="reorder_quantity" class="form-control">
                </div>
                <div class="col-md-6">
                    <label>Reorder Level</label>
                    <input type="number" name="reorder_level" class="form-control">
                </div>
                <div class="col-md-6">
                    <label>Tax Type</label>
                    <select name="tax_type" class="form-control" required>
                        <option value="">Select</option>
                        <option value="included">Included</option>
                        <option value="excluded">Excluded</option>
                        <option value="nil">Nil</option>
                    </select>
                </div>
                <div class="col-md-6">
                    <label>Tax Rate</label>
                    <select name="tax_rate_id" class="form-control">
                        <option value="">Select</option>
                        <?php foreach ($tax_rates as $rate): ?>
                        <option value="<?= $rate['id'] ?>"><?= $rate['name'] ?> (<?= $rate['rate'] ?>%)</option>
                        <?php endforeach; ?>
                    </select>
                </div>
                <div class="col-md-12">
                    <label>Item Type</label>
                    <select name="item_type" id="item_type" class="form-control" required>
                        <option value="loose">Loose</option>
                        <option value="bulk">Bulk</option>
                    </select>
                </div>

                <div class="col-md-12">
    <label>Product Image</label>
    <input type="file" name="product_image" class="form-control" accept="image/*">
    <small class="text-muted">Supported formats: JPG, PNG. Max 2MB.</small>
</div>


                <div id="bulkFields" class="row g-3" style="display:none;">
                    <div class="col-md-3">
                        <label>Bulk Qty</label>
                        <input name="bulk_qty" class="form-control" type="number">
                    </div>
                    <div class="col-md-3">
                        <label>Bulk Price</label>
                        <input name="bulk_price" class="form-control" type="number" step="0.01">
                    </div>
                    <div class="col-md-3">
                        <label>Pkg Qty</label>
                        <input name="pkg_qty" class="form-control" type="number">
                    </div>
                    <div class="col-md-3">
                        <label>UOM</label>
                        <select name="uom_id" class="form-control">
                            <option value="">Select UOM</option>
                            <?php foreach ($uom_groups as $group => $units): ?>
                            <optgroup label="<?= htmlspecialchars($group) ?>">
                                <?php foreach ($units as $uom): ?>
                                <option value="<?= $uom['id'] ?>"><?= htmlspecialchars($uom['name']) ?></option>
                                <?php endforeach; ?>
                            </optgroup>
                            <?php endforeach; ?>
                        </select>
                    </div>
                </div>
            </div>

            <div class="modal-footer">
                <button class="btn btn-secondary" data-bs-dismiss="modal">Cancel</button>
                <button class="btn btn-primary" type="submit">Save Item</button>
            </div>
        </form>
    </div>
</div>


<!-- Import Modal -->
<!-- Import Modal -->
<div class="modal fade" id="importModal" tabindex="-1">
    <div class="modal-dialog">
        <form action="import_items.php" method="POST" enctype="multipart/form-data" class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title">Import Products</h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
            </div>
            <div class="modal-body">
                <div class="mb-3">
                    <label for="import_file" class="form-label">Select CSV File</label>
                    <input type="file" name="import_file" id="import_file" class="form-control" accept=".csv" required>
                </div>
                <div class="mb-2">
                    <small class="text-muted">
                        Download sample CSV:
                        <a href="assets/files/ITRPOS_product_import.csv" download>ITRPOS_product_import.csv</a>
                    </small>
                </div>
            </div>
            <div class="modal-footer">
                <button class="btn btn-secondary" data-bs-dismiss="modal">Cancel</button>
                <button type="submit" class="btn btn-primary">Import</button>
            </div>
        </form>
    </div>
</div>

<!-- Print Barcode Modal -->
<div class="modal fade" id="printModal" tabindex="-1">
    <div class="modal-dialog">
        <form target="_blank" action="print_barcode_bulk.php" method="GET" class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title">Print Barcode</h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
            </div>
            <div class="modal-body">
                <input type="hidden" name="code" id="barcodeItemCode">
                <div class="mb-3">
                    <label for="quantity" class="form-label">Number of Copies</label>
                    <input type="number" name="copies" id="copies" class="form-control" min="1" value="1" required>
                </div>
                <div class="mb-3">
                    <label for="note" class="form-label">Custom Note (optional)</label>
                    <input type="text" name="note" id="note" class="form-control" maxlength="100" placeholder="Enter a note to print (optional)">
                </div>
            </div>
            <div class="modal-footer">
                <button type="submit" class="btn btn-primary">Print</button>
            </div>
        </form>
    </div>
</div>
<script>
function setPrintItemCode(code) {
    document.getElementById('barcodeItemCode').value = code;
}
</script>





<!-- JS Script -->

<script>
window.itemCostMap = {};
<?php
$res = $conn->query("SELECT id, cost_price FROM items");
while ($row = $res->fetch_assoc()) {
    echo "window.itemCostMap[{$row['id']}] = " . floatval($row['cost_price']) . ";\n";
}
?>
</script>



<script>

    
$(document).ready(function () {
    $('#item_type').on('change', function () {
        $('#bulkFields').toggle(this.value === 'bulk');
    });

    $('#category_id').on('change', function () {
        const catId = this.value;
        $('#sub_category_id').html('<option>Loading...</option>');
        $.get('fetch_sub_categories.php?category_id=' + catId, function (data) {
            $('#sub_category_id').html('<option value="">Select Sub Category</option>' + data);
        });
    });

    $('#addItemModal').on('show.bs.modal', function () {
        $.get('generate_item_code.php', function (res) {
            let data = JSON.parse(res);
            $('[name="item_code"]').val(data.item_code);
            $('[name="sku_number"]').val(data.sku_number);
        });

        $('#itemForm')[0].reset();
        $('#bulkFields').hide();
    });

 // ✅ Always attach this search handler
    $('#itemSearch').on('keyup', function () {
        var value = $(this).val().toLowerCase();
        $('.datatable tbody tr').filter(function () {
            $(this).toggle(
                $(this).find('td:eq(2)').text().toLowerCase().indexOf(value) > -1 || // Item Code
                $(this).find('td:eq(4)').text().toLowerCase().indexOf(value) > -1    // Name
            );
        });
    });





    // Optional: SweetAlert success feedback
    <?php if (!empty($_GET['added'])): ?>
        Swal.fire({
            icon: 'success',
            title: 'Item added',
            text: 'The item has been successfully added.',
            timer: 2000,
            showConfirmButton: false
        });
    <?php endif; ?>
});
</script>
<?php if (!empty($_GET['edit_error'])): ?>
<script>
    let message = 'An error occurred.';
    <?php if ($_GET['edit_error'] == 1): ?>
        message = 'Please fill all required fields.';
    <?php elseif ($_GET['edit_error'] == 2): ?>
        message = 'Item not found.';
    <?php elseif ($_GET['edit_error'] == 3): ?>
        message = 'Item code already exists.';
    <?php endif; ?>

    Swal.fire({
        icon: 'error',
        title: 'Update Failed',
        text: message
    });
</script>
<?php elseif (!empty($_GET['edited'])): ?>
<script>
    Swal.fire({
        icon: 'success',
        title: 'Item Updated',
        showConfirmButton: false,
        timer: 1500
    });
</script>
<?php endif; ?>

<?php if (!empty($_GET['imported'])): ?>
<script>
Swal.fire({
    icon: 'success',
    title: 'Import Successful',
    text: 'Your items were imported successfully.',
    timer: 2000,
    showConfirmButton: false
});



</script>
<?php endif; ?>

