$(document).ready(()=>{
    var templateslist=$("#template"),
        smsbodyfield=$("#smsbody"),
        customerslist=$("#customerslist"),
        selectallcheckbox=$("#selectall"),
        sendsmsbutton=$("#sendsms"),
        errordiv=$("#errors"),
        sidebarmenu=$("#mailer"),
        propertyownersfield=$("#propertyowner"),
        propertynamefield=$("#propertyname")
        getLoggedInUser()
    sidebarmenu.addClass("active")
    // get all sms templates
    getsmstemplates()
    // get all existing customers
    getallcustomers(0,0)
    // get property owners
    getpropertyowners()
    // get property names
    getpropertynames(0)
    // assign the username

    function getsmstemplates(){
        $.getJSON(
            "../controllers/settingoperations.php",
            {
                 getsmstemplates:true
            },
            (data)=>{
                var results=`<option value=''>&lt;Choose One&gt;</option>`
                for(var i=0;i<data.length;i++){
                    results+=`<option value='${data[i].id}' data-source='${data[i].datasource}'>${data[i].templatename}</option>`
                }
                templateslist.html(results)
             }
        )
    }

    // get template details
    templateslist.on("change",()=>{
        var id=templateslist.val()
        errordiv.html("")
        if(id!=""){
            $.getJSON(
                "../controllers/settingoperations.php",
                {
                 getsmstemplatedetails:true,
                 id:id
                },
                (data)=>{
                    smsbodyfield.val(data[0].templatedata)
                }
            )
        }
    })

    // filter property names based on the selected property owner
    propertyownersfield.on("change",()=>{
        var ownerid=propertyownersfield.val()
        getpropertynames(ownerid)
        getallcustomers(ownerid, 0)
    })

    // filter customers based on the selected property
    propertynamefield.on("change",()=>{
        var ownerid=propertyownersfield.val(),
            propertyid=propertynamefield.val()
        getallcustomers(ownerid, propertyid)
    })

    function getallcustomers(ownerid, propertyid){
        $.getJSON(
            "../controllers/settingoperations.php",
            {
                getallcustomers:true,
                ownerid,
                propertyid
            },
            (data)=>{
                var results="<table class='table table-sm table-borderless'>",
                    customername=""
                for(var i=0;i<data.length;i++){                   
                    //if($.trim(customername)!="" && customername!=undefined) customername=titleCase(customername)
                    if($.trim(data[i].firstname)!="" || $.trim(data[i].middlename)!="" || $.trim(data[i].othernames)!=""){
                        customername=data[i].firstname+" "+data[i].middlename+" "+data[i].othernames
                        customername=titleCase($.trim(customername))
                        results+=`<tr><td><input type='checkbox' id='${data[i].customerid}' class='checkoption'>&nbsp;&nbsp;`
                        results+=`<span class='sentencecase'>${customername}</span></td></tr>` 
                    } 
                }
                results+="</table>"
                customerslist.html(results)
            }
        )
    }


   function titleCase(string) {
       try{
           var sentence = string.toLowerCase().split(" ");
            for(var i = 0; i< sentence.length; i++){
                sentence[i] = sentence[i][0].toUpperCase() + sentence[i].slice(1);
            }
            return sentence.join(" ")
       }catch(err){
            //console.log(err.message)
            return string
       }
       
   }

   selectallcheckbox.on("click",()=>{       
        if (selectallcheckbox.prop("checked")){
            customerslist.find(".checkoption").each(function(){
                $(this).prop("checked",true)
            })
        }else{
            customerslist.find(".checkoption").each(function(){
                $(this).prop("checked",false)
            })
        }
   })

   sendsmsbutton.on("click",()=>{
       var  template=templateslist.val(),
            messagebody=smsbodyfield.val(),
            errors="",
            sendtenantcount=customerslist.find(".checkoption:checked").length   ,
            datasource=$("#template option:selected").attr("data-source")       
            console.log(datasource)
        // check for blank fields

        if(template==""){
            errors="Please select template for sending the SMS"
            templateslist.focus()
        }else if(messagebody==""){
            errors="Please provide message details to send"
            smsbodyfield.focus()
        }

        if(errors==""){
           // mail merge and send the sms
            var counter=0, processmessage="", percentage=0, progressstatus=[]
            customerslist.find(".checkoption:checked").each(function(){
                $this=$(this)
                customerid=$this.prop("id")
                counter++
                percentage=parseInt((counter/sendtenantcount))*100
                processmessage=`Sending message ${counter} of ${sendtenantcount} [${percentage}]`
                errordiv.html(showAlert("processing",processmessage,1))

                $.post(
                    "../controllers/settingoperations.php",
                    {
                        smsmailmerge:true,
                        datasource:datasource,
                        customerid:customerid,
                        template:messagebody
                    },
                    (data)=>{
                        data=$.trim(data)
                        if(data=="success"){
                            progressstatus.push({customerid:"success"})
                        }else{
                            progressstatus.push({customerid:`errors ${data}`})
                        }
                    }
                )

            })

            processmessage=`Sending message(s) complete. Total Processed ${sendtenantcount}`
            errordiv.html(showAlert("success",processmessage))
            
        }else{
            errordiv.html(showAlert("info",errors))
        }
   })

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

   function getpropertynames(ownerid){
       $.getJSON(
           "../controllers/settingoperations.php",
           {
                getproperties:true,
                ownerid
           },
           (data)=>{
                var results2=`<option value='0'>&lt;All&gt;</option>`
                for(var i=0;i<data.length;i++){
                    results2+=`<option value=${data[i].propertyid}>${data[i].propertyname}`
                }
                propertynamefield.html(results2)
           }
       )
   }
  
})