$(document).ready(function () {
    //current_db1()
    //generaterow(getAdvertisementSchedule())
    //console.log(currentdate())
});

$(document).on("click", "#btnAddBanner", function () {
    $(".drop-zone__thumb").remove();
    $("#advertisementid").remove();
    if ($('span.drop-zone__prompt').length == 0) {
        let spantext = document.createElement('span')
        spantext.className = 'drop-zone__prompt'
        spantext.innerHTML = 'Drop file here or click to upload'
        document.getElementById('img').appendChild(spantext)
    }

    document.getElementById('divnote').className = 'd-none'
    $('#modalAddBanner').modal('show');
});

$(document).on("click", "#btnset", function () {
    var $row = $(this).closest("tr");
    var tdid = $row.find("td");
    let id = tdid[0].innerHTML.trim();
    let advertisement = getAdvertisementSchedule();

    $('#txtstart_at').val('00:00')
    $('#txtend_at').val('00:00')

    advertisement = advertisement.filter((e) => e['id'] == id);

    $('#bannerid').val(id)
    $('#bannername').val(advertisement[0]['advertisementname'])

    if (advertisement[0]['schedule'].length > 0) {
        $('#txtstart_at').val(advertisement[0]['schedule'][0]['start_at'])
        $('#txtend_at').val(advertisement[0]['schedule'][0]['end_at'])
    }
    //else {
    //    console.log('aw1')
    //    $('#txtstart_at').val('00:00')
    //    $('#txtend_at').val('00:00')
    //}
    $('#modalSetBannerSchedule').modal('show');
});

$(document).on("click", ".form-check-input", function () {
    let db = current_db().trim()
    var $row = $(this).closest("tr");
    var tdid = $row.find("td");
    let id = tdid[0].innerHTML.trim();
    let getschedule = JSON.parse(getSchedule())
   
    getschedule = getschedule.filter((e) => e['advertisement_id'] == id);
    Swal.fire({
        text: 'Are you sure you want to changes?', 
        showCancelButton: true,
        confirmButtonColor: '#008000',
        cancelButtonColor: '#d33',
        confirmButtonText: 'Yes',
        cancelButtonText: "No",
        allowOutsideClick: false,
    }).then((isConfirm) => {       
        if (isConfirm.value) {
            let advertisement_id = id;
            let start_at = getschedule[0]['start_at']
            let end_at = getschedule[0]['end_at']
            let is_everyday = getschedule[0]['is_everyday'];
            let is_available = document.getElementById('chkavailable' + id).checked;
            if (is_available == false) {
                is_available = 0
            } else {
                is_available = 1
            }

            data = {
                "id": 1,
                "advertisement_id": advertisement_id,
                "start_at": start_at,
                "end_at": end_at,
                "is_everyday": is_everyday,
                "is_available": is_available,
                "dbname": db
            }


            UpdateAvertisementTiming(data)

            Swal.fire({
                position: "center",
                icon: "success",
                text: "Changes successfully saved",
                showConfirmButton: false,
                timer: 1500
            }).then((result) => {
                document.getElementById('tblbody').innerHTML = ''
                generaterow(getAdvertisementSchedule())
                //tblbody
            });

        } else {           
            if (getschedule[0]['is_available'] == 1) {
                document.getElementById('chkavailable' + id).checked = true;
            } else {
                //chkavailable.checked = false
                document.getElementById('chkavailable' + id).checked = false;
            }
        }
    });
})

$(document).on("click", "#btnsaveschedule", function () {
    let db = current_db().trim()
    Swal.fire({
        //title: 'Are you sure you want save changes?',
        //text: "You won't be able to revert this!",
        text: 'Are you sure you want to save changes?',
        showCancelButton: true,
        confirmButtonColor: '#008000',
        cancelButtonColor: '#d33',
        confirmButtonText: 'Yes',
        cancelButtonText: "No",
    }).then((isConfirm) => {
        if (isConfirm.value) {
            let getschedule = JSON.parse(getSchedule())

            let advertisement_id = $('#bannerid').val();
            let start_at = $('#txtstart_at').val().trim();
            let end_at = $('#txtend_at').val().trim();
            let is_everyday = 0;
            let is_available = 1;

            let is_existed = getschedule.filter((e) => e['advertisement_id'] == advertisement_id.trim());
            if (is_existed.length == 0) {
                data = {
                    "advertisement_id": advertisement_id,
                    "start_at": start_at,
                    "end_at": end_at,
                    "is_everyday": is_everyday,
                    "is_available": is_available
                }
                CreateAdvertisementTiming(data);

            } else {
                data = {
                    "id": 1,
                    "advertisement_id": advertisement_id,
                    "start_at": start_at,
                    "end_at": end_at,
                    "is_everyday": is_everyday,
                    "is_available": is_available,
                    "dbname": db
                }
                UpdateAvertisementTiming(data)
            }

            Swal.fire({
                position: "center",
                icon: "success",
                text: "New schedule/timing successfully saved",
                showConfirmButton: false,
                timer: 1500
            }).then((result) => {
                document.getElementById('tblbody').innerHTML = ''
                generaterow(getAdvertisementSchedule())
                $('#modalSetBannerSchedule').modal('hide');
            });
        }
    });
});

$(document).on("click", "#btnsave", function () {
    var imgname = $('.drop-zone__thumb').attr("data-label");
    let db = current_db().trim()
    if (imgname == undefined) {
        //alert("No file selected!");
        Swal.fire({
            position: "center",
            icon: "info",
            text: "Please select file",
            showConfirmButton: false,
            timer: 1500
        }).then((result) => {

        });
        return false;
    }

    var filename = imgname.split(".")[0];
    //var filename = imgname
    var clientname = loadCompanyDetails()['c_id']
    var branchname = loadCompanyDetails()['c_alias']

    if (uploadimg.files[0].size > 200000) {
        //document.getElementById('dvMsg').style.display = "block";
        //alert("File size huge");
        Swal.fire({
            position: "center",
            icon: "info",
            text: "File size huge",
            showConfirmButton: false,
            timer: 1500
        }).then((result) => {

        });
        return false;
    }

    //console.log(fileUploadnew.files[0].size);
    Swal.fire({
        //title: 'Are you sure you want save changes?',
        //text: "You won't be able to revert this!",
        text: 'Are you sure you want to save image?',
        showCancelButton: true,
        confirmButtonColor: '#008000',
        cancelButtonColor: '#d33',
        confirmButtonText: 'Yes',
        cancelButtonText: "No",
    }).then((isConfirm) => {
        if (isConfirm.value) {
            var fd = new FormData();
            fd.append("", uploadimg.files[0]);
            let date = currentdate()
            //console.log(date)
            //console.log(fd)
            $.ajax({
                url: 'https://www.suntoyo.online/api/FileService/Upload',
                type: 'POST',
                mimeType: "multipart/form-data",
                data: fd,
                crossDomain: true,
                async: false,
                success: function (datapath) {


                    //if ($('span.drop-zone__prompt').length == 0) {
                    //    let spantext = document.createElement('span')
                    //    spantext.className = 'drop-zone__prompt'
                    //    spantext.innerHTML = 'Drop file here or click to upload'
                    //    document.getElementById('img').appendChild(spantext)
                    //}

                    if (document.getElementById('advertisementid') == null) {
                        let jsondata =
                        {
                            "id": 0,
                            "advertisementname": filename,
                            "advertisementpath": JSON.parse(datapath)['dbPath'],
                            "created_at": date
                        }
                        CreateAdvertisement(jsondata);
                    } else {
                        let id = document.getElementById('advertisementid').innerHTML
                        let data = {
                            "id": id,
                            "name": filename,
                            "path": JSON.parse(datapath)['dbPath'],
                            "dbname": db
                        }

                        UpdateAvertisement(data)
                    }


                    //var imgCategory = document.createElement("img");
                    //imgCategory.id = "imgCategory";
                    //imgCategory.src = dataUrl + "?nocache=" + Math.random();
                    //imgCategory.style = "width:100px; height:85px; margin-bottom: 10px;";
                    //imgCategory.alt = "no image";
                    //document.getElementById("divImage").appendChild(imgCategory);

                    //$('#<%=lbldbpath.ClientID%>').html(data);
                    //$("#hdnPath").val(data);
                },
                beforeSend: function (request) {
                    request.setRequestHeader("clientName", clientname);
                    request.setRequestHeader("fileName", filename.toLowerCase());
                    request.setRequestHeader("branchName", branchname);
                },
                complete: function (data) {
                    Swal.fire({
                        position: "center",
                        icon: "success",
                        text: "New image successfully saved",
                        showConfirmButton: false,
                        timer: 1500
                    }).then((result) => {
                        document.getElementById('tblbody').innerHTML = ''
                        generaterow(getAdvertisementSchedule())
                        $('#modalAddBanner').modal('hide');
                    });
                },
                cache: false,
                contentType: false,
                processData: false
            });
        } else { }
        location.reload();
    });

});

$(document).on("click", "#btnedit", function () {
    $(".drop-zone__thumb").remove();
    var $row = $(this).closest("tr");
    var tdid = $row.find("td");
    let id = tdid[0].innerHTML.trim();

    let advertisement = getAdvertisementSchedule();
    advertisement = advertisement.filter((e) => e['id'] == id);

    let pid = document.createElement('p')
    pid.id = 'advertisementid'
    pid.innerHTML = id
    pid.className = 'd-none'
    document.getElementById('img').appendChild(pid)

    document.getElementById("divnote").className = "text-danger d-block"
    //dropZoneElement.querySelector(".drop-zone__prompt").remove();
    $(".drop-zone__prompt").remove();
    let divimg = document.createElement('div')
    divimg.className = 'drop-zone__thumb'
    divimg.id = 'advimg'
    //divimg.style.backgroundImage = `url(${advertisement[0]['advertisementpath']})`;
    //+ "?" + parseInt(Math.random() * 1000000000, 10);
    divimg.style.backgroundImage = "url(" + advertisement[0]['advertisementpath'] + "?" + parseInt(Math.random() * 1000000000, 10) + ")";
    divimg.style.width = "100%"
    divimg.setAttribute("data-label", advertisement[0]['advertisementname'])
    document.getElementById('img').appendChild(divimg)
    //$("advimg").attr("data-label", advertisement['advertisementname']);

    $('#modalAddBanner').modal('show');
});

$(document).on("click", "#btnremove", function () {
    let db = current_db().trim()
    var $row = $(this).closest("tr");
    var tdid = $row.find("td");
    let id = tdid[0].innerHTML.trim();

    Swal.fire({
        text: 'Are you sure you want remove this image?',
        showCancelButton: true,
        confirmButtonColor: '#008000',
        cancelButtonColor: '#d33',
        confirmButtonText: 'Yes',
        cancelButtonText: "No",
    }).then((isConfirm) => {
        //let getschedule = JSON.parse(getSchedule())
        //getschedule = getschedule.filter((e) => e['id'] == id);
        if (isConfirm.value) {
            //delete api
            DeleteAdvertisement(id)
            DeleteAdvertisementTiming(id)
            Swal.fire({
                position: "center",
                icon: "success",
                text: "Image successfully removed",
                showConfirmButton: false,
                timer: 1500
            }).then((result) => {
                document.getElementById('tblbody').innerHTML = ''
                generaterow(getAdvertisementSchedule())
                //tblbody
            });

        }
    });
});

document.querySelectorAll(".drop-zone__input").forEach((inputElement) => {
    const dropZoneElement = inputElement.closest(".drop-zone");

    dropZoneElement.addEventListener("click", (e) => {
        inputElement.click();
    });

    inputElement.addEventListener("change", (e) => {
        if (inputElement.files.length) {
            updateThumbnail(dropZoneElement, inputElement.files[0]);
        }
    });

    dropZoneElement.addEventListener("dragover", (e) => {
        e.preventDefault();
        dropZoneElement.classList.add("drop-zone--over");
    });

    ["dragleave", "dragend"].forEach((type) => {
        dropZoneElement.addEventListener(type, (e) => {
            dropZoneElement.classList.remove("drop-zone--over");
        });
    });

    dropZoneElement.addEventListener("drop", (e) => {
        e.preventDefault();

        if (e.dataTransfer.files.length) {
            inputElement.files = e.dataTransfer.files;
            updateThumbnail(dropZoneElement, e.dataTransfer.files[0]);
        }

        dropZoneElement.classList.remove("drop-zone--over");
    });
});

/**
 * Updates the thumbnail on a drop zone element.
 *
 * @param {HTMLElement} dropZoneElement
 * @param {File} file
 */

function updateThumbnail(dropZoneElement, file) {
    let thumbnailElement = dropZoneElement.querySelector(".drop-zone__thumb");

    // First time - remove the prompt
    if (dropZoneElement.querySelector(".drop-zone__prompt")) {
        dropZoneElement.querySelector(".drop-zone__prompt").remove();
    }

    // First time - there is no thumbnail element, so lets create it
    if (!thumbnailElement) {
        thumbnailElement = document.createElement("div");
        thumbnailElement.classList.add("drop-zone__thumb");
        dropZoneElement.appendChild(thumbnailElement);
    }

    thumbnailElement.dataset.label = file.name;

    // Show thumbnail for image files
    if (file.type.startsWith("image/")) {
        const reader = new FileReader();

        reader.readAsDataURL(file);
        reader.onload = () => {
            thumbnailElement.style.backgroundImage = `url('${reader.result}')`;
        };
    } else {
        thumbnailElement.style.backgroundImage = null;
    }
}

//Advertisement
function CreateAdvertisement(data) {
    let url = readWebConfig();
    let token = bearertoken();
    let db = current_db().trim()
    //token = 'Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpZCI6IjEiLCJuYmYiOjE3Mzg3MzkwNDksImV4cCI6MTczOTM0Mzg0OSwiaWF0IjoxNzM4NzM5MDQ5fQ.3fTEZFjF2-IUgZUpjgnuKDEgnX8XbZN2CDDiJXHq3GI'
    var settings = {
        "url": url + "/api/Advertisement/Create?clientdb=" + db,
        "method": "POST",
        "timeout": 0,

        "headers": {
            "Access-Control-Allow-Origin": "*",
            "Access-Control-Allow-Headers": "Origin, X-Requested-With, Content-Type, Accept",
            "Content-Type": "application/json",
            "Authorization": token
        },
        "data": JSON.stringify({
            "id": 0,
            "advertisementname": data['advertisementname'],
            "advertisementpath": data['advertisementpath'],
            "created_at": data['created_at']
        }),

    };

    $.ajax(settings).done(function (response) {
        //console.log(response);
    }).fail(function (jqXHR, textStatus, errorThrown) {
        console.log("error" + errorThrown);
        return;
    });
}

function DeleteAdvertisement(id) {
    let url = readWebConfig();
    let token = bearertoken();
    let db = current_db().trim()
    var settings = {
        "url": url + "/api/" + db + "/Advertisement/Delete?id=" + id,
        "method": "DELETE",
        "timeout": 0,
        "headers":
        {
            "Access-Control-Allow-Origin": "*",
            "Access-Control-Allow-Headers": "Origin, X-Requested-With, Content-Type, Accept",
            "Authorization": token
        },
    };

    $.ajax(settings).done(function (response) {
        //console.log(response);
    });
}

function UpdateAvertisement(data) {
    let url = readWebConfig();
    let token = bearertoken();
    let db = current_db().trim()
    //console.log(data)
    var settings =
    {
        "url": url + "/api/Advertisement/Update",
        "method": "PUT",
        "timeout": 0,
        "headers":
        {
            "Access-Control-Allow-Origin": "*",
            "Access-Control-Allow-Headers": "Origin, X-Requested-With, Content-Type, Accept",
            "Content-Type": "application/json",
            "Authorization": token
        },
        "data": JSON.stringify({
            "id": data['id'],
            "name": data['name'],
            "path": data['path'],
            "dbname": db
        }),
    }; $.ajax(settings).done(function (response) {
        //console.log(response);
    });
}

function getAdvertisment() {
    var data;
    let url = readWebConfig();
    var token = bearertoken();
    let db = current_db().trim()
    var settings = {
        "url": url + "/api/" + db + "/Advertisement/GetAdvertisement",
        "method": "GET",
        "timeout": 0,
        "async": false,
        "headers":
        {
            "Access-Control-Allow-Origin": "*",
            "Access-Control-Allow-Headers": "Origin, X-Requested-With, Content-Type, Accept",
            "Authorization": token
        },
    };

    $.ajax(settings).done(function (response) {
        //generaterow(response);
        data = response;
    }).fail(function (jqXHR, textStatus, errorThrown) {
        console.log("error" + errorThrown);
        return;
    });
    return data;
}

//Advertisement Timing
function CreateAdvertisementTiming(data) {
    let url = readWebConfig();
    let token = bearertoken();
    let db = current_db().trim();
    let date = currentdate()
    var settings = {
        "url": url + "/api/AdvertisementTiming/Create?clientdb=" + db,
        "method": "POST",
        "timeout": 0,
        "headers": {
            "Access-Control-Allow-Origin": "*",
            "Access-Control-Allow-Headers": "Origin, X-Requested-With, Content-Type, Accept",
            "Content-Type": "application/json",
            "Authorization": token
        },
        "data": JSON.stringify({
            "id": 0,
            "advertisement_id": data['advertisement_id'],
            "start_at": data['start_at'],
            "end_at": data['end_at'],
            "is_everyday": 0,
            "is_available": 1,
            "created_at": date
        }),
    };

    $.ajax(settings).done(function (response) {
        //alert('Banner Schedule Successfully Set!')
    });
}

function UpdateAvertisementTiming(data) {
    let url = readWebConfig();
    let token = bearertoken();
    let db = current_db().trim()
    var settings = {
        "url": url + "/api/AdvertisementTiming/update ",
        "method": "PUT",
        "timeout": 0,
        "headers":
        {
            "Access-Control-Allow-Origin": "*",
            "Access-Control-Allow-Headers": "Origin, X-Requested-With, Content-Type, Accept",
            "Content-Type": "application/json",
            "Authorization": token
        },
        "data": JSON.stringify({
            "id": 1,
            "advertisement_id": data['advertisement_id'],
            "start_at": data['start_at'],
            "end_at": data['end_at'],
            "is_everyday": 0,
            "is_available": data['is_available'],
            "dbname": db
        }),

    };

    $.ajax(settings).done(function (response) {
        //console.log(response);
    }).fail(function (jqXHR, textStatus, errorThrown) {
        console.log("error " + errorThrown);
        return;
    });
}

function DeleteAdvertisementTiming(id) {
    let url = readWebConfig();
    let token = bearertoken();
    let db = current_db().trim()
    var settings = {
        "url": url + "/api/" + db + "/AdvertisementTiming/Delete?id=" + id,
        "method": "DELETE",
        "timeout": 0,
        "headers":
        {
            "Access-Control-Allow-Origin": "*",
            "Access-Control-Allow-Headers": "Origin, X-Requested-With, Content-Type, Accept",
            "Authorization": token
        },
    };

    $.ajax(settings).done(function (response) {
        console.log(response);
    });
}

function getSchedule() {
    var data;
    let url = readWebConfig();
    var token = bearertoken();
    let db = current_db().trim()
    var settings = {
        "url": url + "/api/" + db + "/AdvertisementTiming/GetAdvertisementTiming",
        "method": "GET",
        "async": false,
        "timeout": 0,
        "headers": {
            "Access-Control-Allow-Origin": "*",
            "Access-Control-Allow-Headers": "Origin, X-Requested-With, Content-Type, Accept",
            "Authorization": token
        },
    };

    $.ajax(settings).done(function (response) {
        data = response;
    }).fail(function (jqXHR, textStatus, errorThrown) {
        console.log("error" + errorThrown);
        return;
    });
    return data
}

function getAdvertisementSchedule() {
    let advertisementlist = JSON.parse(getAdvertisment());
    let advertisementsched = JSON.parse(getSchedule());

    let advertisementschedule = [];
    let schedules = []
    let schedule;
    advertisementlist.forEach(function (advertisement) {
        schedules = []
        let sched = advertisementsched.filter((sched) => sched['advertisement_id'] == advertisement['id']);

        if (sched.length > 0) {
            ///*schedules.push*/(JSON.parse(schedule))

            //schedule = {
            //    'start_at': advertisementsched[0]['start_at'],
            //    'end_at': advertisementsched[0]['end_at'],
            //    'is_everyday': advertisementsched[0]['is_everyday'],
            //    'is_available': advertisementsched[0]['is_available'],
            //}
            sched.forEach(function (x) {
                schedule = {
                    'start_at': x['start_at'],
                    'end_at': x['end_at'],
                    'is_everyday': x['is_everyday'],
                    'is_available': x['is_available'],
                }
                schedules.push(schedule)
            })

        }
        //advertisementsched.forEach(function (sched) {
        //    if (advertisement['id'] == sched['advertisement_id']) {
        //         schedule = {
        //            'start_at': sched['start_at'],
        //            'end_at': sched['start_at'],
        //            'is_everyday': sched['start_at'],
        //            'is_availabe': sched['start_at'],
        //        }
        //        
        //    }
        //})

        let adverstimentSchedule = {
            'id': advertisement['id'],
            'advertisementname': advertisement['advertisementname'],
            'advertisementpath': advertisement['advertisementpath'],
            'schedule': schedules
        }
        advertisementschedule.push(adverstimentSchedule)
        //advertisementsched.filter((sched) => sched['advertisement_id'] == advertisement['advertisement_id'])

    })

    return advertisementschedule
}

function generaterow(data) {
    const tblbody = document.getElementById('tblbody')

    let x = 1
    $.each(data, function (key, item) {

        var tr = document.createElement('tr')

        var tdid = document.createElement('td')
        id = document.createTextNode(item['id']);
        tdid.className = 'd-none'
        id.innerHTML = item['id']

        //col1
        var tdno = document.createElement('td')
        var no = document.createElement('text')
        no.innerHTML = x

        //col2
        var tdname = document.createElement('td')
        var spantxt = document.createElement('span')
        spantxt.className = 'hiddentxt'

        var aname = document.createElement('a')
        aname.innerText = item['advertisementname']

        var spanimg = document.createElement('span')
        spanimg.className = 'hiddenimg'
        var img = document.createElement('img')
        img.src = item['advertisementpath'] + "?" + parseInt(Math.random() * 1000000000, 10);
        img.style = 'height:30vh'

        //col3
        var tdedit = document.createElement('td')
        var btnedit = document.createElement('button')
        btnedit.type = 'button'
        btnedit.id = 'btnedit'
        btnedit.className = 'btn btn-primary btn-sm'
        btnedit.innerHTML = 'Edit Banner'

        //col4
        var tdaction = document.createElement('td')
        var btnset = document.createElement('button')
        btnset.type = 'button'
        btnset.id = 'btnset'
        btnset.className = 'btn btn-primary btn-sm'
        btnset.innerHTML = 'Set Schedule'

        //col5
        var tdstart_at = document.createElement('td')
        //var start_at = document.createElement('text')
        //start_at.innerHTML = '09:00'

        //col6
        var tdend_at = document.createElement('td')
        //var end_at = document.createElement('text')
        //end_at.innerHTML = '12:00'

        var tdavailable = document.createElement('td')
        var chkavailable = document.createElement('input')
        chkavailable.className = 'form-check-input m-0 position-static'
        chkavailable.type = 'checkbox'
        chkavailable.id = 'chkavailable' + item['id'];
        //chkavailable.checked = true

        var tdremove = document.createElement('td')
        var btnremove = document.createElement('button')
        btnremove.type = 'button'
        btnremove.id = 'btnremove'
        btnremove.className = 'btn btn-primary btn-sm'
        btnremove.innerHTML = 'Remove'


        var txtstart_at = document.createElement('text')
        var txtend_at = document.createElement('text')
        if (item['schedule'].length > 0) {
            $.each(item['schedule'], function (key, item) {
                //col4
                txtstart_at = document.createElement('text')
                txtstart_at.innerHTML = item['start_at']

                //col5
                txtend_at = document.createElement('text')
                txtend_at.innerHTML = item['end_at']

                if (item['is_available'] == 1) {
                    chkavailable.checked = true
                } else {
                    chkavailable.checked = false
                }
            })
        } else {
            //col4
            txtstart_at = document.createElement('text')
            txtstart_at.innerHTML = '00:00'

            ////col5
            txtend_at = document.createElement('text')
            txtend_at.innerHTML = '00:00'

            chkavailable.checked = true
        }

        //tdstart_at.appendChild(txtstart_at)
        //tdend_at.appendChild(txtend_at)

        tr.appendChild(tdid)
        tr.appendChild(tdno)    
        tr.appendChild(tdname)
        tr.appendChild(tdedit)
        tr.appendChild(tdaction)
        tr.appendChild(tdstart_at)
        tr.appendChild(tdend_at)
        tr.appendChild(tdavailable)
        tr.appendChild(tdremove)


        tdid.appendChild(id)
        tdno.appendChild(no)
        tdname.appendChild(spantxt)
        tdname.appendChild(spanimg)
        tdedit.appendChild(btnedit)
        tdaction.appendChild(btnset)
        tdstart_at.appendChild(txtstart_at)
        tdend_at.appendChild(txtend_at)
        tdavailable.appendChild(chkavailable)
        tdremove.appendChild(btnremove)

        spantxt.appendChild(aname)
        spanimg.appendChild(img)

        tblbody.appendChild(tr)

        x++
    });

}

function currentdate() {
    var today = new Date();
    var dd = String(today.getDate()).padStart(2, '0');
    var mm = String(today.getMonth() + 1).padStart(2, '0'); //January is 0!
    var yyyy = today.getFullYear();

    let currentDate = `${yyyy}-${mm}-${dd}`;
    return currentDate;
}

