<!DOCTYPE html>
<html>
<head>
    <!-- TABLES CSS CODE -->
    <?php include "comman/code_css.php"; ?>
    <style>
        .box .box-title{font-weight:600}
        .text-danger{font-size:.9em}
        #items_preview table{width:100%}
        #items_preview th,#items_preview td{padding:6px 8px;border:1px solid #eee}
        #items_preview th{background:#f7f7f7}
    </style>
</head>
<body class="hold-transition skin-blue sidebar-mini">
<div class="wrapper">
<?php include "sidebar.php"; ?>

<input type="hidden" id="base_url" value="<?= isset($base_url) ? $base_url : base_url(); ?>">

<!-- Content Wrapper. Contains page content -->
<div class="content-wrapper">
    <section class="content-header">
        <h1>
            Bulk Stock Level Management
            <small>Set minimum stock and reorder levels for multiple items</small>
        </h1>
        <ol class="breadcrumb">
            <li><a href="<?= isset($base_url)?$base_url:base_url(); ?>dashboard"><i class="fa fa-dashboard"></i> Home</a></li>
            <li><a href="<?= isset($base_url)?$base_url:base_url(); ?>items">Items</a></li>
            <li class="active">Bulk Stock Levels</li>
        </ol>
    </section>

    <section class="content">
        <div class="row">
            <?php include "comman/code_flashdata.php"; ?>

            <div class="col-md-12">
                <div class="box box-primary">
                    <div class="box-header with-border">
                        <h3 class="box-title">Bulk Stock Level Management</h3>
                    </div>

                    <?= form_open('#', ['class' => 'form', 'id' => 'bulk-stock-form', 'autocomplete' => 'off']); ?>
                    <div class="box-body">
                        <div class="row">
                            <div class="form-group col-md-6">
                                <label for="bulk_type">Select Management Type <span class="text-danger">*</span></label>
                                <select class="form-control select2" id="bulk_type" name="bulk_type" style="width: 100%;" required>
                                    <option value="">-Select Type-</option>
                                    <option value="individual">Individual Item</option>
                                    <option value="all_items">All Items</option>
                                    <option value="by_brand">By Brand</option>
                                    <option value="by_category">By Category</option>
                                </select>
                                <span id="bulk_type_msg" class="text-danger" style="display:none"></span>
                            </div>

                            <div class="form-group col-md-6" id="item_selection_div" style="display:none;">
                                <label for="item_id">Select Item <span class="text-danger">*</span></label>
                                <select class="form-control select2" id="item_id" name="item_id" style="width: 100%;">
                                    <option value="">-Select Item-</option>
                                    <?= get_items_select_list(); ?>
                                </select>
                                <span id="item_id_msg" class="text-danger" style="display:none"></span>
                            </div>

                            <div class="form-group col-md-6" id="brand_selection_div" style="display:none;">
                                <label for="brand_id">Select Brand <span class="text-danger">*</span></label>
                                <select class="form-control select2" id="brand_id" name="brand_id" style="width: 100%;">
                                    <option value="">-Select Brand-</option>
                                    <?= get_brands_select_list(); ?>
                                </select>
                                <span id="brand_id_msg" class="text-danger" style="display:none"></span>
                            </div>

                            <div class="form-group col-md-6" id="category_selection_div" style="display:none;">
                                <label for="category_id">Select Category <span class="text-danger">*</span></label>
                                <select class="form-control select2" id="category_id" name="category_id" style="width: 100%;">
                                    <option value="">-Select Category-</option>
                                    <?= get_categories_select_list(); ?>
                                </select>
                                <span id="category_id_msg" class="text-danger" style="display:none"></span>
                            </div>
                        </div>

                        <div class="row">
                            <div class="form-group col-md-6">
                                <label for="minimum_stock_level">Minimum Stock Level <span class="text-danger">*</span></label>
                                <input type="number" class="form-control" id="minimum_stock_level" name="minimum_stock_level" placeholder="Minimum stock before alert" min="0" step="1" required>
                                <span id="minimum_stock_level_msg" class="text-danger" style="display:none"></span>
                            </div>

                            <div class="form-group col-md-6">
                                <label for="reorder_level">Reorder Level <span class="text-danger">*</span></label>
                                <input type="number" class="form-control" id="reorder_level" name="reorder_level" placeholder="Stock level to trigger reorder" min="0" step="1" required>
                                <span id="reorder_level_msg" class="text-danger" style="display:none"></span>
                            </div>
                        </div>

                        <div class="row" id="preview_div" style="display:none;">
                            <div class="col-md-12">
                                <div class="box box-info">
                                    <div class="box-header">
                                        <h3 class="box-title">Items to be Updated</h3>
                                    </div>
                                    <div class="box-body">
                                        <div id="items_preview"></div>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>

                    <div class="box-footer">
                        <button type="button" class="btn btn-info" id="preview_btn" style="display:none;">
                            <i class="fa fa-eye"></i> Preview Items
                        </button>
                        <button type="button" class="btn btn-success" id="update_btn" style="display:none;">
                            <i class="fa fa-save"></i> Update Stock Levels
                        </button>
                        <a href="<?= isset($base_url)?$base_url:base_url(); ?>items" class="btn btn-default">
                            <i class="fa fa-arrow-left"></i> Back to Items
                        </a>
                        <button type="button" class="btn btn-default pull-right" id="reset_btn">
                            <i class="fa fa-refresh"></i> Reset
                        </button>
                    </div>
                    <?= form_close(); ?>
                </div>
            </div>
        </div>
    </section>
</div>

<?php include "comman/code_js.php"; ?>

<script>
(function() {
    var $doc = $(document);

    function initToastr() {
        toastr.options = {
            closeButton: true,
            progressBar: true,
            preventDuplicates: true,
            newestOnTop: true,
            timeOut: 3000,
            extendedTimeOut: 1000,
            showMethod: "fadeIn",
            hideMethod: "fadeOut"
        };
    }

    function clearToasts() {
        try { toastr.clear(); } catch(e){}
        $("#toast-container").remove(); // hard cleanup if any
    }

    function toggleSelectors(bulkType) {
        $("#item_selection_div, #brand_selection_div, #category_selection_div").hide();

        if (bulkType === "individual") {
            $("#item_selection_div").show();
        } else if (bulkType === "by_brand") {
            $("#brand_selection_div").show();
        } else if (bulkType === "by_category") {
            $("#category_selection_div").show();
        }
    }

    function inputsValid() {
        var bulkType = $("#bulk_type").val();
        var minLvl   = $("#minimum_stock_level").val();
        var reLvl    = $("#reorder_level").val();

        if (!bulkType || minLvl === "" || reLvl === "") return false;

        // additional selection checks
        if (bulkType === "individual" && !$("#item_id").val()) return false;
        if (bulkType === "by_brand"   && !$("#brand_id").val()) return false;
        if (bulkType === "by_category"&& !$("#category_id").val()) return false;

        // logical check: reorder should be >= minimum (you can adjust rule as needed)
        if (Number(reLvl) < Number(minLvl)) {
            $("#reorder_level_msg").text("Reorder level should be greater than or equal to minimum stock level.").show();
            return false;
        } else {
            $("#reorder_level_msg").hide();
        }

        return true;
    }

    function currentPayload() {
        var bulkType = $("#bulk_type").val();
        var payload = {
            bulk_type: bulkType,
            minimum_stock_level: $("#minimum_stock_level").val(),
            reorder_level: $("#reorder_level").val()
        };
        if (bulkType === "individual") payload.item_id = $("#item_id").val();
        if (bulkType === "by_brand")   payload.brand_id = $("#brand_id").val();
        if (bulkType === "by_category")payload.category_id = $("#category_id").val();
        return payload;
    }

    function setLoading($btn, isLoading, normalHtml) {
        if (isLoading) {
            $btn.prop("disabled", true).data("normal", normalHtml).html('<i class="fa fa-spinner fa-spin"></i> Please wait...');
        } else {
            $btn.prop("disabled", false).html($btn.data("normal"));
        }
    }

    function renderPreviewTable(html) {
        // If backend returns ready-made HTML, use it; otherwise create a simple table fallback
        if (html && html.trim() !== "") {
            $("#items_preview").html(html);
            return;
        }
        $("#items_preview").html(
            '<table class="table table-striped">' +
                '<thead><tr><th>#</th><th>Item</th><th>Current Min</th><th>Current Reorder</th><th>New Min</th><th>New Reorder</th></tr></thead>' +
                '<tbody><tr><td>1</td><td>—</td><td>—</td><td>—</td><td>' + $("#minimum_stock_level").val() + '</td><td>' + $("#reorder_level").val() + '</td></tr></tbody>' +
            '</table>'
        );
    }

    function showActionButtons() {
        if (inputsValid()) {
            $("#preview_btn").show();
        } else {
            $("#preview_btn, #update_btn, #preview_div").hide();
        }
    }

    $doc.ready(function() {
        initToastr();
        clearToasts();

        // Select2
        if ($.fn.select2) {
            $(".select2").select2({ width: "100%" });
        }

        // Show/hide selectors on bulk type change
        $("#bulk_type").on("change", function() {
            var val = $(this).val();
            toggleSelectors(val);
            $("#items_preview").empty();
            $("#preview_div, #update_btn").hide();
            showActionButtons();
        });

        // Inputs watcher
        $("#minimum_stock_level, #reorder_level, #item_id, #brand_id, #category_id").on("input change", function() {
            showActionButtons();
        });

        // Reset
        $("#reset_btn").on("click", function() {
            try {
                $("#bulk-stock-form")[0].reset();
            } catch(e){}
            $(".select2").val(null).trigger("change");
            $("#item_selection_div, #brand_selection_div, #category_selection_div").hide();
            $("#preview_div, #preview_btn, #update_btn").hide();
            $("#items_preview").empty();
            $("#minimum_stock_level_msg, #reorder_level_msg, #bulk_type_msg, #item_id_msg, #brand_id_msg, #category_id_msg").hide().text("");
            clearToasts();
            toastr.info("Form reset.", "Info");
        });

        // Preview
        $("#preview_btn").on("click", function() {
            clearToasts();
            if (!inputsValid()) {
                toastr.warning("Please complete required fields correctly.", "Warning");
                return;
            }

            var payload = currentPayload();
            var $btn = $("#preview_btn");
            setLoading($btn, true, '<i class="fa fa-eye"></i> Preview Items');

            $.ajax({
                url: $("#base_url").val() + "items/preview_bulk_stock_levels",
                type: "POST",
                data: payload,
                dataType: "json"
            })
            .done(function(res){
                setLoading($btn, false);
                if (res && res.status === "success") {
                    renderPreviewTable(res.html || "");
                    $("#preview_div").show();
                    $("#update_btn").show();
                    toastr.success("Preview loaded successfully!", "Success");
                } else {
                    toastr.error((res && res.message) ? res.message : "Error loading preview", "Error", { timeOut: 5000 });
                }
            })
            .fail(function(xhr){
                setLoading($btn, false);
                console.error("Preview Error:", xhr.responseText);
                toastr.error("Error loading preview. Please try again.", "Error", { timeOut: 5000 });
            });
        });

        // Update
        $("#update_btn").on("click", function() {
            clearToasts();
            if (!inputsValid()) {
                toastr.warning("Please complete required fields correctly.", "Warning");
                return;
            }
            if (!confirm("Are you sure you want to update stock levels for the selected items?")) return;

            var payload = currentPayload();
            var $btn = $("#update_btn");
            setLoading($btn, true, '<i class="fa fa-save"></i> Update Stock Levels');

            $.ajax({
                url: $("#base_url").val() + "items/update_bulk_stock_levels",
                type: "POST",
                data: payload,
                dataType: "json"
            })
            .done(function(res){
                setLoading($btn, false);
                if (res && res.status === "success") {
                    toastr.success(res.message || "Stock levels updated.", "Success", { timeOut: 4000 });
                    // Hard reset after success
                    $("#reset_btn").trigger("click");
                } else {
                    toastr.error((res && res.message) ? res.message : "Error updating stock levels", "Error", { timeOut: 5000 });
                }
            })
            .fail(function(xhr){
                setLoading($btn, false);
                console.error("Update Error:", xhr.responseText);
                toastr.error("Error updating stock levels. Please try again.", "Error", { timeOut: 5000 });
            });
        });

        // Clean toasts on navigation
        $(window).on("beforeunload", function(){ clearToasts(); });
        $(window).on("pageshow", function(e){ if (e.originalEvent && e.originalEvent.persisted) clearToasts(); });
    });
})();
</script>

</div>
</body>
</html>
