{% load i18n static %}
{% load common %}
<!-- Monthly Attendance Report -->
<style type="text/css">
    .table-bordered>thead>tr>th {
        border-bottom-width: 25px !important;
        border-color: #7ac145 !important;
    }
    td{
      padding: 8px;
      border: 1px solid #ddd;
    }
    .table-bordered>thead>tr>td {
        border-color: #7ac145 !important;
    }
    .table>thead:first-child>tr:first-child>th {
        border-top: 1px solid;
    }
    /*.verticleText {
        transform: rotate(90deg);
    }*/
    .monthlyattendancesummary{
        overflow: scroll;
    }
</style>
<style>
.scrollbar
{
	margin-left: 0px;

	width: 100%;
	background: #F5F5F5;

	margin-bottom: 25px;
}

.force-overflow
{
	min-height: 300px;
  overflow: scroll;

}
    #style-1::-webkit-scrollbar-track
{
	-webkit-box-shadow: inset 0 0 6px rgba(0,0,0,0.3);
	border-radius: 10px;
	background-color: #F5F5F5;
}

#style-1::-webkit-scrollbar
{
	width: 12px;
	background-color: #F5F5F5;
}

#style-1::-webkit-scrollbar-thumb
{
	border-radius: 10px;
	-webkit-box-shadow: inset 0 0 6px rgba(0,0,0,.3);
	background-color: #555;
}
</style>
<!-- //End -->
<div id="{{ model_name }}_fluid" class="layui-fluid">
  <div class="layui-row layui-col-space15" style="margin-bottom: 0px">
    <div class="layui-col-md10">
      <div class="layui-card">
        <div class="layui-card-header" style="background-color: #ffffff;">
          <form id="{{ model_name }}-search-form" action="" class="layui-form fixed-search-form att-report-search-form">
            {% csrf_token %}
            <div class="layui-form-item">
              <div class="layui-inline">
                <label for="{{ model_name }}-start-date" class="layui-form-label">{% trans 'report_searchField_startDate' %}</label>
                <div class="layui-input-inline">
                  <input id="{{ model_name }}-start-date" type="text" name="start_date"
                         lay-verify="required"
                         autocomplete="off" class="layui-input">
                </div>
              </div>
              <div class="layui-inline">
                <label for="{{ model_name }}-end-date" class="layui-form-label">{% trans 'report_searchField_endDate' %}</label>
                <div class="layui-input-inline">
                  <input id="{{ model_name }}-end-date" type="text" name="end_date"
                         lay-verify="required"
                         autocomplete="off" class="layui-input">
                </div>
              </div>
              <div class="layui-inline" id="{{ model_name }}_search_employee">
                <label for="" class="layui-form-label">{% trans 'report_searchField_employee' %}</label>
                <div class="layui-input-inline">
                  <div class="layui-form-select">
                    <div class="layui-select-title">
                      <input id="{{ model_name }}-employee" type="text" autocomplete="off" class="layui-input" readonly>
                      <i id="{{ model_name }}-employee-select" class="layui-edge"></i>
                    </div>
                  </div>
                </div>
              </div>

              <div class="layui-inline">
                <div class="button-3d {{ model_name }}-search" >
                  <i class="fa fa-fw fa-search"></i>
                </div>
              </div>
            </div>
            <div class="layui-hide"><input id="{{ model_name }}-selected-emp-container" type="hidden"></div>
            <div class="layui-hide"><input id="{{ model_name }}SelectedEmployeeDetail" type="hidden"></div>
          </form>
        </div>
        <script type="text/html" id="{{ model_name }}_toolbar">
          <div class="layui-btn-container grid-toolbar" style="">
            <ul class="layui-nav"></ul>
          </div>
        </script>
      </div>
    </div>
  </div>
</div>

<div class="container-fluid">
{#    <input type="button" class='btn btn-success createPdfPrint' value="Create PDF" />#}
{#    <button class='btn btn-success' onclick="exportTableToExcel('tab_exc1', 'test')">Create Excel</button>#}

    <div class="row">
        <div class="col-md-10">
        </div>
        <div class="col-md-2 dropdown">
            <span style="font-size: 16px">Export</span>
                <i class="fa fa-share dropdown-toggle" type="button" data-toggle="dropdown" style="font-size: larger; padding: 5px; border: 1px solid #ddd;cursor: pointer;"></i>
            <ul class="dropdown-menu" style="left: 15px;border-radius: 0;min-width: 125px;">
                <li><a href="#" class="summaryReportExportCsv">CSV Export</a></li>
                <li><a href="#" onclick="tableToPdf('summaryReportTest')">PDF Export</a></li>
                <li><a href="#" onclick="tableToExcel('summaryReportTest', 'Monthly Attendance Summary Report')">Excel Export</a></li>
            </ul>
        </div>
    </div>
    <div id="tab_exc1" class="scrollbar divTableDataHolder" id="style-1" style="margin-right: 30px;width: -webkit-fill-available;">
        <div class="force-overflow" id="summaryReportTest">
            <table id="summaryReport" class="table table-condensed table-bordered">
                    <thead id="attendancesummary">

                    </thead>
                    <tbody class="other-data">

                    </tbody>

                </table>

        </div>
    </div>
    <div class="layui-table-page" style="background-color: #ffffff;">
        <div id="layui-table-page1">
            <div class="layui-box layui-laypage layui-laypage-default" id="layui-laypage-2">
                <a href="javascript:;" data-page="1" class="layui-laypage-refresh"><i class="layui-icon layui-icon-refresh" id="layui-icon-refresh"></i></a>
                <span class="layui-laypage-limits"><select id="SummaryReportPageLimit" lay-ignore="">
                    <option value="20">20</option>
                    <option value="50" selected="">50</option>
                    <option value="100">100</option>
                    <option value="200">200</option>
                    <option value="500">500</option>
                    <option value="1000">1000</option>
                    <option value="2000">2000</option>

                </select></span>
                <a href="javascript:;" id="summaryPrevious" class="layui-laypage layui-disabled" data-page="0"><i class="layui-icon"></i></a>
                <a href="javascript:;" id="summaryNext" class="layui-laypage layui-disabled" data-page="1"><i class="layui-icon"></i></a>
                <span class="layui-laypage-count"></span>
                <span class="layui-laypage-skip">
                    <input id="findpage" type="number" min="1" value="1" class="layui-input">Page<button type="button" class="layui-laypage-btn summaryReportPageFind">Confirm</button>
                </span>
            </div>
        </div>
    </div>
</div>
<script>
var company_name = '';
var company_logo = '';
var company_logo_pos = '';
  $(function () {
  var loadIndex = layer.load();
  var h = $('#main_body').height()-200;

  $('#summaryReportTest').height(h);

    layui.use(['form', 'element', 'laydate', 'tablePlug'], function () {
      form = layui.form, laydate = layui.laydate,
        element = layui.element;
      form.render();
      {% block search_form_init %}
      var date = new Date();
      var _start = date.getFullYear() + '-' + leftInsertZero(date.getMonth() + 1) + '-01';
      var _end = date.getFullYear() + '-' + leftInsertZero(date.getMonth() + 1) + '-' + leftInsertZero(date.getDate());
      $('#{{ model_name }}-start-date').val(_start);
      $('#{{ model_name }}-end-date').val(_end);
      var startDate = laydate.render({
        elem: '#{{ model_name }}-start-date',
        type: 'date',
        value: _start,
        max: _end,
        done: function (value, date) {
          if (Object.keys(date).length !== 0) {
              endDate.config.min = {
                year: date.year,
                month: date.month - 1,
                date: date.date
              };
          }
          else {
              endDate.config.min = {
                  year: 1900,
                  month: 01,
                  date: 01
              };
              endDate.config.max = {
                  year: 2099,
                  month: 12,
                  date: 31
              };
          }
        }
      });
      var endDate = laydate.render({
        elem: '#{{ model_name }}-end-date',
        type: 'date',
        value: _end,
        min: _start,
        done: function (value, date) {
          if (Object.keys(date).length !== 0) {
              startDate.config.max = {
                year: date.year,
                month: date.month - 1,
                date: date.date
              };
          }
          else {
              startDate.config.min = {
                  year: 1900,
                  month: 01,
                  date: 01
              };
              startDate.config.max = {
                  year: 2099,
                  month: 12,
                  date: 31
              };
          }
        }
      });
      $("#{{ model_name }}_search_employee").click(function () {
        $.ajax({
          url: "/personnel/filter_resign_employee/"
          , type: "GET"
          , dataType: "html"
          , success: function (response) {
            layer.open({
              title: gettext("employee_frame_title")
              , btn: [gettext("btn_confirm"), gettext("btn_cancel")]
              , area: ['auto', 'auto']
              , content: response
              , yes: function (index, layero) {
                var selectedEmp = $(layero).find("#employee-frame-selected-container").val();
                var selectedEmpDetail = $(layero).find("#employeeFrameSelectedDetailContainer").val();
                $("#{{ model_name }}-selected-emp-container").val(selectedEmp);
                $("#{{ model_name }}-employee").val(selectedEmpDetail);
                layer.close(index);
              }
            });
          }
        });
      });

      var getDates = function(startDate, endDate) {
        var dates = [],
        currentDate = startDate,
        addDays = function(days) {
            var date = new Date(this.valueOf());
            date.setDate(date.getDate() + days);
            return date;
        };
        while (currentDate <= endDate) {
            dates.push(currentDate);
            currentDate = addDays.call(currentDate, 1);
        }
        return dates;
    };
    var weekday = new Array(7);
    weekday[0] = "Su";
    weekday[1] = "Mo";
    weekday[2] = "Tu";
    weekday[3] = "We";
    weekday[4] = "Th";
    weekday[5] = "Fr";
    weekday[6] = "Sa";
    $(".{{ model_name }}-search").click(function () {
<!--        $('.other-data').html('');-->
        var loadIndex = layer.load();
        var start = $('#{{ model_name }}-start-date').val();
        var end = $('#{{ model_name }}-end-date').val();
        if (start == '' && end == '') {
            $('#{{ model_name }}-start-date').addClass("layui-form-danger");
            $('#{{ model_name }}-end-date').addClass("layui-form-danger");
            $('#{{ model_name }}-start-date').attr('title', 'This Field is Required');
            $('#{{ model_name }}-end-date').attr('title', 'This Field is Required');
            layer.alert("{% trans 'field_required' %}", {title: gettext("layer_title_error"), icon: 5, time: 1500, btn: []});
            return;
        } else if(start == ''){
            $('#{{ model_name }}-end-date').removeClass("layui-form-danger");
            $('#{{ model_name }}-end-date').removeAttr('title');
            $('#{{ model_name }}-start-date').addClass("layui-form-danger");
            $('#{{ model_name }}-start-date').attr('title', 'This Field is Required');
            layer.alert("{% trans 'field_required' %}", {title: gettext("layer_title_error"), icon: 5, time: 1500, btn: []});
            return;
        } else if (end == '') {
            $('#{{ model_name }}-start-date').removeClass("layui-form-danger");
            $('#{{ model_name }}-start-date').removeAttr('title');
            $('#{{ model_name }}-end-date').addClass("layui-form-danger");
            $('#{{ model_name }}-end-date').attr('title', 'This Field is Required');
            layer.alert("{% trans 'field_required' %}", {title: gettext("layer_title_error"), icon: 5, time: 1500, btn: []});
            return;
        } else {
            $('#{{ model_name }}-start-date').removeClass("layui-form-danger");
            $('#{{ model_name }}-end-date').removeClass("layui-form-danger");
            $('#{{ model_name }}-start-date').removeAttr('title');
            $('#{{ model_name }}-end-date').removeAttr('title');
        }
        var emp = $("#{{ model_name }}-selected-emp-container").val();
        var pageLimit = $('#SummaryReportPageLimit').find(":selected").text();
        var page = $('#findpage').val();
        var dates = getDates(new Date(start), new Date(end));
        var tr2 = '<tr><td class="text-center" colspan="2"></td>';
        var tr3 = '<tr><td class="text-center" colspan="2"></td>';
        dates.forEach(function(date) {
            var day = date.getDate();
            var days = weekday[date.getDay()];
            tr2 += '<td class="text-center">'+days+'</td>';
            tr3 += '<td class="text-center">'+day+'</td>';
        });
        tr2 += '</tr>';
        tr3 += '</tr>';
    var color_report = '';
    $.ajax({
          url: "/att/color_report/",
          type: "get",
          dataType: "json",
          success: function(datas) {
              var test = datas['result'];
              color_report = test;
              company_name = test['company_name'];
              company_logo = test['company_logo'];
              company_logo_pos = test['company_logo_pos'];
          }
    });
       $.ajax({
          url: "att/api/monthlyattendanceReport/?start_date="+start+"&end_date="+end+"&employees="+emp+"&page_size="+pageLimit+"&page="+page
          , type: "get"
          , dataType: "json"
          , success: function (response) {
              var total_records = response["count"];
              var summaryNext = response['next'];
              var summaryPrevious = response['previous'];
              if(summaryNext){
                  $('#summaryNext').attr('class', "layui-laypage layui-enabled");
              }else{
                  $('#summaryNext').attr('class', "layui-laypage layui-disabled");
              }
              if(summaryPrevious){
                  $('#summaryPrevious').attr('class', "layui-laypage layui-enabled");
              }else{
                  $('#summaryPrevious').attr('class', "layui-laypage layui-disabled");
              }
              $('.layui-laypage-count').text('Total '+total_records+' Records');
              var data = response["data"];
              var data_count = data.length;
              function appendLeadingZeroes(n){
                if(n <= 9){
                return "0" + n;
                }
                return n
              }
              $('.other-data').html('');
              var tr_test_th = '<tr><td width="" class="text-center" colspan="2">Emp Code</td><td width="" class="text-center" colspan="5">Name</td><td width="" class="text-center" colspan="2">Present</td><td width="" class="text-center" colspan="2">Absent</td><td width="" class="text-center" colspan="2">HD</td><td width="" class="text-center" colspan="2">WO</td><td width="" class="text-center" colspan="2">HL</td><td width="" class="text-center" colspan="2">Paid_Lv</td><td width="" class="text-center" colspan="2">Unpaid_Lv</td><td width="" class="text-center" colspan="2">Paid_Days</td><td width="" class="text-center" colspan="2">LateHrs</td><td width="" class="text-center" colspan="2">EarlHrs</td><td width="" class="text-center" colspan="2">Work Hrs</td><td width="" class="text-center" colspan="2">OvTime</td><td width="" class="text-center" colspan="2">Leave Bal</td></tr>';
              for(var i=0;i<data_count;i++){
                  var tr_test = '';
                  var tr_test1 = '';
                  var tr_test2 = '';
                  var tr_test4 = '';
                  var tr_test5 = '';
                  var tr_test6 = '';
                  var tr_test7 = '';
                  var tr_test8 = '';
                  var tr_test3='';
                  tr_test +=tr_test_th;
                  tr_test1 += '<tr><td class="text-center" colspan="2">Clock In</td>';
                  tr_test2 += '<tr><td class="text-center" colspan="2">Clock Out</td>';
                  tr_test3 += '<tr><td class="text-center" colspan="2">Working Hrs</td>';
                  tr_test4 += '<tr><td class="text-center" colspan="2">OT Hrs</td>';
                  tr_test6 += '<tr><td class="text-center" colspan="2">Late Hrs</td>';
                  tr_test7 += '<tr style="white-space:nowrap;"><td class="text-center" colspan="2">Early Leave Hrs</td>';
                  tr_test8 += '<tr><td class="text-center" colspan="2">Time Table</td>';
                  tr_test5 += '<tr><td class="text-center" colspan="2">Status</td>';
                  String.prototype.toHHMMSS = function () {
                    var sec_num = parseInt(this, 10); // don't forget the second param
                    var hours   = Math.floor(sec_num / 3600);
                    var minutes = Math.floor((sec_num - (hours * 3600)) / 60);
                    var seconds = sec_num - (hours * 3600) - (minutes * 60);
                    if (seconds > 30) {minutes = minutes+1;}
                    if (seconds > 30) {seconds = "00"}
                    if (minutes < 10) {minutes = "0"+minutes;}
                    return hours + ':' + minutes;
              }
                  dates.forEach(function(date) {
                        var punch_date = date.getFullYear() + "-" + appendLeadingZeroes(date.getMonth() + 1) + "-" + appendLeadingZeroes(date.getDate());
                        var day = date.getDate();
                        var days = weekday[date.getDay()];
                        var month = date.getMonth()+1;
                        var mon = month.toString();
                        var key1 = '';
                        if(mon.length < 2){
                            var mon = '0'+month.toString();
                        }else{
                            var mon = month.toString();
                        }
                        var key = day.toString();
                        if(key.length < 2){
                            var key1 = mon+'/0'+day.toString();
                        }else{
                            var key1 = mon+'/'+day.toString();
                        }
                        var a = data[i];
                        var b = a[key1];
                        var c = a['OT_'+key1];
                        var d = a['late_'+key1];
                        var e = a['earlyLeave_'+key1];
                        var f = a['shift_'+key1];
                        var g = a['checkin_'+key1];
                        var h = a['checkout_'+key1];
                        var totalt=a['totalt_'+key1];
                        if(totalt && totalt!="0"){
                            tr_test3 += '<td class="text-center">'+totalt.toHHMMSS()+'</td>';
                        }else{
                            tr_test3 += '<td class="text-center"></td>';
                        }
                        if(b){
                            tr_test5 += '<td class="text-center" style=color:'+color_report[b]+'>'+b+'</td>';
                        }else{
                            tr_test5 += '<td class="text-center"></td>';
                        }
                        if(c){

                            tr_test4 += '<td class="text-center">'+new Date(parseInt(c) * 1000).toISOString().substr(11, 5)+'</td>';
                        }else{
                            tr_test4 += '<td class="text-center"></td>';
                        }
                        if(d){
                            tr_test6 += '<td class="text-center">'+new Date(parseInt(d) * 1000).toISOString().substr(11, 5)+'</td>';
                        }else{
                            tr_test6 += '<td class="text-center"></td>';
                        }
                        if(e){
                            tr_test7 += '<td class="text-center">'+new Date(parseInt(e) * 1000).toISOString().substr(11, 5)+'</td>';
                        }else{
                            tr_test7 += '<td class="text-center"></td>';
                        }
                        if(f){
                            tr_test8 += '<td class="text-center">'+f+'</td>';
                        }else{
                            tr_test8 += '<td class="text-center"></td>';
                        }
                        if(g){
                            tr_test1 += '<td class="text-center">'+g.slice(11, 16)+'</td>';
                        }else{
                            tr_test1 += '<td class="text-center"></td>';
                        }
                        if(h){
                            tr_test2 += '<td class="text-center">'+h.slice(11, 16)+'</td>';
                        }else{
                            tr_test2 += '<td class="text-center"></td>';
                        }

                  });

                  function get_overtime_hours(total_not, total_wot, total_hot){
                      var hours = 0;
                      var minutes = 0;
                      if (total_not !== null && total_not != "") {
                        not_hours_minutes = total_not.split(":");
                        hours += Number(not_hours_minutes[0]);
                        minutes += Number(not_hours_minutes[1]);
                      }
                      if (total_wot !== null && total_wot != "") {
                        wot_hours_minutes = total_wot.split(":");
                        hours += Number(wot_hours_minutes[0]);
                        minutes += Number(wot_hours_minutes[1]);
                      }
                      if (total_hot !== null && total_hot != "") {
                        hot_hours_minutes = total_hot.split(":");
                        hours += Number(hot_hours_minutes[0]);
                        minutes += Number(hot_hours_minutes[1]);
                      }
                      hours = (hours + Math.floor(minutes / 60)).toString().padStart(2, "0");
                      minutes = (minutes % 60).toString().padStart(2, "0");
                      return (hours + ":" + minutes);
                  }

                  function get_late_hours(late_hours){
                      hours = late_hours == "" ? "00:00" : late_hours;
                      return hours;
                  }

                  function get_early_hours(early_hours){
                      hours = early_hours == "" ? "00:00" : early_hours;
                      return hours;
                  }

                  function get_work_hours(work_hours){
                      hours = work_hours == "" ? "00:00" : work_hours;
                      return hours;
                  }

                  var colspan_2 = '</td><td class="text-center" colspan="2">';
                  var colspan_5 = '</td><td class="text-center" colspan="5">';

                  var emp_code = '<tr style="background-color:#7ac145;">' + colspan_2 + data[i].emp_code;
                  var first_name = colspan_5 + data[i].first_name;
                  var present_count = colspan_2 + eval(0.5*data[i].total_halfday_count+data[i].total_present_count);
                  var absent_count = colspan_2 + data[i].total_absent;
                  var half_day = colspan_2 + data[i].total_halfday_count;
                  var week_off = colspan_2 + data[i].total_weekend;
                  var holiday = colspan_2 + data[i].total_holiday;
                  var paid_leave = colspan_2 + data[i].paid_leave;
                  var unpaid_leave = colspan_2 + data[i].unpaid_leave;
                  var paid_days = colspan_2 + eval(0.5*data[i].total_halfday_count+data[i].paid_leave+data[i].total_present_count+data[i].total_holiday+data[i].total_weekend);
                  var late_hours = colspan_2 + get_late_hours(data[i].total_late);
                  var early_hours = colspan_2 + get_early_hours(data[i].total_early_leave);
                  var work_hours = colspan_2 + get_work_hours(data[i].total_worked);
                  var overtime_hours = colspan_2 + get_overtime_hours(data[i].total_not, data[i].total_wot, data[i].total_hot);
                  var leave_balance = colspan_2 + (data[i].leave_balance_mr) + '</td></tr>';

                  tr_test = tr_test + emp_code + first_name + present_count + absent_count + half_day + week_off +
                            holiday + paid_leave + unpaid_leave + paid_days + late_hours + early_hours + work_hours +
                            overtime_hours + leave_balance;

                  tr_test += tr2;
                  tr_test += tr3;
                  tr_test1 += '</tr>';
                  tr_test2 += '</tr>';
                  tr_test3+='</tr>';
                  tr_test4 += '</tr>';
                  tr_test6 += '</tr>';
                  tr_test7 += '</tr>';
                  tr_test8 += '</tr>';
                  tr_test5 += '</tr>';
                  tr_test5 += '<tr><td style="background:#d8d8ce;" colspan="33"></td></tr>';
                  tr_test += tr_test1;
                  tr_test += tr_test2;
                  tr_test += tr_test3;
                  tr_test += tr_test4;
                  tr_test += tr_test6;
                  tr_test += tr_test7;
                  tr_test += tr_test8;
                  tr_test += tr_test5;
                  tr_test='<table>'+tr_test+'</table>'
                  $('.other-data').append(tr_test);
              }
              layer.close(loadIndex);
          }
          , error: function (xhr, error, e) {
            layer.close(loadIndex);
          }
        });
      });
        $(".{{ model_name }}-search").click();
      {% endblock %}
    });
    function display(a){
        var hours = Math.trunc(a/60);
        var minutes = Math.trunc(a % 60);
        if(minutes < 10){
            var minutes = '0'+minutes;
        }
        if(hours < 10){
            var hours = '0'+hours;
        }
        return hours +":"+ minutes
    }
  });
</script>
<script>
$('.summaryReportExportCsv').click(function(){
    var csv = [];
	var rows = document.querySelectorAll("#summaryReport tr");
    var start = $('#{{ model_name }}-start-date').val();
    var end = $('#{{ model_name }}-end-date').val();
    var header_data = 'Monthy summary report';
    var csv = [header_data];
    for (var i = 0; i < rows.length; i++) {
		var row = [], cols = rows[i].querySelectorAll("td, th");

        for (var j = 0; j < cols.length; j++)
            row.push(cols[j].innerText);

		csv.push(row.join(","));
	}
    console.log(csv);
    var filename =  'MonthlyAttendanceSummaryReport.csv';
    // Download CSV
    download_csv(csv.join("\n"), filename);

    document.querySelector("button").addEventListener("click", function () {
        var html = document.querySelector("table").outerHTML;
	    export_table_to_csv(html, "table.csv");
    });
    function download_csv(csv, filename) {
        var csvFile;
        var downloadLink;

        // CSV FILE
        csvFile = new Blob([csv], {type: "text/csv"});

        // Download link
        downloadLink = document.createElement("a");

        // File name
        downloadLink.download = filename;

        // We have to create a link to the file
        downloadLink.href = window.URL.createObjectURL(csvFile);

        // Make sure that the link is not displayed
        downloadLink.style.display = "none";

        // Add the link to your DOM
        document.body.appendChild(downloadLink);

        // Lanzamos
        downloadLink.click();
    }
    });

var tableToExcel = (function() {
let uri = 'data:application/vnd.ms-excel;base64,',
        template = '<html xmlns:o="urn:schemas-microsoft-com:office:office" xmlns:x="urn:schemas-microsoft-com:office:excel" xmlns="http://www.w3.org/TR/REC-html40"><title></title><head><!--[if gte mso 9]><xml><x:ExcelWorkbook><x:ExcelWorksheets><x:ExcelWorksheet><x:Name>{worksheet}</x:Name><x:WorksheetOptions><x:DisplayGridlines/></x:WorksheetOptions></x:ExcelWorksheet></x:ExcelWorksheets></x:ExcelWorkbook></xml><![endif]--><meta http-equiv="content-type" content="text/plain; charset=UTF-8"/></head><body><table>{table}</table></body></html>',
        base64 = function(s) { return window.btoa(decodeURIComponent(encodeURIComponent(s))) },
        format = function(s, c) { return s.replace(/{(\w+)}/g, function(m, p) { return c[p]; })}
        return function(table, name) {
     var start = $('#{{ model_name }}-start-date').val();
     var end = $('#{{ model_name }}-end-date').val();
    const monthNames = ["January", "February", "March", "April", "May", "June",
                            "July", "August", "September", "October", "November", "December"
    ];
    var start_dater = new Date(start);
    var end_dater = new Date(end);
    var gen_on = new Date().toString().substr(0, 25);

    var sTable = '<tr><td  colspan="33" style="font-size: 2em;border-top: 0; text-align: center;">Monthly Attendance Summary</td></tr>';
        sTable += '<tr><td colspan="33" style="text-align: center;"><small>'+monthNames[start_dater.getMonth()]+'-'+start_dater.getDate()+'-'+start_dater.getFullYear()+' To '+monthNames[end_dater.getMonth()]+'-'+end_dater.getDate()+'-'+end_dater.getFullYear()+'</small></td></tr>';
        sTable += '<tr><td style="text-align:left;">Company: '+company_name+'</td><td colspan="32" style="text-align:right">Generated on: '+gen_on+'</td></tr>';

    if (!table.nodeType) table = document.getElementById(table)
    var ctx = {worksheet: name || 'Worksheet', table: sTable+table.innerHTML}
    //window.location.href = uri + base64(format(template, ctx))
    var link= document.createElement("a");
    link.download= "MonthlyAttendanceSummaryReport.xls";
    link.href= uri + base64(format(template, ctx));
    link.click();
  }
})()

 function tableToPdf(tabId){
        var start = $('#{{ model_name }}-start-date').val();
        var end = $('#{{ model_name }}-end-date').val();
        const monthNames = ["January", "February", "March", "April", "May", "June",
                            "July", "August", "September", "October", "November", "December"
        ];
        var start_dater = new Date(start);
        var end_dater = new Date(end);
        var gen_on = new Date().toString().substr(0, 25);
        if(company_logo !== ''){
            if(company_logo_pos == '1'){
                var logo_style = 'left';
            }else if(company_logo_pos == '2'){
                var logo_style = 'center';
            }else{
                var logo_style = 'right';
            }
            var sTable = '<table><thead><tr><td><span style="float:'+logo_style+';"><img src='+company_logo+'  width="200px" height="75px"></img><span></td></tr><tr><th width="100%" class="text-center" style="font-size: 2em;border-top: 0;">Monthly Attendance Summary</th></tr>';
        }else{
            var sTable = '<table><thead><tr><th width="100%" class="text-center" style="font-size: 2em;border-top: 0;">Monthly Attendance Summary</th></tr>';
        }

        sTable += '<tr><th width="100%" class="text-center"><small>'+monthNames[start_dater.getMonth()]+'-'+start_dater.getDate()+'-'+start_dater.getFullYear()+' To '+monthNames[end_dater.getMonth()]+'-'+end_dater.getDate()+'-'+end_dater.getFullYear()+'</small></th></tr>';
        sTable += '</thead><tbody><tr><td><span style="float:left;">Company: '+company_name+'</span><span style="float:right;">Generated on: '+gen_on+'</span></td></tr></tbody></table>';
        sTable += $('#'+tabId).html();
        var style = "<style> @page { size: 84.1cm 59.4cm;margin: 1cm 1cm 1cm 1cm; }";
        style = style + "table {width: 100%;font: 23px Calibri;}";
        style = style + "table, th, td {border: solid 1px #DDD; border-collapse: collapse;page-break-inside: avoid !important;";
        style = style + "padding: 2px 3px;text-align: center;}";
        style = style + "</style>";

        // CREATE A WINDOW OBJECT.
        var win = window.open('', '', 'height=700,width=700');

        win.document.write('<html><head>');
        win.document.write(style);          // ADD STYLE INSIDE THE HEAD TAG.
        win.document.write('</head>');
        win.document.write('<body>');
        win.document.write(sTable);         // THE TABLE CONTENTS INSIDE THE BODY TAG.
        win.document.write('</body></html>');

        win.document.close(); 	// CLOSE THE CURRENT WINDOW.

        win.print();    // PRINT THE CONTENTS.
    }
</script>
<script>
    //this is for pagination
    $("#layui-icon-refresh").click(function(){
        $(".{{ model_name }}-search").click();
    })
    $(".summaryReportPageFind").click(function(){
        $(".{{ model_name }}-search").click();
    })
    $('#SummaryReportPageLimit').change(function(){
        $(".{{ model_name }}-search").click();
    })
    $('#summaryPrevious').click(function(){
        var current_page_value =  eval($('#findpage').val());
        if(current_page_value > 1) {
            $('#findpage').val(current_page_value - 1);
        }
        $(".{{ model_name }}-search").click();
    });
    $('#summaryNext').click(function(){
        var current_page_value = eval($('#findpage').val());
        $('#findpage').val(current_page_value+1);
        $(".{{ model_name }}-search").click();
    });
</script>





