<?php 
function outputCsv( $assocDataArray ) {

        if ( !empty( $assocDataArray ) ):

            $fp = fopen( 'php://output', 'w' );
            fputcsv( $fp, array_keys( reset($assocDataArray) ) );

            foreach ( $assocDataArray AS $values ):
                fputcsv( $fp, $values );
            endforeach;

            fclose( $fp );
        endif;

        exit();
}
if(isset($_POST['action']) && $_POST['action'] == 'generate_report'){
  include("db.php");  
  $req = $_POST['req_for'];
  $u_info = get_user_by_id($_SESSION['loggedin_user']);
  if($req == 'csv_selected'){
    $u_id = $_SESSION['loggedin_user'];
    if(isset($_POST['pass_user_id']) && !empty($_POST['pass_user_id'])){
        $u_id = $_POST['pass_user_id'];
    }
    if(isset($_POST['p_user_id']) && !empty($_POST['p_user_id'])){
         $u_id = $_POST['p_user_id'];
    }
   
    $all_data = mysqli_query($conn,"SELECT * FROM db_timelog where task_date BETWEEN '" .date("Y-m-d",strtotime($_POST['r_start_date'])). " 00:00:00' AND '" .date("Y-m-d",strtotime($_POST['r_end_date'])). " 00:00:00' AND user_id=".$u_id);
    
  } else {
    if($u_info['type'] == 'manager'){
        $all_e_ids = array();
        $q = mysqli_query($conn, "SELECT * FROM db_projects WHERE manager_id=".$_SESSION['loggedin_user']);
        while($d = mysqli_fetch_assoc($q)){
            $e_ids = array_column(unserialize($e['employee_ids']), 'employe_id');

            if(!empty($e_ids)){
                foreach ( $e_ids as $val) {
                    if(!in_array($val, $all_emp_ids)){
                        array_push($all_e_ids, $val);
                    }
                }
            }

        }
        $all_data = mysqli_query($conn,"SELECT * FROM db_timelog where task_date BETWEEN '" .date("Y-m-d",strtotime($_POST['r_start_date'])). " 00:00:00' AND '" .date("Y-m-d",strtotime($_POST['r_end_date'])). " 00:00:00' and user_id in(".implode(',', $all_e_ids).")");
    } else if($u_info['type'] == 'company'){
            $all_e_ids = array();
            $q = mysqli_query($conn, "SELECT * FROM db_users WHERE company_name=".$_SESSION['loggedin_user']);
             while($d = mysqli_fetch_assoc($q)){
                array_push($all_e_ids, $d['id']);
            }
           
            $all_data = mysqli_query($conn,"SELECT * FROM db_timelog where task_date BETWEEN '" .date("Y-m-d",strtotime($_POST['r_start_date'])). " 00:00:00' AND '" .date("Y-m-d",strtotime($_POST['r_end_date'])). " 00:00:00' and user_id in(".implode(',', $all_e_ids).")");
    } else {
        $all_data = mysqli_query($conn,"SELECT * FROM db_timelog where task_date BETWEEN '" .date("Y-m-d",strtotime($_POST['r_start_date'])). " 00:00:00' AND '" .date("Y-m-d",strtotime($_POST['r_end_date'])). " 00:00:00'");

    }
    
  }

  $all_datas = array();
    while($r = mysqli_fetch_assoc($all_data)){
        $inner_arr = array();
        $inner_arr["Date"]          = date("d M Y", strtotime($r['task_date']));
        $inner_arr["Total Time"]    = $r['total_time'];
        $inner_arr["User"]          = get_user_by_id($r['user_id'])['full_name'];
        $inner_arr["Project"]       = mysqli_fetch_assoc(mysqli_query($conn, "SELECT * FROM db_projects WHERE id=".$r['project_id']))['name'];
        $inner_arr["Task"]          = mysqli_fetch_assoc(mysqli_query($conn, "SELECT * FROM db_tasks WHERE id=".$r['task_id']))['name'];
        $inner_arr["status"]        = $r['status'];


        array_push($all_datas, $inner_arr);

    }
    outputCsv($all_datas);
  die;
}

if(isset($_POST['action']) && $_POST['action'] == 'generate_report_docs'){

    include("db.php");  
    $req = $_POST['req_for'];

    if($req == 'pdf_selected' || $req == 'docs_selected'){

        $u_id = $_SESSION['loggedin_user'];
        if(get_user_by_id($u_id)['type'] == 'company'){
            $comp_mem_ids = mysqli_fetch_assoc(mysqli_query($conn, "SELECT GROUP_CONCAT(id SEPARATOR ',') AS ids FROM db_users WHERE company_name=".$_SESSION['loggedin_user']));
            if(!empty($comp_mem_ids)){
                 $u_id = $comp_mem_ids['ids'];
            }
        }
        if(isset($_POST['pass_user_id']) && !empty($_POST['pass_user_id'])){
            $u_id = $_POST['pass_user_id'];
        }
        if(isset($_POST['p_user_id'])){
            $u_id = $_POST['p_user_id'];
        }
        $u_info = get_user_by_id($_SESSION['loggedin_user']);
        $all_data = mysqli_query($conn,"SELECT * FROM db_timelog where task_date BETWEEN '" .date("Y-m-d",strtotime($_POST['r_start_date'])). " 00:00:00' AND '" .date("Y-m-d",strtotime($_POST['r_end_date'])). " 00:00:00' AND user_id=".$u_id); 
        
    } else {
        $u_info = get_user_by_id($_SESSION['loggedin_user']);
        if($u_info['type'] == 'manager'){
            $all_e_ids = array();
            $q = mysqli_query($conn, "SELECT * FROM db_projects WHERE manager_id=".$_SESSION['loggedin_user']);

            while($d = mysqli_fetch_assoc($q)){
                
                $e_ids = array_column(unserialize($d['employee_ids']), 'employe_id');

                if(!empty($e_ids)){
                    foreach ( $e_ids as $val) {
                        if(!in_array($val, $all_e_ids)){
                            array_push($all_e_ids, $val);
                        }
                    }
                }

            }
            
            $all_data = mysqli_query($conn,"SELECT * FROM db_timelog where task_date BETWEEN '" .date("Y-m-d",strtotime($_POST['r_start_date'])). "' AND '" .date("Y-m-d",strtotime($_POST['r_end_date'])). "' and user_id in(".implode(',', $all_e_ids).")");
        } else if($u_info['type'] == 'company'){
            $all_e_ids = array();
            $q = mysqli_query($conn, "SELECT * FROM db_users WHERE company_name=".$_SESSION['loggedin_user']);
             while($d = mysqli_fetch_assoc($q)){
                array_push($all_e_ids, $d['id']);
            }
            
            $all_data = mysqli_query($conn,"SELECT * FROM db_timelog where task_date BETWEEN '" .date("Y-m-d",strtotime($_POST['r_start_date'])). " 00:00:00' AND '" .date("Y-m-d",strtotime($_POST['r_end_date'])). " 00:00:00' and user_id in(".implode(',', $all_e_ids).")");
        } else {
            $all_data = mysqli_query($conn,"SELECT * FROM db_timelog where task_date BETWEEN '" .date("Y-m-d",strtotime($_POST['r_start_date'])). " 00:00:00' AND '" .date("Y-m-d",strtotime($_POST['r_end_date'])). " 00:00:00'");
        }
        
    }

  $all_datas = array();
  echo "<table border='1'><tbody><tr><td><b>Date</b></td><td><b>Total Time</b></td><td><b>User Name</b></td><td><b>Project Name</b></td><td><b>Task Name</b></td><td><b>Status</b></td></tr>";
    while($r = mysqli_fetch_assoc($all_data)){

        $p_name  = mysqli_fetch_assoc(mysqli_query($conn, "SELECT * FROM db_projects WHERE id=".$r['project_id']))['name'];
        $t_name  = mysqli_fetch_assoc(mysqli_query($conn, "SELECT * FROM db_tasks WHERE id=".$r['task_id']))['name'];
        
        //array_push($all_datas, $inner_arr);
        echo '<tr><td>'.date("d M Y", strtotime($r['task_date'])).'</td><td>'.$r['total_time'].'</td><td>'.get_user_by_id($r['user_id'])['full_name'].'</td><td>'.$p_name.'</td><td>'.$t_name.'</td><td>'.$r['status'].'</td></tr>';

    }
    echo "</tbody>";
    die();

}
include("header.php");

?>

    <div class="body d-flex py-lg-3 py-md-2">
        <div class="container-xxl">
            <div class="row align-items-center">
                <div class="border-0 mb-4">
                    <div class="card-header py-3 no-bg bg-transparent d-flex align-items-center px-0 justify-content-between border-bottom flex-wrap">
                        <h3 class="h4 mb-0">All Reports</h3>
                        <div class="inline-filter">
                            <?php if($emp_list['type'] == 'admin' || $emp_list['type'] == 'manager' || $emp_list['type'] == 'company'): ?>
                            <select class="select_emp" name="select_emp">
                                <?php
                                if($emp_list['type'] == 'admin'){
                                    $all_u = mysqli_query($conn, "SELECT * FROM db_users");
                                } else if($emp_list['type'] == 'manager'){
                                    $get_comp_emp_ids = mysqli_fetch_assoc(mysqli_query($conn, "SELECT GROUP_CONCAT(id SEPARATOR ',') AS ids FROM db_users where company_name=".$emp_list['company_name']));
                                    $all_u = mysqli_query($conn, "SELECT * FROM db_users where id in(".$get_comp_emp_ids['ids'].")");
                                    
                                } else {
                                    $get_comp_emp_ids = mysqli_fetch_assoc(mysqli_query($conn, "SELECT GROUP_CONCAT(id SEPARATOR ',') AS ids FROM db_users where company_name=".$emp_list['id']));
                                    
                                    $all_u = mysqli_query($conn, "SELECT * FROM db_users where id in(".$get_comp_emp_ids['ids'].")");

                                }
                                
                                if($emp_list['type'] == 'manager'){
                                    $manager_info = get_user_by_id($_SESSION['loggedin_user']);
                                   // echo "<option value='".$manager_info['id']."'>".$manager_info['full_name']."</option>";
                                    $all_ids = mysqli_query($conn, "SELECT * FROM db_projects WHERE manager_id=".$_SESSION['loggedin_user']);

                                    $all_emp_ids = array();
                                    
                                    while($e = mysqli_fetch_assoc($all_ids)){

                                        $e_ids = array_column(unserialize($e['employee_ids']), 'employe_id');

                                        if(!empty($e_ids)){
                                            foreach ( $e_ids as $val) {
                                                if(!in_array($val, $all_emp_ids)){
                                                    array_push($all_emp_ids, $val);
                                                }
                                            }
                                        }

                                    }
                                    if(!empty($all_emp_ids)){
                                        $all_u = mysqli_query($conn, "SELECT * FROM db_users where id in(".implode(',', $all_emp_ids).")");
                
                                    } else {
                                        $all_u = mysqli_query($conn, "SELECT * FROM db_users where id=0;");
                                    }
                                }
                                if($all_u->num_rows > 0){
                                    while($row = mysqli_fetch_assoc($all_u)){
                                        echo "<option value='".$row['id']."'>".$row['full_name']."</option>";
                                    } 
                                }
                               
                                ?>
                            </select>   
                            <?php endif; ?>                             
                        </div>
                        <div class="d-flex py-2 project-tab flex-wrap w-sm-100 ms-auto">
                                    
                            <input type="text" name="daterange" value="" placeholder="Filter By Date" autocomplete="off" style="width:192px;">
                                
                        </div>
                    </div>


                    <div class="row clearfix g-3">
                        <div class="col-sm-12">
                        </div>
                    </div>
                    
                </div>
            </div>
            <div class="download_div">
                <div class="dropdown">
                  <button onclick="myFunction()" class="dropbtn">Download Report</button>
                  <div id="myDropdown" class="dropdown-content">
                    
                    <?php 
                        if($emp_list['type'] == 'admin' || $emp_list['type'] == 'manager' || $emp_list['type'] == 'company'):
                    ?>
                        <a href="javascript:void(0);" class="dwnload_csv_selected">Selected User CSV</a>
                        <a href="javascript:void(0);" class="dwnload_csv_all">All User CSV</a>
                        <a href="javascript:void(0);" class="dwnload_docs_selected">Selected User Docs</a>
                        <a href="javascript:void(0);" class="dwnload_docs_all">All User Docs</a>
                        <a href="javascript:void(0);" class="dwnload_pdf_selected">Selected User Pdf</a>
                        <a href="javascript:void(0);" class="dwnload_pdf_all">All User Pdf</a>
                    <?php  else:  ?>
                        <a href="javascript:void(0);" class="dwnload_csv_selected">CSV format</a>
                        <a href="javascript:void(0);" class="dwnload_docs_selected">DOCS format</a>
                        <a href="javascript:void(0);" class="dwnload_pdf_selected">PDF format</a>
                    <?php endif; ?>
                  </div>
                </div>
            </div>
            <div class="row align-items-center">
                <h3 style="text-align: center;text-decoration: underline;">Timelog Report</h3>
                <div class="chart-div timelog-chart" style="height: 500px;width: 100%;display: flex;justify-content: center;">
                    
                    <canvas id="myChart"></canvas>
                </div>
                <h3 style="text-align: center;margin-top: 50px;text-decoration: underline;">Project Report</h3>
                <div class="chart-div project-chart" style="height: 500px;width: 100%;display: flex;justify-content: center;">
                    
                    <canvas id="myChart_1"></canvas>
                </div>
            </div>
        </div>
    </div>
    <div class="clearfix">
      <div class="spinner-border float-right" role="status" style="display:none;">
        <span class="sr-only">Loading...</span>
      </div>
    </div>
<?php
    include("footer.php");
?>
<style type="text/css">
.download_div {
    display: flex;
    flex-direction: row-reverse;
}
    
.spinner-border.float-right {
    position: fixed;
    top: 50%;
    left: 50%;
}

.dropbtn {
  background-color: #cea254;
  color: white;
  padding: 12px;
  font-size: 16px;
  border: none;
  cursor: pointer;
}

.dropbtn:hover, .dropbtn:focus {
  background-color: #2980B9;
}

.dropdown {
  position: relative;
  display: inline-block;
}

.dropdown-content {
  display: none;
  position: absolute;
  background-color: #f1f1f1;
  min-width: 160px;
  overflow: auto;
  box-shadow: 0px 8px 16px 0px rgba(0,0,0,0.2);
  z-index: 1;
}

.dropdown-content a {
  color: black;
  padding: 12px 14px;
  text-decoration: none;
  display: block;
}

.dropdown a:hover {background-color: #ddd;}

.show {display: block;}

</style>
<script type="text/javascript" src="https://cdn.jsdelivr.net/momentjs/latest/moment.min.js"></script>
<script type="text/javascript" src="https://cdn.jsdelivr.net/npm/daterangepicker/daterangepicker.min.js"></script>
 <script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.7/umd/popper.min.js"></script>
<link rel="stylesheet" type="text/css" href="https://cdn.jsdelivr.net/npm/daterangepicker/daterangepicker.css" />
<script src="https://cdn.jsdelivr.net/npm/chart.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jspdf/1.3.4/jspdf.debug.js"></script>


<script type="text/javascript">
    /* When the user clicks on the button, 
    toggle between hiding and showing the dropdown content */
    function myFunction() {
      document.getElementById("myDropdown").classList.toggle("show");
    }

    // Close the dropdown if the user clicks outside of it
    window.onclick = function(event) {
      if (!event.target.matches('.dropbtn')) {
        var dropdowns = document.getElementsByClassName("dropdown-content");
        var i;
        for (i = 0; i < dropdowns.length; i++) {
          var openDropdown = dropdowns[i];
          if (openDropdown.classList.contains('show')) {
            openDropdown.classList.remove('show');
          }
        }
      }
    }
    var chart_obj = '';
    var chart_obj_1 = '';
    <?php 

        $time_data = array();
        $project_data = array();
        $project_names = array();

        $qry = mysqli_query($conn, "SELECT * FROM db_timelog where task_date BETWEEN '" .date("Y-m-d",strtotime('this week monday')). " 00:00:00' AND '" .date("Y-m-d",strtotime('this week sunday')). " 00:00:00' AND user_id=".$_SESSION['loggedin_user']); 

        while($row = mysqli_fetch_assoc($qry)){
            array_push($time_data, $row['total_time']);
        }

        $qry_1 = mysqli_query($conn, "SELECT SUM( TIME_TO_SEC( total_time ) ) AS timeSum , task_date, project_id FROM db_timelog where task_date BETWEEN '" .date("Y-m-d",strtotime('this week monday')). " 00:00:00' AND '" .date("Y-m-d",strtotime('this week sunday')). " 00:00:00' AND user_id=".$_SESSION['loggedin_user']." GROUP by project_id"); 
        echo $qry_1;
        while($row_1 = mysqli_fetch_assoc($qry_1)){
            print_r($row_1);
            $time = gmdate("H", $row_1['timeSum']); //date('h', $date_hour);
            $time .= '.'.gmdate("i", $row_1['timeSum']);
            array_push($project_data, $time);
            $get_name = mysqli_fetch_assoc(mysqli_query($conn, "SELECT * FROM db_projects WHERE id=".$row_1['project_id']));
            array_push($project_names, $get_name['name']);
        }


    ?>
    function convert_to_time_format (pass_val) {
    var sec_num = parseInt(pass_val, 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 (hours   < 10) {hours   = "0"+hours;}
    if (minutes < 10) {minutes = "0"+minutes;}
    if (seconds < 10) {seconds = "0"+seconds;}
    return hours + ':' + minutes + ':' + seconds;
}
    
    var start   = moment().startOf('isoWeek');
    var end     = moment().endOf('isoWeek');

    function cb(start, end) {
        
            $(".spinner-border").show();
            $.ajax({
                type:"post",
                datType:"json",
                url:window.location.pathname,
                data:{report_start_date:start.format('DD-MM-YYYY'),report_end_date:end.format('DD-MM-YYYY'),pass_user_id: $("select.select_emp").val()},
                success: function(res){
                    /*$('select.form-select.sel_project').html($(res).find('select.sel_project').html());
                    f_2 = $(res).find('select.sel_project').html() ;
                    $(full_row).find("select").html($(res).find('select.sel_project').html());
                    $('select.form-select.sel_project').change();
                    $("div#addemp .clone_last_week").remove();
                    $("div#addemp button.add_new_pro").after($(res).find(".clone_last_week")[0].outerHTML);*/
                    var all_dates = [];
                    var new_res = [];
                    new_res[0] = {};
                    new_res[1] = {};
                    new_res[2] = {};

                    
                    new_res[0]['label'] = 'Approved Hours';
                    new_res[0]['borderWidth'] = 1;
                    new_res[0]['backgroundColor'] = '#1485d1';

                    new_res[1]['label'] = 'Pending Hours';
                    new_res[1]['borderWidth'] = 1;
                    new_res[1]['backgroundColor'] = '#ff9f40';

                    new_res[2]['label'] = 'Rejected Hours';
                    new_res[2]['borderWidth'] = 1;
                    new_res[2]['backgroundColor'] = 'red';

                    new_res[0]['data'] = [];
                    new_res[1]['data'] = [];
                    new_res[2]['data'] = [];

                    for(var i=0; i<=end.diff(start,'days'); i++){
                        
                        all_dates.push(moment(start).add(i,'days').format('DD MMM YYYY'));
                        var str_date = moment(start).add(i,'days').format('YYYY-MM-DD').toString();
                        var is_found = 0;
                        var is_val = '';
                        var appr_val = 0; var pend_val = 0; var rej_val = 0;

                        $.each(JSON.parse(res).time_data, function(k,m){
                            if(k == str_date){ is_found = 1; is_val = m; 
                                if(m['approved'] != undefined){ appr_val = 1; new_res[0]['data'].push(m['approved'].join(","));} 
                                if(m['pending approval'] != undefined){ pend_val = 1; new_res[1]['data'].push(m['pending approval'].join(","));} 
                                if(m['rejected'] != undefined){ rej_val = 1; new_res[2]['data'].push(m['rejected'].join(","));}

                            }
                        });
                        

                        //if(is_found == 0){
                            if(new_res[0] != undefined && appr_val == 0){ new_res[0]['data'].push('0');} 
                            if(new_res[1] != undefined && pend_val == 0){ new_res[1]['data'].push('0');} 
                            if(new_res[2] != undefined && rej_val == 0){ new_res[2]['data'].push('0');}
                        //}
                        /*if(is_found == 1){
                            new_res.push(is_val);
                        } else {
                            new_res.push(0);
                        }*/
                        /*if(res[moment(start).add(i,'days').format('YYYY-MM-DD')] == undefined){
                            new_res.push(0);
                        } else {
                            new_res.push(res[moment(start).add(i,'days').format('YYYY-MM-DD')]);
                        }*/
                    }
                    /*new_res[0]['data'] = Object.assign({}, new_res[0]['data']);
                    new_res[1]['data'] = Object.assign({}, new_res[1]['data']);
                    new_res[2]['data'] = Object.assign({}, new_res[2]['data']);*/
                    console.log(new_res);
                    
                    chart_obj.data.labels.pop();
                    chart_obj_1.data.labels.pop();
                     //chart_obj.data.datasets[0].data = [];
                     /*$.each(chart_obj.data.datasets,function(d,m){
                       
                       // d.data.pop();
                     })*/
                    setTimeout(function(){
                        chart_obj.data.labels = all_dates;
                        
                        chart_obj.data.datasets =new_res/*[{
                            label: 'Hours',
                            data: new_res,
                            borderWidth: 1
                          }]*/;
                        chart_obj.update();

                        chart_obj_1.data.labels = Object.values(JSON.parse(res).project_names);
                        
                        chart_obj_1.data.datasets = [{
                            label: 'Hours',
                            data: Object.values(JSON.parse(res).project_data),
                            borderWidth: 1
                          }];
                        chart_obj_1.update();
                        $(".spinner-border").hide();
                    },100);
                     
                    /*chart_obj.data.datasets = res;
                    chart_obj.update();*/
                    
                }
            });
               
    }
    $(document).ready(function(){

        
        

        $('input[name="daterange"]').daterangepicker({
            locale: {
                format: 'YYYY-MM-DD',
                firstDay:1,
            },weekStart: 1,
            startDate: start,
            endDate: end,
            ranges: {
               'This Week': [moment().startOf('isoWeek'), moment().endOf('isoWeek')],
               'Last 7 Days': [moment().startOf('isoWeek').subtract(7, 'days'), moment().startOf('isoWeek').subtract(1, 'days')],
            }
        }, cb);
        cb(start, end);

    });
    const ctx = document.getElementById('myChart');
    const ctx_1 = document.getElementById('myChart_1');

    var week_range = [];
    for(var i=0;i<=6;i++){
        week_range.push(moment().startOf('isoWeek').add(i, 'days').format("DD MMM Y"));
    }

   chart_obj = new Chart(ctx, {
        type: 'bar',
        data: {
          labels: week_range,
          datasets: [{
            label: 'Hours',
            data: <?= json_encode($time_data); ?>,
            borderWidth: 1
          }]
        },
        options: {
          scales: {
           /* y: {
              beginAtZero: true
            }*/
             y: {
                ticks: {
                    // Include a dollar sign in the ticks
                    callback: function(value, index, ticks) {
                        //console.log(ticks);
                        return convert_to_time_format(value);
                        //return new Date(value  * 1000).toISOString().substr(12, 7);
                    }
                }
            }
          },
           plugins: {
            tooltip: {
                callbacks: {
                    label: function(context) {
                        let label = context.dataset.label || '';
                        if (context.parsed.y !== null) {
                            label += " : "+convert_to_time_format(context.parsed.y);
                        }
                        
                        return label;
                    }
                }
            }
           }
        }
      });
   chart_obj_1 = new Chart(ctx_1, {
        type: 'doughnut',
       
        data: {
          labels: <?= json_encode($project_names); ?>, 
          datasets: [{
            label: 'Hours',
            data: <?= json_encode($project_data); ?>,
            hoverOffset: 4
          }]
        },
        options: {
            plugins: {
            tooltip: {
                callbacks: {
                    label: function(context) {
                        console.log(context);
                        let label = context.dataset.label || '';
                        if (context.parsed !== null) {
                            label += " : "+convert_to_time_format(context.parsed);
                        }
                        
                        return label;
                    }
                }
            }
           }
        }

        /*options: {
          scales: {
            y: {
              beginAtZero: true
            }
          }
        }*/
      });



   $(document).on("change", ".select_emp", function(){
        cb($('input[name="daterange"]').data('daterangepicker').startDate,$('input[name="daterange"]').data('daterangepicker').endDate);
   });

   $(document).on( 'click', '.dwnload_csv_selected, .dwnload_csv_all', function(e) {

    var product_id = $(this).data('product_id');
    var req_for = 'csv_all';
    if($(this).hasClass('dwnload_csv_selected')){
        req_for = 'csv_selected';
    }

    $.ajax({
        url :window.location.pathname, 
        type: 'POST',
        data: { action:"generate_report",req_for:req_for,r_start_date:$('input[name="daterange"]').data('daterangepicker').startDate.format('DD-MM-YYYY'),r_end_date:$('input[name="daterange"]').data('daterangepicker').endDate.format('DD-MM-YYYY'),p_user_id: $("select.select_emp").val()},
        success: function(data){

              /*
               * Make CSV downloadable
               */
              var downloadLink = document.createElement("a");
              var fileData = ['\ufeff'+data];

              var blobObject = new Blob(fileData,{
                 type: "text/csv;charset=utf-8;"
               });

              var url = URL.createObjectURL(blobObject);
              downloadLink.href = url;
              downloadLink.download = "reports.csv";

              /*
               * Actually download CSV
               */
              document.body.appendChild(downloadLink);
              downloadLink.click();
              document.body.removeChild(downloadLink);

        }
    });
});
  $(document).on("click",".dwnload_docs_all, .dwnload_docs_selected, .dwnload_pdf_selected, .dwnload_pdf_all", function(){
    var req_for = 'docs_all';
    var is_pdf = 0;
    if($(this).hasClass('dwnload_docs_selected')){
        req_for = 'docs_selected';
    }
    if($(this).attr("class").indexOf('pdf') > -1){
        is_pdf = 1;
        req_for = 'pdf_all';
        if($(this).hasClass('dwnload_pdf_selected')){
            req_for = 'pdf_selected';
        }
    }
      $.ajax({
        url :window.location.pathname, 
        type: 'POST',
        data: { action:"generate_report_docs",req_for:req_for,r_start_date:$('input[name="daterange"]').data('daterangepicker').startDate.format('DD-MM-YYYY'),r_end_date:$('input[name="daterange"]').data('daterangepicker').endDate.format('DD-MM-YYYY'),p_user_id: $("select.select_emp").val()},
        success: function(data){

            if(is_pdf == 0){

              var downloadLink = document.createElement("a");
              var fileData = ['\ufeff'+data];

              var blobObject = new Blob(fileData,{
                 type: "application/force-download;charset=utf-8;"
               });

              var url = URL.createObjectURL(blobObject);
              downloadLink.href = url;
              downloadLink.download = "reports.doc";

              document.body.appendChild(downloadLink);
              downloadLink.click();
              document.body.removeChild(downloadLink);
            } else {
                //var pdfdoc = new jsPDF("p", "mm", "tabloid");
                //var pdfdoc = new jsPDF('p','pt','a4');
                var pdfdoc = new jsPDF('landscape', 'pt', 'letter');
                
                //pdfdoc.setFontSize(14);
                margins = {
                    top: 30,
                    bottom: 30,
                    left: 30,
                    width: '100%'
                };
                var specialElementHandlers = {

                    '#ignoreContent': function (element, renderer) {

                        return true;

                    }

                    };
                  pdfdoc.fromHTML(data, 30, 30, {

                        'width': 600,

                        'elementHandlers': specialElementHandlers

                    });

                        pdfdoc.save('reports.pdf');

            }

        }
    });  
  });  



</script>