is_authenticatedUser = false
let currentPath = window.location.pathname
let userName = $('div.sidebar').find('div.info').find('a').text()

if (userName == "")
    userName = $('div.sidebar').find('div.info').find('span').text()

var content_HTML = ''
const months = [
    'January', 'February', 'March', 'April', 'May', 'June',
    'July', 'August', 'September', 'October', 'November', 'December'
];
const API_TOKEN = "00f656ef-118e-4521-bac0-ed3273c2ac33"


function fn_StringfyError(error) {
    if (Array.isArray(error)) {
        // Convert the array to a string
        var stringifiedArray = error.join(',');
        return stringifiedArray;
    } else {
        return error;
    }
}
function fn_EncryptResponse(response) {
    try {

        if (response.status >= 200 && response.status < 300) {
            let clone = response.clone();
            var data = clone.json();
            return Promise.resolve(data).then(function (res) { return res });
        } else {
            return Promise.reject(new Error(response.statusText))
        }
    } catch (objErrorText) {
        fn_CatchError(objErrorText, 0, true);
        fn_UnblockUI('.pendingLoader');
    }
}

function fn_TestJSON(text) {
    if (typeof text == "string") {
        return false;
    }
    try {
        text = JSON.stringify(text)
        JSON.parse(text);
        return true;
    } catch (error) {
        console.log(error)
        return false;
    }
}

$(function () {
    let nav = $('nav').find('ul.nav-pills')
    let path = window.location.pathname
    $('.main-footer').find('div.float-right').empty().append('Developed by <b>Parvati and sons</b> | <small>designed by Jazzmin version 2.4.8</small>')

    let spt = path.split('/'), anc = ''

    if (spt.length > 5) {
        let newPath = '',
            index = 0
        $.each(spt, function () {

            if (index < 4) {
                if (this == '') {
                    newPath += '/'
                } else {
                    newPath += this + '/'
                }


            }
            index++;
        })

        anc = $(nav).find('a[href="' + newPath + '"]')

    } else {
        anc = $(nav).find('a[href="' + path + '"]')
    }

    $(anc).parent().parent().css('display', 'block')
    $(anc).parent().parent().parent('li').addClass('menu-is-opening menu-open')
    $(anc).parent().parent().parent('li').children('a.nav-link').addClass('active')



})

if (window.location.pathname != '/admin/') {
    function isVisible($el) {
        if ($el.length) {
            var winTop = $(window).scrollTop();
            var winBottom = winTop + $(window).height();
            var elTop = $el.offset().top;

            var elBottom = elTop + $el.height();
            return ((elTop >= winTop));
        } return false
    }


    $(function () {

        // $('#content').remove()

        if ($('#result_list')) {

            let wdth = $('#result_list').width() + 'px'
            let dv_wdth = $('#result_list').parent().width() + 'px'

            $('#result_list').parent().append('<div  style="width:' + dv_wdth + '" class="bottom-scroll"><div style="width:' + wdth + '" >&nbsp;</div></div>')

            $('.bottom-scroll, #stickyhead').on('scroll', function () {
                $('#result_list').parent().prop("scrollLeft", this.scrollLeft);
                $('#stickyhead').prop("scrollLeft", this.scrollLeft);
            })


            let html_th = ''
            $.each($('#result_list').find('thead').find('tr').find('th'), function () {
                html_th += '<th style="width:' + $(this).width() + 'px;">' + $(this).html() + '</th>'
            })

            let html_tr = ''
            // let trs = $('#result_list').find('tbody').find('tr')
            // $.each(trs, function () {
            //     html_tr += '<tr>' + $(this).html() + '</tr>';
            // });

            $('#result_list').parent().append('<div id="stickyhead" style="width:' + dv_wdth + '" class="table table-striped no-sticky" "> <table style="width: ' + wdth + ';"> <thead><tr>' + html_th + '</tr> </thead> <tbody>' + html_tr + '</tbody> </table></div>')

            $('#stickyhead').find('thead').find('input[type="checkbox"]').on('change', function () {
                $('#result_list').find('thead').find('input[type="checkbox"]').click()
                // $('#result_list').find('thead').find('input[type="checkbox"]').prop('checked', $(this).prop('checked')).trigger('change')
                // console.log($(this).prop('checked'), $('#result_list').find('thead').find('input[type="checkbox"]').prop('checked'))
            })


            $(window).scroll(function () {
                if (!isVisible($("#result_list"))) {
                    $('#stickyhead').addClass("sticky")
                    $('#stickyhead').removeClass("no-sticky")
                } else {
                    $('#stickyhead').addClass("no-sticky")
                    $('#stickyhead').removeClass("sticky")
                }
            });
            // $('#stickyhead').on('scroll', function () {
            //     $('#result_list').parent().prop("scrollLeft", this.scrollLeft);
            //     $('.bottom-scroll').prop("scrollLeft", this.scrollLeft);
            // })


            $('#result_list').parent().on('scroll', function () {
                $('#stickyhead').parent().prop("scrollLeft", this.scrollLeft);
                $('.bottom-scroll').prop("scrollLeft", this.scrollLeft);
            })

            $('#result_list').find('td.field-is_sean').find('img[alt="False"]').parent().parent().addClass('unread')

            $('span[data-id="is_seen"][data-value="False"]').parent().parent().addClass('unread')
        }

    })


    if (window.location.pathname == '/admin/retailers/recharge/') {
        $(function () {
            let rows = $("#result_list").find('tbody').find("tr");
            let amount = 0;
            let deduction_amount = 0;
            let commission_amount = 0;

            $.each(rows, function () {
                amount += parseFloat($(this).find(".field-amount").text());
                deduction_amount += parseFloat($(this).find(".field-deduction_amount").text());
                commission_amount += parseFloat($(this).find(".field-commission_amount").text());
            });

            amount = parseFloat(amount).toFixed(2);
            deduction_amount = parseFloat(deduction_amount).toFixed(2);
            commission_amount = parseFloat(commission_amount).toFixed(2);

            $("#result_list").find('tbody').prepend(`<tr><th colspan="7">Totals</th><th>${amount}</th><th>${deduction_amount}</th><th>${commission_amount}</th><th colspan="6"></th></tr>`)

        })
    }
    // 62862.00	60816.25	2045.75 Recharge Summary
    // 62862.00		 Debit Summary
    // 47556.00	 Credit Summary


    if (window.location.pathname == '/admin/retailers/transaction/') {
        $(function () {
            let rows = $("#result_list").find('tbody').find("tr");
            let amount = 0;
            let deduction_amount = 0;

            $.each(rows, function () {
                amount += parseFloat($(this).find(".field-amount").text());
                deduction_amount += parseFloat($(this).find(".field-deduction_amount").text());
            });

            amount = parseFloat(amount).toFixed(2);
            deduction_amount = parseFloat(deduction_amount).toFixed(2);

            $("#result_list").find('tbody').prepend(`<tr><th colspan="6">Totals</th><th>${amount}</th><th>${deduction_amount}</th><th colspan="5"></th></tr>`)

        })
    }
}

function fn_MenuUI(url, name) {
    return `
    <li class="nav-item">
        <a href="${url}" class="nav-link">
            <i class="nav-icon fas fa-eye"></i>
            <p>${name}</p>
        </a>
    </li>
    `
}

async function fn_SetOverviewMenu() {

    let main = document.querySelector('ul.nav.nav-pills.nav-sidebar.flex-column ');

    if (main) {
        let liLeads = main.querySelectorAll('li');

        liLeads.forEach(function (li) {
            let txt = li.querySelector('p');

            if (txt) {
                txt = txt.textContent.trim().replace(/\s/g, '');

                if (txt === 'retailer') {
                    let ul = li.querySelector('ul');
                    if (ul) {
                        ul.insertAdjacentHTML('afterbegin', fn_MenuUI('/admin/retailer/', 'Overview'));
                    }
                }
            }
        });

        // fn_SetActiveURL()
    }

}

fn_SetOverviewMenu()



if (window.location.pathname == '/admin/') {
    if (userName == "admin") {
        document.getElementById('content').innerHTML = ''
        fn_init()
    }
}

async function fn_init() {
    document.getElementById('content').innerHTML = `
    <div id="dvReportsInit">
        <div id="dvSidePanel" class="sidepanel"></div>
        <div class="row">
            <div class="col-md-4">
                <div class="card card-primary card-outline">
                    <div class="card-body">
                        <div class="btn-group table-responsive">
                            <h2>&nbsp;</h2>
                            <button class="btn btn-outline-success" onclick="fn_InitRecharge()">Recharge</button>
                            <button class="btn btn-outline-primary" onclick="">Incomes</button>
                            <button class="btn btn-outline-danger" >Demo 19 Recharge</button>
                            <button class="btn btn-outline-info" onclick="fn_CheckBalance()">Check Balance</button>
                        </div>
                    </div>
                    <div class="card-footer">
                        &nbsp;
                    </div>
                </div>
            </div>
             ${await fn_Stats()}
        </div>
        <div class="row">
            ${await fn_Recharge()}
            ${await fn_Retailer()}
        </div>
        
        </div>
    `
    // fn_InitBooking()

    // fn_InitBillingView(9, 'sfs')
}

async function fn_Stats() {
    let res = await fn_GetAsyncCall(`/api/retailers/get-stats/`)
    let retailers = '0'
    let recharge = '0'
    let wallet = '0'
    let balance = '0'

    if (res.ok > 0) {
        retailers = res.data.retailers;
        recharge = res.data.recharge;
        wallet = res.data.wallet;
    } 
    
    return `
    <div class="col-6 col-md-2">
        <div class="card card-primary card-outline">
            <div class="card-body">
                <h2>${retailers}</h2>
            </div>
            <div class="card-footer">
                Total Retailer
            </div>
        </div>
    </div>
    <div class="col-6 col-md-2">
        <div class="card card-primary card-outline">
            <div class="card-body">
                <h2>${recharge}</h2>
            </div>
            <div class="card-footer">
            Total Recharge
            </div>
        </div>
    </div>
    <div class="col-6 col-md-2">
        <div class="card card-primary card-outline">
            <div class="card-body">
                <h2>${wallet}</h2>
            </div>
            <div class="card-footer">
                Total Balance
            </div>
        </div>
    </div>
    <div class="col-6 col-md-2">
        <div class="card card-primary card-outline">
            <div class="card-body">
                <h2>${balance}</h2>
            </div>
            <div class="card-footer">
                Balance
            </div>
        </div>
    </div>
    `
}


async function fn_Recharge() {

    let res = await fn_GetAsyncCall(`/api/retailers/get-latest-recharge/`)

    let TRs = '';
    let status = ['NA', 'CREATED', 'STARTED', 'COMPLETED', 'CANCELLED']

    if (res.ok > 0) {
        count = 1
        $.each(res.data, function () {

            console.log(this)
            // let balance_amount = 0
            // if (this.is_fully_paid) {
            //     balance_amount = `<span class="badge badge-success">Paid</span>`
            // } else {
            //     balance_amount = `<a href="javascript:fn_InitBookingPayment(${this.id},'${this.customer}')">${this.balance_amount}</a>`
            // }
            TRs += `<tr>
            <td class="wht-no">${count}</td>
            <td class="wht-no">${this.order_id}</td>
            <td class="wht-no">${this.source_name}</td>
            <td class="wht-no">${this.operator_name}</td>
            <td class="wht-no">${fn_DateToStr(this.date)}</td>
            <td class="wht-no">${this.recharge_id}</td>
            <td class="wht-no">${this.retailer_name}</td>
            <td class="wht-no">${this.balance}</td>
            </tr>`

            count++;
        })
    } else {
        TRs = `<tr><td colspan="8">${fn_StringfyError(res.error)}</td></tr>`
    }

    return `
        <div class="col-md-6">
            <div class="card card-primary card-outline card-height">
                <div class="card-header">
                    Latest Recharge
                </div>
                <div class="card-body">
                    <div class="table-responsive">
                        <table class="table table-bordered">
                            <tr>
                                <th>S. No</th>
                                <th>Order Id</th>
                                <th>Source</th>
                                <th>Operator</th>                          
                                <th>Date</th>                               
                                <th>Recharge Id</th>
                                <th>Retailer</th>
                                <th>Balance</th>
                            </tr>
                            ${TRs}
                        </table>
                    </div>
                </div>
                <div class="card-footer">
                    &nbsp;
                </div>
            </div>
        </div>
    `
}

async function fn_Retailer() {

    let res = await fn_GetAsyncCall(`/api/retailers/minimum-balance/`)

    let TRs = '';


    if (res.ok > 0) {
        count = 1
        $.each(res.data, function () {


            TRs += `<tr>
            <td class="wht-no">${count}</td>
            <td class="wht-no">${this.retailer_name}</td>
            <td class="wht-no">${this.amount}</td>
            </tr>`

            count++;
        })
    } else {
        TRs = `<tr><td colspan="8">${fn_StringfyError(res.error)}</td></tr>`
    }

    return `
        <div class="col-md-6">
            <div class="card card-primary card-outline card-height">
                <div class="card-header">
                    Latest Retailer
                </div>
                <div class="card-body">
                    <div class="table-responsive">
                        <table class="table table-bordered">
                            <tr>
                                <th>S. No</th>
                                <th>Name</th>
                                <th>Amount</th>
                            </tr>
                            ${TRs}
                        </table>
                    </div>
                </div>
                <div class="card-footer">
                    &nbsp;
                </div>
            </div>
        </div>
    `
}

async function fn_CheckBalance() {

    let res = await fn_GetAsyncCall(`/api/settings/get-all-mrobotics/`)
    // let res={ "error": false, "data": { "AirtelDTH": 0, "TataSky": 0, "Dishtv": 0, "Bsnl": 0, "Airtel": 0, "Vodafone": 0 } }

    console.log(res, "res")
    if (res.error == false) {
        $('#dvSidePanel').empty().append(await fn_BaseHTML('Operator Balance', fn_OptBalanceHTML, 0,
            ``))
        $('#dvSidePanel').addClass('open-side-panel-30')

        console.log(res.data, "res.data")

        optTD = ""
        if (res.data) {
            $.each(res.data, function () {
                optTD +=
                    `<tr>
                    <th>${this.operator_name}</th>
                    <th>${this.balance}</th>
                </tr>`;
            })


        }

        $("#optBalanceRecord").empty().append(optTD);
    }

}

// {
//     "order_id":"1231",
//     "mobile_no":"9837994101",
//     "amount":1,
//     "company_id":5,
//     "is_stv":false,
//     "api_token":"00f656ef-118e-4521-bac0-ed3273c2ac33"
// }

async function fn_SaveRecharge() {
    data = [{
        "mrobotics": 1,
        "retailer": 1,
        "order_id": "125",
        'source': 1,
        'amount': 1,
        "operator": 5,
        "mobile": "9837994101",
        "transaction_type": 1
    }
    ]
    let res = await fn_PostAsyncCall("/api/retailers/post-recharge/", JSON.stringify(data))

    if (res.ok > 0) {
        console.log("submit")
        window.location.reload()
    } else {
        console.log(res.error)
    }

}


async function fn_GetAsyncCall(api) {
    var response = await fetch(api, {
        method: 'GET',
        headers: { 'Content-Type': 'application/json' }
    }).then(fn_EncryptResponse).then(function (response) {
        return response
    }).catch(function (err) {
        return { 'ok': 0, "error": err }
    });

    return response;
}

async function fn_PostAsyncCall(api, jsonBody) {
    var response = fetch(api, {
        method: 'POST',
        body: jsonBody,
        headers: { 'Content-Type': 'application/json' }
    }).then(fn_EncryptResponse).then(function (response) {
        return response
    }).catch(function (err) {
        return { 'ok': 0, "error": err }
    });

    return response;
}

function fn_DateToStr(str_dt) {
    if (str_dt != "-") {
        let dt = new Date(str_dt)
        if (dt.getFullYear() == '1970') {
            return 'NA'
        } else {
            return `${dt.getDate()}-${months[dt.getMonth()]}-${dt.getFullYear()}`
        }
    } return ""
}


async function fn_InitRecharge() {
    $('#dvSidePanel').empty().append(await fn_BaseHTML('Add Income', fn_RechargeHTML, 0,
        ``))
    $('#dvSidePanel').addClass('open-side-panel-50')
    $('#frmIncome').find('input[name="amount"]').focus()
}


async function fn_BaseHTML(msg, callback, param, action = "") {
    return `
    <div class="">
        <div class="row">
            <div class="col-md-12">
                <div class="card mb-3">
                    <div class="card-header">
                        <div class="row">
                            <div class="col-md-4"><span><b>${msg}</b></span></div>
                            ${action}
                        </div>
                        <a href="javascript:void(0)" class="closebtn" onclick="fn_CloseSidePanel()">&times;</a>
                    </div>
                    <div class="card-body">
                        ${await callback(param)}
                        <div class="row">
                            <div class="col-md-12" id="dvError">
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>
`
}


async function fn_RechargeHTML() {
    return `
        <form id="frmIncome" class="row">
            <div class="col-md-12 form-group">
                <label>Mobile No.</label>
                <input type="text" name="mobile"  inputmode="numeric" class="form-control" />
            </div>
            <div class="col-md-12 form-group">
                <label>Amount</label>
                <input type="text" name="amount"  inputmode="numeric" class="form-control" />
            </div>
            <div class="col-md-12 form-group">
                <label>Operator</label>
                <select name="operator" id="idOperator" class="form-control">
                   
                    ${await fn_BindDDloperator()}
                </select>
            </div>
            <div class="col-md-12 form-group">
                <button onclick="#" type="button" class="btn btn-outline-primary btn-block">Recharge</button>
            </div>
            <div class="col-md-12 form-group">
                <div id="dvIncomeError"></div>
            </div>
        </form>
    `
}


function fn_CloseSidePanel() {
    $('#dvSidePanel').empty()
    $('#dvSidePanel').removeClass('open-side-panel-30')
    $('#dvSidePanel').removeClass('open-side-panel-50')
}

function fn_OptBalanceHTML() {
    return `
        <div class=""row>
            <table class="table">
                <thead>
                    <tr>
                        <th>Name</th>
                        <th>Balance</th>
                    </tr>
                </thead>
                <tbody id="optBalanceRecord"> 
                    
                </tbody>
            </table>
        </div>
    `
}


async function fn_GetStats(url) {
    let res = await fn_GetAsyncCall(`/api/${url}`)
    let TRs = '0';
    if (res.ok > 0) {
        if (typeof res.data === 'object') {
            TRs = res.data.length

        } else {
            TRs = parseFloat(res.data)
        }
    } else {
        TRs = `${fn_StringfyError(res.error)}`
    }

    return TRs;
}


async function fn_BindDDloperator() {
    let res = await fn_GetAsyncCall("/api/settings/get-all-operator/")
    console.log(res, 'res')
    if (res.ok > 0) {
        html = '<option value="">Select operator</option>'
        $.each(res.data, function () {
            html +=
                `<option value="${this.operator_id}">${this.name}</option>`;
        })

        // $("#idOperator").empty().append(html)
        return html

    }
}   