<script>
/* ============================================================
   6️⃣ WAREHOUSE FORM MODULE
============================================================ */

// Add Permission to Menus
$(document).on("click", ".openPermissionmenuModal", function () {

    // Close action sheet first
    $("#PermissionMenuModal").modal("show");
    

    // Wait until it's closed, then open product modal
    setTimeout(function () {
        $("#permissionActionSheet").modal("hide");
    }, 400);

});

// Add Permission to Categories
$(document).on("click", ".openPermissioncatModal", function () {

    // Close action sheet first
    $("#PermissioncatModal").modal("show");
    

    // Wait until it's closed, then open product modal
    setTimeout(function () {
        $("#permissionActionSheet").modal("hide");
    }, 400);

});

// Add Permission to specific accounts

$(document).on("click", ".openPermissionModal", function () {

    // Close action sheet first
    $("#PermissionModal").modal("show");
    

    // Wait until it's closed, then open product modal
    setTimeout(function () {
        $("#permissionActionSheet").modal("hide");
    }, 400);

});

// Add Permission to Menus 
document.getElementById("permmenuaddRow").addEventListener("click", function () {

    const container = document.getElementById("permissionmenuRows");

    const newRow = document.createElement("div");
    newRow.className = "permcat-row row mb-2";

    newRow.innerHTML = `
 <div class="form-group   col-md-3">
                            <div class="live-search-wrapper"
                                     data-endpoint="fetch_scripts/get_users.php"
                                     data-hidden-name="user2_id[]"
                                     data-display-fields="firstname,secondname"
                                     data-value-field="id">
                                
                                    <label class="label">User</label>
                                
                                    <!-- ❌ REMOVE name from text input -->
                                    <input type="text"
                                           class="form-control liveSearchInput"
                                           placeholder="Search..."
                                           autocomplete="off">
                                
                                    <!-- ✅ ADD name here instead -->
                                    <input type="hidden"
                                           class="liveHiddenInput"
                                           name="user2_id[]">
                                
                                    <div class="liveResults"></div>
                                </div>
                        </div>
                       <div class="form-group   col-md-3">
                            <div class="input-wrapper">
                            <label class="label" for="name2">Menu item</label>
                             <select name="mnu[]" class="form-control">
                                <option value="accounts">Accounts</option>
                                <option value="inventory">Inventory</option>
                                <option value="customers">Customers</option>
                                <option value="suppliers">Suppliers</option>
                                <option value="products">Products</option>
                                <option value="permissions">Permissions</option>
                                <option value="accounts_lists">Chart of Accounts</option>
                                <option value="cash_adj">Cash Adjustment</option>
                            </select>
                            </div>
                        </div>
                       
                        <div class="form-group   col-md-4">
                            <div class="input-wrapper">
                            <label class="label" for="name2">Access Level</label>
                              <select name="access2_lvl[]" class="form-control">
                                    <option value="0">View Only</option>
                                    <option value="11">View & Create</option>
                                  
                                </select>
                            </div>
                        </div>
                        <div class="form-group basic col-md-2 d-flex align-items-center">
                            <button type="button" class="btn btn-danger btn-sm removemenuRow" >Remove</button>
                        </div>
    `;

            container.appendChild(newRow);
            
        
});

// Add Permission to categories 
document.getElementById("permcataddRow").addEventListener("click", function () {

    const container = document.getElementById("permissioncatRows");

    const newRow = document.createElement("div");
    newRow.className = "permcat-row row mb-2";

    newRow.innerHTML = `
 <div class="form-group   col-md-3">
                            <div class="live-search-wrapper"
                                     data-endpoint="fetch_scripts/get_users.php"
                                     data-hidden-name="user_id[]"
                                     data-display-fields="firstname,secondname"
                                     data-value-field="id">
                                
                                    <label class="label">User</label>
                                
                                    <!-- ❌ REMOVE name from text input -->
                                    <input type="text"
                                           class="form-control liveSearchInput"
                                           placeholder="Search..."
                                           autocomplete="off">
                                
                                    <!-- ✅ ADD name here instead -->
                                    <input type="hidden"
                                           class="liveHiddenInput"
                                           name="user_id[]">
                                
                                    <div class="liveResults"></div>
                                </div>
                        </div>
                       <div class="form-group   col-md-3">
                            <div class="input-wrapper">
                            <label class="label" for="name2">Category</label>
                              <select name="categ[]" class="form-control">
                                <option value="cash_wallet">Cash Wallet</option>
                                <option value="bank_wallet">Bank Wallet</option>
                                <option value="expense">Expense</option>
                                <option value="customer">Customer</option>
                                <option value="warehouse">Warehouse</option>
                                <option value="sales_person">Sales person</option>
                                <option value="supplier">Supplier</option>
                            </select>
                            </div>
                        </div>
                       
                        <div class="form-group   col-md-4">
                            <div class="input-wrapper">
                            <label class="label" for="name2">Access Level</label>
                              <select name="access_lvl[]" class="form-control">
                                    <option value="0">View Only</option>
                                    <option value="1">View & Confirm Transactions</option>
                                    <option value="2">View & Transfer to Account </option>
                                    <option value="3">View & Transfer from Account </option>
                                    <option value="4">View,Transfer to & from Account</option>
                                    <option value="5">View,confirm,Transfer to & from Account</option>
                                    <option value="6">View & Approve Transactions</option>
                                    <option value="7">All access</option>
                                </select>
                            </div>
                        </div>
                        <div class="form-group basic col-md-2 d-flex align-items-center">
                            <button type="button" class="btn btn-danger btn-sm removepermcatRow" >Remove</button>
                        </div>
    `;

            container.appendChild(newRow);
            
        
});



// Add Permission to specific accounts
document.getElementById("permaddRow").addEventListener("click", function () {

    const container = document.getElementById("permissionRows");

    const pmnewRow = document.createElement("div");
    pmnewRow.className = "perm-row row mb-2";

    pmnewRow.innerHTML = `
 <div class="form-group   col-md-3">
                            <div class="live-search-wrapper"
                                     data-endpoint="fetch_scripts/get_users.php"
                                     data-hidden-name="user1_id[]"
                                     data-display-fields="firstname,secondname"
                                     data-value-field="id">
                                
                                    <label class="label">User</label>
                                
                                    <!-- ❌ REMOVE name from text input -->
                                    <input type="text"
                                           class="form-control liveSearchInput"
                                           placeholder="Search..."
                                           autocomplete="off">
                                
                                    <!-- ✅ ADD name here instead -->
                                    <input type="hidden"
                                           class="liveHiddenInput"
                                           name="user1_id[]">
                                
                                    <div class="liveResults"></div>
                                </div>
                        </div>
                          <div class="form-group   col-md-3">
                            <div class="live-search-wrapper"
                                     data-endpoint="fetch_scripts/get_account.php"
                                     data-hidden-name="account1_id[]"
                                     data-display-fields="acc_name"
                                     data-value-field="id">
                                
                                    <label class="label">Account</label>
                                
                                    <!-- ❌ REMOVE name from text input -->
                                    <input type="text"
                                           class="form-control liveSearchInput"
                                           placeholder="Search..."
                                           autocomplete="off">
                                
                                    <!-- ✅ ADD name here instead -->
                                    <input type="hidden"
                                           class="liveHiddenInput"
                                           name="account1_id[]">
                                
                                    <div class="liveResults"></div>
                                </div>
                        </div>
                        <div class="form-group   col-md-4">
                            <div class="input-wrapper">
                            <label class="label" for="name2">Access Level</label>
                              <select name="access1_lvl[]" class="form-control">
                                    <option value="0">View Only</option>
                                    <option value="1">View & Confirm Transactions</option>
                                    <option value="2">View & Transfer to Account </option>
                                    <option value="3">View & Transfer from Account </option>
                                    <option value="4">View,Transfer to & from Account</option>
                                    <option value="5">View,confirm,Transfer to & from Account</option>
                                    <option value="6">View & Approve Transactions</option>
                                    <option value="7">All access</option>
                                </select>
                            </div>
                        </div>
                     
                        <div class="form-group basic col-md-2 d-flex align-items-center">
    <button type="button" class="btn btn-danger btn-sm removepermRow">Remove</button>
</div>
    `;

            container.appendChild(pmnewRow);
            
           
});

/* Remove Row (Event Delegation) */
document.getElementById("permissionmenuRows")
    .addEventListener("click", function (e) {
        if (e.target.classList.contains("removemenuRow")) {
            e.target.closest(".permcat-row").remove();
        }
    });
    
document.getElementById("permissionRows")
    .addEventListener("click", function (e) {
        if (e.target.classList.contains("removepermRow")) {
            e.target.closest(".perm-row").remove();
        }
    });
    
document.getElementById("permissioncatRows")
    .addEventListener("click", function (e) {
        if (e.target.classList.contains("removepermcatRow")) {
            e.target.closest(".permcat-row").remove();
        }
    });    
    
    
/* Submit Multiple specific account permissions */
document.getElementById("permissionForm")
    .addEventListener("submit", function (e) {

        e.preventDefault();

        const formData = new FormData(this);

        fetch('../includes/save_account_permissions.php', {
            method: 'POST',
            body: formData
        })
        .then(res => res.json())
        .then(data => {

            if (data.status === "success") {

                //alert("Warehouses saved successfully");
                showToast("Permission saved successfully", "success");
                 $("#PermissionModal").modal("hide");
                 refreshperm();

                this.reset();
                document.getElementById("permissionRows").innerHTML = "";
                document.getElementById("permaddRow").click();

            } else {

               // alert("Error: " + (data.message || "Unknown error"));
               showToast(data.message || "Unknown error", "error");

            }
        })
        .catch(err => {
            console.error(err);
            alert("Server error — check console");
        });
    });
    
document.getElementById("permissioncatForm")
    .addEventListener("submit", function (e) {

        e.preventDefault();

        const formData = new FormData(this);

        fetch('../includes/save_category_permissions.php', {
            method: 'POST',
            body: formData
        })
        .then(res => res.json())
        .then(data => {

            if (data.status === "success") {

                //alert("Warehouses saved successfully");
                showToast("Permission Category saved successfully", "success");
                 $("#PermissioncatModal").modal("hide");
                  refreshperm(); // reload table

                this.reset();
                document.getElementById("permissioncatRows").innerHTML = "";
                document.getElementById("permcataddRow").click();

            } else {

               // alert("Error: " + (data.message || "Unknown error"));
               showToast(data.message || "Unknown error", "error");

            }
        })
        .catch(err => {
            console.error(err);
            alert("Server error — check console");
        });
    });
    
    
    document.getElementById("permissionmenuForm")
    .addEventListener("submit", function (e) {

        e.preventDefault();

        const formData = new FormData(this);

        fetch('../includes/save_menu_access_permissions.php', {
            method: 'POST',
            body: formData
        })
        .then(res => res.json())
        .then(data => {

            if (data.status === "success") {

                //alert("Warehouses saved successfully");
                showToast("Menu Access saved successfully", "success");
                 $("#PermissionMenuModal").modal("hide");
                  refreshperm(); // reload table

                this.reset();
                document.getElementById("permissionmenuRows").innerHTML = "";
                document.getElementById("permmenuaddRow").click();

            } else {

               // alert("Error: " + (data.message || "Unknown error"));
               showToast(data.message || "Unknown error", "error");

            }
        })
        .catch(err => {
            console.error(err);
            alert("Server error — check console");
        });
    });
    
let perm_limit = 10;
let perm_offset = 0;
let perm_loading = false;
let perm_finished = false;

$(document).ready(function () {

    loadPerm();

    $("#permissionScroll").on("scroll", function () {

        if (perm_loading || perm_finished) return;

        let container = $(this);

        let scrollTop = container.scrollTop();
        let scrollHeight = container[0].scrollHeight;
        let height = container.height();

        if (scrollTop + height >= scrollHeight - 50) {
            loadPerm();
        }

    });

});

function loadPerm() {

    if (perm_loading || perm_finished) return;

    perm_loading = true;

    showLoader2();

    $.ajax({
        url: "fetch_scripts/fetch_permissions.php",
        type: "GET",
        data: {
            perm_limit: perm_limit,
            perm_offset: perm_offset,
            pm_user: $("#pm_user").val()
        },
        dataType: "json",
        success: function (response) {

            hideLoader2();

            if (response.length === 0) {

                perm_finished = true;

                $("#permissionslist").append(`
                <tr>
                    <td colspan="5" class="text-center text-muted p-3">
                        No more accounts
                    </td>
                </tr>
                `);

                return;
            }

            let rows = "";

            response.forEach(function (perm) {

                //let badge = perm.status.toLowerCase() === "active"
                //    ? '<span class="badge badge-success">Active</span>'
                //    : '<span class="badge badge-danger">Inactive</span>';
                    
                //let salePrice = Number(product.p_sale_px).toLocaleString();
                //let purchasePrice = Number(product.p_prch_px).toLocaleString();

                rows += `
                <tr class="permissionRow" data-id="${perm.pm_id}">
                    <td>${perm.name}</td>
                    <td>${perm.acc_name}</td>
                    <td>${perm.pm_acc_categ}</td>
                    <td>${perm.menu}</td>
                    <td>${perm.permission_level}</td>
                </tr>
                `;
            });

            $("#permissionslist").append(rows);

            perm_offset += perm_limit;
            perm_loading = false;
        }
    });
}

       // Live Search
    $("#pm_user").on("keyup", function () {

        refreshperm();

    });



function refreshperm() {

    perm_offset = 0;
    perm_finished = false;
    perm_loading = false;

    $("#permissionslist").html("");

    loadPerm();
}

$(document).on("click", ".permissionRow", function () {

    let permId = $(this).data("id");

    $.ajax({
        url: "fetch_scripts/get_single_permission.php",
        type: "POST",
        data: { id: permId },
        dataType: "json",
        success: function (perm) {

            $("#del_id").val(perm.pm_id);
            $("#del_user").val(perm.name);
            $("#del_acc").val(perm.acc_name);
            $("#del_categ").val(perm.pm_acc_categ);
            $("#del_acclvl").val(perm.permission_level);
          

            $("#DeletFormModal").modal("show");
        }
    });
});

$("#deletepermissionForm").submit(function (e) {
    e.preventDefault();

    $.ajax({
        url: "fetch_scripts/delete_permission.php",
        type: "POST",
        data: $(this).serialize(),
        success: function (response) {

            $("#DeletFormModal").modal("hide");
            refreshperm(); // reload table
        }
    });
});

function showLoader2() {

    let loader = `
    <tr id="loadingRow">
        <td colspan="5" class="text-center p-3">
            <div class="spinner-border spinner-border-sm text-primary"></div>
            Loading accounts...
        </td>
    </tr>
    `;

    $("#permissionslist").append(loader);
}

function hideLoader2() {
    $("#loadingRow").remove();
}
</script>