function filter_payload_db(val) {
    return {
        name: val.name,
        id: val.id,
        regular_rate: val.regular_rate,
        item_code: val.code,
        barcode: val.barcode,
        vat_percentage: val.vat_percentage
    };
}

function load_items(cat_id) {
    //alert();
    $.ajax({
        "url": BASE_URL + "web/pos/get_item_over_category",
        "method": "POST",
        "dataType": "JSON",
        "data": {
            cat_id: cat_id
        },
        success: function (data) {
            let html = "";
            $.each(data, function (ind, val) {
                let meta = filter_payload_db(val);
                html += `<div class="col-xl-4 col-lg-2 col-md-3 col-sm-4 col-6 add_item_to_cart" meta="` + btoa(JSON.stringify(meta)) + `">
                            <div class="productCard">
                                <div class="productThumb">
                                    <img class="img-fluid" src="` + (val.image === "" || val.image === null ? BASE_URL + 'assets/images/no-image.png' : BASE_URL + "assets/images/products/" + val.image) + `" alt="ix">
                                </div>
                                <div class="productContent">
                                    <div>
                                        <div>Price: ` + val.regular_rate + `</div>
                                        <div class="small">` + val.name + `</div>
                                        <div>` + val.name_ar + `</div>
                                    </div>
                                </div>
                            </div>
                        </div>`;
            });
            $(".tbl_products").html(html);
        }
    });
}

load_items($(".tbl_category").val());

$(document).on('change', "select.tbl_category", function () {
    load_items($(this).val());
});

function append_into_cart(item) {
    let item_html = `<tr>
                        <td>` + item.name + `</td>
                        <td>` + item.barcode + `</td>
                        <td>
                            <input type="number" value="` + item.quantity + `" class="form-control border-dark w-60px update_quantity" item_id="` + item.item_id + `" placeholder="">
                        </td>
                        <td>` + item.regular_rate + `</td>
                        <td>` + (parseFloat(item.vat_charge) * parseFloat(item.quantity)) + `</td>
                        <td>` + ((parseFloat(item.regular_rate) + parseFloat(item.vat_charge)) * parseFloat(item.quantity)) + `</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 = 'PosWeb';
var Version = 1.0;
var Text_Description = 'Pos Web DB';
var Database_Size = 2 * 1024 * 1024;

var session_id = 1;
var operator_id = 1;
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}`;

var dbObj = openDatabase(Database_Name, Version, Text_Description, Database_Size);

dbObj.transaction(function (tx) {
    //tx.executeSql('DROP TABLE IF EXISTS cart_item');
    tx.executeSql('CREATE TABLE IF NOT EXISTS cart_item (item_id,name,item_code,barcode,quantity,regular_rate,session_id,vat_charge)');
});

function manage_bill_session_id(sess_id, on_hold) {
    //on_hold: 0-none,1-hold,2-unhold
    dbObj.transaction(function (tx) {
        //tx.executeSql('DROP TABLE IF EXISTS bill_session');
        //tx.executeSql('DROP TABLE IF EXISTS cart_item');
        tx.executeSql('CREATE TABLE IF NOT EXISTS bill_session (s_no,date,session_id,till,operator_id,cs_mobile,discount,discount_type,status)');//status:0-active,1-hold,2-processed # discount_type: 0 - %,1 - /-

        if (on_hold > 0) {
            if (on_hold == 1) {
                tx.executeSql('update bill_session set status=1 where session_id=' + sess_id);
                tx.executeSql('SELECT * from bill_session order by session_id desc limit 1', [], function (tx, results) {
                    if (results.rows.length > 0) {
                        sess_id = parseFloat(results.rows[0].session_id)
                        sess_id = ++sess_id;
                    } else {
                        sess_id = 1;
                    }
                }, null);
            } else {
                tx.executeSql('update bill_session set status=1');
                tx.executeSql('update bill_session set status=0 where session_id=' + sess_id);
            }
        }

        tx.executeSql('SELECT * from bill_session where status=0', [], function (tx, results) {
            if (results.rows.length > 0) {
                session_id = parseFloat(results.rows[0].session_id);
                load_all(session_id);
            } else {
                tx.executeSql('SELECT * from bill_session where session_id=' + sess_id, [], function (tx, results) {
                    if (results.rows.length > 0) {
                        tx.executeSql('update bill_session set status=0 where session_id=' + sess_id);
                    } else {
                        tx.executeSql('insert into bill_session(s_no,date,session_id,operator_id,status) values(' + sess_id + ',"' + formattedDate + '",' + sess_id + ',"' + operator_id + '",' + 0 + ')');
                    }
                    session_id = sess_id;
                    load_all(session_id);
                }, null);
            }
        }, null);
    });
}

function manage_bill_amount(sess_id, amount, pay_via, txn_id, type) {
    dbObj.transaction(function (tx) {
        //tx.executeSql('DROP TABLE IF EXISTS bill_session_payment');
        tx.executeSql('CREATE TABLE IF NOT EXISTS bill_session_payment (session_id,amount,pay_via,txn_id)');
        if (type === "-") {
            tx.executeSql('delete from bill_session_payment where session_id=' + sess_id + ' and amount=' + amount + ' and pay_via="' + pay_via + '"');
            load_all(session_id);
        } else if (type === "+") {
            tx.executeSql('SELECT * from bill_session_payment where session_id=' + sess_id + ' and pay_via="' + pay_via + '"', [], function (tx, results) {
                if (results.rows.length > 0) {
                    tx.executeSql('update bill_session_payment set amount=' + (results.rows[0].amount + amount) + ' where session_id=' + sess_id + ' and pay_via="' + pay_via + '"');
                } else {
                    tx.executeSql('insert into bill_session_payment(session_id,amount,pay_via,txn_id) values(' + sess_id + ',' + amount + ',"' + pay_via + '","' + txn_id + '")');
                }
                load_all(session_id);
            }, null);
        }
    });
}

function load_all(session_id) {
    $(".cart_items").html("");
    dbObj.transaction(function (tx) {
        tx.executeSql('SELECT * from cart_item where session_id=' + session_id + '', [], function (tx, results) {
            $(".total_itme_cart").text("I : " + results.rows.length);
            let total_quantity = 0;
            let total_amt = 0;
            let total_vat = 0;
            if (results.rows.length > 0) {
                //console.log(results.rows);
                $.each(results.rows, function (ind, item) {
                    total_quantity += item.quantity;
                    total_amt += ((parseFloat(item.regular_rate) + parseFloat(item.vat_charge)) * parseFloat(item.quantity));
                    total_vat += (parseFloat(item.vat_charge) * parseFloat(item.quantity));
                    append_into_cart(item);
                });
            }

            tx.executeSql('SELECT * from bill_session where session_id=' + session_id + '', [], function (tx, results) {
                let dis = results.rows[0];

                let discount_percent = 0;
                let discount_flat = 0;
                if (total_amt > 0 && dis.discount !== null && parseFloat(dis.discount) > 0) {
                    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);
                    }
                }
                $(".bill_discount_percent").text(discount_percent);
                $(".bill_discount_flat").text(discount_flat);
                $(".total_quantity_cart").text("Q : " + total_quantity);
                $(".total_bill_price").text((total_amt - discount_flat).toFixed(2));
                $(".grand_total_bill_price").text((total_amt).toFixed(2));

                customer_paid_cash = 0;
                tx.executeSql('SELECT * from bill_session_payment where session_id=' + session_id, [], function (tx, results) {
                    let html = '';
                    if (results.rows.length > 0) {
                        $.each(results.rows, function (index, val) {
                            customer_paid_cash += parseFloat(val.amount);
                            html += `<tr class="pay_row" 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 - discount_flat) > 0 ? $(".customer_total_cash").text((customer_paid_cash - (total_amt - discount_flat)).toFixed(2)) : "";
                        total_amt - (customer_paid_cash + discount_flat) > 0 ? $("#customer_paid_cash").val(total_amt - (customer_paid_cash + discount_flat)) : "";
                    } else {
                        $(".customer_total_paid,.customer_total_cash").text("00.00");
                    }
                    $(".total_vat_price").text(total_vat);
                }, null);
            }, null);
        }, null);
    });
}

manage_bill_session_id(1, 0);

function add_update_cart(meta) {
    dbObj.transaction(function (tx) {
        tx.executeSql('SELECT * from cart_item where item_id=' + meta.id + ' and session_id=' + session_id + '', [], function (tx, results) {
            if (results.rows.length > 0) {
                tx.executeSql('update cart_item set quantity=quantity+1 where item_id=' + meta.id + ' and session_id=' + session_id)
                //console.log(results);
            } else {
                vat_charge = 0;
                price = parseFloat(meta.regular_rate);
                if (TAX_SETTING.sales_tax === "1" && parseFloat(meta.vat_percentage) > 0) {
                    vat_charge = ((price * parseFloat(meta.vat_percentage)) / 100).toFixed(2);
                }
                tx.executeSql('insert into cart_item(item_id,name,item_code,barcode,quantity,regular_rate,session_id,vat_charge) values(' + meta.id + ',"' + meta.name + '","' + meta.item_code + '","' + meta.barcode + '",' + 1 + ',' + price + ',' + session_id + ',' + vat_charge + ')');
            }
            load_all(session_id);
        }, null);
    });
}

$(document).on("click", ".add_item_to_cart", function () {
    let meta = $(this).attr("meta");
    meta = JSON.parse(atob(meta))
    //console.log(meta);
    add_update_cart(meta);
});

$(document).on('keyup input', '.update_quantity', function () {
    let item_id = $(this).attr("item_id");
    let val = $(this).val();
    dbObj.transaction(function (tx) {
        if (val > 0) {
            tx.executeSql('update cart_item set quantity=' + val + ' where item_id=' + item_id + ' and session_id=' + session_id);
        } else {
            tx.executeSql('delete from cart_item where item_id=' + item_id + ' and session_id=' + session_id);
        }
        load_all(session_id);
    });
});

$(document).on('click', '.confirm-delete', function () {
    let item_id = $(this).attr("item_id");
    $(this).parent().parent().parent().remove();
    dbObj.transaction(function (tx) {
        tx.executeSql('delete from cart_item where item_id=' + item_id + ' and session_id=' + session_id);
        load_all(session_id);
    });
});

$("#hold_bill").click(function () {
    manage_bill_session_id(session_id, 1);
});

$("#search_text").keyup(function (e) {
    let val = $(this).val();
    let search_type = $("#search_type").val();
    if (val === "") {
        return false;
    }
    if (e.keyCode === 13) {
        $.ajax({
            "url": BASE_URL + "web/pos/search_product",
            "method": "POST",
            "dataType": "JSON",
            "data": {
                search: val,
                search_type: search_type
            },
            success: function (data) {
                if (data.length > 0) {
                    if (search_type === "1") {
                        let meta = filter_payload_db(data[0]);
                        add_update_cart(meta);
                    } else {
                        let html = ``;
                        $.each(data, function (ind, val) {
                            html += `<option value="` + val.name + `" meta="` + btoa(JSON.stringify(filter_payload_db(val))) + `">`;
                        });
                        $("#browsers").html(html);
                    }
                } else {
                    alert("No product found.")
                }
            }
        });
    } else {
        $.each($("#browsers option"), function () {
            let selector = $(this);
            if (val == selector.attr("value")) {
                let meta = $(this).attr("meta");
                meta = JSON.parse(atob(meta))
                //console.log(meta);
                add_update_cart(meta);
            }
        })
    }
});

$(".recall_holded_bill").click(function () {
    dbObj.transaction(function (tx) {
        tx.executeSql('SELECT * from bill_session', [], function (tx, results) {
            if (results.rows.length > 0) {
                let html = ``;
                $.each(results.rows, function (ind, val) {
                    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;
                    }
                    html += `<tr>
                                <th scope="row">` + (ind + 1) + `</th>
                                <td>` + val.session_id + `</td>
                                <td>` + val.date + `</td>
                                <td>` + val.operator_id + `</td>
                                <td>` + status + `</td>
                                <td>` + action + `</td>
                            </tr>`;
                });
                $("#recallModal tbody").html(html);
            }
        }, null);
    });
});

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

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

    selector.parent().siblings("input").val("");
    selector.parent().siblings("label.cus").css({display: "none"});

    let val = selector.val();
    if (e.keyCode === 13 && val !== "") {
        $.ajax({
            "url": BASE_URL + "web/pos/search_customer",
            "method": "POST",
            "dataType": "JSON",
            "data": {
                mobile: val
            },
            success: function (data) {
                if (Object.keys(data).length > 0) {
                    selector.parent().siblings("input").val(data.id);
                    selector.parent().siblings("label.cus").css({display: "block"});
                    selector.parent().siblings("label.cus").text("Customer Name: " + data.name);
                } else {
                    selector.parent().prev().find("span").click();
                    $("#add_customer").find("input[name=mobile]").val(val);
                    selector.parent().siblings("label.cus").css({display: "block"});
                    selector.parent().siblings("label.cus").text("Customer not found. Please add new one.");
                }
            }
        });
    }
});

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

    let payload = {
        name: form.find("input[name=name]").val(),
        mobile: form.find("input[name=mobile]").val(),
        email: form.find("input[name=email]").val(),
        cus_type: form.find("select[name=cus_type]").val(),
        address: form.find("input[name=address]").val(),
        trn_no: form.find("input[name=trn_no]").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.mobile === "") {
        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) {
            data = data.user;
            $("#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("");
        }
    });
});

$(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();
        }
    }
});

$(".apply_discount_modal").click(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;
        }
        dbObj.transaction(function (tx) {
            tx.executeSql('update bill_session set discount_type=' + type + ',discount=' + value + ' where session_id=' + session_id);
            load_all(session_id);
        });
    }
});

$(".btn-billdiscount").click(function () {
    dbObj.transaction(function (tx) {
        tx.executeSql('SELECT * from bill_session where session_id=' + session_id + '', [], function (tx, results) {
            let row = results.rows[0];
            row.discount !== null ? $("#bill_discount_modal").find("select").val(row.discount_type) : "";
            row.discount !== null ? $("#bill_discount_modal").find("input").val(row.discount) : "";
        });
    });
});

$(".btn-completesale").click(async function () {
//    if (!confirm("Are you sure want to complete this order")) {
//        return false;
//    }

    async function fetch_meta(query) {
        return new Promise((resolve, reject) => {
            dbObj.transaction(function (tx) {
                tx.executeSql(query, [], function (tx, results) {
                    let return_ = [];
                    if (results.rows.length > 0) {
                        $.each(results.rows, function (index, val) {
                            return_.push(val);
                        });
                    }
                    resolve(return_);
                }, (_, error) => reject(error));
            });
        });
    }

    let cart_items = await fetch_meta("select * from cart_item where session_id=" + session_id);
    let bill_session = await fetch_meta("select * from bill_session where session_id=" + session_id);
    let bill_session_payment = await fetch_meta("select * from bill_session_payment where session_id=" + session_id);

    let payload = {
        bill_session: bill_session,
        cart_items: cart_items,
        bill_session_payment: bill_session_payment
    };

    $.ajax({
        url: BASE_URL + "web/pos/complete_order",
        method: "POST",
        dataType: "JSON",
        data: payload,
        success: function (data) {
            dbObj.transaction(function (tx) {
                tx.executeSql('delete from cart_item where session_id=' + session_id + '', [], function (tx, results) {});
                tx.executeSql('delete from bill_session where session_id=' + session_id + '', [], function (tx, results) {});
                tx.executeSql('delete from bill_session_payment where session_id=' + session_id + '', [], function (tx, results) {});
            });
            setTimeout(function () {
                manage_bill_session_id(session_id, 1);
                window.location.href = BASE_URL + "web/pos/receipt?bill_id=" + data.insert_billing_id;
            }, 200);
        }
    });
});

$(".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()));
});

$(".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() + ".");
    }
});

$(".cash-f1,.credit-card-f3,.debit-card-f4,.wallet-f5,.credit-customer-f6,.loylaty-card-f7").click(function () {
    if ($("#customer_paid_cash").val() !== "" && parseFloat($("#customer_paid_cash").val()) > 0) {
        manage_bill_amount(session_id, parseFloat($("#customer_paid_cash").val()), $(this).attr("title"), "", "+");
        $("#customer_paid_cash").val("0.00");
    }
});

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

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