$(document).ready(()=>{
    var datasourceslist=$("#datasource"),
        mergefieldlist=$("#insertmergefield"),
        smsdetailsfield=$("#smstext"),
        savetemplatebutton=$("#savesmstemplate"),
        templatenamefield=$("#templatename"),
        errordiv=$("#errors"),
        idfield=$("#id"),
        inputfields=$("input"),
        selectfields=$("select"),
        templateslist=$("#templateslist"),
        templatecount=$("#templatecount"),
        sidebarmenu=$("#templates")
        sidebarmenu.addClass("active")
    // get loggedin user
    getLoggedInUser()
    // get data sources
    getSMSDataSources()
    // get existing sms templates
    getexistingtemplates()

    // get datasource filed names
    datasourceslist.on("change",()=>{
        var datasourcename=datasourceslist.val()
        if(datasourcename!==""){
            $.getJSON(
                "../controllers/settingoperations.php",
                {
                    getdatasourcecollumns:true,
                    datasourcename:datasourcename
                },
                (data)=>{
                    results="<option value=''>&lt;Choose One&gt;</option>"
                    for(var i=0;i<data.length;i++){
                        results+=`<option value='${data[i].column_name}'>${data[i].column_name}</option>`
                    }
                    mergefieldlist.html(results)
                }
            )
        } 
    })

    function getSMSDataSources(){
        $.getJSON(
            "../controllers/settingoperations.php",
            {
                getsmsdatasources:true
            },
            (data)=>{
                var results="<option value=''>&lt;Choose One&gt;</option>"
                for(var i=0;i<data.length;i++){
                    results+=`<option value='${data[i].viewname}'>${data[i].viewname}</option>`
                }
                console.log(results)
                datasourceslist.html(results)
            }
        )
    }

    function typeInTextarea(newText, el = document.activeElement) {
        const start = el.selectionStart
        const end = el.selectionEnd
        const text = el.value
        const before = text.substring(0, start)
        const after  = text.substring(end, text.length)
        el.value = (before + newText + after)
        el.selectionStart = el.selectionEnd = start + newText.length
        el.focus()
    }
    
    smsdetailsfield.on("keydown", (e) => {
        if(mergefieldlist.val()!=""){
            var mergefield=`@${mergefieldlist.val()}`
            if (e.key === "Enter"){
                e.preventDefault()
                typeInTextarea(mergefield)
                mergefieldlist.val("")
                mergefieldlist.focus()
            } 
        }
        errordiv.html("")
    })

   // listen to save template button
   savetemplatebutton.on("click",()=>{
        var templatename=templatenamefield.val(),  
            templatebody=smsdetailsfield.val(),
            id=idfield.val(),
            datasource=datasourceslist.val()
            errors=""
        // check for blank fields
        if(templatename=="") {
            errors="Please provide the template name"
            templatenamefield.focus()
        }else if(datasource==""){
            errors="Please select the template's data source"
            datasourceslist.focus()
        } else if(templatebody=="") {
            errors="Please provide template body details"
            smsdetailsfield.focus()
        }
        if(errors==""){
            // save the template
            $.post(
                "../controllers/settingoperations.php",
                {
                    savesmstemplate:true,
                    id:id,
                    templatename:templatename,
                    templatedata:templatebody,
                    datasource:datasource
                },
                (data)=>{
                    data=$.trim(data)
                    if(data=="exists"){
                        errors="Sorry, the template name is already in use"
                        errordiv.html(showAlert("info",errors))
                        templatenamefield.focus()
                    }else if(data=="success"){
                        errors="The template has been saved successully"
                        errordiv.html(showAlert("success", errors))
                        templatenamefield.val("")
                        smsdetailsfield.val("")
                        templatenamefield.focus()
                    }else{
                        errors=`An error occured.<br/>${data}`
                        errordiv.html(showAlert("danger",errors))
                    }
                }
            )
        }else{
            // display the errors
            errordiv.html(showAlert("info",errors))
        }
   })

   // hide any errors displayed
   inputfields.on("input",()=>{
       errordiv.html("")
   })

   selectfields.on("change",()=>{
       errordiv.html("")
   })

   // get existing templates
   function getexistingtemplates(){
       $.getJSON(
           "../controllers/settingoperations.php",
           {
                getsmstemplates:true
           },
           (data)=>{
                var results=``
                for(var i=0;i<data.length;i++){
                    results+=`<option value='${data[i].id}'>${data[i].templatename}</option>`
                }
                templateslist.html(results)
                templatecount.html(data.length)
            }
       )
   }

   // listen to on click of li on templates list
   templateslist.on("change",()=>{
       id=parseInt(templateslist.val())
       $.getJSON(
           "../controllers/settingoperations.php",
           {
            getsmstemplatedetails:true,
            id:id
           },
           (data)=>{
                datasourceslist.val(data[0].datasource)
                idfield.val(data[0].id),
                templatenamefield.val(data[0].templatename)
                smsdetailsfield.val(data[0].templatedata)
           }
       )
   })

})