/* global JsStore, startDate, endDate, is_gtr */

var USER_INFO = {};
var PET_LIST = [];
var GROOMER_LIST = [];
var APPOINTMENT_ID = 0;

/*
 TRUNCATE tbl_pos_billing;
 TRUNCATE tbl_pos_bill_items;
 TRUNCATE tbl_pos_payments;
 */

function filter_payload_db(val) {
    return {
        name: val.name,
        id: val.id,
        pet_id: val.pet_id,
        groomer_id: val.groomer_id,
        regular_rate: val.regular_rate,
        item_code: val.code,
        barcode: val.barcode,
        vat_percentage: val.vat_percentage,
        purchase_rate: val.purchase_rate,
        minimal_sales_rate: val.minimal_sales_rate,
        quantity: parseInt(val?.quantity || 1)
    };
}

function load_items(cat_id, page, is_clear) {
    //alert();
    $.ajax({
        "url": BASE_URL + "web/pos/get_item_over_category",
        "method": "POST",
        "dataType": "JSON",
        "data": {
            cat_id: cat_id,
            page: page,
            search: $("input[name=search_products]").val()
        },
        success: function (data) {
            let html = "";
            $.each(data, function (ind, val) {
                let meta = filter_payload_db(val);
                html += `<div class="col-xl-4 col-lg-4 col-md-4 col-sm-4 col-6 pl-2 pr-2 mb-3 vikash add_item_to_cart" meta="` + btoa(encodeURIComponent(JSON.stringify(meta))) + `">
                            <div class="productCard justify-content-between d-flex flex-column h-100 mt-0 mb-0 ` + (store_setting.hide_image_in_pos === "0" ? "" : "c_btn_view") + `">`;
                if (store_setting.hide_image_in_pos === "0") {
                    let image = "";
                    if(val.image === "" || val.image === null){
                        image = BASE_URL + 'assets/images/no-image.png';
                    } else if (val.image.includes("http")){
                        image = val.image;
                    } else if (val.image !== ""){
                        image = BASE_URL + 'assets/images/products/' + val.image;
                    } else {
                        image = BASE_URL + 'assets/images/no-image.png';
                    }
                    html += `<div class="productThumb">
                                    <img class="img-fluid" src="` + image + `" alt="ix">
                                </div>`;
                }
                html += `<div class="productContent h-100 mt-0">
                                    <div class="pro-details d-flex flex-column align-items-center justify-content-center h-100">
                                        <div class="pro-name">` + val.name + `</div>
                                        <div class="pro-price">Price: <img src="` + BASE_URL + 'assets/pos/images/dirham-b.svg' + `"  alt="Dirham"> ` + val.regular_rate + `</div>`;
                                        
                html += (val.name_ar ? `<div>` + val.name_ar + `</div>` : '');
                html += `</div>
                                </div>
                            </div>
                        </div>`;
            });
            if (is_clear === 1) {
                $(".tbl_products").html("");
            }
            if (data.length > 0) {
                html += `<div class="col-xl-12 col-lg-12 col-md-12 col-sm-12 col-12 load_more_cat_wise_item" meta="" style="text-align: center;">
                            <button class="btn btn-info btn-xs">Load More <i class="fa fa-arrow-down"></i></button>
                        </div>`;
            }
            $(".tbl_products").children().last('.load_more_cat_wise_item').remove();
            $(".tbl_products").append(html);
        }
    });
}

let cat_loaded_page = 1;
load_items($(".tbl_category").val(), cat_loaded_page, 0);
$(document).on('change', "select.tbl_category", function () {
    cat_loaded_page = 1;
    load_items($(this).val(), cat_loaded_page, 1);
}).on('click', '.load_more_cat_wise_item', function () {
    ++cat_loaded_page;
    load_items($(".tbl_category").val(), cat_loaded_page, 0);
});

let add_active_on_item = null;
function append_into_cart(item) {
    let html = "<option value='0'>Select</option>";
    if (PET_LIST.length > 0) {
        $.each(PET_LIST, function (index, value) {
            html += "<option value='" + value.id + "' " + (value.id === item.pet_id ? "selected" : "") + ">" + value.title + "</option>";
        });
    }

    let groomer_html = "<option value='0'>Select</option>";
    if (GROOMER_LIST.length > 0) {
        $.each(GROOMER_LIST, function (index, value) {
            groomer_html += "<option value='" + value.id + "' " + (value.id === item.groomer_id ? "selected" : "") + ">" + value.title + "</option>";
        });
    }

    let item_html = `<tr item_id="` + item.item_id + `" class="` + (add_active_on_item === item.item_id ? "active" : "") + `">
                        <td>` + item.name + `</td>
                        <td>` + item.barcode + `</td>
                        <td>
                            <input type="number" value="` + item.quantity + `" class="form-control border-dark w-70px update_quantity" item_id="` + item.item_id + `" placeholder="">
                        </td>
                        <td>` + item.rate + `</td>
                        <td>` + item.discount_price + `</td>
                        <td>` + item.final_discounted_price + `</td>
                        <td>` + item.vat_charge + `</td>
                        <td>` + item.total + `</td>
                        <td class="pet_row" style="display: none;"><select item_id="` + item.item_id + `" id="arabic_select_` + item.item_id + `" class="arabic_select arabic-select select-down">` + html + `</select></td>
                        <td class="pet_row" style="display: none;"><select item_id="` + item.item_id + `" id="groomer_select_` + item.item_id + `" class="groomer_select arabic-select select-down">` + groomer_html + `</select></td>
                        <td>
                            <div class="card-toolbar text-right">
                                <a href="javascrt:void(O)" class="confirm-delete" item_id="` + item.item_id + `" title="Delete"><i class="fa fa-trash"></i></a>
                            </div>
                        </td>
                    </tr>`;
    $(".cart_items").append(item_html);
}

var Database_Name = 'RetailPro';
var Version = 1.0;
var Text_Description = 'Retail Pro Pos Web DB';
var Database_Size = 2 * 1024 * 1024;

var session_id = 1;
var operator_id = OPERATOR_ID;
var customer_paid_cash = 0;

const currentDate = new Date();
const year = currentDate.getFullYear();
const month = String(currentDate.getMonth() + 1).padStart(2, '0');
const day = String(currentDate.getDate()).padStart(2, '0');
const formattedDate = `${year}-${month}-${day}`;

const idb = window.indexedDB || window.mozIndexedDB || window.webkitIndexedDB || window.msIndexedDB || window.shimIndexedDB;
if (!idb) {
    console.log("This browser doesn't support IndexedDB");
    alert("PLease change your browser as POS not supported here.");
}
var dbName = 'RETAIL_PRO';
var tables = [
    {
        table: 'bill_session_payment',
        index: {
            bspSessionIdAmountPayVia: ["session_id", "amount", "pay_via"],
            bspSessionId: "session_id",
            bspAmountPayVia: ["pay_via", "amount"],
            bspSessionIdPayVia: ["session_id", "pay_via"]
        }
    },
    {
        table: 'bill_session',
        index: {
            bsSessionId: "session_id",
            bsStatus: "status"
        }
    },
    {
        table: 'cart_item',
        index: {
            ciSessionId: "session_id",
            ciSessionIdItemId: ['session_id', 'item_id']
        }
    }
];

/*
 var index = store.index('tags');
 var range = IDBKeyRange.bound(['101', 999],['101', 2001]);
 var req = index.openCursor(range);
 req.onsuccess = function(e){
 */

function init_db() {
    var request = idb.open(dbName, 1);

    request.onerror = function (event) {
        console.error("An error occurred with IndexedDB");
        console.error(event);
    };

    request.onupgradeneeded = function (event) {
        var db = request.result;
        $.each(tables, function (ind, val) {
            if (!db.objectStoreNames.contains(val.table)) {
                let obj_store = db.createObjectStore(val.table, {keyPath: "id", autoIncrement: true});
                if (Object.keys(val.index).length > 0) {
                    $.each(Object.keys(val.index), function (ind_ind, ind_val) {
                        obj_store.createIndex(ind_val, val.index[ind_val]);
                    });
                }
            }
        });
    };
    return request;
}

async function insert_db(table, item) {
    return new Promise(async function (resolve, reject) {
        var request = init_db();
        request.onsuccess = function () {
            var db = request.result;
            var tx = db.transaction(table, "readwrite");
            var userData = tx.objectStore(table);
            userData.add(item);
            resolve(userData);
        };
    });
}

let apply_condition = null;
async function get_db(table, index, where) {
    return new Promise(async function (resolve, reject) {
        var request = init_db();
        request.onsuccess = () => {
            const db = request.result;

            var tx = db.transaction(table, "readonly");
            var obj_table = tx.objectStore(table);

            var table_data = null;
            if (index === "") {
                table_data = obj_table.getAll();
            } else {
                var tab_index = obj_table.index(index);
                table_data = tab_index.getAll(IDBKeyRange.only(where));
            }
            let custom_where = apply_condition;
            apply_condition = null;
            table_data.onsuccess = (query) => {
                let return_ = [];
                $.each(Object.keys(query.srcElement.result), function (index, val) {
                    if (custom_where !== null && query.srcElement.result[val].status < custom_where[Object.keys(custom_where)[0]]) {
                        return_.push(query.srcElement.result[val]);
                    } else if (custom_where === null) {
                        return_.push(query.srcElement.result[val]);
                    }
                });
                resolve(return_);
            };

            tx.oncomplete = function () {
                db.close();
            };
        };
    });
}

async function update_db(table, index, where, update) {
    return new Promise(async function (resolve, reject) {
        let get_result = await get_db(table, index, where);
        if (get_result.length > 0) {
            var request = init_db();
            request.onsuccess = () => {
                var db = request.result;
                var tx = db.transaction(table, "readwrite");
                var userData = tx.objectStore(table);
                var update_val = null;
                $.each(get_result, function (index, val) {
                    $.each(Object.keys(update), function (up_ind, up_val) {
                        val[up_val] = update[up_val];
                    });

                    update_val = userData.put(val);
                });

                update_val.onsuccess = (query) => {
                    tx.oncomplete = function () {
                        db.close();
                    };
                    //console.log("User update!");
                    resolve(userData);
                };
            };
        } else {
            resolve({});
        }
    });
}

async function delete_db(table, index, where) {
    return new Promise(async function (resolve, reject) {
        let get_result = await get_db(table, index, where);
        if (get_result.length > 0) {
            var request = init_db();
            request.onsuccess = function () {
                var db = request.result;
                var tx = db.transaction(table, "readwrite");
                var obj_table = tx.objectStore(table);
                var deleteUser = null;
                $.each(get_result, function (index, val) {
                    deleteUser = obj_table.delete(val.id);
                });
                deleteUser.onsuccess = (query) => {
                    tx.oncomplete = function () {
                        db.close();
                    };
                    console.log("deleted!");
                    resolve({});
                };
            };
        } else {
            resolve({});
        }
    });
}

async function a() {
    //console.log(await insert_db('bill_session_payment',{'session_id':1,'amount':1,'pay_via':'PAY','txn_id':'ss'}));
    //console.log(await get_db('bill_session_payment',"bspSessionId",1));
    //console.log(await get_db('bill_session_payment',"bspAmountPayVia",['PAY',1]));
    //console.log(await delete_db('bill_session_payment',"bspAmountPayVia",['PAY',1]));
    //console.log(await update_db('bill_session_payment',"bspAmountPayVia",['PAY',1],{amount:10}));
}
a();

async function manage_bill_session_id(sess_id, on_hold, bill_id) {
    //on_hold: 0-none,1-hold,2-unhold,3-completed
    if (on_hold > 0) {
        if (on_hold === 1 || on_hold === 3) {
            await update_db('bill_session', "bsSessionId", sess_id, {status: on_hold});
            var results = await get_db('bill_session', "", "");
            if (results.length > 0) {
                sess_id = parseFloat(results[results.length - 1].session_id);
                sess_id = ++sess_id;
            } else {
                sess_id = 1;
            }
        } else {
            apply_condition = {status: 3};
            await update_db('bill_session', "", "", {status: 1});
            await update_db('bill_session', "bsSessionId", sess_id, {status: 0});
        }
    }

    var results = await get_db('bill_session', "bsStatus", 0);
    if (results.length > 0) {
        session_id = parseFloat(results[results.length - 1].session_id);
        await load_all(session_id);
    } else {
        var results = await get_db('bill_session', "bsSessionId", sess_id);
        if (results.length > 0) {
            await update_db('bill_session', "bsSessionId", sess_id, {status: 0});
        } else {
            await insert_db('bill_session', {s_no: sess_id, date: formattedDate, session_id: sess_id, operator_id: operator_id, discount: 0, sales_man_id: 0, status: 0, bill_id: bill_id, bill_note: "", quotation_id: 0});
        }
        session_id = sess_id;
        await load_all(session_id);
    }
}

async function manage_bill_amount(sess_id, amount, min_amount, pay_via, txn_id, type, cc_id, is_load) {
    var results = await get_db('bill_session_payment', "bspSessionIdPayVia", [sess_id, pay_via]);
    if (type === "-") {
        await delete_db('bill_session_payment', "bspSessionIdAmountPayVia", [sess_id, amount, pay_via]);
    } else if (type === "+") {
        if (results.length > 0) {
            await update_db('bill_session_payment', "bspSessionIdPayVia", [sess_id, pay_via], {amount: results[0].amount + amount});
        } else {
            await insert_db('bill_session_payment', {'session_id': sess_id, 'amount': amount, 'min_amount': min_amount, 'pay_via': pay_via, 'txn_id': txn_id, cc_id: cc_id});
        }
    }

    if (is_load === 1) {
        await load_all(session_id);
    }
}

async function load_all(session_id) {
    $(".cart_items").html("");
    var results = await get_db('cart_item', "ciSessionId", session_id);
    $(".total_itme_cart").text("I : " + results.length);
    let total_quantity = 0;
    let total_amt = 0;
    let total_rate = 0;
    let total_vat = 0;

    let discount_flat = 0;
    if (results.length > 0) {
        //console.log(results);
        $.each(results, function (ind, item) {
            item.discount_price = 0;
            item.rate = parseFloat(item.regular_rate);
            let rate_with_qty = parseFloat(item.regular_rate * item.quantity);
            if (item.discount_type.toString() === "0") {//0-percent,1-flat
                item.discount_price = parseFloat(((rate_with_qty * item.discount) / 100).toFixed(2));
            } else if (item.discount_type.toString() === "1") {
                item.discount_price = parseFloat(item.discount);
            }

            item.discount_price > 0 ? item.final_discounted_price = rate_with_qty - item.discount_price : item.final_discounted_price = 0;

            item.vat_charge = 0;
            if (parseFloat(item.vat_percentage) > 0) {
                let calc_on_price = item.discount_price > 0 ? item.final_discounted_price : rate_with_qty;
                if (TAX_SETTING.sales_tax === "1") {
                    var gstRate = parseFloat(item.vat_percentage) / 100;
                    item.vat_charge = (calc_on_price / (1 + gstRate) * gstRate).toFixed(2);
                    item.final_discounted_price = calc_on_price - item.vat_charge;
                } else {
                    item.vat_charge = ((calc_on_price * parseFloat(item.vat_percentage)) / 100).toFixed(2);
                    item.final_discounted_price = calc_on_price;
                }
            }

            discount_flat += item.discount_price;
            total_vat += parseFloat(item.vat_charge);

            total_quantity += parseFloat(item.quantity);
            item.total = (rate_with_qty - (parseFloat(item.discount_price)) + (TAX_SETTING.sales_tax === "1" ? 0 : parseFloat(item.vat_charge))).toFixed(2);

            if (item.barcode.startsWith("9900")) {
                let bc_val = item.barcode.slice(7);
                bc_val = parseInt(bc_val);
                if (bc_val > 0) {
                    item.total = bc_val / 1000;
                    item.quantity = item.total / item.regular_rate;
                }
            }

            total_rate += parseInt(rate_with_qty);
            total_amt += parseFloat(item.total);
//            console.log(item);
            append_into_cart(item);
        });
    } else {
        await update_discount(0, 0);
    }
//    console.log("Total Rate: ",total_rate);
//    console.log("Total amt: ",total_amt);
//    console.log("Total vat: ",total_vat);
//    console.log("Total Discount Flat: ",discount_flat);

    if (PET_LIST.length > 0) {
        $(document).find(".pet_row").css({"display": "table-cell"});
        $(document).find("select.arabic-select").each(function () {
            jQuery("#" + $(this).attr("id")).multipleSelect({
                filter: true,
                filterAcceptOnEnter: true
            });
        });
    } else {
        $(document).find(".pet_row").css({"display": "none"});
    }

    let discount_percent = 0;
    let total_bill_discount = 0;

    results = await get_db('bill_session', "bsSessionId", session_id);
    let dis = results[0];

    let loyalty_points_used = parseFloat($("#remainingLoyaltyPoints").val()) > 0 ? parseFloat($("#remainingLoyaltyPoints").val()) : 0;
    if (loyalty_points_used > 0) {
        total_rate = total_rate - loyalty_points_used;
    }
//    console.log("loyalty_points_used: ",loyalty_points_used);
//    console.log("discount_flat: ",discount_flat);

    if (parseInt(dis.discount) > 0 || loyalty_points_used > 0) {
        if (dis.discount_type === "1") {//Flat
            total_bill_discount += parseFloat(dis.discount);
        } else {//Percent
            total_bill_discount += (((total_amt - (TAX_SETTING.sales_tax === "1" ? 0 : total_vat)) * parseInt(dis.discount)) / 100);
        }

        discount_flat += total_bill_discount;

        if(total_vat > 0){
            if (TAX_SETTING.sales_tax === "1") {
                var vat = 5 / 100;
                total_vat = (((total_rate - discount_flat)) / (1 + vat) * vat);
            } else {
                total_vat = ((((total_rate - discount_flat)) * 5) / 100);
                total_rate += total_vat;
            }
        }

        $(".total_bill_price").text((total_rate - discount_flat - total_vat).toFixed(2));
        $(".grand_total_bill_price").text((total_rate - discount_flat).toFixed(2));
        $(".total_vat_price").text(total_vat.toFixed(2));

        if (total_amt > 0 && discount_flat > 0) {
            //discount_percent = ((discount_flat) / (total_rate + loyalty_points_used - (TAX_SETTING.sales_tax === "1" ? 0 : discount_flat)) * 100).toFixed(2);
            discount_percent = ((discount_flat) / (total_rate + loyalty_points_used - (TAX_SETTING.sales_tax === "1" ? 0 : total_vat)) * 100).toFixed(2);
        }

        $(".bill_discount_percent").text(discount_percent);

        total_amt = total_rate - discount_flat - loyalty_points_used;
    } else {
        $(".total_bill_price").text((total_amt - total_bill_discount - total_vat).toFixed(2));
        $(".grand_total_bill_price").text((total_amt - total_bill_discount).toFixed(2));
        $(".total_vat_price").text(total_vat.toFixed(2));

        if (total_amt > 0 && discount_flat > 0) {
            discount_percent = ((discount_flat) / ((total_amt - total_bill_discount)) * 100).toFixed(2);
        }

        $(".bill_discount_percent").text(discount_percent);

        total_amt = total_amt - total_bill_discount - loyalty_points_used;
    }
    $(".bill_discount_flat").text(discount_flat.toFixed(2));
    $(".total_quantity_cart").text("Q : " + total_quantity);

    customer_paid_cash = 0;
    var payments = await get_db('bill_session_payment', "bspSessionId", session_id);
    let html = '';
    if (payments.length > 0) {
        $.each(payments, function (index, val) {
            customer_paid_cash += parseFloat(val.amount);
            html += `<tr class="pay_row" min_amt="` + val.min_amount + `" style="font-size: 1.3rem;font-weight: 600;">
                        <td style="padding:0">` + val.pay_via + `</td>
                        <td style="padding:0">` + val.amount + `</td>
                    </tr>`;
        });
    }
    $(".payment_entries").html(html);

    if (customer_paid_cash > 0) {
        $(".customer_total_paid").text(customer_paid_cash);
        customer_paid_cash - total_amt > 0 ? $(".customer_total_cash").text((customer_paid_cash - total_amt).toFixed(2)) : $(".customer_total_cash").text("00.00");
        total_amt - customer_paid_cash > 0 ? $("#customer_paid_cash").val(total_amt - customer_paid_cash) : "";
    } else {
        $(".customer_total_paid,.customer_total_cash").text("00.00");
    }
}

async function add_update_cart(meta, is_load) {
    var results = await get_db('cart_item', "ciSessionIdItemId", [session_id, meta.id]);
    if((results.length && results[0].barcode.startsWith("9900") || (meta.id.toString() === "0"))){
        results = [];
    }
    if (results.length > 0) {
        await update_db('cart_item', "ciSessionIdItemId", [session_id, meta.id], {quantity: results[0].quantity + 1});
        //console.log(results);
    } else {
        price = parseFloat(meta.regular_rate);
        await insert_db('cart_item', {item_id: meta.id, name: meta.name, item_code: meta.item_code, barcode: meta.barcode, quantity: meta.quantity, regular_rate: price, purchase_rate: meta.purchase_rate, session_id: session_id, vat_percentage: meta.vat_percentage, discount_type: 0, discount: 0, minimal_sales_rate: meta.minimal_sales_rate, pet_id: meta.pet_id, groomer_id: meta.groomer_id});
    }
    if (is_load === 1) {
        await load_all(session_id);
    }
}

$(".clear_cart_items").click(async function () {
    if (!confirm("Are you sure want to delete item that is added in cart?")) {
        return false;
    }
    await delete_db('cart_item', "ciSessionId", session_id);
    await delete_db('bill_session_payment', "bspSessionId", session_id);
    await update_discount(0, 0);
    await load_all(session_id);
    load_pets("");
    hide_show_btns("1");
    $("#search_cus_mobile").val("");
    $("#search_cus_mobile").parent().siblings("input").val("");
    $("#search_cus_mobile").parent().siblings("label.cus").css({display: "none"});
    $("#search_cus_mobile").parent().siblings("label.cus").text("");
    $("input[name=discount_code]").val("");
    $("#customer_paid_cash").val("0.00");
});

$(document).on("click", ".add_item_to_cart", async function () {
    let meta = $(this).attr("meta");
    meta = JSON.parse(decodeURIComponent(atob(meta)));
    //console.log(meta);
    $("input[name=search_products]").val("");
    $(".add_item_to_cart").css({display: "block"});
    await add_update_cart(meta, 1);
});

$(".select_sales_man").click(async function () {
    let sales_man_id = $(this).data("id");
    await update_db('bill_session', "bsSessionId", session_id, {sales_man_id: sales_man_id});

    $("#salesManModal").find('.modal-footer').find('button').click();
});

$(document).on('keyup input', '.update_quantity', async function () {
    let item_id = $(this).attr("item_id");
    add_active_on_item = item_id;
    let val = $(this).val();
    if (val > 0) {
        await update_db('cart_item', "ciSessionIdItemId", [session_id, item_id], {quantity: val});
    } else {
        await delete_db('cart_item', "ciSessionIdItemId", [session_id, item_id]);
    }
    await load_all(session_id);
});

$(document).on('click', '.update_quantity_alt', async function () {
    let is_active_tr = $(".cart_items tr.active");
    if (is_active_tr.length > 0) {
        let item_id = is_active_tr.attr("item_id");
        add_active_on_item = item_id;
        let val = is_active_tr.find("input").val();
        $(this).hasClass("plus") ? ++val : --val;
        if (val > 0) {
            await update_db('cart_item', "ciSessionIdItemId", [session_id, item_id], {quantity: val});
        } else {
            await delete_db('cart_item', "ciSessionIdItemId", [session_id, item_id]);
        }
        await load_all(session_id);
    }
});

$(document).on('click', '.delete_item_alt', async function () {
    let is_active_tr = $(".cart_items tr.active");
    if (is_active_tr.length > 0) {
        let item_id = is_active_tr.attr("item_id");
        await delete_db('cart_item', "ciSessionIdItemId", [session_id, item_id]);
        await load_all(session_id);
    }
});

$(document).on('click', '.arrow_alt', async function () {
    let is_active_tr = $(".cart_items tr.active");
    if (is_active_tr.length > 0) {
        if ($(this).hasClass("down")) {
            if (($(".cart_items tr").length - 1) > (is_active_tr.index())) {
                is_active_tr.removeClass("active");
            }
            is_active_tr.next().addClass("active");
        } else {
            if (is_active_tr.index() > 0) {
                is_active_tr.removeClass("active");
            }
            is_active_tr.prev().addClass("active");
        }
    } else {
        $(".cart_items tr:first-child").addClass("active");
    }
});

$(document).on("change", ".arabic_select", async function () {
    let val = $(this).val();
    if (val !== "") {
        await update_db('cart_item', "ciSessionIdItemId", [session_id, $(this).attr("item_id")], {pet_id: val});
    }
});

$(document).on("change", ".groomer_select", async function () {
    let val = $(this).val();
    if (val !== "") {
        await update_db('cart_item', "ciSessionIdItemId", [session_id, $(this).attr("item_id")], {groomer_id: val});
    }
});

$(document).on('click', '.confirm-delete', async function () {
    let item_id = $(this).attr("item_id");
    $(this).parent().parent().parent().remove();
    await delete_db('cart_item', "ciSessionIdItemId", [session_id, item_id]);
    await load_all(session_id);
});

$("#hold_bill").click(function () {
    manage_bill_session_id(session_id, 1, 0);
    Swal.fire("Your Bill Holded Successfully.");
});

$(".search_text").keyup(function (e) {
    let selector = $(this);
    let search_type = $(this).prev().val();
    if (selector.val() === "") {
        return false;
    }
    if (e.keyCode === 13) {
        if(search_type === "1" && selector.val().length == 0){
            Swal.fire("Please enter valid barcode");
            return;
        }
        $.ajax({
            "url": BASE_URL + "web/pos/search_product",
            "method": "POST",
            "dataType": "JSON",
            "data": {
                search: selector.val(),
                search_type: search_type
            },
            success: async function (data) {
                if (data.length > 0) {
                    selector.val("");
                    if (search_type === "1") {
                        let meta = filter_payload_db(data[0]);
                        await add_update_cart(meta, 1);
                    } else {
                        let html = ``;
                        $.each(data, function (ind, val) {
                            html += `<tr style='cursor:pointer;' class='select_product' meta="` + btoa(JSON.stringify(filter_payload_db(val))) + `">
                                        <th scope="row">` + val.name + `</th>
                                        <td>` + val.barcode + `</td>
                                        <td>` + val.purchase_rate + `</td>
                                        <td>` + val.regular_rate + `</td>
                                        <td>` + val.unit + `</td>
                                    </tr>`;
                            //html += `<option value="` + val.name + `" meta="` + btoa(JSON.stringify(filter_payload_db(val))) + `">`;
                        });
                        //$("#browsers").html(html);
                        $("#productListModal").find("tbody").html(html);
                        $("#productListModal").css({display: "block"});
                        $("#productListModal").addClass("show");
                    }
                } else {
                    alert("No product found.");
                }
            }
        });
    } else {
        $.each($("#browsers option"), async function () {
            let selector = $(this);
            if (selector.val() === selector.attr("value")) {
                let meta = $(this).attr("meta");
                meta = JSON.parse(atob(meta));
                await add_update_cart(meta, 1);
            }
        });
    }
});

$(document).on("click", ".select_product", async function () {
    let meta = $(this).attr("meta");
    meta = JSON.parse(atob(meta));
    await add_update_cart(meta, 1);
    hide_product_list_modal();
});

function hide_product_list_modal() {
    $("#productListModal").css({display: "none"});
    $("#productListModal").removeClass("show");
}

$(".recall_holded_bill").click(async function () {
    var results = await get_db('bill_session', "", {});
    if (results.length > 0) {
        let html = ``;
        for (var [ind, val] of results.entries()) {
            if (val.status < 3) {
                let action = "";
                let status = "";
                switch (val.status) {
                    case 0:
                        status = `<span class='badge badge-success'>Running</span>`;
                        action = `--`;
                        break;
                    case 1:
                        status = `<span class='badge badge-warning'>On Hold</span>`;
                        action = `<button class='btn btn-info btn-sm reactivate_bill' session_id='` + val.session_id + `'>Activate</button>`;
                        break;
                    default:
                        status = `<span class='badge badge-success'>Processed</span>`;
                        action = ``;
                        break;
                }
                
                var c_results = await get_db('cart_item', "ciSessionId", val.session_id);
                let total_amt = 0;
                let total_rate = 0;
                let total_vat = 0;

                let discount_flat = 0;
                if (c_results.length > 0) {
                    //console.log(c_results);
                    $.each(c_results, function (ind, item) {
                        item.discount_price = 0;
                        item.rate = parseFloat(item.regular_rate);
                        let rate_with_qty = parseFloat(item.regular_rate * item.quantity);
                        if (item.discount_type.toString() === "0") {//0-percent,1-flat
                            item.discount_price = parseFloat(((rate_with_qty * item.discount) / 100).toFixed(2));
                        } else if (item.discount_type.toString() === "1") {
                            item.discount_price = parseFloat(item.discount);
                        }

                        item.discount_price > 0 ? item.final_discounted_price = rate_with_qty - item.discount_price : item.final_discounted_price = 0;

                        item.vat_charge = 0;
                        if (parseFloat(item.vat_percentage) > 0) {
                            let calc_on_price = item.discount_price > 0 ? item.final_discounted_price : rate_with_qty;
                            if (TAX_SETTING.sales_tax === "1") {
                                var gstRate = parseFloat(item.vat_percentage) / 100;
                                item.vat_charge = (calc_on_price / (1 + gstRate) * gstRate).toFixed(2);
                                item.final_discounted_price = calc_on_price - item.vat_charge;
                            } else {
                                item.vat_charge = ((calc_on_price * parseFloat(item.vat_percentage)) / 100).toFixed(2);
                                item.final_discounted_price = calc_on_price;
                            }
                        }

                        discount_flat += item.discount_price;
                        total_vat += parseFloat(item.vat_charge);

                        item.total = (rate_with_qty - (parseFloat(item.discount_price)) + (TAX_SETTING.sales_tax === "1" ? 0 : parseFloat(item.vat_charge))).toFixed(2);
                        total_rate += parseInt(rate_with_qty);
                        total_amt += parseFloat(item.total);
                    });
                }

                let total_bill_discount = 0;

                let dis = val;

                let loyalty_points_used = parseFloat($("#remainingLoyaltyPoints").val()) > 0 ? parseFloat($("#remainingLoyaltyPoints").val()) : 0;
                if (loyalty_points_used > 0) {
                    total_rate = total_rate - loyalty_points_used;
                }
            //    console.log("loyalty_points_used: ",loyalty_points_used);
            //    console.log("discount_flat: ",discount_flat);

                if (parseInt(dis.discount) > 0 || loyalty_points_used > 0) {
                    if (dis.discount_type === "1") {//Flat
                        total_bill_discount += parseFloat(dis.discount);
                    } else {//Percent
                        total_bill_discount += (((total_amt - (TAX_SETTING.sales_tax === "1" ? 0 : total_vat)) * parseInt(dis.discount)) / 100);
                    }

                    discount_flat += total_bill_discount;

                    if(total_vat > 0){
                        if (TAX_SETTING.sales_tax === "1") {
                            var vat = 5 / 100;
                            total_vat = (((total_rate - discount_flat)) / (1 + vat) * vat);
                        } else {
                            total_vat = ((((total_rate - discount_flat)) * 5) / 100);
                            total_rate += total_vat;
                        }
                    }

//                    $(".total_bill_price").text((total_rate - discount_flat - total_vat).toFixed(2));
//                    $(".grand_total_bill_price").text((total_rate - discount_flat).toFixed(2));
//                    $(".total_vat_price").text(total_vat.toFixed(2));
                }
                
                html += `<tr>
                            <th scope="row">` + (ind + 1) + `</th>
                            <td>` + val.session_id + `</td>
                            <td>` + val.date + `</td>
                            <td>` + total_vat.toFixed(2) + `</td>
                            <td>` + (total_rate - discount_flat).toFixed(2) + `</td>
                            <td>` + val.operator_id + `</td>
                            <td>` + status + `</td>
                            <td>` + action + `</td>
                        </tr>`;
            }
        }
        $("#recallModal tbody").html(html);
        $("#recallModal #recallModalLabel").html("Re-call Modal");
    }
});

$(document).on("click", ".reactivate_bill", function () {
    manage_bill_session_id(parseInt($(this).attr("session_id")), 2, 0);
    $(".close_recallModel").click();
});

$(".recall_completed_bill,#btn_customer_filter").click(async function () {
    $("#btn_customer_filter").removeClass('is_quotation');
    if($(this).hasClass("recall_completed_bill") && $(this).hasClass("is_quotation")){
        $("#btn_customer_filter").addClass('is_quotation');
    }
    let modal = $("#salesModal");
    let is_quotation = $(this).hasClass("is_quotation") ? "1" : "0";
    is_quotation ? $("#btn_customer_filter").addClass("is_quotation") : $("#btn_customer_filter").removeClass("is_quotation");
    $.ajax({
        url: BASE_URL + 'web/pos/recall_payments',
        dataType: 'JSON',
        type: 'POST',
        data: {
            date_from: startDate,
            date_to: endDate,
            cus_name: modal.find("input[name=name]").val(),
            cus_mobile: modal.find("input[name=mobile]").val(),
            is_quotation: is_quotation
        },
        success: function (data) {
            //console.log(data);
            let html = ``;
            let dataSource = [];
            $.each(data, function (ind, val) {
                let action = "";
                let status = "";
                //console.log(val.status);
                switch (val.sale_status) {
                    case 0:
                    case '0':
                        status = `<span class='badge badge-success'>Completed</span>`;
                        action = `<button class='btn btn-info btn-sm reactivate_c_bill' is_quotation='` + is_quotation + `' bill_id='` + val.id + `'>Activate</button>`;
                        break;
                    default:
                        status = `<span class='badge badge-success'>Processed</span>`;
                        action = ``;
                        break;
                }
                html += `<tr>
                            <th scope="row">` + (ind + 1) + `</th>
                            <td>` + action + `</td>
                            <td>` + val.invoice_no + `</td>
                            <td>` + val.invoice_date + `</td>
                            <td>` + val.cus_name + `</td>
                            <td>` + val.cus_mobile + `</td>
                            <td>` + val.username + `</td>
                        </tr>`;
                dataSource.push([
                    ind + 1, 
                    action,
                    val.invoice_no, 
                    val.invoice_date, 
                    val.cus_name, 
                    val.cus_mobile, 
                    val.username, 
                    //status, 
                ]);
            });
            if (salesModalTable === null) {
                $("#salesModalTable").html(html);
            } else {
                salesModalTable.clear();
                salesModalTable.rows.add(dataSource);
                salesModalTable.draw();
            }
            $("#salesModal #salesModalLabel").html(parseInt(is_quotation) > 0 ? "Quotation List" : "Sales List");
        }
    });
});

$(".sales_return").click(async function () {
    let modal = $("#salesModal");
    let sales_return = 1;
    let is_quotation = "0";
    $.ajax({
        url: BASE_URL + 'web/pos/recall_payments',
        dataType: 'JSON',
        type: 'POST',
        data: {
            date_from: startDate,
            date_to: endDate,
            cus_name: modal.find("input[name=name]").val(),
            cus_mobile: modal.find("input[name=mobile]").val(),
            sales_return: sales_return 
        },
        success: function (data) {
            //console.log(data);
            let html = ``;
            let dataSource = [];
            $.each(data, function (ind, val) {
                let action = "";
                let status = "";
                //console.log(val.status);
                switch (val.sale_status) {
                    case 0:
                    case '0':
                        status = `<span class='badge badge-success'>Completed</span>`;
                        action = `<button class='btn btn-info btn-sm reactivate_c_bill' is_quotation='` + is_quotation + `' bill_id='` + val.id + `'>Activate</button>`;
                        action = `<a href="` + BASE_URL + 'web/pos/return_sale?id=' + val.id + `" class='btn btn-info btn-sm'>Return Sale</a>`;                        
                        break;
                    default:
                        status = `<span class='badge badge-success'>Processed</span>`;
                        action = ``;
                        break;
                }

                html += `<tr>
                            <th scope="row">` + (ind + 1) + `</th>
                            <td>` + action + `</td>
                            <td>` + val.invoice_no + `</td>
                            <td>` + val.invoice_date + `</td>
                            <td>` + val.cus_name + `</td>
                            <td>` + val.cus_mobile + `</td>
                            <td>` + val.username + `</td>
                        </tr>`;
                dataSource.push([
                    ind + 1, 
                    action, 
                    val.invoice_no, 
                    val.invoice_date, 
                    val.cus_name, 
                    val.cus_mobile, 
                    val.username, 
                    //status
                ]);
            });
            

            if (salesModalTable === null) {
                $("#salesModalTable").html(html);
            } else {
                salesModalTable.clear();
                salesModalTable.rows.add(dataSource);
                salesModalTable.draw();
            }
        }
    });
});

function hide_show_btns(is_quotation) {
    if(is_quotation === "0") {
        $(".btn-quickcash,.btn-quickcard,.settle-as-credit-cus").css({display: 'none'});
    } else {
        $(".btn-quickcash,.btn-quickcard,.settle-as-credit-cus").css({display: 'block'});
    }
}

$(document).on("click", ".reactivate_c_bill", function () {
    let selector = $(this);
    let is_quotation = selector.attr("is_quotation");
    hide_show_btns(is_quotation);
    
    let bill_id = selector.attr("bill_id");
    $.ajax({
        url: BASE_URL + 'web/pos/recall_payments',
        dataType: 'JSON',
        type: 'POST',
        data: {
            bill_id: bill_id,
            is_quotation: is_quotation
        },
        success: async function (data) {
            if(is_quotation === "1"){
                data.id = 0;
            }
            var results = await get_db('bill_session', "bsStatus", 0);
            let is_loaded = false;
            if (results.length > 0) {
                $.each(results, async function (k_ind, k_val) {
                    if (k_val.bill_id === bill_id) {
                        is_loaded = true;
                        session_id = k_val.session_id;
                        await load_all(session_id);
                    } else {
                        await manage_bill_session_id(k_val.session_id, 3, 0);
                    }
                });
            }

            if (is_loaded === false) {
                results = await get_db('bill_session', "bsStatus", 0);
                if (results.length > 0) {
                    session_id = parseFloat(results[results.length - 1].session_id);
                    session_id = ++session_id;
                } else {
                    session_id = 1;
                }
                await manage_bill_session_id(session_id, -1, data.id);
                $.each(data.items, async function (ind, meta) {
                    let payload = filter_payload_db(meta);
                    await add_update_cart(payload, 0);
                });
            }
            await update_db('bill_session', "bsSessionId", session_id, {discount_type: parseFloat(data.discount_type) > 1 ? '0' : '1', discount: parseFloat(data.discount_type), quotation_id: bill_id});
            setTimeout(async function () {
                if (data.payments.length > 0) {
                    $.each(data.payments, async function (ind, meta) {
                        await manage_bill_amount(session_id, parseFloat(meta.amount), parseFloat(meta.amount), meta.pay_via, "", "+", 0, 0);
                    });

                    setTimeout(async function () {
                        await load_all(session_id);
                    }, 500);
                } else {
                    await load_all(session_id);
                }
            }, 500);
            
            let item = data.cus_data;
            $("input[name=customer_id]").next("label.cus").css({display: 'block'});
            $("input[name=customer_id]").next("label.cus").text(item.name);
            USER_INFO = item;
            $("#cus_id,input[name=customer_id]").val(item.id);
            $("#assignedLoyaltyPoints").val(item.loyalty_points);
            $("#search_cus_mobile").val(item.mobile);
            
            $("#completedModal button.close").click();
            $("#salesModal button.close").click();
        }
    });
});

$("#search_cus_mobile1").keyup(function (e) {
    let selector = $(this);

    selector.parent().siblings("input").val("");
    selector.parent().siblings("label.cus").css({display: "none"});
    $(".credit-customer-f6").removeClass("disabled");

    let val = selector.val();
    if (e.keyCode === 13 && val !== "") {
        $.ajax({
            "url": BASE_URL + "web/pos/search_customer",
            "method": "POST",
            "dataType": "JSON",
            "data": {
                mobile: val,
                user_type: "0"
            },
            success: function (data) {
                if (data.customers) {
                    if (data.customers.length > 0) {
                        $("#customerModal").css({display: "block"});
                        $("#customerModal").addClass("show");

                        let html = "";
                        $.each(data.customers, function (k_ind, k_val) {
                            html += `<tr>`;
                            html += `<td>${k_ind + 1}</td>`;
                            html += `<td>${k_val.name}</td>`;
                            html += `<td>${k_val.email}</td>`;
                            html += `<td>${k_val.mobile}</td>`;
                            html += `<td><button class="btn btn-info btn-sm select_customer" meta="${btoa(JSON.stringify(k_val))}">Select</button></td>`;
                            html += `</tr>`;
                        });
                        $("#customerModal").find("tbody").html(html);
                    } else {
                        load_pets("0");
                        selector.parent().siblings("label.cus").css({display: "block"});
                        selector.parent().siblings("label.cus").text("Customer not found. Please add new one.");
                    }
                } else if (Object.keys(data.customer).length > 0) {
                    $(".credit-customer-f6").addClass("disabled");
                    USER_INFO = data.customer;
                    selector.parent().siblings("input").val(USER_INFO.id);
                    selector.parent().siblings("label.cus").css({display: "block"});
                    selector.parent().siblings("label.cus").text("Customer Name: " + USER_INFO.name);
                    load_pets(USER_INFO.id);
                } else {
                    load_pets("");
                    selector.parent().prev().find("span").click();
                    $("#add_customer").find("input[name=mobile]").val(val);
                    $("#add_customer").find("input[name=file_code]").val(data.cus_next_id);
                    selector.parent().siblings("label.cus").css({display: "block"});
                    selector.parent().siblings("label.cus").text("Customer not found. Please add new one.");
                }
            }
        });
    }
});

function hide_customer_modal() {
    $("#customerModal").css({display: "none"});
    $("#customerModal").removeClass("show");
}

$(document).on('click', '.select_customer', function () {
    let meta = JSON.parse(atob($(this).attr("meta")));
    USER_INFO = {id: meta.id, name: meta.name};
    let selector = $("#search_cus_mobile");
    selector.parent().siblings("input").val(USER_INFO.id);
    selector.parent().siblings("label.cus").css({display: "block"});
    selector.parent().siblings("label.cus").text("Customer Name: " + USER_INFO.name);
    load_pets(USER_INFO.id);
    hide_customer_modal();
});

$(".choosecustomer_btn").click(function () {
    $.ajax({
        "url": BASE_URL + "web/pos/search_customer",
        "method": "POST",
        "dataType": "JSON",
        "data": {
            mobile: "12345412345",
            user_type: "0"
        },
        success: function (data) {
            if (Object.keys(data.customer).length > 0) {
                $(".credit-customer-f6").addClass("disabled");
                load_pets(USER_INFO.id);
            } else {
                load_pets("");
                $("#add_customer").find("input[name=file_code]").val(data.cus_next_id);
            }
        }
    });
});

$("#add_customer").submit(function (e) {
    e.preventDefault();
    let form = $(this);

    let payload = {};
    form.find("input").each(function () {
        let attr_name = $(this).attr("name");
        if (attr_name) {
            payload[attr_name] = $(this).val();
        }
    });

    form.find("select").each(function () {
        let attr_name = $(this).attr("name");
        if (attr_name) {
            payload[attr_name] = $(this).val();
        }
    });

    if (payload.name === "") {
        form.find("input[name=name]").parent().prev().find("span.error").text("* Mandatory");
        setTimeout(function () {
            form.find("input[name=name]").parent().prev().find("span.error").text("*");
        }, 1500);
        return false;
    }
    
    if (payload.l_name === "" && is_gtr === "0") {
        form.find("input[name=l_name]").parent().prev().find("span.error").text("* Mandatory");
        setTimeout(function () {
            form.find("input[name=l_name]").parent().prev().find("span.error").text("*");
        }, 1500);
        return false;
    }
    if (payload.mobile === "" && is_gtr === "0") {
        form.find("input[name=mobile]").parent().prev().find("span.error").text("* Mandatory");
        setTimeout(function () {
            form.find("input[name=mobile]").parent().prev().find("span.error").text("*");
        }, 1500);
        return false;
    }

    $.ajax({
        url: BASE_URL + "web/pos/add_customer",
        method: "POST",
        dataType: "JSON",
        data: payload,
        success: function (data) {
            if (data.status === false) {
                Swal.fire(data.message);
            } else {
                data = data.user;
                USER_INFO = data;
                $("#search_cus_mobile").parent().siblings("input").val(data.id);
                $("#search_cus_mobile").parent().siblings("label.cus").css({display: "block"});
                $("#search_cus_mobile").parent().siblings("label.cus").text("Customer Name: " + data.name);
                $("#choosecustomer").find("button.close").click();
                form.find("input").val("");
                load_pets(data.id);
            }
        }
    });
});

$(document).on("keypress", ".number", function (event) {
    var charCode = (event.which) ? event.which : event.keyCode;
    var inputValue = $(this).val();

    // Allow decimal point, backspace, and delete keys
    if (charCode == 8 || charCode == 0) {
        return;
    }

    // Allow only digits
    if (charCode != 46 && (charCode < 48 || charCode > 57)) {
        event.preventDefault();
    }

    // Allow only one decimal point
    if (inputValue.indexOf('.') !== -1) {
        if (charCode == 46) {
            event.preventDefault();
        }
    }
});

async function update_discount(discount_type, discount) {
    await update_db('bill_session', "bsSessionId", session_id, {discount_type: discount_type, discount: discount});
    await update_db('cart_item', "ciSessionId", session_id, {discount_type: discount_type, discount: discount});
}

$(document).ready(async function () {
    await manage_bill_session_id(1, 0, 0);
    await update_discount(0, 0);
    //await load_all(session_id);
    await manage_bill_session_id(session_id, 0, 0);
});

$(".apply_discount_modal").click(async function () {
    let selector = $(this);
    let type = selector.parent().parent().prev().find("select").val();
    let value = selector.parent().parent().prev().find("input").val();
    if (value !== "") {
        if (type === "0" && parseFloat(value) > 100) {
            alert("Invalid discount percent entered.");
            return false;
        } else if (type === "0" && parseFloat(value) > parseInt(max_discount_percent)) {
            alert("You are not allowed to provide discount more than " + max_discount_percent + ".");
            return false;
        } else if (type === "1" && parseFloat(value) > parseInt(max_discount_percent)) {
            alert("You are not allowed to provide discount more than " + max_discount_percent + ".");
            return false;
        }
        await update_db('bill_session', "bsSessionId", session_id, {discount_type: type, discount: value});
        await load_all(session_id);
    }
});

$(".btn-billdiscount").click(async function () {
    var results = await get_db('bill_session', "bsSessionId", session_id);
    let row = results[0];
    row.discount !== null ? $("#bill_discount_modal").find("select").val(row.discount_type) : "";
    row.discount !== null ? $("#bill_discount_modal").find("input").val(row.discount) : "";
});

function getBrowserType() {
    const test = regexp => {
        return regexp.test(navigator.userAgent);
    };

    if (test(/opr\//i) || !!window.opr) {
        return 'Opera';
    } else if (test(/edg/i)) {
        return 'Microsoft Edge';
    } else if (test(/chrome|chromium|crios/i)) {
        return 'Google Chrome';
    } else if (test(/firefox|fxios/i)) {
        return 'Mozilla Firefox';
    } else if (test(/safari/i)) {
        return 'Apple Safari';
    } else if (test(/trident/i)) {
        return 'Microsoft Internet Explorer';
    } else if (test(/ucbrowser/i)) {
        return 'UC Browser';
    } else if (test(/samsungbrowser/i)) {
        return 'Samsung Browser';
    } else {
        return 'Unknown browser';
    }
}

$(".btn-quickcash").click(async function () {
    let bill_session_payment = await get_db('bill_session_payment', "bspSessionId", session_id);

    let paid_amt = 0;
    $.each(bill_session_payment, function (ind, val) {
        paid_amt += parseFloat(val.amount);
    });
    let to_be_amt = parseFloat($(".grand_total_bill_price:eq(0)").text());
    manage_bill_amount(session_id, to_be_amt - paid_amt, 0, $(".cash-f1").attr("title"), "", "+", 0, 1);
    $(".btn-completesale").click();
});

$(".btn-quickcard").click(async function () {
    let bill_session_payment = await get_db('bill_session_payment', "bspSessionId", session_id);

    let paid_amt = 0;
    $.each(bill_session_payment, function (ind, val) {
        paid_amt += parseFloat(val.amount);
    });
    let to_be_amt = parseFloat($(".grand_total_bill_price:eq(0)").text());
    manage_bill_amount(session_id, to_be_amt - paid_amt, 0, $(".credit-card-f3").attr("title"), "", "+", 0, 1);
    $(".btn-completesale").click();
});

$(".btn-completesale").click(async function () {
    if (Object.keys(USER_INFO).length === 0) {
        USER_INFO = {
            id: 0
        }
    }
//    if (!confirm("Are you sure want to complete this order")) {
//        return false;
//    }

    let cart_items = await get_db('cart_item', "ciSessionId", session_id);
    let bill_session = await get_db('bill_session', "bsSessionId", session_id);
    let bill_session_payment = await get_db('bill_session_payment', "bspSessionId", session_id);
    let customer_total_cash = $(".customer_total_cash").text();

    let paid_amt = 0;
    $.each(bill_session_payment, function (ind, val) {
        paid_amt += parseFloat(val.amount);
    });
    let to_be_amt = parseFloat($(".grand_total_bill_price:eq(0)").text());
    if (paid_amt < to_be_amt) {
        Swal.fire("Grand total is less than payment mode, Please add payment.");
        return false;
    }

    if (bill_session_payment.length > 0) {
        let credit_card_exist = false;
        $.each(bill_session_payment, function (ind, val) {
            if (credit_card_exist === false && val.pay_via === "Credit Card") {
                credit_card_exist = true;
            }
        });
        if (credit_card_exist === true && parseFloat(customer_total_cash) > 0) {
            Swal.fire("Change not allowed with card payment.");
            return false;
        }
    }

    let payload = {
        bill_session: bill_session,
        cart_items: cart_items,
        appointment_id: APPOINTMENT_ID,
        bill_session_payment: bill_session_payment,
        user_info: USER_INFO,
        change: customer_total_cash,
        till_id: getBrowserType(),
        bill_discount_percent: $(".bill_discount_percent:eq(0)").text(),
        bill_discount_flat: $(".bill_discount_flat:eq(0)").text(),
        sub_total: $(".total_bill_price:eq(0)").text(),
        total_vat: $(".total_vat_price:eq(0)").text(),
        redeem_points: $("#remainingLoyaltyPoints").val()
    };

    $.ajax({
        url: BASE_URL + "web/pos/complete_order",
        method: "POST",
        dataType: "JSON",
        data: payload,
        success: async function (data) {
            await update_db('bill_session', "bsSessionId", session_id, {status: 2});
            //await delete_db('cart_item', "ciSessionId", session_id);
            //await delete_db('bill_session', "bsSessionId", session_id);
            //await delete_db('bill_session_payment', "bspSessionId", session_id);

            USER_INFO = {};
            $("#search_cus_mobile").parent().siblings("input").val("");
            $("#search_cus_mobile").parent().siblings("label.cus").css({display: "none"});
            $("#search_cus_mobile").parent().siblings("label.cus").text("");

            setTimeout(function () {
                manage_bill_session_id(session_id, 3, 0);
                localStorage.setItem("last_inv_no", data.invoice_no);
                if (PRINT_TYPE === "4") {
                    $("#chooseReceiptModal").find("input[name=status]").val(data.insert_billing_id);
                    $("#chooseReceiptModal").css({display: "block"});
                    $("#chooseReceiptModal").addClass("show");
                } else {
                    window.location.href = BASE_URL + "web/pos/receipt?bill_id=" + data.insert_billing_id;
                }
            }, 200);
        }
    });
});

$(".submit_print_type").click(function () {
    let modal = $("#chooseReceiptModal");
    window.location.href = BASE_URL + "web/pos/receipt?bill_id=" + modal.find("input[name=status]").val() + "&receipt=" + $(this).attr("type");
});

$("#close_register_form").submit(async function () {
    await delete_db('cart_item', "", "");
    await delete_db('bill_session', "", "");
    await delete_db('bill_session_payment', "", "");
});

$(".num-pad").click(function () {
    $("#customer_paid_cash").val() === "0.00" ? $("#customer_paid_cash").val("") : "";
    $("#customer_paid_cash").val($("#customer_paid_cash").val() + $(this).text());
});

$(".num-pad-add").click(function () {
    $("#customer_paid_cash").val(parseFloat($("#customer_paid_cash").val()) + parseInt($(this).text()));
});

$("input[name=search_products]").keyup(function () {
    load_items($(".tbl_category").val(), 1, 1);
});

$(".btn-ce").click(function () {
    $("#customer_paid_cash").val("0.00");
});

$(".btn-dot").click(function () {
    if (!$("#customer_paid_cash").val().includes(".")) {
        $("#customer_paid_cash").val($("#customer_paid_cash").val() + ".");
    }
});

$(".btn-clear").click(function () {
    $("#customer_paid_cash").val("0.00");
});

$(document).on("click", ".cash-f1,.credit-card-f3,.debit-card-f4,.wallet-f5,.loylaty-card-f7,.select_cc_customer", function () {
    if ($("#customer_paid_cash").val() === "0.00") {
        $("#customer_paid_cash").val($(".grand_total_bill_price").text());
    }
    if ($("#customer_paid_cash").val() !== "" && parseFloat($("#customer_paid_cash").val()) > 0) {
        let cc_id = $(this).attr("_id");
        if (cc_id === undefined) {
            cc_id = 0;
        }
        manage_bill_amount(session_id, parseFloat($("#customer_paid_cash").val()), 0, $(this).attr("title"), "", "+", cc_id, 1);
        $("#customer_paid_cash").val("0.00");
    }
});

$(document).on("click", ".add_loyalty_point", function () {
    if ($("#remainingLoyaltyPoints").val() !== "" && parseFloat($("#remainingLoyaltyPoints").val()) > -1) {
        if (parseFloat($("#remainingLoyaltyPoints").val()) > parseFloat($("#assignedLoyaltyPoints").val())) {
            $("#remainingLoyaltyPoints").val($("#assignedLoyaltyPoints").val());
            Swal.fire("Customer have not sufficients points: " + $("#remainingLoyaltyPoints").val());
        } else {
            load_all(session_id);
//            let cc_id = 0;
//            manage_bill_amount(session_id, parseFloat($("#remainingLoyaltyPoints").val()), 0, $(this).attr("title"), "", "+", cc_id, 1);
//            $("#remainingLoyaltyPoints").val("0.00");
        }
    }
});

$(".btn-remove-f10").click(function () {
    if ($(document).find(".pay_row.active").length > 0) {
        let attr = $(document).find(".pay_row.active");
        let min_amt = parseFloat(attr.attr("min_amt"));
        let amt = parseFloat(attr.find("td:eq(1)").text());
        if (min_amt > 0) {
            manage_bill_amount(session_id, min_amt - amt, min_amt, attr.find("td:eq(0)").text(), "", "+", "0", 1);
        } else {
            manage_bill_amount(session_id, amt, min_amt, attr.find("td:eq(0)").text(), "", "-", "0", 1);
        }
    }
});

function loadCreditCustomerList() {
    $.ajax({
        url: BASE_URL + "web/pos/ajax_credit_customers_list",
        type: "POST",
        dataType: "JSON",
        data: {
            search: $("#creditCustomerSearch").val()
        }, success: function (data) {
            let html = "";
            $.each(data.data, function (ind, val) {
                html += `<tr>`;
                $.each(Object.keys(val), function (k_ind, k_val) {
                    html += `<td>${val[k_val]}</td>`;
                });
                html += `</tr>`;
            });
            $("#creditCustomerLists").find("tbody").html(html);
        }
    });
}

$("#creditCustomerSearch").on("input", function () {
    loadCreditCustomerList();
});

$(".credit-customer-f6").click(function () {
    let selector = $(this);
    if (selector.hasClass("disabled")) {
        return false;
    }

    loadCreditCustomerList();
});

$(document).on("click", ".pay_row", function () {
    $(document).find(".pay_row").removeClass("active");
    $(this).addClass("active");
});

$(".close_register_modal").click(async function () {
    let results = await get_db('bill_session_payment', "bspSessionId", session_id);

    let cc_id = 0;
    $.each(results, function (index, val) {
        parseInt(val.cc_id) > 0 ? cc_id = val.cc_id : "";
    })

    //alert();
    $.ajax({
        "url": BASE_URL + "web/pos/get_close_register_details",
        "method": "POST",
        "dataType": "JSON",
        "data": {
            //cat_id: cat_id,
            cc_id: cc_id
        },
        success: function (data) {
            let html = "";
            $(".total_closing_cash").text(`(${data.cash_in_hand})`)
            $.each(data.data, function (ind, val) {
                if (val.title !== "Credit Customer") {
                    html += `<tr>
                                <td>` + val.title + `</td>
                                <td style='text-align: right;'>` + val.value + `</td>
                            </tr>`;
                }
            });
            $("#closeRegisterModal").find(".modal-body").find("tbody").html(html);
        }
    });
});

$(".today_sale_modal").click(async function () {
    let results = await get_db('bill_session_payment', "bspSessionId", session_id);

    let cc_id = 0;
    $.each(results, function (index, val) {
        parseInt(val.cc_id) > 0 ? cc_id = val.cc_id : "";
    });

    //alert();
    $.ajax({
        "url": BASE_URL + "web/pos/ajax_get_today_sales",
        "method": "POST",
        "dataType": "JSON",
        "data": {
            //cat_id: cat_id,
            cc_id: cc_id
        },
        success: function (data) {
            let html = "";
            $.each(data, function (ind, val) {
                html += `<tr>
                            <td>` + val.title + `</td>
                            <td style='text-align: right;'>` + val.value + `</td>
                        </tr>`;
            });
            $("#todaySaleModal").find(".modal-body").find("tbody").html(html);
        }
    });
});

$(".today_profit_modal").click(async function () {
    let results = await get_db('bill_session_payment', "bspSessionId", session_id);

    let cc_id = 0;
    $.each(results, function (index, val) {
        parseInt(val.cc_id) > 0 ? cc_id = val.cc_id : "";
    });

    //alert();
    $.ajax({
        "url": BASE_URL + "web/pos/ajax_get_today_profit",
        "method": "POST",
        "dataType": "JSON",
        "data": {
            //cat_id: cat_id,
            cc_id: cc_id
        },
        success: function (data) {
            let html = "";
            $.each(data, function (ind, val) {
                html += `<tr>
                            <td>` + val.title + `</td>
                            <td style='text-align: right;'>` + val.value + `</td>
                        </tr>`;
            });
            $("#todayProfitModal").find(".modal-body").find("tbody").html(html);
        }
    });
});

$(document).on("click", ".cart_items tr", function () {
    $(".cart_items tr").removeClass("active");
    $(this).addClass("active");
});

document.addEventListener('keydown', function (e) {
    if(e.ctrlKey) {
        e.preventDefault(); // stop browser default if any
        if (e.key === 'F1') {
            $(".cash-f1").click();
        } else if (e.key === 'F3') {
            $(".credit-card-f3").click();
        } else if (e.key === 'F4') {
            $(".debit-card-f4").click();
        } else if (e.key === 'F5') {
            $('button[data-target="#walletTypesModal"]').click();
        } else if (e.key === 'F6') {
            $('.credit-customer-f6"]').click();
        } else if (e.key === 'F7') {
            $('.loylaty-card-f7"]').click();
        }   
    }
});

$(".item-discount").click(async function (ev) {
    if ($(".cart_items tr.active").length === 0) {
        Swal.fire("Please select cart item first.").then(function () {
            $("#item_discount_modal").modal("hide");
        });
        
        return false;
    }
    let item_id = $(".cart_items tr.active").attr("item_id");
    //console.log(item_id);

    //0-percent,1-flat
    var results = await get_db('cart_item', "ciSessionIdItemId", [session_id, item_id]);
    let row = results[0];
    row.discount !== null ? $("#item_discount_modal").find("select").val(row.discount_type) : "";
    row.discount !== null ? $("#item_discount_modal").find("input").val(row.discount) : "";
});

$(".change_rate").click(async function (ev) {
    if ($(".cart_items tr.active").length === 0) {
        Swal.fire("Please select cart item first.");
        return false;
    }
    let item_id = $(".cart_items tr.active").attr("item_id");
    //console.log(item_id);

    //0-percent,1-flat
    var results = await get_db('cart_item', "ciSessionIdItemId", [session_id, item_id]);
    let row = results[0];
    //$("#changeProductRate").val(row.regular_rate);
    $("#changeProductRate").val("0");
    $("#changeProductRateId").val(item_id);
    $("#minProductRate").val(row.minimal_sales_rate);
});

$("#changeratemodal").find("button").click(async function () {
    let c_amt = $("#changeProductRate").val();
    if ($(this).text() === "CE") {
        $("#changeProductRate").val("0");
    } else if ($(this).hasClass("enter")) {
        if (parseFloat($("#minProductRate").val()) <= parseFloat(c_amt)) {
            await update_db('cart_item', "ciSessionIdItemId", [session_id, $("#changeProductRateId").val()], {regular_rate: c_amt});
            await load_all(session_id);
        } else {
            Swal.fire("Less than " + $("#minProductRate").val() + " not allowed.");
            return false;
        }
    } else if ($(this).hasClass("font-cal")) {
        $("#changeProductRate").val((c_amt === "0" ? "" : c_amt) + $(this).text());
    }
});

$(".changeqty").click(async function (ev) {
    if ($(".cart_items tr.active").length === 0) {
        setTimeout(function(){
            $("#changeqtymodal").modal("hide");
        },1000);
        Swal.fire("Please select cart item first.");
        return false;
    }
    let item_id = $(".cart_items tr.active").attr("item_id");
    // console.log(item_id);

    $("#changeProductQty").val("0");
    $("#changeProductQtyId").val(item_id);
});

$("#changeqtymodal").find("button").click(async function () {
    let c_qty = $("#changeProductQty").val();
    if ($(this).text() === "CE") {
        $("#changeProductQty").val("0");
    } else if ($(this).hasClass("font-cal") && !$(this).hasClass("enter")) {
        $("#changeProductQty").val((c_qty === "0" ? "" : c_qty) + $(this).text());
    } else if ($(this).hasClass("enter")) {
        if (c_qty > 0) {
            await update_db('cart_item', "ciSessionIdItemId", [session_id, $("#changeProductQtyId").val()], {quantity: parseFloat(c_qty)});
        } else {
            await delete_db('cart_item', "ciSessionIdItemId", [session_id, $("#changeProductQtyId").val()]);
        }
        await load_all(session_id);
    }
});

$("#smallitemmodal").find("button").click(async function () {
    let input = $(this).parentsUntil("#smallitemmodal").find("#smallItemRate");
    let localVat = $(this).parentsUntil("#smallitemmodal").find("select").val();
    let c_qty = input.val();
    if ($(this).text() === "CE") {
        input.val("0");
    } else if ($(this).hasClass("enter")) {
        let meta = {
            name: "Small Item",
            id: "0",
            pet_id: "0", 
            groomer_id: "0",
            regular_rate: c_qty,
            item_code: "SI-0000",
            barcode: "0000",
            vat_percentage: localVat,
            purchase_rate: c_qty,
            minimal_sales_rate: "0", 
            quantity: 1
        };
        
        $("input[name=search_products]").val("");
        await add_update_cart(meta, 1);
        input.val("0");
    } else if ($(this).hasClass("font-cal")) {
        input.val((c_qty === "0" ? "" : c_qty) + $(this).text());
    }
});

$(".apply_item_discount_modal").click(async function () {
    let selector = $(this);
    let type = selector.parent().prev().find("select").val();
    let value = selector.parent().prev().find("input").val();
    if (value !== "") {
        if (type === "0" && parseFloat(value) > 100) {
            alert("Invalid discount percent entered.");
            return false;
        }
        let item_id = $(".cart_items").find("tr.active").attr("item_id");
        console.log(item_id);
        await update_db('cart_item', "ciSessionIdItemId", [session_id, item_id], {discount_type: type, discount: value});
        await load_all(session_id);
    }
//    if (dis.discount_type.toString() === "0") {//0-percent,1-flat
//            discount_percent = dis.discount;
//            discount_flat = parseFloat(((total_amt * discount_percent) / 100).toFixed(2));
//        } else if (dis.discount_type.toString() === "1") {
//            if (parseFloat(dis.discount) > total_amt) {
//                total_amt = 0;
//            } else {
//                discount_percent = 100 - ((total_amt - dis.discount) / (total_amt) * 100).toFixed();
//            }
//            discount_flat = parseFloat(dis.discount);
//        }
});

$(".re_print").click(async function () {
    let last_inv_no = localStorage.getItem("last_inv_no");
    const {value: invoice_no} = await Swal.fire({
        title: "Enter invoice number.",
        input: "text",
        inputLabel: "Your IP address",
        inputValue: parseInt(last_inv_no) > 0 ? last_inv_no : "",
        showCancelButton: true,
        inputValidator: (value) => {
            if (!value) {
                return "You need to write invoice number!";
            }
        }
    });
    if (invoice_no !== undefined) {
        let inv_no = invoice_no.replace(/INV/g, "");
        inv_no = parseInt(inv_no.replace(/inv/g, ""));
        if (inv_no > 0) {
            window.location.href = BASE_URL + "web/pos/receipt?inv_no=" + inv_no;
        }
    }
});

$(".apply_code_modal").click(async function () {
    let code = $("#discountCodeModal").find("input").val();
    if (code === "") {
        Swal.fire("Please enter valid coupon code!")
    }
    $.ajax({
        "url": BASE_URL + "web/pos/ajax_get_discount_code",
        "method": "POST",
        "dataType": "JSON",
        "data": {
            code: code
        },
        success: async function (data) {
            if (Object.keys(data.code).length === 0) {
                Swal.fire("Discount code does not exist or expired!")
            } else {
                let type = 1;//1-flat/0-percent
                await update_db('bill_session', "bsSessionId", session_id, {discount_type: type, discount: parseInt(data.code.amount)});
                await load_all(session_id);
                $(".apply_code_modal").next().click();
            }
        }
    });
});

$(".btn_bill_note").click(async function(){
    var results = await get_db('bill_session', "bsSessionId", session_id);
    let existing_value = results.length > 0 ? results[0].bill_note : "";
    Swal.fire({
        title: "Enter bill note",
        input: "text",
        confirmButtonText: "Confirm",
        inputValue: existing_value
    }).then(async (result) => {
        await update_db('bill_session', "bsSessionId", session_id, {bill_note: result.value});
    });
});

function screen_lock(message) {
    let msg = message !== "" ? message : sessionStorage.getItem("lock_screen");
    if (msg) {
        Swal.fire({
            title: msg,
            input: "password",
            confirmButtonText: "Confirm"
        }).then((result) => {
            if (result.value) {
                if (result.value === psw) {
                    sessionStorage.removeItem('lock_screen');
                } else {
                    screen_lock("Please enter correct password.");
                }
            } else {
                screen_lock("");
            }
        });
    }
}

function load_pets(cus_id) {
    if (cus_id !== "") {
        $.ajax({
            "url": BASE_URL + "web/pos/ajax_get_pet_list",
            "method": "POST",
            "dataType": "JSON",
            "data": {
                cus_id: cus_id
            },
            success: function (data) {
                PET_LIST = data.pets;
                GROOMER_LIST = data.groomer;
                load_all(session_id);
            }
        });
    } else {
        PET_LIST = [];
        load_all(session_id);
    }
}

screen_lock("");

$(".btn-lock").click(function () {
    sessionStorage.setItem('lock_screen', "Screen locked. Please re-enter password.");
    screen_lock("");
});

let expire_in_mins = 60;
setTimeout(function () {
    $.ajax({
        "url": BASE_URL + "login/ajax_logout",
        "method": "POST",
        "dataType": "JSON",
        "data": {},
        success: function (data) {
            Swal.fire("Session destroyed. Please login again!").then(function () {
                window.location.reload();
            });
        }
    });
}, expire_in_mins * 60 * 1000);