$(document).ready(function(){
    var statuslist=$("#status"),
        datefields=$(".datepicker"),
        startdatefield=$("#startdate"),
        enddatefield=$("#enddate"),
        sidebarmenu=$("#smslog"),
        filterlogs=$("#filtersmslog"),
        errordiv=$("#errodiv")
        sidebarmenu.addClass("active"),
        smslist=$("#smslogs")
        
    // Set Datepickers for start and end date
    datefields.datepicker({maxDate: new Date()})

    $.datepicker.setDefaults({
        dateFormat: 'dd-M-yy'
    })

    $.getJSON(
        "../controllers/settingoperations.php",
        {
            getsmslogstatuses:true
        },
        function(data){
            results="<option value='All'>&lt;All&gt;</option>"
            for(var i=0;i<data.length;i++){
                results+=`<option value='${data[i].status}'>${data[i].status}</option>`
            }
            statuslist.html(results)
        }
    )

    // filter sms
    filterlogs.on("click",function(){
        var startdate=startdatefield.val(),
            enddate=enddatefield.val(),
            errors="",
            status=statuslist.val()
        // check for blank fields
        if(startdate==""){
            errors="Please select start date first"
            startdatefield.focus()
        }else if(enddate==""){
            errors="Please select end date first."
            enddatefield.focus()
        }

        if(errors==""){
            $.getJSON(
                "../controllers/settingoperations.php",
                {
                    filtersmslog:true,
                    startdate,
                    enddate,
                    status
                },
                function(data){
                    var results=""
                    for(var i=0;i<data.length;i++){
                        results+=`<tr><td>${Number(i)+1}</td>`
                        results+=`<td>${data[i].datesent}</td>`
                        results+=`<td>${data[i].customerid}</td>` 
                        results+=`<td>${data[i].mobileno}</td>`
                        results+=`<td>${data[i].customername}</td>`
                        results+=`<td>${data[i].message}</td>`
                        results+=`<td>${data[i].status}</td></tr>`
                    } 
                    smslist.find("tbody").html(results)
                    // convert to datatable
                    smslist.DataTable({
                        dom: 'Bfrtip',
                        lengthChange: true,
                        buttons: [
                            'pageLength','excel', 'pdf','print'
                        ]
                    })
                }
            )
        }else{
            errordiv.html(showAlert("info",errors))
        }
    })
})