<?php
ob_start();
include 'db.php';
include 'auth.php';
require_right('Items');
include 'functions/video_help.php';
include 'layout.php';

// Fetch categories, tax rates, UOMs, and suppliers for the modal
// Only select columns that are actually used in this page to reduce server overhead.
$categoriesResult = $conn->query("SELECT id, name FROM categories");
$categories = $categoriesResult ? $categoriesResult->fetch_all(MYSQLI_ASSOC) : [];
$tax_rates = $conn->query("SELECT id, name, rate FROM tax_rates");
$suppliers = $conn->query("SELECT id, name FROM vendors ORDER BY name");

// Fetch grouped UOMs
$uom_groups = [];
$uoms = $conn->query("SELECT uoms.id, uoms.name, uoms.symbol, 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;
}

// Handle Add Category (from modal on this page)
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['new_category_name'])) {
    require_right('Item Categories');
    $category_icon = $_POST['category_icon'] ?? 'assets/img/categories/category-01.png';
    $stmt = $conn->prepare("INSERT INTO categories (name, icon) VALUES (?, ?)");
    $stmt->bind_param("ss", $_POST['new_category_name'], $category_icon);
    $stmt->execute();
    redirect_with_iframe("item_list.php");
}

// Handle Add Sub Category (from modal on this page)
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['new_sub_category_name'])) {
    require_right('Item Categories');
    $display_color = !empty($_POST['display_color']) ? trim($_POST['display_color']) : NULL;
    $stmt = $conn->prepare("INSERT INTO sub_categories (category_id, name, display_color) VALUES (?, ?, ?)");
    $stmt->bind_param("iss", $_POST['new_sub_category_category_id'], $_POST['new_sub_category_name'], $display_color);
    $stmt->execute();
    redirect_with_iframe("item_list.php");
}

function getCategoryIcons() {
    // Avoid re-scanning the filesystem on every request (category modal opens often).
    if (session_status() === PHP_SESSION_ACTIVE
        && isset($_SESSION['category_icons_cache'])
        && is_array($_SESSION['category_icons_cache'])) {
        return $_SESSION['category_icons_cache'];
    }

    $icons = [];
    $category_path = 'assets/img/categories/';
    if (is_dir($category_path)) {
        $files = scandir($category_path);
        foreach ($files as $file) {
            if (preg_match('/\.(png|jpg|jpeg|svg|gif)$/i', $file)) {
                $icons[] = $category_path . $file;
            }
        }
    }
    natsort($icons);
    if (session_status() === PHP_SESSION_ACTIVE) {
        $_SESSION['category_icons_cache'] = $icons;
    }
    return $icons;
}
$available_category_icons = getCategoryIcons();
?>

<div class="page-wrapper item-list-page">
    <div class="content">
        <?php
        // Handle import results
        if (isset($_GET['imported'])) {
            $imported_count = (int)$_GET['imported'];
            $success_message = isset($_GET['import_message']) ? $_GET['import_message'] : '';
            $error_count = isset($_GET['error_count']) ? (int)$_GET['error_count'] : 0;
            
            // Show success message
            if ($error_count > 0) {
                // Partial success - show warning
                echo '<div class="alert alert-warning alert-dismissible fade show" role="alert">
                        <i class="fa fa-exclamation-triangle"></i> <strong>Import Partially Completed:</strong>
                        <p class="mb-2">Successfully imported ' . $imported_count . ' product(s).';
                if (!empty($success_message)) {
                    echo '<br><small class="text-muted">' . htmlspecialchars($success_message) . '</small>';
                }
                echo '</p>';
                
                // Show errors if available
                if (isset($_GET['import_errors'])) {
                    $errors = explode('|', $_GET['import_errors']);
                    echo '<strong>Errors (' . $error_count . ' row(s) had issues):</strong>
                            <ul class="mb-0 mt-2" style="max-height: 300px; overflow-y: auto;">';
                    foreach ($errors as $error) {
                        echo '<li class="small">' . htmlspecialchars($error) . '</li>';
                    }
                    echo '</ul>';
                }
                
                echo '<button type="button" class="btn-close" data-bs-dismiss="alert"></button>
                      </div>';
            } else {
                // Full success
                echo '<div class="alert alert-success alert-dismissible fade show" role="alert">
                        <i class="fa fa-check-circle"></i> Successfully imported ' . $imported_count . ' product(s)!';
                if (!empty($success_message)) {
                    echo '<br><small class="text-muted">' . htmlspecialchars($success_message) . '</small>';
                }
                echo '<button type="button" class="btn-close" data-bs-dismiss="alert"></button>
                      </div>';
            }
        }
        
        // Show errors if import failed completely (no successful imports)
        if (isset($_GET['import_errors']) && !isset($_GET['imported'])) {
            $errors = explode('|', $_GET['import_errors']);
            $error_count = isset($_GET['error_count']) ? (int)$_GET['error_count'] : count($errors);
            echo '<div class="alert alert-danger alert-dismissible fade show" role="alert">
                    <i class="fa fa-exclamation-triangle"></i> <strong>Import Failed:</strong>
                    <p class="mb-2">No items were imported. Please fix the errors below and try again.</p>
                    <strong>Errors (' . $error_count . ' row(s) had issues):</strong>
                    <ul class="mb-0 mt-2" style="max-height: 400px; overflow-y: auto;">';
            foreach ($errors as $error) {
                echo '<li class="small">' . htmlspecialchars($error) . '</li>';
            }
            echo '</ul>
                    <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
                  </div>';
        }
        
        if (isset($_GET['import_error'])) {
            $error_msg = '';
            switch ($_GET['import_error']) {
                case 'file_read':
                    $error_msg = 'Could not read the uploaded file. Please ensure it\'s a valid CSV file.';
                    break;
                default:
                    $error_msg = 'An error occurred during import. Please try again.';
            }
            echo '<div class="alert alert-danger alert-dismissible fade show" role="alert">
                    <i class="fa fa-exclamation-triangle"></i> ' . $error_msg . '
                    <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
                  </div>';
        }

        if (isset($_GET['delete_error'])) {
            echo '<div class="alert alert-warning alert-dismissible fade show" role="alert">
                    <i class="fa fa-exclamation-triangle"></i> ' . htmlspecialchars($_GET['delete_error']) . '
                    <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
                  </div>';
        }
        if (isset($_GET['delete_success'])) {
            echo '<div class="alert alert-success alert-dismissible fade show" role="alert">
                    <i class="fa fa-check-circle"></i> ' . htmlspecialchars($_GET['delete_success']) . '
                    <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
                  </div>';
        }
        ?>
        
        <div class="page-header">
            <div class="page-title">
                <h4>Item List</h4>
                <h6>Manage your items</h6>
                <!-- Search functionality will be handled by DataTable's built-in search -->

                <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-outline-secondary" data-bs-toggle="modal" data-bs-target="#filterItemsModal">
                        <i class="fa fa-filter"></i> Filter Items
                    </button>
                    <div class="btn-group">
                        <button type="button" class="btn btn-outline-primary dropdown-toggle" data-bs-toggle="dropdown" aria-expanded="false">
                            <i class="fa fa-tasks"></i> Actions <span class="badge bg-secondary ms-1" id="selectedItemsCount">0</span>
                        </button>
                        <ul class="dropdown-menu dropdown-menu-end">
                            <li>
                                <a class="dropdown-item" href="#" id="actionEditSelected">
                                    <i class="fa fa-edit"></i> Edit Selected
                                </a>
                            </li>
                            <li>
                                <a class="dropdown-item" href="#" id="actionPrintSelected">
                                    <i class="fa fa-barcode"></i> Print Barcode
                                </a>
                            </li>
                            <li>
                                <a class="dropdown-item" href="#" id="actionManageBarcodes">
                                    <i class="fa fa-qrcode"></i> Manage Barcodes
                                </a>
                            </li>
                            <li>
                                <a class="dropdown-item" href="#" id="actionBOMSelected">
                                    <i class="fa fa-cogs"></i> BOM Selected
                                </a>
                            </li>
                            <li><hr class="dropdown-divider"></li>
                            <li>
                                <a class="dropdown-item text-danger" href="#" id="actionDeleteSelected">
                                    <i class="fa fa-trash"></i> Delete Selected
                                </a>
                            </li>
                        </ul>
                    </div>
                    <div class="btn-group">
                        <button type="button" class="btn btn-outline-primary dropdown-toggle" data-bs-toggle="dropdown" aria-expanded="false">
                            <i class="fa fa-tags"></i> Categories
                        </button>
                        <ul class="dropdown-menu dropdown-menu-end">
                            <li>
                                <a class="dropdown-item" href="#" data-bs-toggle="modal" data-bs-target="#addCategoryModal">
                                    <i class="fa fa-plus"></i> Add Category
                                </a>
                            </li>
                            <li>
                                <a class="dropdown-item" href="#" data-bs-toggle="modal" data-bs-target="#addSubCategoryModal">
                                    <i class="fa fa-plus"></i> Add Sub-Category
                                </a>
                            </li>
                            <li><hr class="dropdown-divider"></li>
                            <li>
                                <a class="dropdown-item" href="category_list.php">
                                    <i class="fa fa-folder"></i> Manage Categories
                                </a>
                            </li>
                            <li>
                                <a class="dropdown-item" href="sub_category_list.php">
                                    <i class="fa fa-list"></i> Manage Sub-Categories
                                </a>
                            </li>
                        </ul>
                    </div>
                    <div class="btn-group">
                        <button type="button" class="btn btn-outline-primary dropdown-toggle" data-bs-toggle="dropdown" aria-expanded="false">
                            <i class="fa fa-file-excel"></i> Excel Operations
                        </button>
                        <ul class="dropdown-menu dropdown-menu-end">
                            <li>
                                <a class="dropdown-item" href="#" data-bs-toggle="modal" data-bs-target="#importModal">
                                    <i class="fa fa-upload"></i> Import Items
                                </a>
                            </li>
                            <li>
                                <a class="dropdown-item" href="#" data-bs-toggle="modal" data-bs-target="#updatePricesModal">
                                    <i class="fa fa-dollar-sign"></i> Update Prices from Excel
                                </a>
                            </li>
                            <li>
                                <a class="dropdown-item" href="#" data-bs-toggle="modal" data-bs-target="#updateTaxesModal">
                                    <i class="fa fa-percent"></i> Update Taxes from Excel
                                </a>
                            </li>
                            <li><hr class="dropdown-divider"></li>
                            <li>
                                <a class="dropdown-item" href="#" onclick="exportItems(); return false;">
                                    <i class="fa fa-download"></i> Export Items
                                </a>
                            </li>
                        </ul>
                    </div>
                    <?= display_video_help_dropdown('item_list', $conn, [
                        [
                            'url' => 'https://youtu.be/GBS_uIDuU9I?si=g6l3Ivea4LYAqMW2',
                            'title' => 'ITR POS Recipe Management & Inventory Deduction Explained',
                            'description' => 'Learn how to manage recipes and inventory deduction in ITR POS system.'
                        ],
                        [
                            'url' => 'https://youtu.be/pubnprBL1kk',
                            'title' => 'How to Update Item Prices from Excel',
                            'description' => 'Update retail, wholesale & cost prices in bulk from Excel in ITR POS.'
                        ]
                    ], '<i class="fa fa-play-circle"></i> Watch Videos', 'btn-outline-primary') ?>
                    <button type="button" class="btn btn-outline-secondary" id="refreshItemsBtn" title="Refresh item list">
                        <i class="fa fa-refresh"></i> Refresh
                    </button>
                </div>

                <div class="card">
                    <div class="table-responsive" style="overflow-x: auto;">
                        <table id="itemTable" class="table">
                            <thead>
                                <tr>
                                    <th>ID</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>
                                </tr>
                            </thead>
                            <tbody>
                                <!-- Data will be loaded via AJAX -->
                            </tbody>
                        </table>
                    </div>
                </div>
            </div>
        </div>
    </div>
</div>

<!-- Filter Items Modal -->
<div class="modal fade" id="filterItemsModal" tabindex="-1">
    <div class="modal-dialog modal-lg modal-dialog-centered">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title"><i class="fa fa-filter me-2 text-primary"></i>Filter Items</h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
            </div>
            <div class="modal-body">
                <div class="row">
                    <div class="col-md-4 mb-3 mb-md-0">
                        <div class="nav flex-column nav-pills filter-modal-nav" id="filterTab" role="tablist" aria-orientation="vertical">
                            <button class="nav-link active" id="filter-role-tab" data-bs-toggle="pill" data-bs-target="#filter-role" type="button" role="tab">
                                Item Roles
                            </button>
                            <button class="nav-link" id="filter-category-tab" data-bs-toggle="pill" data-bs-target="#filter-category" type="button" role="tab">
                                Categories
                            </button>
                            <button class="nav-link" id="filter-serial-tab" data-bs-toggle="pill" data-bs-target="#filter-serial" type="button" role="tab">
                                Serial Tracking
                            </button>
                            <button class="nav-link" id="filter-third-schedule-tab" data-bs-toggle="pill" data-bs-target="#filter-third-schedule" type="button" role="tab">
                                3rd Schedule
                            </button>
                        </div>
                    </div>
                    <div class="col-md-8">
                        <div class="tab-content filter-modal-tab-content" id="filterTabContent">
                            <div class="tab-pane fade show active" id="filter-role" role="tabpanel">
                                <h6 class="mb-3">Select Item Roles</h6>
                                <div class="row g-2">
                                    <div class="col-sm-6">
                                        <div class="form-check">
                                            <input class="form-check-input filter-role" type="checkbox" value="stock" id="roleStock">
                                            <label class="form-check-label" for="roleStock">Stock Item</label>
                                        </div>
                                    </div>
                                    <div class="col-sm-6">
                                        <div class="form-check">
                                            <input class="form-check-input filter-role" type="checkbox" value="material" id="roleMaterial">
                                            <label class="form-check-label" for="roleMaterial">Material Item</label>
                                        </div>
                                    </div>
                                    <div class="col-sm-6">
                                        <div class="form-check">
                                            <input class="form-check-input filter-role" type="checkbox" value="non_stock" id="roleNonStock">
                                            <label class="form-check-label" for="roleNonStock">Non-Stock Item</label>
                                        </div>
                                    </div>
                                </div>
                            </div>
                            <div class="tab-pane fade" id="filter-category" role="tabpanel">
                                <div class="d-flex justify-content-between align-items-center mb-2">
                                    <h6 class="mb-0">Categories</h6>
                                    <div class="small">
                                        <a href="#" id="selectAllCategories" class="me-3">Select all</a>
                                        <a href="#" id="clearCategorySelection">Clear</a>
                                    </div>
                                </div>
                                <div class="category-scroll border rounded p-2">
                                    <?php if (!empty($categories)): ?>
                                        <?php foreach ($categories as $cat): ?>
                                            <div class="form-check">
                                                <input class="form-check-input filter-category" type="checkbox" value="<?= htmlspecialchars($cat['name']) ?>" id="cat<?= $cat['id'] ?>">
                                                <label class="form-check-label" for="cat<?= $cat['id'] ?>"><?= htmlspecialchars($cat['name']) ?></label>
                                            </div>
                                        <?php endforeach; ?>
                                    <?php else: ?>
                                        <p class="text-muted small mb-0">No categories found.</p>
                                    <?php endif; ?>
                                </div>
                            </div>
                            <div class="tab-pane fade" id="filter-serial" role="tabpanel">
                                <h6 class="mb-3">Serial Tracking</h6>
                                <div class="form-check mb-2">
                                    <input class="form-check-input filter-serial" type="checkbox" value="serial_yes" id="serialYes">
                                    <label class="form-check-label" for="serialYes">Serial items only</label>
                                </div>
                                <div class="form-check">
                                    <input class="form-check-input filter-serial" type="checkbox" value="serial_no" id="serialNo">
                                    <label class="form-check-label" for="serialNo">Non-serial items</label>
                                </div>
                                <p class="text-muted small mt-2 mb-0">Select one or both options to match your search.</p>
                            </div>
                            <div class="tab-pane fade" id="filter-third-schedule" role="tabpanel">
                                <h6 class="mb-3">3rd Schedule Items</h6>
                                <div class="form-check mb-2">
                                    <input class="form-check-input filter-third-schedule" type="checkbox" value="third_schedule_yes" id="thirdScheduleYes">
                                    <label class="form-check-label" for="thirdScheduleYes">3rd Schedule items only</label>
                                </div>
                                <div class="form-check">
                                    <input class="form-check-input filter-third-schedule" type="checkbox" value="third_schedule_no" id="thirdScheduleNo">
                                    <label class="form-check-label" for="thirdScheduleNo">Non-3rd Schedule items</label>
                                </div>
                                <p class="text-muted small mt-2 mb-0">Select one or both options to match your search.</p>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
            <div class="modal-footer justify-content-between flex-wrap">
                <div class="mb-2 mb-sm-0">
                    <button type="button" class="btn btn-link text-danger px-0" id="resetFiltersBtn"><i class="fa fa-undo me-1"></i>Reset</button>
                </div>
                <div>
                    <button type="button" class="btn btn-secondary me-2" data-bs-dismiss="modal">Cancel</button>
                    <button type="button" class="btn btn-primary" id="applyFiltersBtn">
                        <i class="fa fa-check me-1"></i>Filter
                    </button>
                </div>
            </div>
        </div>
    </div>
</div>

<!-- Add Category Modal -->
<div class="modal fade" id="addCategoryModal" tabindex="-1">
    <div class="modal-dialog">
        <form method="POST" action="item_list.php" class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title"><i class="fa fa-plus"></i> Add New Category</h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
            </div>
            <div class="modal-body">
                <div class="form-group mb-3">
                    <label for="new_category_name" class="form-label">Category Name</label>
                    <input type="text" id="new_category_name" name="new_category_name" placeholder="Enter category name" class="form-control" required>
                </div>
                <div class="form-group">
                    <label for="category_icon" class="form-label">Category Icon</label>
                    <select id="category_icon" name="category_icon" class="form-select" onchange="previewCategoryIcon(this.value, 'addCategoryIconPreview')">
                        <optgroup label="Category Images (<?= count($available_category_icons) ?> available)">
                            <?php foreach ($available_category_icons as $index => $icon_path):
                                $icon_name = basename($icon_path);
                                $display_name = ucwords(str_replace(['-', '_', '.png', '.jpg', '.jpeg', '.svg', '.gif'], [' ', ' ', '', '', '', '', ''], $icon_name));
                            ?>
                                <option value="<?= htmlspecialchars($icon_path) ?>" <?= $index === 0 ? 'selected' : '' ?>>
                                    <?= htmlspecialchars($display_name) ?>
                                </option>
                            <?php endforeach; ?>
                        </optgroup>
                        <optgroup label="General Icons">
                            <option value="assets/img/icons/dashboard.svg">Dashboard</option>
                            <option value="assets/img/icons/folder.svg">Folder</option>
                            <option value="assets/img/icons/product.svg">Product</option>
                        </optgroup>
                    </select>
                    <div class="mt-2 text-center">
                        <img id="addCategoryIconPreview" src="<?= !empty($available_category_icons) ? htmlspecialchars($available_category_icons[0]) : 'assets/img/categories/category-01.png' ?>" alt="Icon Preview" style="width: 60px; height: 60px; object-fit: contain; border: 1px solid #ddd; border-radius: 5px; padding: 5px;">
                    </div>
                </div>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Cancel</button>
                <button type="submit" class="btn btn-primary">
                    <i class="fa fa-save"></i> Save Category
                </button>
            </div>
        </form>
    </div>
</div>

<!-- Add Sub-Category Modal -->
<div class="modal fade" id="addSubCategoryModal" tabindex="-1">
    <div class="modal-dialog">
        <form method="POST" action="item_list.php" class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title"><i class="fa fa-plus"></i> Add New Sub-Category</h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
            </div>
            <div class="modal-body">
                <div class="form-group mb-3">
                    <label for="new_sub_category_category_id" class="form-label">Parent Category</label>
                    <select id="new_sub_category_category_id" name="new_sub_category_category_id" class="form-select" required>
                        <option value="">Select a category</option>
                        <?php foreach ($categories as $cat): ?>
                            <option value="<?= (int)$cat['id'] ?>"><?= htmlspecialchars($cat['name']) ?></option>
                        <?php endforeach; ?>
                    </select>
                </div>
                <div class="form-group mb-3">
                    <label for="new_sub_category_name" class="form-label">Sub-Category Name</label>
                    <input type="text" id="new_sub_category_name" name="new_sub_category_name" placeholder="Enter sub-category name" class="form-control" required>
                </div>
                <div class="form-group">
                    <label class="form-label">POS Display Color <small class="text-muted">(Optional)</small></label>
                    <div class="color-picker-grid">
                        <input type="radio" name="display_color" value="" id="item_sub_color_default" checked>
                        <label for="item_sub_color_default" class="color-option" style="background-color: #0D3B66; color: #fff;" title="Default Navy Blue"><span class="color-label">Default</span></label>
                        <input type="radio" name="display_color" value="primary" id="item_sub_color_primary">
                        <label for="item_sub_color_primary" class="color-option" style="background-color: #FF9F43;" title="Orange"><span class="color-label">Orange</span></label>
                        <input type="radio" name="display_color" value="success" id="item_sub_color_success">
                        <label for="item_sub_color_success" class="color-option" style="background-color: #28C76F;" title="Green"><span class="color-label">Green</span></label>
                        <input type="radio" name="display_color" value="danger" id="item_sub_color_danger">
                        <label for="item_sub_color_danger" class="color-option" style="background-color: #FF0000;" title="Red"><span class="color-label">Red</span></label>
                        <input type="radio" name="display_color" value="warning" id="item_sub_color_warning">
                        <label for="item_sub_color_warning" class="color-option" style="background-color: #FF9900;" title="Warning"><span class="color-label">Warning</span></label>
                        <input type="radio" name="display_color" value="info" id="item_sub_color_info">
                        <label for="item_sub_color_info" class="color-option" style="background-color: #17a2b8;" title="Info Blue"><span class="color-label">Info</span></label>
                        <input type="radio" name="display_color" value="purple" id="item_sub_color_purple">
                        <label for="item_sub_color_purple" class="color-option" style="background-color: #7367F0;" title="Purple"><span class="color-label">Purple</span></label>
                        <input type="radio" name="display_color" value="teal" id="item_sub_color_teal">
                        <label for="item_sub_color_teal" class="color-option" style="background-color: #02a8b5;" title="Teal"><span class="color-label">Teal</span></label>
                        <input type="radio" name="display_color" value="pink" id="item_sub_color_pink">
                        <label for="item_sub_color_pink" class="color-option" style="background-color: #ff63a5;" title="Pink"><span class="color-label">Pink</span></label>
                        <input type="radio" name="display_color" value="yellow" id="item_sub_color_yellow">
                        <label for="item_sub_color_yellow" class="color-option" style="background-color: #ffff00; color: #333;" title="Yellow"><span class="color-label">Yellow</span></label>
                    </div>
                    <small class="text-muted">Select a color to highlight this sub-category in POS screen</small>
                </div>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Cancel</button>
                <button type="submit" class="btn btn-primary">
                    <i class="fa fa-save"></i> Save Sub-Category
                </button>
            </div>
        </form>
    </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">
                <div class="alert alert-info py-2 mb-2">
                    <b>Note:</b> All quantities are in the <b>base unit</b> of the material (e.g., grams, pieces, liters). The base unit is shown next to each material.
                </div>
                <table class="table table-bordered" id="bomTable">
                    <thead>
                        <tr>
                            <th>Material Item</th>
                            <th>Quantity</th>
                            <th>Unit</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 previewCategoryIcon(iconPath, previewElementId) {
    var el = document.getElementById(previewElementId);
    if (el) el.src = iconPath;
}
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);
        let itemMap = {};
        items.forEach(i => {
            options += `<option value="${i.id}" ${i.id == selectedId ? 'selected' : ''}>${i.name}</option>`;
            itemMap[i.id] = i;
        });

      $('#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="any" value="${qty ? parseFloat(qty).toFixed(6) : ''}" required></td>
        <td><span class="bom-unit"></span></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();

        // Set the unit for the selected material
        const $lastRow = $('#bomTable tbody tr').last();
        const $select = $lastRow.find('select[name="component_item_id[]"]');
        const $unit = $lastRow.find('.bom-unit');
        function updateUnit() {
            const val = $select.val();
            if (val && itemMap[val]) {
                $unit.text(itemMap[val].unit_name + ' (' + itemMap[val].unit_symbol + ')');
            } else {
                $unit.text('');
            }
        }
        $select.on('change', updateUnit);
        $select.trigger('change');
    });
}
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-xl item-form-modal">
        <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 item-form-body">
                <div class="row item-form-columns g-4">
                    <div class="col-lg-6">
                        <div class="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>
                                    <option value="non_stock">Non-Stock Item (Bundle/Service/Recipe)</option>
                                </select>
                            </div>
                            <div class="col-md-12">
                                <div class="form-check mb-2">
                                    <input type="checkbox" name="is_serialized" id="is_serialized" class="form-check-input" value="1">
                                    <label class="form-check-label" for="is_serialized">
                                        <strong>Serial/IMEI Tracking</strong>
                                        <small class="text-muted d-block">Enable for items requiring unique serial numbers (mobiles, electronics, etc.)</small>
                                    </label>
                                </div>
                            </div>
                            <div class="col-md-12">
                                <div class="form-check mb-2">
                                    <input type="checkbox" name="is_third_schedule" id="is_third_schedule" class="form-check-input" value="1">
                                    <label class="form-check-label" for="is_third_schedule">
                                        <strong>3rd Schedule Item</strong>
                                        <small class="text-muted d-block">Mark this if the product falls under FBR Third Schedule so invoices send type 11.</small>
                                    </label>
                                </div>
                            </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-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>
                                <small class="text-muted d-block mt-1">Loose = sell single units. Bulk = sell complete packs/cartons (e.g. a carton you scan and sell as one line).</small>
                            </div>
                            <div class="col-md-4">
                                <label>Retail Price</label>
                                <input type="number" step="0.01" name="retail_price" id="retail_price" class="form-control" required>
                            </div>
                            <div class="col-md-4">
                                <label>Wholesale Price</label>
                                <input type="number" step="0.01" min="0" name="wholesale_price" id="wholesale_price" class="form-control" value="0.00">
                            </div>
                            <div class="col-md-4">
                                <label>Cost Price <small class="text-muted">(Default: 0.00)</small></label>
                                <input type="number" step="0.01" min="0" name="cost_price" id="cost_price" class="form-control" required value="0.00">
                            </div>
                            <div class="col-md-12">
                                <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-12">
                                <div class="alert alert-info" id="profitAlert" style="display: none;">
                                    <div class="row">
                                        <div class="col-md-4">
                                            <strong>Profit Amount:</strong> <span id="profitAmount" class="text-success">Rs 0.00</span>
                                        </div>
                                        <div class="col-md-4">
                                            <strong>Profit Percentage:</strong> <span id="profitPercentage" class="text-success">0%</span>
                                        </div>
                                        <div class="col-md-4">
                                            <strong>Margin:</strong> <span id="marginPercentage" class="text-primary">0%</span>
                                        </div>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>
                    <div class="col-lg-6">
                        <div class="row g-3">
                            <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-12">
                                <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>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 class="col-md-12">
                                <label>POS Display Color <small class="text-muted">(Optional)</small></label>
                                <div class="color-picker-grid">
                                    <input type="radio" name="display_color" value="" id="color_default" checked>
                                    <label for="color_default" class="color-option" style="background-color: #EFF6FF; color: #092C4C;" title="Default Light Blue">
                                        <span class="color-label">Default</span>
                                    </label>
                                    
                                    <input type="radio" name="display_color" value="primary" id="color_primary">
                                    <label for="color_primary" class="color-option" style="background-color: #FF9F43;" title="Orange">
                                        <span class="color-label">Orange</span>
                                    </label>
                                    
                                    <input type="radio" name="display_color" value="success" id="color_success">
                                    <label for="color_success" class="color-option" style="background-color: #28C76F;" title="Green">
                                        <span class="color-label">Green</span>
                                    </label>
                                    
                                    <input type="radio" name="display_color" value="danger" id="color_danger">
                                    <label for="color_danger" class="color-option" style="background-color: #FF0000;" title="Red">
                                        <span class="color-label">Red</span>
                                    </label>
                                    
                                    <input type="radio" name="display_color" value="warning" id="color_warning">
                                    <label for="color_warning" class="color-option" style="background-color: #FF9900;" title="Warning">
                                        <span class="color-label">Warning</span>
                                    </label>
                                    
                                    <input type="radio" name="display_color" value="info" id="color_info">
                                    <label for="color_info" class="color-option" style="background-color: #17a2b8;" title="Info Blue">
                                        <span class="color-label">Info</span>
                                    </label>
                                    
                                    <input type="radio" name="display_color" value="purple" id="color_purple">
                                    <label for="color_purple" class="color-option" style="background-color: #7367F0;" title="Purple">
                                        <span class="color-label">Purple</span>
                                    </label>
                                    
                                    <input type="radio" name="display_color" value="teal" id="color_teal">
                                    <label for="color_teal" class="color-option" style="background-color: #02a8b5;" title="Teal">
                                        <span class="color-label">Teal</span>
                                    </label>
                                    
                                    <input type="radio" name="display_color" value="pink" id="color_pink">
                                    <label for="color_pink" class="color-option" style="background-color: #ff63a5;" title="Pink">
                                        <span class="color-label">Pink</span>
                                    </label>
                                    
                                    <input type="radio" name="display_color" value="yellow" id="color_yellow">
                                    <label for="color_yellow" class="color-option" style="background-color: #ffff00; color: #333;" title="Yellow">
                                        <span class="color-label">Yellow</span>
                                    </label>
                                </div>
                                <small class="text-muted">Select a color to highlight this item in POS screen for easy identification</small>
                            </div>
                            <div class="col-md-12">
                                <label>Unit of Measurement (UOM) <span class="text-danger">*</span></label>
                                <select name="uom_id" class="form-control" required>
                                    <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']) ?> (<?= htmlspecialchars($uom['symbol']) ?>)</option>
                                        <?php endforeach; ?>
                                    </optgroup>
                                    <?php endforeach; ?>
                                </select>
                                <small class="text-muted">Choose the unit for this item (e.g. Piece, Kilogram, Liter).</small>
                            </div>
                            <div class="col-md-12">
                                <label>Supplier <small class="text-muted">(Optional)</small></label>
                                <select name="supplier_id" id="supplier_id" class="form-control">
                                    <option value="">Select Supplier (Optional)</option>
                                    <?php 
                                    if ($suppliers && $suppliers->num_rows > 0):
                                        $suppliers->data_seek(0);
                                        while ($supplier = $suppliers->fetch_assoc()): 
                                    ?>
                                        <option value="<?= $supplier['id'] ?>"><?= htmlspecialchars($supplier['name']) ?></option>
                                    <?php 
                                        endwhile;
                                    endif; 
                                    ?>
                                </select>
                                <small class="text-muted">Select the primary supplier for this item (optional).</small>
                            </div>
                            <div class="col-12">
                                <div id="bulkFields" class="row g-3" style="display:none;">
                                    <div class="col-md-4">
                                        <label>Bulk Qty</label>
                                        <input name="bulk_qty" class="form-control" type="number">
                                        <small class="text-muted">How many loose pieces sit inside one pack (e.g. 1 pack = 10 bottles).</small>
                                    </div>
                                    <div class="col-md-4">
                                        <label>Bulk Price</label>
                                        <input name="bulk_price" class="form-control" type="number" step="0.01">
                                        <small class="text-muted">Selling price of the whole pack/carton when you sell it as bulk.</small>
                                    </div>
                                    <div class="col-md-4">
                                        <label>Pkg Qty</label>
                                        <input name="pkg_qty" class="form-control" type="number">
                                        <small class="text-muted">How many packs count as one bulk unit (usually 1 pack = 1). Bulk Qty tells you the loose pieces inside that pack.</small>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </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 -->
<div class="modal fade" id="importModal" tabindex="-1">
    <div class="modal-dialog modal-xl" style="max-width: 95%;">
        <div 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">
                <!-- Tabs for Import Methods -->
                <ul class="nav nav-tabs mb-3" id="importTabs" role="tablist">
                    <li class="nav-item" role="presentation">
                        <button class="nav-link active" id="clipboard-tab" data-bs-toggle="tab" data-bs-target="#clipboard-pane" type="button" role="tab">
                            <i class="fa fa-paste"></i> Copy from Excel (Recommended)
                        </button>
                    </li>
                    <li class="nav-item" role="presentation">
                        <button class="nav-link" id="csv-tab" data-bs-toggle="tab" data-bs-target="#csv-pane" type="button" role="tab">
                            <i class="fa fa-file-csv"></i> Upload CSV File
                        </button>
                    </li>
                </ul>
                
                <div class="tab-content" id="importTabContent">
                    <!-- Clipboard Import Tab -->
                    <div class="tab-pane fade show active" id="clipboard-pane" role="tabpanel">
                        <div class="row mb-3">
                            <div class="col-12 text-end">
                                <a href="import_items.php?download_template=1" class="btn btn-success btn-sm">
                                    <i class="fa fa-download"></i> Download Template
                                </a>
                                <a href="view_import_instructions.php" target="_blank" class="btn btn-info btn-sm">
                                    <i class="fa fa-question-circle"></i> View Instructions
                                </a>
                            </div>
                        </div>
                        
                        <div class="row">
                            <div class="col-md-6">
                                <label for="clipboardData" class="form-label fw-bold">
                                    <i class="fa fa-paste"></i> Paste Excel Data Here:
                                </label>
                                <textarea id="clipboardData" class="form-control" rows="18" 
                                          placeholder="Paste your Excel data here...&#10;&#10;Make sure to include all columns:&#10;Item Code, SKU Number, Name, Category Name, Sub Category Name, Retail Price, Cost Price, etc."
                                          style="font-family: 'Courier New', monospace; font-size: 12px;"></textarea>
                                <div class="d-flex justify-content-between align-items-center mt-2">
                                    <small class="text-muted">
                                        <i class="fa fa-lightbulb"></i> Tip: Copy directly from Excel (including headers)
                                    </small>
                                    <button type="button" class="btn btn-sm btn-outline-secondary" onclick="clearClipboardData()">
                                        <i class="fa fa-eraser"></i> Clear
                                    </button>
                                </div>
                            </div>
                            <div class="col-md-6">
                                <label class="form-label fw-bold">
                                    <i class="fa fa-eye"></i> Preview:
                                </label>
                                <div class="alert alert-info mb-0" id="importPreview" style="display: none; height: 100%; min-height: 450px;">
                                    <div class="d-flex justify-content-between align-items-center mb-2">
                                        <strong>Preview:</strong>
                                        <span class="badge bg-primary" id="previewCount">0 rows</span>
                                    </div>
                                    <div class="table-responsive" style="max-height: 400px; overflow-y: auto;">
                                        <div id="previewContent"></div>
                                    </div>
                                </div>
                                <div id="previewPlaceholder" class="text-center text-muted p-4 border rounded" style="min-height: 450px; display: flex; align-items: center; justify-content: center;">
                                    <div>
                                        <i class="fa fa-eye-slash fa-3x mb-2"></i>
                                        <p class="mb-0">Preview will appear here after pasting data</p>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>
                    
                    <!-- CSV Upload Tab -->
                    <div class="tab-pane fade" id="csv-pane" role="tabpanel">
                        <form id="csvImportForm" action="import_items.php" method="POST" enctype="multipart/form-data">
                            <div class="row">
                                <div class="col-md-8">
                                    <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">
                                        <div class="form-text">Only CSV files are supported</div>
                                    </div>
                                </div>
                                <div class="col-md-4">
                                    <div class="mb-3">
                                        <label class="form-label">Template & Help</label>
                                        <div class="d-grid gap-2">
                                            <a href="import_items.php?download_template=1" class="btn btn-success btn-sm">
                                                <i class="fa fa-download"></i> Download Template
                                            </a>
                                            <a href="view_import_instructions.php" target="_blank" class="btn btn-info btn-sm">
                                                <i class="fa fa-question-circle"></i> View Instructions
                                            </a>
                                        </div>
                                    </div>
                                </div>
                            </div>
                        </form>
                    </div>
                </div>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Cancel</button>
                <button type="button" class="btn btn-primary" id="importClipboardBtn" onclick="importFromClipboard()">
                    <i class="fa fa-upload"></i> Import Products
                </button>
                <button type="submit" form="csvImportForm" class="btn btn-primary" id="importCsvBtn" style="display: none;">
                    <i class="fa fa-upload"></i> Import Products
                </button>
            </div>
        </div>
    </div>
</div>

<!-- Update Prices Modal -->
<div class="modal fade" id="updatePricesModal" tabindex="-1">
    <div class="modal-dialog modal-xl" style="max-width: 95%;">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title">
                    <i class="fa fa-dollar-sign"></i> Update Item Prices
                </h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
            </div>
            <div class="modal-body">
                <!-- Field Selection Checkboxes -->
                <div class="row mb-3">
                    <div class="col-12">
                        <label class="form-label fw-bold">Select Fields to Update:</label>
                        <div class="d-flex gap-3 flex-wrap">
                            <div class="form-check">
                                <input class="form-check-input" type="checkbox" id="chkItemCode" checked disabled>
                                <label class="form-check-label" for="chkItemCode">
                                    Item Code
                                </label>
                            </div>
                            <div class="form-check">
                                <input class="form-check-input" type="checkbox" id="chkRetailPrice" checked>
                                <label class="form-check-label" for="chkRetailPrice">
                                    Retail Price
                                </label>
                            </div>
                            <div class="form-check">
                                <input class="form-check-input" type="checkbox" id="chkWholesalePrice">
                                <label class="form-check-label" for="chkWholesalePrice">
                                    Wholesale Price
                                </label>
                            </div>
                            <div class="form-check">
                                <input class="form-check-input" type="checkbox" id="chkItemCost">
                                <label class="form-check-label" for="chkItemCost">
                                    Item Cost
                                </label>
                            </div>
                        </div>
                    </div>
                </div>
                
                <!-- Clipboard Paste Area and Data Display -->
                <div class="row">
                    <div class="col-md-6">
                        <label for="pricesClipboardData" class="form-label fw-bold">
                            <i class="fa fa-paste"></i> Paste Excel Data Here:
                        </label>
                        <textarea id="pricesClipboardData" class="form-control" rows="18" 
                                  placeholder="Paste your Excel data here...&#10;&#10;Format: Item Code, Retail Price, Wholesale Price (optional), Cost Price (optional)&#10;&#10;Example:&#10;ITM001	100.00	80.00	50.00"
                                  style="font-family: 'Courier New', monospace; font-size: 12px;"></textarea>
                        <div class="d-flex justify-content-between align-items-center mt-2">
                            <small class="text-muted">
                                <i class="fa fa-lightbulb"></i> Tip: Copy directly from Excel (including headers)
                            </small>
                            <button type="button" class="btn btn-sm btn-outline-secondary" onclick="clearPricesClipboardData()">
                                <i class="fa fa-eraser"></i> Clear
                            </button>
                        </div>
                    </div>
                    <div class="col-md-6">
                        <label class="form-label fw-bold">
                            <i class="fa fa-eye"></i> Preview:
                        </label>
                        <div class="table-responsive" style="max-height: 500px; overflow-y: auto;">
                            <table class="table table-bordered table-hover" id="pricesTable">
                                <thead class="table-light sticky-top">
                                    <tr>
                                        <th width="5%">
                                            <input type="checkbox" id="selectAllPrices" onchange="toggleAllPrices(this)">
                                        </th>
                                        <th width="15%">Code</th>
                                        <th width="25%">Item</th>
                                        <th width="15%" class="retail-col">Retail</th>
                                        <th width="15%" class="wholesale-col" style="display: none;">Wholesale</th>
                                        <th width="15%" class="cost-col" style="display: none;">Cost</th>
                                    </tr>
                                </thead>
                                <tbody id="pricesTableBody">
                                    <tr>
                                        <td colspan="6" class="text-center text-muted py-5">
                                            <i class="fa fa-inbox fa-3x mb-3"></i>
                                            <p class="mb-0">No records found</p>
                                            <small>Paste Excel data in the textarea</small>
                                        </td>
                                    </tr>
                                </tbody>
                            </table>
                        </div>
                    </div>
                </div>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-secondary" onclick="copySelectedPrices()">
                    <i class="fa fa-copy"></i> Copy Selected
                </button>
                <button type="button" class="btn btn-outline-danger" onclick="removeSelectedPrices()">
                    <i class="fa fa-trash"></i> Remove Selected
                </button>
                <span class="flex-grow-1 text-center text-muted" id="pricesStatus">No records found</span>
                <button type="button" class="btn btn-primary" onclick="updatePrices()" id="updatePricesBtn" disabled>
                    <i class="fa fa-save"></i> Update
                </button>
                <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Cancel</button>
            </div>
        </div>
    </div>
</div>

<!-- Update Taxes Modal -->
<div class="modal fade" id="updateTaxesModal" tabindex="-1">
    <div class="modal-dialog modal-xl" style="max-width: 95%;">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title">
                    <i class="fa fa-percent"></i> Update Item Taxes
                </h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
            </div>
            <div class="modal-body">
                <!-- Field Selection Checkboxes -->
                <div class="row mb-3">
                    <div class="col-12">
                        <label class="form-label fw-bold">Select Fields to Update:</label>
                        <div class="d-flex gap-3 flex-wrap">
                            <div class="form-check">
                                <input class="form-check-input" type="checkbox" id="chkTaxItemCode" checked disabled>
                                <label class="form-check-label" for="chkTaxItemCode">
                                    Item Code
                                </label>
                            </div>
                            <div class="form-check">
                                <input class="form-check-input" type="checkbox" id="chkTaxType" checked>
                                <label class="form-check-label" for="chkTaxType">
                                    Tax Type
                                </label>
                            </div>
                            <div class="form-check">
                                <input class="form-check-input" type="checkbox" id="chkTaxRate" checked>
                                <label class="form-check-label" for="chkTaxRate">
                                    Tax Rate Name
                                </label>
                            </div>
                        </div>
                        <small class="text-muted mt-2 d-block">
                            <strong>Tax Type values:</strong> 'included', 'excluded', or 'nil'<br>
                            <strong>Tax Rate Name:</strong> Must match an existing tax rate name in the system
                        </small>
                    </div>
                </div>
                
                <!-- Clipboard Paste Area and Data Display -->
                <div class="row">
                    <div class="col-md-6">
                        <label for="taxesClipboardData" class="form-label fw-bold">
                            <i class="fa fa-paste"></i> Paste Excel Data Here:
                        </label>
                        <textarea id="taxesClipboardData" class="form-control" rows="18" 
                                  placeholder="Paste your Excel data here...&#10;&#10;Format: Item Code, Tax Type, Tax Rate Name (optional)&#10;&#10;Example:&#10;ITM001	included	Standard Rate&#10;ITM002	excluded	Zero Rate&#10;ITM003	nil"
                                  style="font-family: 'Courier New', monospace; font-size: 12px;"></textarea>
                        <div class="d-flex justify-content-between align-items-center mt-2">
                            <small class="text-muted">
                                <i class="fa fa-lightbulb"></i> Tip: Copy directly from Excel (including headers)
                            </small>
                            <button type="button" class="btn btn-sm btn-outline-secondary" onclick="clearTaxesClipboardData()">
                                <i class="fa fa-eraser"></i> Clear
                            </button>
                        </div>
                    </div>
                    <div class="col-md-6">
                        <label class="form-label fw-bold">
                            <i class="fa fa-eye"></i> Preview:
                        </label>
                        <div class="table-responsive" style="max-height: 500px; overflow-y: auto;">
                            <table class="table table-bordered table-hover" id="taxesTable">
                                <thead class="table-light sticky-top">
                                    <tr>
                                        <th width="5%">
                                            <input type="checkbox" id="selectAllTaxes" onchange="toggleAllTaxes(this)">
                                        </th>
                                        <th width="20%">Code</th>
                                        <th width="30%">Item</th>
                                        <th width="20%" class="taxtype-col">Tax Type</th>
                                        <th width="25%" class="taxrate-col">Tax Rate</th>
                                    </tr>
                                </thead>
                                <tbody id="taxesTableBody">
                                    <tr>
                                        <td colspan="5" class="text-center text-muted py-5">
                                            <i class="fa fa-inbox fa-3x mb-3"></i>
                                            <p class="mb-0">No records found</p>
                                            <small>Paste Excel data in the textarea</small>
                                        </td>
                                    </tr>
                                </tbody>
                            </table>
                        </div>
                    </div>
                </div>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-secondary" onclick="copySelectedTaxes()">
                    <i class="fa fa-copy"></i> Copy Selected
                </button>
                <button type="button" class="btn btn-outline-danger" onclick="removeSelectedTaxes()">
                    <i class="fa fa-trash"></i> Remove Selected
                </button>
                <span class="flex-grow-1 text-center text-muted" id="taxesStatus">No records found</span>
                <button type="button" class="btn btn-primary" onclick="updateTaxes()" id="updateTaxesBtn" disabled>
                    <i class="fa fa-save"></i> Update
                </button>
                <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Cancel</button>
            </div>
        </div>
    </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>

<!-- Manage Alternate Barcodes Modal -->
<div class="modal fade" id="manageBarcodesModal" tabindex="-1">
    <div class="modal-dialog modal-lg modal-dialog-centered">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title">
                    <i class="fa fa-qrcode text-primary me-2"></i>
                    Manage Barcodes - <span id="barcodeModalItemName">Item</span>
                </h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
            </div>
            <div class="modal-body">
                <input type="hidden" id="barcodeModalItemId">
                <div class="row g-2 align-items-end mb-3">
                    <div class="col-md-5">
                        <label class="form-label">Barcode</label>
                        <input type="text" class="form-control" id="newBarcodeValue" placeholder="Scan or type barcode">
                    </div>
                    <div class="col-md-5">
                        <label class="form-label">Label (optional)</label>
                        <input type="text" class="form-control" id="newBarcodeLabel" placeholder="Vendor Pack / Carton / Alternate">
                    </div>
                    <div class="col-md-2 d-grid">
                        <button type="button" class="btn btn-primary" id="saveBarcodeBtn">
                            <i class="fa fa-plus"></i> Add
                        </button>
                    </div>
                </div>
                <div class="table-responsive border rounded">
                    <table class="table table-sm mb-0">
                        <thead>
                            <tr>
                                <th>Barcode</th>
                                <th>Label</th>
                                <th class="text-end">Action</th>
                            </tr>
                        </thead>
                        <tbody id="barcodeListBody">
                            <tr>
                                <td colspan="3" class="text-center text-muted py-3">No alternate barcodes added.</td>
                            </tr>
                        </tbody>
                    </table>
                </div>
                <small class="text-muted d-block mt-2">
                    Primary item code remains unchanged. Alternate barcodes will also scan this same item in POS.
                </small>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Close</button>
            </div>
        </div>
    </div>
</div>


<!-- Edit Item Modal -->
<div class="modal fade" id="editItemModal" tabindex="-1">
    <div class="modal-dialog modal-xl item-form-modal">
        <form method="POST" action="update_item.php" enctype="multipart/form-data" class="modal-content" id="editItemForm">
            <input type="hidden" name="id" id="edit_id">
            <div class="modal-header">
                <h5 class="modal-title">Edit Item</h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
            </div>
            <div class="modal-body item-form-body">
                <div class="row item-form-columns g-4">
                    <div class="col-lg-6">
                        <div class="row g-3">
                            <div class="col-md-6">
                                <label>Item Code</label>
                                <input type="text" name="item_code" id="edit_item_code" class="form-control" required>
                            </div>
                            <div class="col-md-6">
                                <label>SKU Number</label>
                                <input type="text" name="sku_number" id="edit_sku_number" class="form-control" required>
                            </div>
                            <div class="col-md-12">
                                <label>Item Role</label>
                                <select name="item_role" id="edit_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>
                                    <option value="non_stock">Non-Stock Item (Bundle/Service/Recipe)</option>
                                </select>
                            </div>
                            <div class="col-md-12">
                                <div class="form-check mb-2">
                                    <input type="checkbox" name="is_serialized" id="edit_is_serialized" class="form-check-input" value="1">
                                    <label class="form-check-label" for="edit_is_serialized">
                                        <strong>Serial/IMEI Tracking</strong>
                                        <small class="text-muted d-block">Enable for items requiring unique serial numbers (mobiles, electronics, etc.)</small>
                                    </label>
                                </div>
                            </div>
                            <div class="col-md-12">
                                <div class="form-check mb-2">
                                    <input type="checkbox" name="is_third_schedule" id="edit_is_third_schedule" class="form-check-input" value="1">
                                    <label class="form-check-label" for="edit_is_third_schedule">
                                        <strong>3rd Schedule Item</strong>
                                        <small class="text-muted d-block">Keep this checked only for products taxed under Third Schedule (FBR Invoice Type 11).</small>
                                    </label>
                                </div>
                            </div>
                            <div class="col-md-12">
                                <label>Name</label>
                                <input type="text" name="name" id="edit_name" class="form-control" required>
                            </div>
                            <div class="col-md-6">
                                <label>Category</label>
                                <select name="category_id" id="edit_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="edit_sub_category_id" class="form-control">
                                    <option value="">Select</option>
                                </select>
                            </div>
                            <div class="col-md-12">
                                <label>Item Type</label>
                                <select name="item_type" id="edit_item_type" class="form-control" required>
                                    <option value="loose">Loose</option>
                                    <option value="bulk">Bulk</option>
                                </select>
                                <small class="text-muted d-block mt-1">Loose = sell single units. Bulk = sell packs/cartons as one line item.</small>
                            </div>
                            <div class="col-md-4">
                                <label>Retail Price</label>
                                <input type="number" step="0.01" name="retail_price" id="edit_retail_price" class="form-control" required>
                            </div>
                            <div class="col-md-4">
                                <label>Wholesale Price</label>
                                <input type="number" step="0.01" min="0" name="wholesale_price" id="edit_wholesale_price" class="form-control" value="0.00">
                            </div>
                            <div class="col-md-4">
                                <label>Cost Price <small class="text-muted">(Default: 0.00)</small></label>
                                <input type="number" step="0.01" min="0" name="cost_price" id="edit_cost_price" class="form-control" required>
                            </div>
                            <div class="col-md-12">
                                <label>Tax Type</label>
                                <select name="tax_type" id="edit_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-12">
                                <div class="alert alert-info" id="editProfitAlert" style="display: none;">
                                    <div class="row">
                                        <div class="col-md-4">
                                            <strong>Profit Amount:</strong> <span id="editProfitAmount" class="text-success">Rs 0.00</span>
                                        </div>
                                        <div class="col-md-4">
                                            <strong>Profit Percentage:</strong> <span id="editProfitPercentage" class="text-success">0%</span>
                                        </div>
                                        <div class="col-md-4">
                                            <strong>Margin:</strong> <span id="editMarginPercentage" class="text-primary">0%</span>
                                        </div>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>
                    <div class="col-lg-6">
                        <div class="row g-3">
                            <div class="col-md-6">
                                <label>Reorder Qty</label>
                                <input type="number" name="reorder_quantity" id="edit_reorder_quantity" class="form-control">
                            </div>
                            <div class="col-md-6">
                                <label>Reorder Level</label>
                                <input type="number" name="reorder_level" id="edit_reorder_level" class="form-control">
                            </div>
                            <div class="col-md-12">
                                <label>Tax Rate</label>
                                <select name="tax_rate_id" id="edit_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>Product Image</label>
                                <input type="file" name="product_image" id="edit_product_image" class="form-control" accept="image/*">
                                <small class="text-muted">Supported formats: JPG, PNG. Max 2MB.</small>
                            </div>
                            <div class="col-md-12">
                                <label>POS Display Color <small class="text-muted">(Optional)</small></label>
                                <div class="color-picker-grid">
                                    <input type="radio" name="display_color" value="" id="edit_color_default">
                                    <label for="edit_color_default" class="color-option" style="background-color: #EFF6FF; color: #092C4C;" title="Default Light Blue">
                                        <span class="color-label">Default</span>
                                    </label>
                                    
                                    <input type="radio" name="display_color" value="primary" id="edit_color_primary">
                                    <label for="edit_color_primary" class="color-option" style="background-color: #FF9F43;" title="Orange">
                                        <span class="color-label">Orange</span>
                                    </label>
                                    
                                    <input type="radio" name="display_color" value="success" id="edit_color_success">
                                    <label for="edit_color_success" class="color-option" style="background-color: #28C76F;" title="Green">
                                        <span class="color-label">Green</span>
                                    </label>
                                    
                                    <input type="radio" name="display_color" value="danger" id="edit_color_danger">
                                    <label for="edit_color_danger" class="color-option" style="background-color: #FF0000;" title="Red">
                                        <span class="color-label">Red</span>
                                    </label>
                                    
                                    <input type="radio" name="display_color" value="warning" id="edit_color_warning">
                                    <label for="edit_color_warning" class="color-option" style="background-color: #FF9900;" title="Warning">
                                        <span class="color-label">Warning</span>
                                    </label>
                                    
                                    <input type="radio" name="display_color" value="info" id="edit_color_info">
                                    <label for="edit_color_info" class="color-option" style="background-color: #17a2b8;" title="Info Blue">
                                        <span class="color-label">Info</span>
                                    </label>
                                    
                                    <input type="radio" name="display_color" value="purple" id="edit_color_purple">
                                    <label for="edit_color_purple" class="color-option" style="background-color: #7367F0;" title="Purple">
                                        <span class="color-label">Purple</span>
                                    </label>
                                    
                                    <input type="radio" name="display_color" value="teal" id="edit_color_teal">
                                    <label for="edit_color_teal" class="color-option" style="background-color: #02a8b5;" title="Teal">
                                        <span class="color-label">Teal</span>
                                    </label>
                                    
                                    <input type="radio" name="display_color" value="pink" id="edit_color_pink">
                                    <label for="edit_color_pink" class="color-option" style="background-color: #ff63a5;" title="Pink">
                                        <span class="color-label">Pink</span>
                                    </label>
                                    
                                    <input type="radio" name="display_color" value="yellow" id="edit_color_yellow">
                                    <label for="edit_color_yellow" class="color-option" style="background-color: #ffff00; color: #333;" title="Yellow">
                                        <span class="color-label">Yellow</span>
                                    </label>
                                </div>
                                <small class="text-muted">Select a color to highlight this item in POS screen for easy identification</small>
                            </div>
                            <div class="col-md-12">
                                <label>Unit of Measurement (UOM) <span class="text-danger">*</span></label>
                                <select name="uom_id" id="edit_uom_id" class="form-control" required>
                                    <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']) ?> (<?= htmlspecialchars($uom['symbol']) ?>)</option>
                                        <?php endforeach; ?>
                                    </optgroup>
                                    <?php endforeach; ?>
                                </select>
                                <small class="text-muted">Choose the unit for this item (e.g. Piece, Kilogram, Liter).</small>
                            </div>
                            <div class="col-md-12">
                                <label>Supplier <small class="text-muted">(Optional)</small></label>
                                <select name="supplier_id" id="edit_supplier_id" class="form-control">
                                    <option value="">Select Supplier (Optional)</option>
                                    <?php 
                                    if ($suppliers && $suppliers->num_rows > 0):
                                        $suppliers->data_seek(0);
                                        while ($supplier = $suppliers->fetch_assoc()): 
                                    ?>
                                        <option value="<?= $supplier['id'] ?>"><?= htmlspecialchars($supplier['name']) ?></option>
                                    <?php 
                                        endwhile;
                                    endif; 
                                    ?>
                                </select>
                                <small class="text-muted">Select the primary supplier for this item (optional).</small>
                            </div>
                            <div class="col-12">
                                <div id="edit_bulkFields" class="row g-3" style="display:none;">
                                    <div class="col-md-4">
                                        <label>Bulk Qty</label>
                                        <input name="bulk_qty" id="edit_bulk_qty" class="form-control" type="number">
                                        <small class="text-muted">Number of loose units inside one pack (e.g. 1 pack holds 10 bottles).</small>
                                    </div>
                                    <div class="col-md-4">
                                        <label>Bulk Price</label>
                                        <input name="bulk_price" id="edit_bulk_price" class="form-control" type="number" step="0.01">
                                        <small class="text-muted">Selling price you charge when the customer buys the pack/carton.</small>
                                    </div>
                                    <div class="col-md-4">
                                        <label>Pkg Qty</label>
                                        <input name="pkg_qty" id="edit_pkg_qty" class="form-control" type="number">
                                        <small class="text-muted">How many packs count as one bulk unit (typically 1). Bulk Qty shows the loose pieces in that pack.</small>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Cancel</button>
                <button class="btn btn-primary" type="submit">Update Item</button>
            </div>
        </form>
    </div>
</div>


<!-- 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);
        });
    });

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

    $('#editItemModal').on('hidden.bs.modal', function () {
        $('#edit_sub_category_id').html('<option value="">Select Sub Category</option>');
    });

    $('#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();
        // Set default cost price and wholesale price after form reset
        $('[name="cost_price"]').val('0.00');
        $('[name="wholesale_price"]').val('0.00');
        $('#bulkFields').hide();
        $('#is_serialized').prop('checked', false);
        $('#is_third_schedule').prop('checked', false);
        $('#supplier_id').val('');
        
        // Ensure cost price and wholesale price are set to 0.00 with a small delay to override any form reset issues
        setTimeout(function() {
            $('[name="cost_price"]').val('0.00');
            $('[name="wholesale_price"]').val('0.00');
        }, 100);
    });

    // AJAX form submission for Add Item
    $('#itemForm').on('submit', function(e) {
        e.preventDefault();
        
        var costPrice = $('[name="cost_price"]').val();
        if (!costPrice || costPrice === '' || parseFloat(costPrice) < 0) {
            $('[name="cost_price"]').val('0.00');
        }
        
        var formData = new FormData(this);
        var submitBtn = $(this).find('button[type="submit"]');
        var originalText = submitBtn.html();
        
        // Disable submit button and show loading
        submitBtn.prop('disabled', true).html('<i class="fa fa-spinner fa-spin"></i> Saving...');
        
        $.ajax({
            url: 'add_item.php',
            type: 'POST',
            data: formData,
            processData: false,
            contentType: false,
            dataType: 'json',
            success: function(response) {
                if (response.success) {
                    Swal.fire({
                        icon: 'success',
                        title: 'Item Added Successfully!',
                        text: response.message || 'The item has been saved.',
                        timer: 2000,
                        showConfirmButton: false
                    });
                    
                    // Reset form and close modal
                    $('#itemForm')[0].reset();
                    $('#addItemModal').modal('hide');
                    
                    // Refresh DataTable
                    if (window.itemTable) {
                        window.itemTable.ajax.reload(null, false);
                    }
                } else {
                    Swal.fire({
                        icon: 'error',
                        title: 'Error',
                        text: response.error || 'Failed to add item. Please try again.'
                    });
                }
            },
            error: function(xhr, status, error) {
                Swal.fire({
                    icon: 'error',
                    title: 'Error',
                    text: 'An error occurred while adding the item. Please try again.'
                });
            },
            complete: function() {
                // Re-enable submit button
                submitBtn.prop('disabled', false).html(originalText);
            }
        });
    });
    
    // AJAX form submission for Edit Item
    $('#editItemForm').on('submit', function(e) {
        e.preventDefault();
        
        var formData = new FormData(this);
        var submitBtn = $(this).find('button[type="submit"]');
        var originalText = submitBtn.html();
        
        // Disable submit button and show loading
        submitBtn.prop('disabled', true).html('<i class="fa fa-spinner fa-spin"></i> Updating...');
        
        $.ajax({
            url: 'update_item.php',
            type: 'POST',
            data: formData,
            processData: false,
            contentType: false,
            dataType: 'json',
            success: function(response) {
                if (response.success) {
                    Swal.fire({
                        icon: 'success',
                        title: 'Item Updated Successfully!',
                        text: response.message || 'The item has been updated.',
                        timer: 2000,
                        showConfirmButton: false
                    });
                    
                    // Close modal
                    $('#editItemModal').modal('hide');
                    
                    // Refresh DataTable
                    if (window.itemTable) {
                        window.itemTable.ajax.reload(null, false);
                    }
                } else {
                    Swal.fire({
                        icon: 'error',
                        title: 'Update Failed',
                        text: response.error || 'An error occurred. Please try again.'
                    });
                }
            },
            error: function(xhr, status, error) {
                Swal.fire({
                    icon: 'error',
                    title: 'Error',
                    text: 'An error occurred while updating the item. Please try again.'
                });
            },
            complete: function() {
                // Re-enable submit button
                submitBtn.prop('disabled', false).html(originalText);
            }
        });
    });

    // Prevent Enter key from submitting the form in Add Item modal
    $('#addItemModal').on('keydown', function (e) {
        if (e.keyCode === 13) { // Enter key
            e.preventDefault();
            return false;
        }
    });

    // Initialize server-side DataTable for item list
    if ($('#itemTable').length > 0) {
        // Store filter state
        window.itemFilters = {
            roles: [],
            categories: [],
            serial: [],
            third_schedule: []
        };

        // Keep a single selected item across redraw/page changes.
        let selectedItemId = null;
        let selectedItemsMeta = {};

        function updateSelectedStateUI() {
            $('#selectedItemsCount').text(selectedItemId ? '1' : '0');
        }

        function syncSelectionOnCurrentPage() {
            $('#itemTable tbody tr').each(function () {
                const $row = $(this);
                const rowData = itemTable.row(this).data();
                const id = rowData ? parseInt(rowData[0], 10) : null;
                if (!id) return;
                $row.toggleClass('table-active', selectedItemId === id);
            });
        }

        function buildSelectedMeta() {
            selectedItemsMeta = {};
            itemTable.rows().every(function () {
                const rowData = this.data();
                const id = parseInt(rowData[0], 10);
                if (!id || selectedItemId !== id) return;

                selectedItemsMeta[id] = {
                    id: id,
                    itemCode: $('<div>').html(rowData[1]).text().trim(),
                    name: $('<div>').html(rowData[4]).text().trim(),
                    roleText: $('<div>').html(rowData[3]).text().trim().toLowerCase()
                };
            });
        }

        function getSelectedId() {
            return selectedItemId;
        }

        function requireSingleSelection(actionLabel) {
            const id = getSelectedId();
            if (!id) {
                Swal.fire({
                    icon: 'warning',
                    title: 'Invalid Selection',
                    text: 'Please select one item for ' + actionLabel + '.'
                });
                return null;
            }
            return id;
        }
        
        function getEffectiveTableWidth() {
            // Use the real table container width (more accurate than window width on collapsed sidebars/layouts).
            const wrapperWidth = $('#itemTable').closest('.table-responsive').innerWidth();
            return wrapperWidth || window.innerWidth || 1366;
        }

        function applyResponsiveColumnVisibility() {
            const width = getEffectiveTableWidth();
            const profileXL = width >= 1700;
            const profileLG = width >= 1360;
            const profileMD = width >= 1080;
            const profileSM = width >= 860;

            // Always keep key business columns visible.
            itemTable.column(0).visible(true); // ID
            itemTable.column(1).visible(true); // Item Code
            itemTable.column(3).visible(true); // Item Role
            itemTable.column(4).visible(true); // Name
            itemTable.column(7).visible(true); // Retail Price

            // Progressive disclosure for smaller screens.
            itemTable.column(2).visible(profileMD); // SKU
            itemTable.column(5).visible(profileSM); // Category
            itemTable.column(6).visible(profileLG); // Sub-Category
            itemTable.column(8).visible(profileXL); // Cost Price
            itemTable.column(9).visible(profileSM); // Tax Type
            itemTable.column(10).visible(profileMD); // Tax Rate
        }

        var itemTable = $('#itemTable').DataTable({
            "processing": true,
            "serverSide": true,
            "responsive": true,
            "autoWidth": false,
            "scrollX": true,
            "ajax": {
                "url": "ajax/get_items_datatable.php",
                "type": "GET",
                "data": function(d) {
                    // Add custom filter parameters (with safety checks)
                    d.filter_roles = (window.itemFilters.roles || []).join(',');
                    d.filter_categories = (window.itemFilters.categories || []).join(',');
                    d.filter_serial = (window.itemFilters.serial || []).join(',');
                    d.filter_third_schedule = (window.itemFilters.third_schedule || []).join(',');
                },
                "error": function(xhr, error, code) {
                    console.error("DataTable error:", error, code);
                    Swal.fire({
                        icon: 'error',
                        title: 'Error Loading Items',
                        text: 'Failed to load items. Please refresh the page.',
                        timer: 3000
                    });
                }
            },
            "pageLength": 10,
            "lengthMenu": [[10, 25, 50, 100, 200], [10, 25, 50, 100, 200]],
            "order": [[0, "desc"]],
            "columns": [
                { "data": 0 },  // ID
                { "data": 1 },  // Item Code
                { "data": 2 },  // SKU
                { "data": 3, "orderable": false },  // Item Role
                { "data": 4 },  // Name
                { "data": 5 },  // Category
                { "data": 6 },  // Sub-Category
                { "data": 7 },  // Retail Price
                { "data": 8 },  // Cost Price
                { "data": 9 }, // Tax Type
                { "data": 10 } // Tax Rate
            ],
            "language": {
                "processing": "<i class='fa fa-spinner fa-spin'></i> Loading items...",
                "search": "Search items:",
                "searchPlaceholder": "Search by Item Code, Name, SKU, Category...",
                "lengthMenu": "Show _MENU_ items per page",
                "info": "Showing _START_ to _END_ of _TOTAL_ items",
                "infoEmpty": "Showing 0 to 0 of 0 items",
                "infoFiltered": "(filtered from _MAX_ total items)",
                "emptyTable": "No items found",
                "zeroRecords": "No matching items found"
            },
            "drawCallback": function(settings) {
                // Re-initialize tooltips only inside the items DataTable after redraw.
                // This avoids repeatedly initializing tooltips on the whole page.
                $('#itemTable [data-bs-toggle="tooltip"]').each(function () {
                    // Guard against repeated initialization on the same element.
                    if (this._tooltipInitialized) return;
                    $(this).tooltip();
                    this._tooltipInitialized = true;
                });
                applyResponsiveColumnVisibility();
                itemTable.columns.adjust();
                syncSelectionOnCurrentPage();
                buildSelectedMeta();
                updateSelectedStateUI();
            }
        });

        applyResponsiveColumnVisibility();

        // Filter functionality (server-side filtering)
        function applyFilters() {
            // Get selected filter values
            var roleValues = $('.filter-role:checked').map(function () { return this.value; }).get();
            var categoryValues = $('.filter-category:checked').map(function () { return this.value; }).get();
            var serialValues = $('.filter-serial:checked').map(function () { return this.value; }).get();
            var thirdScheduleValues = $('.filter-third-schedule:checked').map(function () { return this.value; }).get();

            // Update global filter state
            window.itemFilters.roles = roleValues;
            window.itemFilters.categories = categoryValues;
            window.itemFilters.serial = serialValues;
            window.itemFilters.third_schedule = thirdScheduleValues;

            // Reload DataTable with new filters (this will trigger ajax.data callback)
            itemTable.ajax.reload();
        }

        $('#applyFiltersBtn').on('click', function () {
            applyFilters();
            $('#filterItemsModal').modal('hide');
        });

        $('#resetFiltersBtn').on('click', function () {
            $('.filter-role, .filter-category, .filter-serial, .filter-third-schedule').prop('checked', false);
            window.itemFilters.roles = [];
            window.itemFilters.categories = [];
            window.itemFilters.serial = [];
            window.itemFilters.third_schedule = [];
            itemTable.ajax.reload();
        });

        $('#selectAllCategories').on('click', function (e) {
            e.preventDefault();
            $('.filter-category').prop('checked', true);
        });

        $('#clearCategorySelection').on('click', function (e) {
            e.preventDefault();
            $('.filter-category').prop('checked', false);
        });

        // Row click keeps strict single selection (0 or 1).
        $('#itemTable tbody').on('click', 'tr', function (e) {
            if ($(e.target).is('input, button, a, label, i') || $(e.target).closest('a, button').length) {
                return;
            }
            // Second click of a double-click has detail === 2; skip toggle so selection stays and dblclick can open edit.
            if (e.detail === 2) {
                return;
            }
            const rowData = itemTable.row(this).data();
            const id = rowData ? parseInt(rowData[0], 10) : null;
            if (!id) return;
            selectedItemId = (selectedItemId === id) ? null : id;
            syncSelectionOnCurrentPage();
            buildSelectedMeta();
            updateSelectedStateUI();
        });

        $('#itemTable tbody').on('dblclick', 'tr', function (e) {
            if ($(e.target).is('input, button, a, label, i') || $(e.target).closest('a, button').length) {
                return;
            }
            const rowData = itemTable.row(this).data();
            const id = rowData ? parseInt(rowData[0], 10) : null;
            if (!id) return;
            selectedItemId = id;
            syncSelectionOnCurrentPage();
            buildSelectedMeta();
            updateSelectedStateUI();
            openEditItemModal(id);
        });

        $('#actionEditSelected').on('click', function (e) {
            e.preventDefault();
            const selectedId = requireSingleSelection('editing');
            if (!selectedId) return;
            openEditItemModal(selectedId);
        });

        $('#actionPrintSelected').on('click', function (e) {
            e.preventDefault();
            const selectedId = requireSingleSelection('barcode printing');
            if (!selectedId) return;
            buildSelectedMeta();
            const meta = selectedItemsMeta[selectedId];
            if (!meta || !meta.itemCode) {
                Swal.fire({ icon: 'error', title: 'Selection Error', text: 'Unable to resolve selected item code. Please reselect item.' });
                return;
            }
            setPrintItemCode(meta.itemCode);
            $('#printModal').modal('show');
        });

        function renderBarcodeList(rows) {
            const $tbody = $('#barcodeListBody');
            $tbody.empty();

            if (!Array.isArray(rows) || rows.length === 0) {
                $tbody.html('<tr><td colspan="3" class="text-center text-muted py-3">No alternate barcodes added.</td></tr>');
                return;
            }

            rows.forEach(function (row) {
                const label = row.barcode_label ? $('<div>').text(row.barcode_label).html() : '<span class="text-muted">-</span>';
                const barcode = $('<div>').text(row.barcode).html();
                $tbody.append(
                    '<tr>' +
                    '<td><strong>' + barcode + '</strong></td>' +
                    '<td>' + label + '</td>' +
                    '<td class="text-end">' +
                    '<button type="button" class="btn btn-sm btn-outline-danger delete-alt-barcode-btn" data-barcode-id="' + row.id + '">' +
                    '<i class="fa fa-trash"></i>' +
                    '</button>' +
                    '</td>' +
                    '</tr>'
                );
            });
        }

        function loadItemBarcodes(itemId) {
            return fetch('ajax/get_item_barcodes.php?item_id=' + encodeURIComponent(itemId), { credentials: 'same-origin' })
                .then(function (res) { return res.json(); })
                .then(function (data) {
                    if (!data.success) {
                        throw new Error(data.message || 'Failed to load barcodes');
                    }
                    renderBarcodeList(data.barcodes || []);
                });
        }

        $('#actionManageBarcodes').on('click', function (e) {
            e.preventDefault();
            const selectedId = requireSingleSelection('barcode management');
            if (!selectedId) return;
            buildSelectedMeta();
            const meta = selectedItemsMeta[selectedId];
            if (!meta) {
                Swal.fire({ icon: 'error', title: 'Selection Error', text: 'Unable to resolve selected item.' });
                return;
            }

            $('#barcodeModalItemId').val(meta.id);
            $('#barcodeModalItemName').text(meta.name || ('Item #' + meta.id));
            $('#newBarcodeValue').val('');
            $('#newBarcodeLabel').val('');
            $('#barcodeListBody').html('<tr><td colspan="3" class="text-center text-muted py-3">Loading...</td></tr>');
            $('#manageBarcodesModal').modal('show');

            loadItemBarcodes(meta.id).catch(function (err) {
                $('#barcodeListBody').html('<tr><td colspan="3" class="text-center text-danger py-3">Unable to load barcodes.</td></tr>');
                Swal.fire({ icon: 'error', title: 'Load Failed', text: err.message || 'Failed to load item barcodes.' });
            });
        });

        $('#saveBarcodeBtn').on('click', function () {
            const itemId = $('#barcodeModalItemId').val();
            const barcode = ($('#newBarcodeValue').val() || '').trim();
            const barcodeLabel = ($('#newBarcodeLabel').val() || '').trim();

            if (!itemId) {
                Swal.fire({ icon: 'warning', title: 'No Item', text: 'Please select an item first.' });
                return;
            }
            if (barcode.length < 3) {
                Swal.fire({ icon: 'warning', title: 'Invalid Barcode', text: 'Barcode must be at least 3 characters.' });
                return;
            }

            fetch('ajax/save_item_barcode.php', {
                method: 'POST',
                credentials: 'same-origin',
                headers: { 'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8' },
                body: new URLSearchParams({
                    item_id: itemId,
                    barcode: barcode,
                    barcode_label: barcodeLabel
                }).toString()
            })
            .then(function (res) { return res.json(); })
            .then(function (data) {
                if (!data.success) {
                    throw new Error(data.message || 'Failed to add barcode.');
                }
                $('#newBarcodeValue').val('').focus();
                $('#newBarcodeLabel').val('');
                return loadItemBarcodes(itemId);
            })
            .catch(function (err) {
                Swal.fire({ icon: 'error', title: 'Save Failed', text: err.message || 'Unable to save barcode.' });
            });
        });

        $('#barcodeListBody').on('click', '.delete-alt-barcode-btn', function () {
            const barcodeId = $(this).data('barcode-id');
            const itemId = $('#barcodeModalItemId').val();
            if (!barcodeId || !itemId) return;

            Swal.fire({
                title: 'Delete Barcode?',
                text: 'This barcode will stop working for scan lookup.',
                icon: 'warning',
                showCancelButton: true,
                confirmButtonColor: '#d33',
                confirmButtonText: 'Yes, Delete',
                cancelButtonText: 'Cancel'
            }).then(function (result) {
                if (!result.isConfirmed) return;
                fetch('ajax/delete_item_barcode.php', {
                    method: 'POST',
                    credentials: 'same-origin',
                    headers: { 'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8' },
                    body: new URLSearchParams({ id: String(barcodeId) }).toString()
                })
                .then(function (res) { return res.json(); })
                .then(function (data) {
                    if (!data.success) {
                        throw new Error(data.message || 'Failed to delete barcode.');
                    }
                    return loadItemBarcodes(itemId);
                })
                .catch(function (err) {
                    Swal.fire({ icon: 'error', title: 'Delete Failed', text: err.message || 'Unable to delete barcode.' });
                });
            });
        });

        $('#actionBOMSelected').on('click', function (e) {
            e.preventDefault();
            const selectedId = requireSingleSelection('BOM');
            if (!selectedId) return;
            buildSelectedMeta();
            const meta = selectedItemsMeta[selectedId];
            const allowedRoles = ['stock', 'non-stock', 'non_stock'];
            if (!meta || !allowedRoles.some(function (role) { return meta.roleText.indexOf(role) !== -1; })) {
                Swal.fire({
                    icon: 'warning',
                    title: 'BOM Not Available',
                    text: 'BOM is available for Stock and Non-Stock items only.'
                });
                return;
            }
            loadBOM(meta.id, meta.name || ('Item #' + meta.id));
            $('#bomModal').modal('show');
        });

        $('#actionDeleteSelected').on('click', function (e) {
            e.preventDefault();
            const selectedId = requireSingleSelection('deleting');
            if (!selectedId) {
                return;
            }

            Swal.fire({
                title: 'Delete Selected Item?',
                text: 'This action cannot be undone.',
                icon: 'warning',
                showCancelButton: true,
                confirmButtonColor: '#d33',
                confirmButtonText: 'Yes, Delete',
                cancelButtonText: 'Cancel'
            }).then(function (result) {
                if (!result.isConfirmed) return;

                fetch('delete_item.php?id=' + encodeURIComponent(selectedId), {
                    method: 'GET',
                    credentials: 'same-origin',
                    headers: {
                        'X-Requested-With': 'XMLHttpRequest',
                        'Accept': 'application/json'
                    }
                })
                .then(function (res) {
                    return res.text().then(function (text) {
                        try {
                            return JSON.parse(text);
                        } catch (e) {
                            // Fallback for unexpected HTML/PHP warnings in response.
                            return {
                                success: false,
                                message: (text && text.trim().length)
                                    ? text.trim().substring(0, 500)
                                    : 'Delete failed (invalid server response). Check that you have permission and try again.'
                            };
                        }
                    });
                })
                .then(function (data) {
                    if (!data.success) {
                        throw new Error(data.message || 'The item could not be deleted.');
                    }
                    selectedItemId = null;
                    updateSelectedStateUI();
                    itemTable.ajax.reload(null, false);
                    Swal.fire({
                        icon: 'success',
                        title: 'Deleted',
                        text: data.message || 'Selected item deleted successfully.'
                    });
                })
                .catch(function (err) {
                    Swal.fire({
                        icon: 'warning',
                        title: 'Delete Blocked',
                        text: err.message || 'The item could not be deleted.'
                    });
                });
            });
        });

        let resizeDebounceTimer = null;
        $(window).on('resize.itemList', function () {
            clearTimeout(resizeDebounceTimer);
            resizeDebounceTimer = setTimeout(function () {
                applyResponsiveColumnVisibility();
                itemTable.columns.adjust().draw(false);
            }, 120);
        });

        $('#refreshItemsBtn').on('click', function () {
            window.location.reload();
        });

        // Store reference globally for refresh after add/edit
        window.itemTable = itemTable;
    }

    // Ensure cost price field always has proper decimal format
    $('[name="cost_price"]').on('blur', function() {
        var value = parseFloat($(this).val());
        if (isNaN(value) || value < 0) {
            $(this).val('0.00');
        } else {
            $(this).val(value.toFixed(2));
        }
    });

    // Ensure wholesale price field always has proper decimal format
    $('[name="wholesale_price"]').on('blur', function() {
        var value = parseFloat($(this).val());
        if (isNaN(value) || value < 0) {
            $(this).val('0.00');
        } else {
            $(this).val(value.toFixed(2));
        }
    });

    // Same for edit form
    $('#edit_cost_price').on('blur', function() {
        var value = parseFloat($(this).val());
        if (isNaN(value) || value < 0) {
            $(this).val('0.00');
        } else {
            $(this).val(value.toFixed(2));
        }
    });

    // Same for edit form wholesale price
    $('#edit_wholesale_price').on('blur', function() {
        var value = parseFloat($(this).val());
        if (isNaN(value) || value < 0) {
            $(this).val('0.00');
        } else {
            $(this).val(value.toFixed(2));
        }
    });

    // Profit calculation for add item form
    window.calculateProfit = function() {
        var retailPrice = parseFloat($('#retail_price').val()) || 0;
        var costPrice = parseFloat($('#cost_price').val()) || 0;
        
        // Show alert if at least one price is entered
        if (retailPrice > 0 || costPrice > 0) {
            var profitAmount = retailPrice - costPrice;
            var profitPercentage = costPrice > 0 ? (profitAmount / costPrice) * 100 : 0;
            var marginPercentage = retailPrice > 0 ? (profitAmount / retailPrice) * 100 : 0;
            
            $('#profitAmount').text('Rs ' + profitAmount.toFixed(2));
            $('#profitPercentage').text(profitPercentage.toFixed(1) + '%');
            $('#marginPercentage').text(marginPercentage.toFixed(1) + '%');
            
            // Color coding based on profitability
            if (profitAmount > 0) {
                $('#profitAmount, #profitPercentage').removeClass('text-danger').addClass('text-success');
            } else if (profitAmount < 0) {
                $('#profitAmount, #profitPercentage').removeClass('text-success').addClass('text-danger');
            } else {
                $('#profitAmount, #profitPercentage').removeClass('text-success text-danger').addClass('text-muted');
            }
            
            if (marginPercentage > 0) {
                $('#marginPercentage').removeClass('text-danger').addClass('text-primary');
            } else if (marginPercentage < 0) {
                $('#marginPercentage').removeClass('text-primary').addClass('text-danger');
            } else {
                $('#marginPercentage').removeClass('text-primary text-danger').addClass('text-muted');
            }
            
            $('#profitAlert').show();
        } else {
            $('#profitAlert').hide();
        }
    }
    
    // Bind profit calculation to price inputs
    $('#retail_price, #cost_price').on('input blur focus click', window.calculateProfit);
    
    // Profit calculation for edit item form
    window.calculateEditProfit = function() {
        var retailPrice = parseFloat($('#edit_retail_price').val()) || 0;
        var costPrice = parseFloat($('#edit_cost_price').val()) || 0;
        
        // Show alert if at least one price is entered
        if (retailPrice > 0 || costPrice > 0) {
            var profitAmount = retailPrice - costPrice;
            var profitPercentage = costPrice > 0 ? (profitAmount / costPrice) * 100 : 0;
            var marginPercentage = retailPrice > 0 ? (profitAmount / retailPrice) * 100 : 0;
            
            $('#editProfitAmount').text('Rs ' + profitAmount.toFixed(2));
            $('#editProfitPercentage').text(profitPercentage.toFixed(1) + '%');
            $('#editMarginPercentage').text(marginPercentage.toFixed(1) + '%');
            
            // Color coding based on profitability
            if (profitAmount > 0) {
                $('#editProfitAmount, #editProfitPercentage').removeClass('text-danger').addClass('text-success');
            } else if (profitAmount < 0) {
                $('#editProfitAmount, #editProfitPercentage').removeClass('text-success').addClass('text-danger');
            } else {
                $('#editProfitAmount, #editProfitPercentage').removeClass('text-success text-danger').addClass('text-muted');
            }
            
            if (marginPercentage > 0) {
                $('#editMarginPercentage').removeClass('text-danger').addClass('text-primary');
            } else if (marginPercentage < 0) {
                $('#editMarginPercentage').removeClass('text-primary').addClass('text-danger');
            } else {
                $('#editMarginPercentage').removeClass('text-primary text-danger').addClass('text-muted');
            }
            
            $('#editProfitAlert').show();
        } else {
            $('#editProfitAlert').hide();
        }
    }
    
    // Bind profit calculation to edit form price inputs
    $('#edit_retail_price, #edit_cost_price').on('input blur focus click', window.calculateEditProfit);

});

// Move this function to global scope
function openEditItemModal(id) {
    $.get('get_item.php', { id: id }, function(data) {
        let item = JSON.parse(data);
        $('#edit_id').val(item.id);
        $('#edit_item_code').val(item.item_code);
        $('#edit_sku_number').val(item.sku_number);
        $('#edit_item_role').val(item.item_role);
        $('#edit_is_serialized').prop('checked', item.is_serialized == 1);
        $('#edit_is_third_schedule').prop('checked', item.is_third_schedule == 1);
        $('#edit_name').val(item.name);
        $('#edit_category_id').val(item.category_id);
        // Fetch subcategories for the selected category
        $.get('fetch_sub_categories.php?category_id=' + item.category_id, function (subData) {
            $('#edit_sub_category_id').html('<option value="">Select Sub Category</option>' + subData);
            $('#edit_sub_category_id').val(item.sub_category_id);
        });
        $('#edit_retail_price').val(item.retail_price);
        $('#edit_wholesale_price').val(item.wholesale_price || '0.00');
        $('#edit_cost_price').val(item.cost_price);
        // Trigger profit calculation for edit modal immediately
        calculateEditProfit();
        $('#edit_reorder_quantity').val(item.reorder_quantity);
        $('#edit_reorder_level').val(item.reorder_level);
        $('#edit_tax_type').val(item.tax_type);
        $('#edit_tax_rate_id').val(item.tax_rate_id);
        $('#edit_item_type').val(item.item_type);
        if(item.item_type === 'bulk') {
            $('#edit_bulkFields').show();
        } else {
            $('#edit_bulkFields').hide();
        }
        $('#edit_bulk_qty').val(item.bulk_qty);
        $('#edit_bulk_price').val(item.bulk_price);
        $('#edit_pkg_qty').val(item.pkg_qty);
        $('#edit_uom_id').val(item.uom_id);
        $('#edit_supplier_id').val(item.supplier_id || '');
        
        // Set the display color radio button
        if (item.display_color) {
            $('#edit_color_' + item.display_color).prop('checked', true);
        } else {
            $('#edit_color_default').prop('checked', true);
        }
        
        // Note: Product image is not pre-filled for security reasons
        $('#editItemModal').modal('show');
    });
}
$(document).on('change', '#edit_item_type', function() {
    if($(this).val() === 'bulk') {
        $('#edit_bulkFields').show();
    } else {
        $('#edit_bulkFields').hide();
    }
});

// Export items function
function exportItems() {
    // Get current filter values
    var filterParams = {
        report: 'items_list'
    };
    
    // Add filters if they exist
    if (window.itemFilters && window.itemFilters.roles && window.itemFilters.roles.length > 0) {
        filterParams.filter_roles = window.itemFilters.roles.join(',');
    }
    if (window.itemFilters && window.itemFilters.categories && window.itemFilters.categories.length > 0) {
        filterParams.filter_categories = window.itemFilters.categories.join(',');
    }
    if (window.itemFilters && window.itemFilters.serial && window.itemFilters.serial.length > 0) {
        filterParams.filter_serial = window.itemFilters.serial.join(',');
    }
    if (window.itemFilters && window.itemFilters.third_schedule && window.itemFilters.third_schedule.length > 0) {
        filterParams.filter_third_schedule = window.itemFilters.third_schedule.join(',');
    }
    
    // Get search value from DataTable if available
    if (window.itemTable) {
        var searchValue = window.itemTable.search();
        if (searchValue) {
            filterParams.search = searchValue;
        }
    }
    
    // Build URL with parameters
    var queryString = Object.keys(filterParams).map(function(key) {
        return encodeURIComponent(key) + '=' + encodeURIComponent(filterParams[key]);
    }).join('&');
    
    // Open export URL in new window
    window.open('export_excel.php?' + queryString, '_blank');
}

// Clipboard Import Functions
function clearClipboardData() {
    document.getElementById('clipboardData').value = '';
    document.getElementById('importPreview').style.display = 'none';
    document.getElementById('previewPlaceholder').style.display = 'flex';
}

// Initialize clipboard import when modal is shown
$(document).ready(function() {
    // Set initial button visibility (clipboard is default)
    $('#importClipboardBtn').show();
    $('#importCsvBtn').hide();
    
    // Handle tab switching
    $('#importTabs button[data-bs-toggle="tab"]').on('shown.bs.tab', function (e) {
        const target = $(e.target).data('bs-target');
        if (target === '#clipboard-pane') {
            $('#importClipboardBtn').show();
            $('#importCsvBtn').hide();
        } else if (target === '#csv-pane') {
            $('#importClipboardBtn').hide();
            $('#importCsvBtn').show();
        }
    });
    
    // Initialize clipboard preview when modal is shown
    $('#importModal').on('shown.bs.modal', function() {
        const clipboardData = document.getElementById('clipboardData');
        if (clipboardData) {
            // Preview on paste
            clipboardData.addEventListener('paste', function() {
                setTimeout(() => {
                    previewClipboardData();
                }, 100);
            });
            
            // Preview on input
            clipboardData.addEventListener('input', function() {
                previewClipboardData();
            });
        }
    });
});

// Preview clipboard data
function previewClipboardData() {
    const data = document.getElementById('clipboardData').value.trim();
    const previewDiv = document.getElementById('importPreview');
    const previewContent = document.getElementById('previewContent');
    const previewCount = document.getElementById('previewCount');
    const placeholder = document.getElementById('previewPlaceholder');
    
    if (!data) {
        previewDiv.style.display = 'none';
        if (placeholder) placeholder.style.display = 'flex';
        return;
    }
    
    const lines = data.split('\n').filter(line => line.trim());
    if (lines.length === 0) {
        previewDiv.style.display = 'none';
        if (placeholder) placeholder.style.display = 'flex';
        return;
    }
    
    // Parse first line to detect delimiter (tab or comma)
    const firstLine = lines[0];
    const hasTabs = firstLine.includes('\t');
    const delimiter = hasTabs ? '\t' : ',';
    
    // Expected columns (17 total)
    const expectedColumns = [
        'Item Code', 'SKU Number', 'Name', 'Category Name', 'Sub Category Name',
        'Retail Price', 'Cost Price', 'Reorder Quantity', 'Reorder Level',
        'Tax Type', 'Tax Rate Name', 'Item Type', 'Bulk Quantity',
        'Bulk Price', 'Package Quantity', 'UOM Name', '3rd Schedule'
    ];
    
    let validRows = 0;
    let previewHtml = '<table class="table table-sm table-bordered table-hover mb-0" style="font-size: 11px;">';
    previewHtml += '<thead class="table-light"><tr>';
    expectedColumns.forEach(col => {
        previewHtml += `<th>${col}</th>`;
    });
    previewHtml += '</tr></thead><tbody>';
    
    lines.forEach((line, index) => {
        const columns = line.split(delimiter).map(col => col.trim());
        
        // Skip header row if it looks like headers
        if (index === 0) {
            const firstCol = columns[0]?.toLowerCase() || '';
            if (firstCol.includes('item code') || firstCol.includes('code*') || firstCol.includes('sku')) {
                return; // Skip header row
            }
        }
        
        // Check if we have minimum required columns (at least 8 for required fields)
        if (columns.length >= 8) {
            const itemCode = columns[0] || '';
            const skuNumber = columns[1] || '';
            const name = columns[2] || '';
            const categoryName = columns[3] || '';
            
            if (itemCode || skuNumber || name) {
                const rowClass = (itemCode && skuNumber && name && categoryName) ? '' : 'table-warning';
                previewHtml += `<tr class="${rowClass}">`;
                
                // Display all columns
                for (let i = 0; i < expectedColumns.length; i++) {
                    const value = columns[i] || '';
                    previewHtml += `<td>${value || '<span class="text-muted">-</span>'}</td>`;
                }
                
                previewHtml += '</tr>';
                validRows++;
            }
        }
    });
    
    previewHtml += '</tbody></table>';
    previewContent.innerHTML = previewHtml;
    previewCount.textContent = `${validRows} row${validRows !== 1 ? 's' : ''}`;
    previewDiv.style.display = 'block';
    
    if (placeholder) placeholder.style.display = 'none';
}

// Import from clipboard
function importFromClipboard() {
    const data = document.getElementById('clipboardData').value.trim();
    
    if (!data) {
        Swal.fire({
            title: 'No Data',
            text: 'Please paste data into the textarea first.',
            icon: 'warning',
            confirmButtonText: 'OK'
        });
        return;
    }
    
    const lines = data.split('\n').filter(line => line.trim());
    if (lines.length === 0) {
        Swal.fire({
            title: 'Invalid Data',
            text: 'No valid data found. Please check your format.',
            icon: 'error',
            confirmButtonText: 'OK'
        });
        return;
    }
    
    // Show loading
    Swal.fire({
        title: 'Importing...',
        text: 'Please wait while we process your data.',
        allowOutsideClick: false,
        didOpen: () => {
            Swal.showLoading();
        }
    });
    
    // Send data to server
    $.ajax({
        url: 'import_items.php',
        type: 'POST',
        data: {
            import_type: 'clipboard',
            clipboard_data: data
        },
        success: function(response) {
            Swal.close();
            
            // Use response as-is if already parsed by jQuery (object), else parse JSON string
            try {
                const result = (typeof response === 'string') ? JSON.parse(response) : response;
                if (result.success) {
                    let message = result.message || `Successfully imported ${result.imported || 0} item(s).`;
                    
                    // Show errors if any
                    if (result.errors && result.errors.length > 0) {
                        let errorList = '<ul class="text-start mt-2 mb-0" style="max-height: 300px; overflow-y: auto; padding-left: 20px;">';
                        const errorsToShow = result.errors.slice(0, 30); // Show up to 30 errors
                        errorsToShow.forEach(error => {
                            errorList += `<li class="small mb-1">${error}</li>`;
                        });
                        if (result.errors.length > 30) {
                            errorList += `<li class="small text-muted mt-2"><em>... and ${result.errors.length - 30} more errors. Please check the full error list after page reload.</em></li>`;
                        }
                        errorList += '</ul>';
                        message += '<div class="mt-3"><strong>Errors (' + result.errors_count + ' row(s) had issues):</strong>' + errorList + '</div>';
                    }
                    
                    Swal.fire({
                        icon: result.errors_count > 0 ? 'warning' : 'success',
                        title: result.errors_count > 0 ? 'Import Partially Completed' : 'Import Successful',
                        html: message,
                        confirmButtonText: 'OK',
                        width: '700px',
                        customClass: {
                            popup: 'text-start'
                        }
                    }).then(() => {
                        location.reload();
                    });
                } else {
                    let errorMessage = result.message || 'An error occurred during import.';
                    if (result.errors && result.errors.length > 0) {
                        let errorList = '<ul class="text-start mt-2 mb-0" style="max-height: 400px; overflow-y: auto; padding-left: 20px;">';
                        const errorsToShow = result.errors.slice(0, 30); // Show up to 30 errors
                        errorsToShow.forEach(error => {
                            errorList += `<li class="small mb-1">${error}</li>`;
                        });
                        if (result.errors.length > 30) {
                            errorList += `<li class="small text-muted mt-2"><em>... and ${result.errors.length - 30} more errors. Please check the full error list after page reload.</em></li>`;
                        }
                        errorList += '</ul>';
                        errorMessage += '<div class="mt-3"><strong>Errors (' + result.errors_count + ' row(s) had issues):</strong>' + errorList + '</div>';
                    }
                    
                    Swal.fire({
                        icon: 'error',
                        title: 'Import Failed',
                        html: errorMessage,
                        confirmButtonText: 'OK',
                        width: '700px',
                        customClass: {
                            popup: 'text-start'
                        }
                    });
                }
            } catch (e) {
                // If response is not JSON, show error
                Swal.fire({
                    icon: 'error',
                    title: 'Import Error',
                    text: 'Invalid response from server. Please try again.',
                    confirmButtonText: 'OK'
                });
                console.error('Parse error:', e, 'Response:', response);
            }
        },
        error: function(xhr, status, error) {
            Swal.close();
            Swal.fire({
                icon: 'error',
                title: 'Import Error',
                text: 'An error occurred: ' + error,
                confirmButtonText: 'OK'
            });
        }
    });
}

// Update Prices from Excel Functions
let pricesData = []; // Store loaded price data

// Handle checkbox changes to show/hide columns
$(document).ready(function() {
    $(document).on('change', '#chkRetailPrice', function() {
        $('.retail-col').toggle(this.checked);
    });
    
    $(document).on('change', '#chkWholesalePrice', function() {
        $('.wholesale-col').toggle(this.checked);
        displayPricesTable(); // Refresh table to update column visibility
    });
    
    $(document).on('change', '#chkItemCost', function() {
        $('.cost-col').toggle(this.checked);
        displayPricesTable(); // Refresh table to update column visibility
    });
    
    // Initialize column visibility based on checkboxes
    $('.wholesale-col').toggle($('#chkWholesalePrice').is(':checked'));
    $('.cost-col').toggle($('#chkItemCost').is(':checked'));
    
    // Initialize clipboard paste for prices when modal is shown
    $('#updatePricesModal').on('shown.bs.modal', function() {
        const pricesClipboardData = document.getElementById('pricesClipboardData');
        if (pricesClipboardData) {
            // Preview on paste
            pricesClipboardData.addEventListener('paste', function() {
                setTimeout(() => {
                    parsePricesDataFromClipboard();
                }, 100);
            });
            
            // Preview on input
            pricesClipboardData.addEventListener('input', function() {
                parsePricesDataFromClipboard();
            });
            
            // Focus on textarea
            setTimeout(() => {
                pricesClipboardData.focus();
            }, 100);
        }
    });
    
    // Reset modal when closed
    $('#updatePricesModal').on('hidden.bs.modal', function() {
        pricesData = [];
        $('#pricesClipboardData').val('');
        $('#pricesTableBody').html('<tr><td colspan="6" class="text-center text-muted py-5"><i class="fa fa-inbox fa-3x mb-3"></i><p class="mb-0">No records found</p><small>Paste Excel data in the textarea</small></td></tr>');
        $('#pricesStatus').text('No records found');
        $('#updatePricesBtn').prop('disabled', true);
        $('#chkRetailPrice').prop('checked', true);
        $('#chkWholesalePrice').prop('checked', false);
        $('#chkItemCost').prop('checked', false);
        $('.wholesale-col, .cost-col').hide();
    });
    
    // Handle row checkbox changes
    $(document).on('change', '.price-row-checkbox', function() {
        const index = $(this).closest('tr').data('index');
        if (pricesData[index]) {
            pricesData[index].selected = this.checked;
        }
        updatePricesStatus();
    });
});

// Clear prices clipboard data
function clearPricesClipboardData() {
    document.getElementById('pricesClipboardData').value = '';
    pricesData = [];
    displayPricesTable();
}

// Parse clipboard data automatically (called on paste/input)
function parsePricesDataFromClipboard() {
    const data = document.getElementById('pricesClipboardData').value.trim();
    if (!data) {
        pricesData = [];
        displayPricesTable();
        return;
    }
    parsePricesData(data);
}

// Parse clipboard data
function parsePricesData(data) {
    const lines = data.split('\n').filter(line => line.trim());
    if (lines.length === 0) {
        Swal.fire({
            icon: 'error',
            title: 'No Data',
            text: 'No valid data found. Please check your format.',
            confirmButtonText: 'OK'
        });
        return;
    }
    
    // Detect delimiter (tab preferred, fallback to comma)
    const firstLine = lines[0];
    const hasTabs = firstLine.includes('\t');
    const delimiter = hasTabs ? '\t' : ',';
    
    // Get which fields are selected
    const retailSelected = $('#chkRetailPrice').is(':checked');
    const wholesaleSelected = $('#chkWholesalePrice').is(':checked');
    const costSelected = $('#chkItemCost').is(':checked');
    
    pricesData = [];
    let headerSkipped = false;
    
    // Helper function to determine column mapping based on selected fields and column count
    function determineColumnMapping(numColumns, retailSel, wholesaleSel, costSel) {
        const mapping = { retail: null, wholesale: null, cost: null };
        let colIndex = 1; // Start after item code (column 0)
        
        // Count how many price fields are selected
        const selectedCount = (retailSel ? 1 : 0) + (wholesaleSel ? 1 : 0) + (costSel ? 1 : 0);
        const dataColumns = numColumns - 1; // Exclude item code column
        
        // If we have exactly the right number of columns for selected fields, map in order
        if (dataColumns === selectedCount && selectedCount > 0) {
            if (retailSel && colIndex < numColumns) {
                mapping.retail = colIndex++;
            }
            if (wholesaleSel && colIndex < numColumns) {
                mapping.wholesale = colIndex++;
            }
            if (costSel && colIndex < numColumns) {
                mapping.cost = colIndex++;
            }
        } else {
            // Default mapping: assume standard order (Retail, Wholesale, Cost)
            // But handle common cases
            if (dataColumns === 3) {
                // 3 columns: assume Retail, Wholesale, Cost (standard)
                mapping.retail = 1;
                mapping.wholesale = 2;
                mapping.cost = 3;
            } else if (dataColumns === 2) {
                // 2 columns: if both retail and cost selected, assume Retail, Cost
                if (retailSel && costSel && !wholesaleSel) {
                    mapping.retail = 1;
                    mapping.cost = 2;
                } else if (retailSel) {
                    // Only retail selected
                    mapping.retail = 1;
                } else if (costSel) {
                    // Only cost selected (unlikely but handle it)
                    mapping.cost = 1;
                } else {
                    // Default: Retail, Wholesale
                    mapping.retail = 1;
                    mapping.wholesale = 2;
                }
            } else if (dataColumns === 1) {
                // 1 column: map to first selected field
                if (retailSel) mapping.retail = 1;
                else if (wholesaleSel) mapping.wholesale = 1;
                else if (costSel) mapping.cost = 1;
            } else {
                // 4+ columns: use standard mapping
                mapping.retail = 1;
                mapping.wholesale = 2;
                mapping.cost = 3;
            }
        }
        
        return mapping;
    }
    
    let columnMapping = null;
    
    lines.forEach((line, index) => {
        const columns = line.split(delimiter).map(col => col.trim());
        
        // Skip header row
        if (index === 0) {
            const firstCol = columns[0]?.toLowerCase() || '';
            if (firstCol.includes('code') || firstCol.includes('item') || firstCol.includes('retail') || firstCol.includes('cost')) {
                headerSkipped = true;
                return;
            }
        }
        
        if (columns.length >= 2) {
            const itemCode = columns[0] || '';
            
            if (!itemCode) {
                return; // Skip rows without item code
            }
            
            // Determine column mapping on first data row
            if (columnMapping === null) {
                columnMapping = determineColumnMapping(columns.length, retailSelected, wholesaleSelected, costSelected);
                console.log('Column mapping determined:', columnMapping, 'for', columns.length, 'columns');
            }
            
            let retailPrice = '';
            let wholesalePrice = '';
            let costPrice = '';
            
            // Map columns based on detected structure
            if (columnMapping.retail !== null && columns[columnMapping.retail]) {
                retailPrice = columns[columnMapping.retail].trim();
            }
            if (columnMapping.wholesale !== null && columns[columnMapping.wholesale]) {
                wholesalePrice = columns[columnMapping.wholesale].trim();
            }
            if (columnMapping.cost !== null && columns[columnMapping.cost]) {
                costPrice = columns[columnMapping.cost].trim();
            }
            
            pricesData.push({
                item_code: itemCode,
                retail_price: retailPrice,
                wholesale_price: wholesalePrice,
                cost_price: costPrice,
                selected: false
            });
        }
    });
    
    if (pricesData.length === 0) {
        Swal.fire({
            icon: 'error',
            title: 'Invalid Data',
            text: 'No valid price data found. Please ensure Item Code is in the first column.',
            confirmButtonText: 'OK'
        });
        return;
    }
    
    // Fetch item names from server
    fetchItemNames();
}

// Fetch item names for display
function fetchItemNames() {
    const itemCodes = pricesData.map(p => p.item_code);
    
    $.ajax({
        url: 'ajax/get_items_by_codes.php',
        type: 'POST',
        data: {
            item_codes: JSON.stringify(itemCodes)
        },
        dataType: 'json',
        success: function(response) {
            if (response.success) {
                const itemMap = {};
                response.items.forEach(item => {
                    itemMap[item.item_code] = item.name;
                });
                
                // Add item names to pricesData
                pricesData.forEach(price => {
                    price.item_name = itemMap[price.item_code] || 'Not Found';
                });
                
                displayPricesTable();
            } else {
                Swal.fire({
                    icon: 'error',
                    title: 'Error',
                    text: response.message || 'Failed to fetch item information.',
                    confirmButtonText: 'OK'
                });
            }
        },
        error: function() {
            // If endpoint doesn't exist, proceed without names
            pricesData.forEach(price => {
                price.item_name = 'Loading...';
            });
            displayPricesTable();
        }
    });
}

// Display prices in table
function displayPricesTable() {
    const tbody = $('#pricesTableBody');
    tbody.empty();
    
    if (pricesData.length === 0) {
        tbody.html('<tr><td colspan="6" class="text-center text-muted py-5"><i class="fa fa-inbox fa-3x mb-3"></i><p class="mb-0">No records found</p></td></tr>');
        $('#pricesStatus').text('No records found');
        $('#updatePricesBtn').prop('disabled', true);
        return;
    }
    
    pricesData.forEach((price, index) => {
        const retailDisplay = price.retail_price ? parseFloat(price.retail_price).toFixed(2) : '-';
        const wholesaleDisplay = price.wholesale_price ? parseFloat(price.wholesale_price).toFixed(2) : '-';
        const costDisplay = price.cost_price ? parseFloat(price.cost_price).toFixed(2) : '-';
        
        const row = $(`
            <tr data-index="${index}">
                <td>
                    <input type="checkbox" class="price-row-checkbox" ${price.selected ? 'checked' : ''}>
                </td>
                <td><strong>${price.item_code}</strong></td>
                <td>${price.item_name || 'Not Found'}</td>
                <td class="retail-col">${retailDisplay}</td>
                <td class="wholesale-col" style="display: ${$('#chkWholesalePrice').is(':checked') ? 'table-cell' : 'none'};">${wholesaleDisplay}</td>
                <td class="cost-col" style="display: ${$('#chkItemCost').is(':checked') ? 'table-cell' : 'none'};">${costDisplay}</td>
            </tr>
        `);
        tbody.append(row);
    });
    
    $('#pricesStatus').text(`${pricesData.length} record(s) loaded`);
    $('#updatePricesBtn').prop('disabled', false);
}

// Toggle select all
function toggleAllPrices(checkbox) {
    $('.price-row-checkbox').prop('checked', checkbox.checked);
    pricesData.forEach(price => {
        price.selected = checkbox.checked;
    });
    updatePricesStatus();
}

// Update status
function updatePricesStatus() {
    const selectedCount = $('.price-row-checkbox:checked').length;
    
    if (selectedCount > 0) {
        $('#pricesStatus').text(`${selectedCount} record(s) selected`);
    } else {
        $('#pricesStatus').text(`${pricesData.length} record(s) loaded`);
    }
}

// Copy selected prices
function copySelectedPrices() {
    const selected = pricesData.filter(p => p.selected);
    if (selected.length === 0) {
        Swal.fire({
            icon: 'warning',
            title: 'No Selection',
            text: 'Please select at least one row to copy.',
            confirmButtonText: 'OK'
        });
        return;
    }
    
    // Create CSV-like text
    let text = 'Item Code\tItem Name\tRetail Price\tWholesale Price\tCost Price\n';
    selected.forEach(price => {
        text += `${price.item_code}\t${price.item_name || ''}\t${price.retail_price || ''}\t${price.wholesale_price || ''}\t${price.cost_price || ''}\n`;
    });
    
    // Copy to clipboard
    navigator.clipboard.writeText(text).then(() => {
        Swal.fire({
            icon: 'success',
            title: 'Copied!',
            text: `${selected.length} record(s) copied to clipboard.`,
            timer: 1500,
            showConfirmButton: false
        });
    }).catch(() => {
        Swal.fire({
            icon: 'error',
            title: 'Copy Failed',
            text: 'Failed to copy to clipboard. Please try again.',
            confirmButtonText: 'OK'
        });
    });
}

// Remove selected prices
function removeSelectedPrices() {
    const selected = pricesData.filter(p => p.selected);
    if (selected.length === 0) {
        Swal.fire({
            icon: 'warning',
            title: 'No Selection',
            text: 'Please select at least one row to remove.',
            confirmButtonText: 'OK'
        });
        return;
    }
    
    Swal.fire({
        title: 'Remove Selected?',
        text: `Are you sure you want to remove ${selected.length} record(s)?`,
        icon: 'warning',
        showCancelButton: true,
        confirmButtonText: 'Yes, Remove',
        cancelButtonText: 'Cancel'
    }).then((result) => {
        if (result.isConfirmed) {
            pricesData = pricesData.filter(p => !p.selected);
            displayPricesTable();
            Swal.fire({
                icon: 'success',
                title: 'Removed',
                text: 'Selected records have been removed.',
                timer: 1500,
                showConfirmButton: false
            });
        }
    });
}

// Update prices
function updatePrices() {
    if (pricesData.length === 0) {
        Swal.fire({
            icon: 'warning',
            title: 'No Data',
            text: 'Please load data first.',
            confirmButtonText: 'OK'
        });
        return;
    }
    
    // Get selected fields
    const chkItemCostChecked = $('#chkItemCost').is(':checked');
    const fieldsToUpdate = {
        item_code: true, // Always required
        retail_price: $('#chkRetailPrice').is(':checked'),
        wholesale_price: $('#chkWholesalePrice').is(':checked'),
        cost_price: chkItemCostChecked
    };
    
    // Debug log
    console.log('Item Cost checkbox checked:', chkItemCostChecked);
    console.log('Fields to update:', fieldsToUpdate);
    
    // Check if at least one price field is selected
    if (!fieldsToUpdate.retail_price && !fieldsToUpdate.wholesale_price && 
        !fieldsToUpdate.cost_price) {
        Swal.fire({
            icon: 'warning',
            title: 'No Fields Selected',
            text: 'Please select at least one price field to update.',
            confirmButtonText: 'OK'
        });
        return;
    }
    
    Swal.fire({
        title: 'Updating Prices...',
        text: 'Please wait while we update the prices.',
        allowOutsideClick: false,
        didOpen: () => {
            Swal.showLoading();
        }
    });
    
    $.ajax({
        url: 'update_prices.php',
        type: 'POST',
        data: {
            prices_data: JSON.stringify(pricesData),
            fields_to_update: JSON.stringify(fieldsToUpdate)
        },
        beforeSend: function() {
            // Debug: log what's being sent
            console.log('Fields to update:', fieldsToUpdate);
            console.log('Sample price data:', pricesData.slice(0, 2));
        },
        dataType: 'json',
        success: function(response) {
            Swal.close();
            if (response.success) {
                Swal.fire({
                    icon: 'success',
                    title: 'Prices Updated',
                    html: `Successfully updated ${response.updated || 0} item(s).${response.errors && response.errors.length > 0 ? '<br><small class="text-danger">' + response.errors.length + ' error(s) occurred.</small>' : ''}`,
                    confirmButtonText: 'OK'
                }).then(() => {
                    location.reload();
                });
            } else {
                Swal.fire({
                    icon: 'error',
                    title: 'Update Failed',
                    text: response.message || 'Failed to update prices.',
                    confirmButtonText: 'OK'
                });
            }
        },
        error: function(xhr, status, error) {
            Swal.close();
            Swal.fire({
                icon: 'error',
                title: 'Update Error',
                text: 'An error occurred: ' + error,
                confirmButtonText: 'OK'
            });
        }
    });
}

// Update Taxes from Excel Functions
let taxesData = []; // Store loaded tax data

// Handle checkbox changes to show/hide columns
$(document).ready(function() {
    $(document).on('change', '#chkTaxType', function() {
        $('.taxtype-col').toggle(this.checked);
        displayTaxesTable(); // Refresh table to update column visibility
    });
    
    $(document).on('change', '#chkTaxRate', function() {
        $('.taxrate-col').toggle(this.checked);
        displayTaxesTable(); // Refresh table to update column visibility
    });
    
    // Initialize column visibility based on checkboxes
    $('.taxtype-col').toggle($('#chkTaxType').is(':checked'));
    $('.taxrate-col').toggle($('#chkTaxRate').is(':checked'));
    
    // Initialize clipboard paste for taxes when modal is shown
    $('#updateTaxesModal').on('shown.bs.modal', function() {
        const taxesClipboardData = document.getElementById('taxesClipboardData');
        if (taxesClipboardData) {
            // Preview on paste
            taxesClipboardData.addEventListener('paste', function() {
                setTimeout(() => {
                    parseTaxesDataFromClipboard();
                }, 100);
            });
            
            // Preview on input
            taxesClipboardData.addEventListener('input', function() {
                parseTaxesDataFromClipboard();
            });
            
            // Focus on textarea
            setTimeout(() => {
                taxesClipboardData.focus();
            }, 100);
        }
    });
    
    // Reset modal when closed
    $('#updateTaxesModal').on('hidden.bs.modal', function() {
        taxesData = [];
        $('#taxesClipboardData').val('');
        $('#taxesTableBody').html('<tr><td colspan="5" class="text-center text-muted py-5"><i class="fa fa-inbox fa-3x mb-3"></i><p class="mb-0">No records found</p><small>Paste Excel data in the textarea</small></td></tr>');
        $('#taxesStatus').text('No records found');
        $('#updateTaxesBtn').prop('disabled', true);
        $('#chkTaxType').prop('checked', true);
        $('#chkTaxRate').prop('checked', true);
        $('.taxtype-col, .taxrate-col').show();
    });
    
    // Handle row checkbox changes
    $(document).on('change', '.tax-row-checkbox', function() {
        const index = $(this).closest('tr').data('index');
        if (taxesData[index]) {
            taxesData[index].selected = this.checked;
        }
        updateTaxesStatus();
    });
});

// Clear taxes clipboard data
function clearTaxesClipboardData() {
    document.getElementById('taxesClipboardData').value = '';
    taxesData = [];
    displayTaxesTable();
}

// Parse clipboard data automatically (called on paste/input)
function parseTaxesDataFromClipboard() {
    const data = document.getElementById('taxesClipboardData').value.trim();
    if (!data) {
        taxesData = [];
        displayTaxesTable();
        return;
    }
    parseTaxesData(data);
}

// Parse clipboard data
function parseTaxesData(data) {
    const lines = data.split('\n').filter(line => line.trim());
    if (lines.length === 0) {
        Swal.fire({
            icon: 'error',
            title: 'Invalid Data',
            text: 'No valid data found. Please check your format.',
            confirmButtonText: 'OK'
        });
        return;
    }
    
    // Detect delimiter (tab preferred, fallback to comma)
    const firstLine = lines[0];
    const hasTabs = firstLine.includes('\t');
    const delimiter = hasTabs ? '\t' : ',';
    
    // Get which fields are selected
    const taxTypeSelected = $('#chkTaxType').is(':checked');
    const taxRateSelected = $('#chkTaxRate').is(':checked');
    
    taxesData = [];
    
    lines.forEach((line, index) => {
        const columns = line.split(delimiter).map(col => col.trim());
        
        // Skip header row
        if (index === 0) {
            const firstCol = columns[0]?.toLowerCase() || '';
            if (firstCol.includes('code') || firstCol.includes('item') || firstCol.includes('tax')) {
                return;
            }
        }
        
        if (columns.length >= 2) {
            const itemCode = columns[0] || '';
            
            if (!itemCode) {
                return; // Skip rows without item code
            }
            
            let taxType = '';
            let taxRateName = '';
            
            // Map columns: Column 1 = Tax Type, Column 2 = Tax Rate Name
            if (columns.length > 1) {
                taxType = columns[1] || '';
            }
            if (columns.length > 2) {
                taxRateName = columns[2] || '';
            }
            
            taxesData.push({
                item_code: itemCode,
                tax_type: taxType,
                tax_rate_name: taxRateName,
                selected: false
            });
        }
    });
    
    if (taxesData.length === 0) {
        Swal.fire({
            icon: 'error',
            title: 'Invalid Data',
            text: 'No valid tax data found. Please ensure Item Code is in the first column.',
            confirmButtonText: 'OK'
        });
        return;
    }
    
    // Fetch item names from server
    fetchTaxItemNames();
}

// Fetch item names for display
function fetchTaxItemNames() {
    const itemCodes = taxesData.map(t => t.item_code);
    
    $.ajax({
        url: 'ajax/get_items_by_codes.php',
        type: 'POST',
        data: {
            item_codes: JSON.stringify(itemCodes)
        },
        dataType: 'json',
        success: function(response) {
            if (response.success) {
                const itemMap = {};
                response.items.forEach(item => {
                    itemMap[item.item_code] = item.name;
                });
                
                // Add item names to taxesData
                taxesData.forEach(tax => {
                    tax.item_name = itemMap[tax.item_code] || 'Not Found';
                });
                
                displayTaxesTable();
            } else {
                // If endpoint doesn't exist, proceed without names
                taxesData.forEach(tax => {
                    tax.item_name = 'Loading...';
                });
                displayTaxesTable();
            }
        },
        error: function() {
            // If endpoint doesn't exist, proceed without names
            taxesData.forEach(tax => {
                tax.item_name = 'Loading...';
            });
            displayTaxesTable();
        }
    });
}

// Display taxes in table
function displayTaxesTable() {
    const tbody = $('#taxesTableBody');
    tbody.empty();
    
    if (taxesData.length === 0) {
        tbody.html('<tr><td colspan="5" class="text-center text-muted py-5"><i class="fa fa-inbox fa-3x mb-3"></i><p class="mb-0">No records found</p></td></tr>');
        $('#taxesStatus').text('No records found');
        $('#updateTaxesBtn').prop('disabled', true);
        return;
    }
    
    taxesData.forEach((tax, index) => {
        const taxTypeDisplay = tax.tax_type || '-';
        const taxRateDisplay = tax.tax_rate_name || '-';
        
        const row = $(`
            <tr data-index="${index}">
                <td>
                    <input type="checkbox" class="tax-row-checkbox" ${tax.selected ? 'checked' : ''}>
                </td>
                <td><strong>${tax.item_code}</strong></td>
                <td>${tax.item_name || 'Not Found'}</td>
                <td class="taxtype-col" style="display: ${$('#chkTaxType').is(':checked') ? 'table-cell' : 'none'};">${taxTypeDisplay}</td>
                <td class="taxrate-col" style="display: ${$('#chkTaxRate').is(':checked') ? 'table-cell' : 'none'};">${taxRateDisplay}</td>
            </tr>
        `);
        tbody.append(row);
    });
    
    $('#taxesStatus').text(`${taxesData.length} record(s) loaded`);
    $('#updateTaxesBtn').prop('disabled', false);
}

// Toggle select all
function toggleAllTaxes(checkbox) {
    const isChecked = checkbox.checked;
    $('.tax-row-checkbox').prop('checked', isChecked);
    taxesData.forEach((tax, index) => {
        tax.selected = isChecked;
    });
    updateTaxesStatus();
}

// Update status
function updateTaxesStatus() {
    const selectedCount = $('.tax-row-checkbox:checked').length;
    
    if (selectedCount > 0) {
        $('#taxesStatus').text(`${selectedCount} record(s) selected`);
    } else {
        $('#taxesStatus').text(`${taxesData.length} record(s) loaded`);
    }
}

// Copy selected taxes
function copySelectedTaxes() {
    const selected = taxesData.filter(t => t.selected);
    if (selected.length === 0) {
        Swal.fire({
            icon: 'warning',
            title: 'No Selection',
            text: 'Please select at least one row to copy.',
            confirmButtonText: 'OK'
        });
        return;
    }
    
    // Create CSV-like text
    let text = 'Item Code\tItem Name\tTax Type\tTax Rate Name\n';
    selected.forEach(tax => {
        text += `${tax.item_code}\t${tax.item_name || ''}\t${tax.tax_type || ''}\t${tax.tax_rate_name || ''}\n`;
    });
    
    // Copy to clipboard
    navigator.clipboard.writeText(text).then(() => {
        Swal.fire({
            icon: 'success',
            title: 'Copied!',
            text: `${selected.length} record(s) copied to clipboard.`,
            timer: 1500,
            showConfirmButton: false
        });
    }).catch(() => {
        Swal.fire({
            icon: 'error',
            title: 'Copy Failed',
            text: 'Failed to copy to clipboard. Please try again.',
            confirmButtonText: 'OK'
        });
    });
}

// Remove selected taxes
function removeSelectedTaxes() {
    const selected = taxesData.filter(t => t.selected);
    if (selected.length === 0) {
        Swal.fire({
            icon: 'warning',
            title: 'No Selection',
            text: 'Please select at least one row to remove.',
            confirmButtonText: 'OK'
        });
        return;
    }
    
    Swal.fire({
        title: 'Remove Selected?',
        text: `Are you sure you want to remove ${selected.length} record(s)?`,
        icon: 'warning',
        showCancelButton: true,
        confirmButtonText: 'Yes, Remove',
        cancelButtonText: 'Cancel'
    }).then((result) => {
        if (result.isConfirmed) {
            taxesData = taxesData.filter(t => !t.selected);
            displayTaxesTable();
            Swal.fire({
                icon: 'success',
                title: 'Removed',
                text: 'Selected records have been removed.',
                timer: 1500,
                showConfirmButton: false
            });
        }
    });
}

// Update taxes
function updateTaxes() {
    if (taxesData.length === 0) {
        Swal.fire({
            icon: 'warning',
            title: 'No Data',
            text: 'Please load data first.',
            confirmButtonText: 'OK'
        });
        return;
    }
    
    // Get selected fields
    const fieldsToUpdate = {
        item_code: true, // Always required
        tax_type: $('#chkTaxType').is(':checked'),
        tax_rate_name: $('#chkTaxRate').is(':checked')
    };
    
    // Check if at least one field is selected
    if (!fieldsToUpdate.tax_type && !fieldsToUpdate.tax_rate_name) {
        Swal.fire({
            icon: 'warning',
            title: 'No Fields Selected',
            text: 'Please select at least one tax field to update.',
            confirmButtonText: 'OK'
        });
        return;
    }
    
    Swal.fire({
        title: 'Updating Taxes...',
        text: 'Please wait while we update the taxes.',
        allowOutsideClick: false,
        didOpen: () => {
            Swal.showLoading();
        }
    });
    
    $.ajax({
        url: 'update_taxes.php',
        type: 'POST',
        data: {
            taxes_data: JSON.stringify(taxesData),
            fields_to_update: JSON.stringify(fieldsToUpdate)
        },
        dataType: 'json',
        success: function(response) {
            Swal.close();
            if (response.success) {
                Swal.fire({
                    icon: 'success',
                    title: 'Taxes Updated',
                    html: `Successfully updated ${response.updated || 0} item(s).${response.errors && response.errors.length > 0 ? '<br><small class="text-danger">' + response.errors.length + ' error(s) occurred.</small>' : ''}`,
                    confirmButtonText: 'OK'
                }).then(() => {
                    location.reload();
                });
            } else {
                Swal.fire({
                    icon: 'error',
                    title: 'Update Failed',
                    text: response.message || 'Failed to update taxes.',
                    confirmButtonText: 'OK'
                });
            }
        },
        error: function(xhr, status, error) {
            Swal.close();
            Swal.fire({
                icon: 'error',
                title: 'Update Error',
                text: 'An error occurred: ' + error,
                confirmButtonText: 'OK'
            });
        }
    });
}
</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; ?>

<?php if (!empty($_GET['added'])): ?>
<script>
Swal.fire({
    icon: 'success',
    title: 'Item Added Successfully!',
    text: 'The item has been saved. Cost price defaults to 0.00 if not specified.',
    timer: 3000,
    showConfirmButton: false
});
</script>
<?php endif; ?>

<?= display_video_help_modal() ?>

<style>
/* Color Picker Styling */
.color-picker-grid {
    display: grid;
    grid-template-columns: repeat(5, 1fr);
    gap: 10px;
    margin-bottom: 10px;
}

.color-picker-grid input[type="radio"] {
    display: none;
}

.color-picker-grid .color-option {
    display: block;
    width: 100%;
    height: 60px;
    border-radius: 8px;
    cursor: pointer;
    border: 3px solid transparent;
    transition: all 0.3s ease;
    display: flex;
    align-items: center;
    justify-content: center;
    font-size: 11px;
    font-weight: 600;
    color: #fff;
    text-align: center;
}

.color-picker-grid .color-option .color-label {
    text-shadow: 1px 1px 2px rgba(0,0,0,0.3);
}

.color-picker-grid input[type="radio"]:checked + .color-option {
    border-color: #092C4C;
    box-shadow: 0 0 15px rgba(9, 44, 76, 0.5);
    transform: scale(1.05);
}

.color-picker-grid .color-option:hover {
    transform: scale(1.05);
    box-shadow: 0 4px 10px rgba(0,0,0,0.2);
}

/* Custom styling for DataTable search input */
.dataTables_filter input {
    border: 1px solid #ddd;
    border-radius: 4px;
    padding: 8px 12px;
    font-size: 14px;
    width: 250px;
    margin-left: 8px;
}

.dataTables_filter input:focus {
    border-color: #007bff;
    box-shadow: 0 0 0 0.2rem rgba(0, 123, 255, 0.25);
    outline: none;
}

.dataTables_filter label {
    font-weight: 600;
    color: #333;
    margin-bottom: 0;
}

/* Improve DataTable overall styling */
.dataTables_wrapper .dataTables_length,
.dataTables_wrapper .dataTables_filter,
.dataTables_wrapper .dataTables_info,
.dataTables_wrapper .dataTables_processing,
.dataTables_wrapper .dataTables_paginate {
    margin: 15px 0;
}

.dataTables_wrapper .dataTables_paginate .paginate_button {
    padding: 8px 12px;
    margin: 0 2px;
    border: 1px solid #ddd;
    border-radius: 4px;
    background: #fff;
    color: #333;
    cursor: pointer;
}

.dataTables_wrapper .dataTables_paginate .paginate_button:hover {
    background: #f8f9fa;
    border-color: #007bff;
    color: #007bff;
}

.dataTables_wrapper .dataTables_paginate .paginate_button.current {
    background: #007bff;
    border-color: #007bff;
    color: #fff;
}

.dataTables_wrapper .dataTables_paginate .paginate_button.disabled {
    color: #6c757d;
    cursor: not-allowed;
    background: #f8f9fa;
}

/* Responsive adjustments */
@media (max-width: 768px) {
    .dataTables_filter input {
        width: 200px;
    }
    
    .dataTables_filter label {
        font-size: 14px;
    }
}

/* Filter modal styling */
.filter-modal-nav .nav-link {
    text-align: left;
    border-radius: 8px;
    margin-bottom: 6px;
    font-weight: 600;
}

.filter-modal-nav .nav-link.active {
    background-color: #0d6efd;
    color: #fff;
}

.filter-modal-tab-content {
    min-height: 250px;
}

.category-scroll {
    max-height: 260px;
    overflow-y: auto;
    background: #f8f9fa;
}

.category-scroll .form-check {
    margin-bottom: 6px;
}

/* Ensure item list content uses available width like enterprise grids */
.item-list-page .page-header {
    display: block;
}

.item-list-page .page-header .page-title {
    width: 100%;
    max-width: 100%;
}

.item-list-page .card {
    width: 100%;
}

/* Keep pagination controls slightly left to avoid clipping on horizontal scroll */
.item-list-page .dataTables_wrapper .dataTables_paginate {
    padding-right: 16px;
}

/* Override global tiny pagination pills so Previous/Next text is not clipped */
.item-list-page .dataTables_paginate .pagination li {
    margin: 0 3px;
}

.item-list-page .dataTables_paginate .pagination li a {
    width: auto;
    min-width: 32px;
    height: 32px;
    padding: 0 10px;
    border-radius: 10px !important;
    white-space: nowrap;
    line-height: 1.2;
}

.item-list-page .dataTables_paginate .pagination li.previous,
.item-list-page .dataTables_paginate .pagination li.next,
.item-list-page .dataTables_paginate .pagination li.previous.disabled,
.item-list-page .dataTables_paginate .pagination li.next.disabled {
    width: auto;
}

.item-list-page .dataTables_paginate .pagination li.previous a,
.item-list-page .dataTables_paginate .pagination li.next a,
.item-list-page .dataTables_paginate .pagination li.previous.disabled a,
.item-list-page .dataTables_paginate .pagination li.next.disabled a {
    width: auto;
    min-width: 72px;
}

/* Item list: scale readability on larger screens */
#itemTable {
    width: 100% !important;
}

#itemTable thead th {
    font-size: 14px;
}

#itemTable tbody td {
    font-size: 13px;
}

@media (min-width: 1600px) {
    .item-list-page .content {
        padding-left: 28px;
        padding-right: 28px;
    }

    #itemTable thead th {
        font-size: 15px;
        padding-top: 0.9rem;
        padding-bottom: 0.9rem;
    }

    #itemTable tbody td {
        font-size: 14px;
        padding-top: 0.85rem;
        padding-bottom: 0.85rem;
    }

    .page-header .page-btn .btn {
        padding: 0.55rem 0.95rem;
        font-size: 14px;
    }
}
</style>

