<?php 

    include("header.php");


    $all_projects_arr = array();
    $all_projects = mysqli_query($conn, "SELECT * FROM db_projects where user_id=".$_SESSION['loggedin_user']." or employee_ids REGEXP '.*\"employe_id\";s:[0-9]+:\"".$_SESSION['loggedin_user']."\".*'  order by id DESC");

    function send_mail_to_manager($project_id, $last_id){
        global $conn;

        // Add entry in activity table.
        $get_project_name = mysqli_fetch_assoc(mysqli_query($conn, "SELECT * FROM db_projects WHERE id=".$project_id));
        $get_timelog = mysqli_fetch_assoc(mysqli_query($conn, "SELECT * FROM db_projects WHERE id=".$last_id));

        if(!empty($get_project_name['manager_id'])){

            $title = "Added time by ".$show_name." for project ".$get_project_name['name'];
            $desc = "<p><b>Start Time:</b>".$get_timelog['start_time']."</p><p><b>End Time:</b>".$get_timelog['end_time']."</p>";

            mysqli_query($conn, "INSERT INTO db_user_activity(title, description, created_by, to_user_id, date_time) VALUES('$title', '','".$_SESSION['loggedin_user']."', '".$get_project_name['manager_id']."', '".date("Y-m-d h:i:s")."')");
            $u_info = get_user_by_id($get_project_name['manager_id']);
            
            if(isset($u_info['email']) && !empty($u_info['email'])){
                send_zoho_mail($u_info['email'],'$title',"Hello ".ucwords($u_info['full_name']).",<br><br> $title<br>$desc <br> You can take action by clicking on <a target='_blank' href='".$site_url."?approve_from_mail=".$last_id."&pass_uid=".$get_project_name['manager_id']."'>approve</a> or <a target='_blank' href='".$site_url."?reject_from_mail=".$last_id."&pass_uid=".$get_project_name['manager_id']."'>reject</a> <br><br> Regards,<br> Timesheethub.");
            }
            
        } 

    }
    function getStartAndEndDate($week, $year, $format) {
     
      $date_string = $year . 'W' . sprintf('%02d', $week);
      $return[0] = date($format, strtotime($date_string));
      $return[1] = date($format, strtotime($date_string . '7'));
      return $return;
    }
    function sum_of_times($time){

        if(empty($time)){
            return "00:00:00";
        }
         
        $sum = strtotime('00:00:00');
        $totaltime = 0;
         
        foreach( $time as $element ) {
            $timeinsec = strtotime($element) - $sum;
            $totaltime = $totaltime + $timeinsec;
        }
         
        $h = intval($totaltime / 3600);
        $totaltime = $totaltime - ($h * 3600);
        $m = intval($totaltime / 60);
        $s = $totaltime - ($m * 60);
         
        return "$h:$m:$s";

    }

    /* function get_log_array($pass_id){
        global $conn;

            $get_log = mysqli_fetch_array(mysqli_query($conn, "SELECT * FROM db_timelog WHERE id=".$pass_id))['log']; 
            if(empty($get_log)){
                $old_log = array();
            } else {
                $old_log = unserialize($get_log); 
            }

        return $old_log;
    } */

    if($emp_list['type'] == 'admin'){
        $all_tasks_inpro = mysqli_query($conn, "SELECT * FROM db_tasks where status='in-progress' order by id DESC");
        
        if (!empty($_GET['filter_proj'])) {
            $all_tasks_inpro = mysqli_query($conn, "SELECT * FROM db_tasks where project_id = '".$_GET['filter_proj']."' and status='in-progress' order by id DESC");
        }
    } elseif($emp_list['type'] == 'manager'){
        
        $all_man_pro = mysqli_query($conn, "SELECT * FROM db_projects where manager_id=".$_SESSION['loggedin_user']);

        
        while($single_row = mysqli_fetch_array($all_man_pro)){

            $all_projects_arr[$single_row['id']] = $single_row;
            
        }
        $all_tasks_inpro = mysqli_query($conn, "SELECT * FROM db_tasks where status='in-progress' and project_id in(".implode(',', array_keys($all_projects_arr)).")  order by id DESC");
        if (!empty($_GET['filter_proj'])) {
            $all_tasks_inpro = mysqli_query($conn, "SELECT * FROM db_tasks where project_id = '".$_GET['filter_proj']."' and status='in-progress' order by id DESC");
            
        }
    } else {
        $all_tasks_inpro = mysqli_query($conn, "SELECT * FROM db_tasks where status='in-progress' and (user_id=".$_SESSION['loggedin_user']." or emplyee_id REGEXP '.*[0-9]+;s:[0-9]+:\"".$_SESSION['loggedin_user']."\".*') order by id DESC");
        if (!empty($_GET['filter_proj'])) {
            $all_tasks_inpro = mysqli_query($conn, "SELECT * FROM db_tasks where project_id = '".$_GET['filter_proj']."' and status='in-progress' and (user_id=".$_SESSION['loggedin_user']." or emplyee_id REGEXP '.*[0-9]+;s:[0-9]+:\"".$_SESSION['loggedin_user']."\".*') order by id DESC");
        }

    }
     
   
     
    

    while ($single_project = mysqli_fetch_array($all_projects)) {
        $all_projects_arr[$single_project['id']]= $single_project;
    }

    $all_tasks_list = array();
    while($at = mysqli_fetch_assoc($all_tasks_inpro)){

        array_push($all_tasks_list, $at);
        if(!in_array($at['project_id'], $all_projects_arr)){
            
            $all_projects_arr[$at['project_id']] = mysqli_fetch_assoc(mysqli_query($conn, "SELECT * FROM db_projects where id=".$at['project_id']));
        }

     }

    if(isset($_POST['update_time'])){

        if(isset($_POST['week_first_day'])){
            foreach($_POST['week_first_day'] as $fd => $v_fd){
                 $start_time  = "09:00:00";
                 $end_time    = date("H:i:s",strtotime($start_time)+strtotime($v_fd));
                 $old_log = get_log_array($_POST['hidden_week_first_day'][$fd]);
                 array_push($old_log, array('user_id'=>$_SESSION['loggedin_user'],'action'=>'Resubmit','date_time'=>strtotime('now')));
                mysqli_query($conn, "UPDATE db_timelog SET total_time='$v_fd', status='pending approval', start_time='$start_time', end_time='$end_time' , log='".serialize($old_log)."'  WHERE id=".$_POST['hidden_week_first_day'][$fd]);
            }
        }

        if(isset($_POST['week_second_day'])){
            foreach($_POST['week_second_day'] as $sd => $v_sd){
                $start_time  = "09:00:00";
                $end_time    = date("H:i:s",strtotime($start_time)+strtotime($v_sd));
                $old_log = get_log_array($_POST['hidden_week_second_day'][$sd]);
                 array_push($old_log, array('user_id'=>$_SESSION['loggedin_user'],'action'=>'Resubmit','date_time'=>strtotime('now')));
                mysqli_query($conn, "UPDATE db_timelog SET total_time='$v_sd', status='pending approval', start_time='$start_time', end_time='$end_time', log='".serialize($old_log)."' WHERE id=".$_POST['hidden_week_second_day'][$sd]);
            }
        }

        if(isset($_POST['week_third_day'])){
            foreach($_POST['week_third_day'] as $td => $v_td){
                $start_time  = "09:00:00";
                $end_time    = date("H:i:s",strtotime($start_time)+strtotime($v_td));
                $old_log = get_log_array($_POST['hidden_week_third_day'][$td]);
                 array_push($old_log, array('user_id'=>$_SESSION['loggedin_user'],'action'=>'Resubmit','date_time'=>strtotime('now')));
                mysqli_query($conn, "UPDATE db_timelog SET total_time='$v_td', status='pending approval', start_time='$start_time', end_time='$end_time', log='".serialize($old_log)."' WHERE id=".$_POST['hidden_week_third_day'][$td]);
                
            }
        }

        if(isset($_POST['week_fourth_day'])){
            foreach($_POST['week_fourth_day'] as $fod => $v_fod){
                $start_time  = "09:00:00";
                $end_time    = date("H:i:s",strtotime($start_time)+strtotime($v_fod));
                $old_log = get_log_array($_POST['hidden_week_fourth_day'][$fod]);
                 array_push($old_log, array('user_id'=>$_SESSION['loggedin_user'],'action'=>'Resubmit','date_time'=>strtotime('now')));
                mysqli_query($conn, "UPDATE db_timelog SET total_time='$v_fod', status='pending approval', start_time='$start_time', end_time='$end_time', log='".serialize($old_log)."' WHERE id=".$_POST['hidden_week_fourth_day'][$fod]);
                
            }
        }

        if(isset($_POST['week_fifth_day'])){
            foreach($_POST['week_fifth_day'] as $fid => $v_fid){
                $start_time  = "09:00:00";
                $end_time    = date("H:i:s",strtotime($start_time)+strtotime($v_fid));
                $old_log = get_log_array($_POST['hidden_week_fifth_day'][$fid]);
                 array_push($old_log, array('user_id'=>$_SESSION['loggedin_user'],'action'=>'Resubmit','date_time'=>strtotime('now')));
                mysqli_query($conn, "UPDATE db_timelog SET total_time='$v_fid', status='pending approval', start_time='$start_time', end_time='$end_time', log='".serialize($old_log)."' WHERE id=".$_POST['hidden_week_fifth_day'][$fid]);
                
            }
        }

        if(isset($_POST['week_six_day'])){
            foreach($_POST['week_six_day'] as $sid => $v_sid){
                $start_time  = "09:00:00";
                $end_time    = date("H:i:s",strtotime($start_time)+strtotime($v_sid));
                $old_log = get_log_array($_POST['hidden_week_six_day'][$sid]);
                 array_push($old_log, array('user_id'=>$_SESSION['loggedin_user'],'action'=>'Resubmit','date_time'=>strtotime('now')));
                mysqli_query($conn, "UPDATE db_timelog SET total_time='$v_sid', status='pending approval', start_time='$start_time', end_time='$end_time', log='".serialize($old_log)."' WHERE id=".$_POST['hidden_week_six_day'][$sid]);
                
            }
        }

        if(isset($_POST['week_seven_day'])){
            foreach($_POST['week_seven_day'] as $sed => $v_sed){
                $start_time  = "09:00:00";
                $end_time    = date("H:i:s",strtotime($start_time)+strtotime($v_sed));
                $old_log = get_log_array($_POST['hidden_week_seven_day'][$sed]);
                 array_push($old_log, array('user_id'=>$_SESSION['loggedin_user'],'action'=>'Resubmit','date_time'=>strtotime('now')));
                mysqli_query($conn, "UPDATE db_timelog SET total_time='$v_sed', status='pending approval', start_time='$start_time', end_time='$end_time', log='".serialize($old_log)."' WHERE id=".$_POST['hidden_week_seven_day'][$sed]);
                
            }
        }
        echo "<script>window.history.replaceState( null, null, window.location.href );</script>";

    }

    if(isset($_POST['save_time'])){
         
       

        foreach($_POST['project_id'] as $p => $pi){
            $timelog_ids = array();
            $mail_table = "<table><thead><tr><th>".$_POST['hidden_first_week']."</th><th>".$_POST['hidden_second_week']."</th><th>".$_POST['hidden_third_week']."</th><th>".$_POST['hidden_forth_week']."</th><th>".$_POST['hidden_fifth_week']."</th><th>".$_POST['hidden_six_week']."</th><th>".$_POST['hidden_seven_week']."</th></tr></thead><tbody>";
            $mail_table += '<tr>';
            $task_id = '';
           if(isset($_POST['hidden_task_id'][$p]) && !empty($_POST['hidden_task_id'][$p])){
              $task_id = $_POST['hidden_task_id'][$p];
           } 
               $mail_table += '<td>'; 
                if(isset($_POST['week_first_day'][$p]) && !empty($_POST['week_first_day'][$p])){
                   $start_time  = "09:00:00";
                   $end_time    = date("H:i:s",strtotime($start_time)+strtotime($_POST['week_first_day'][$p]));
                    
                    mysqli_query($conn, "INSERT INTO db_timelog(task_details, start_time, end_time, total_time, task_date, project_id, task_id, user_id, status) VALUES('', '".$start_time."','".$end_time."', '".$_POST['week_first_day'][$p]."', '".$_POST['hidden_first_week']." 00:00:00', '".$pi."', '".$task_id."', '".$_SESSION['loggedin_user']."', 'pending approval')");
                    $last_id = mysqli_insert_id($conn);
                    array_push($timelog_ids, $last_id);
                    $mail_table += $_POST['week_first_day'][$p];
                    // if(!empty($last_id)){
                    //      send_mail_to_manager($pi,$last_id);
                    // }
                   
                }
                $mail_table += '</td><td>';

                if(isset($_POST['week_second_day'][$p]) && !empty($_POST['week_second_day'][$p])){
                   
                   $start_time  = "09:00:00";
                   $end_time    = date("H:i:s",strtotime($start_time)+strtotime($_POST['week_second_day'][$p]));

                    mysqli_query($conn, "INSERT INTO db_timelog(task_details, start_time, end_time, total_time, task_date, project_id, task_id, user_id, status) VALUES('', '".$start_time."','".$end_time."', '".$_POST['week_second_day'][$p]."', '".$_POST['hidden_second_week']." 00:00:00', '".$pi."', '".$task_id."', '".$_SESSION['loggedin_user']."', 'pending approval')");
                    $last_id = mysqli_insert_id($conn);
                    array_push($timelog_ids, $last_id);
                    $mail_table += $_POST['week_second_day'][$p];
                    // if(!empty($last_id)){
                    //      send_mail_to_manager($pi,$last_id);
                    // }
                }
                $mail_table += '</td><td>';

                if(isset($_POST['week_third_day'][$p]) && !empty($_POST['week_third_day'][$p])){
                   
                   $start_time  = "09:00:00";
                   $end_time    = date("H:i:s",strtotime($start_time)+strtotime($_POST['week_third_day'][$p]));

                    mysqli_query($conn, "INSERT INTO db_timelog(task_details, start_time, end_time,  total_time, task_date, project_id, task_id, user_id, status) VALUES('', '".$start_time."','".$end_time."', '".$_POST['week_third_day'][$p]."', '".$_POST['hidden_third_week']." 00:00:00', '".$pi."', '".$task_id."', '".$_SESSION['loggedin_user']."', 'pending approval')");
                    $last_id = mysqli_insert_id($conn);
                    array_push($timelog_ids, $last_id);
                    $mail_table += $_POST['week_third_day'][$p];
                    // if(!empty($last_id)){
                    //      send_mail_to_manager($pi,$last_id);
                    // }
                }
                $mail_table += '</td><td>';

                if(isset($_POST['week_fourth_day'][$p]) && !empty($_POST['week_fourth_day'][$p])){
                   
                    $start_time  = "09:00:00";
                    $end_time    = date("H:i:s",strtotime($start_time)+strtotime($_POST['week_fourth_day'][$p]));

                    mysqli_query($conn, "INSERT INTO db_timelog(task_details, start_time, end_time,  total_time, task_date, project_id, task_id, user_id, status) VALUES('', '".$start_time."','".$end_time."', '".$_POST['week_fourth_day'][$p]."', '".$_POST['hidden_forth_week']." 00:00:00', '".$pi."', '".$task_id."', '".$_SESSION['loggedin_user']."', 'pending approval')");

                    $last_id = mysqli_insert_id($conn);
                    array_push($timelog_ids, $last_id);
                    $mail_table += $_POST['week_fourth_day'][$p];
                    /*if(!empty($last_id)){
                         send_mail_to_manager($pi,$last_id);
                    }*/
                }
                $mail_table += '</td><td>';

                if(isset($_POST['week_fifth_day'][$p]) && !empty($_POST['week_fifth_day'][$p])){
                    
                    $start_time  = "09:00:00";
                    $end_time    = date("H:i:s",strtotime($start_time)+strtotime($_POST['week_fifth_day'][$p]));

                    mysqli_query($conn, "INSERT INTO db_timelog(task_details, start_time, end_time,  total_time, task_date, project_id, task_id, user_id, status) VALUES('', '".$start_time."','".$end_time."', '".$_POST['week_fifth_day'][$p]."', '".$_POST['hidden_fifth_week']." 00:00:00', '".$pi."', '".$task_id."', '".$_SESSION['loggedin_user']."', 'pending approval')");

                    $last_id = mysqli_insert_id($conn);
                    array_push($timelog_ids, $last_id);
                    $mail_table += $_POST['week_fifth_day'][$p];
                    /*if(!empty($last_id)){
                         send_mail_to_manager($pi,$last_id);
                    }*/
                }
                $mail_table += '</td><td>';

                if(isset($_POST['week_six_day'][$p]) && !empty($_POST['week_six_day'][$p])){
                    
                    $start_time  = "09:00:00";
                    $end_time    = date("H:i:s",strtotime($start_time)+strtotime($_POST['week_six_day'][$p]));

                    mysqli_query($conn, "INSERT INTO db_timelog(task_details, start_time, end_time,  total_time, task_date, project_id, task_id, user_id, status) VALUES('', '".$start_time."','".$end_time."', '".$_POST['week_six_day'][$p]."', '".$_POST['hidden_six_week']." 00:00:00', '".$pi."', '".$task_id."', '".$_SESSION['loggedin_user']."', 'pending approval')");

                    $last_id = mysqli_insert_id($conn);
                    array_push($timelog_ids, $last_id);
                    $mail_table += $_POST['week_six_day'][$p];
                    /*if(!empty($last_id)){
                         send_mail_to_manager($pi,$last_id);
                    }*/
                }
                $mail_table += '</td><td>';

                if(isset($_POST['week_seven_day'][$p]) && !empty($_POST['week_seven_day'][$p])){
                    

                    $start_time  = "09:00:00";
                    $end_time    = date("H:i:s",strtotime($start_time)+strtotime($_POST['week_seven_day'][$p]));

                    mysqli_query($conn, "INSERT INTO db_timelog(task_details, start_time, end_time, task_date, project_id, task_id, user_id, status) VALUES('', '".$start_time."','".$end_time."',  '".$_POST['week_seven_day'][$p]."', '".$_POST['hidden_seven_week']." 00:00:00', '".$pi."', '".$task_id."', '".$_SESSION['loggedin_user']."', 'pending approval')");

                    $last_id = mysqli_insert_id($conn);
                    array_push($timelog_ids, $last_id);
                    $mail_table += $_POST['week_seven_day'][$p];
                    /*if(!empty($last_id)){
                         send_mail_to_manager($pi,$last_id);
                    }*/
                }
                $mail_table += '</td>';
           
            $mail_table += '</tr></tbody></table>';

        $get_project_name = mysqli_fetch_assoc(mysqli_query($conn, "SELECT * FROM db_projects WHERE id=".$pi));
        

        if(!empty($get_project_name['manager_id'])){

            $title = "Added time by ".$show_name." for project ".$get_project_name['name'];
        

            mysqli_query($conn, "INSERT INTO db_user_activity(title, description, created_by, to_user_id, date_time) VALUES('$title', '','".$_SESSION['loggedin_user']."', '".$get_project_name['manager_id']."', '".date("Y-m-d h:i:s")."')");
            $u_info = get_user_by_id($get_project_name['manager_id']);
            
            if(isset($u_info['email']) && !empty($u_info['email'])){
                $app_query = http_build_query(array('approve_from_mail' => $timelog_ids));
                $rej_query = http_build_query(array('reject_from_mail' => $timelog_ids));
                send_zoho_mail($u_info['email'],'$title',"Hello ".ucwords($u_info['full_name']).",<br><br> $title<br>$mail_table <br> You can take action by clicking on <a target='_blank' href='".$site_url."?".$app_query."&pass_uid=".$get_project_name['manager_id']."'>approve</a> or <a target='_blank' href='".$site_url."?".$rej_query."&pass_uid=".$get_project_name['manager_id']."'>reject</a> <br><br> Regards,<br> Timesheethub.");
            }
            
        } 

        }
        

        /*mysqli_query($conn, "INSERT INTO db_timelog(task_details, start_time, end_time, task_date, project_id, user_id, status) VALUES('".$_POST['task_details']."', '".$_POST['start_time']."','".$_POST['end_time']."', '".$_POST['task_date']."', '".$_POST['project_id']."', '".$_SESSION['loggedin_user']."', 'pending approval')");*/
        

       echo "<script>window.location.href=window.location.pathname;</script>" ;

    }

    if(isset($_GET['delete_timelog']) && !empty($_GET['delete_timelog'])){
        mysqli_query($conn, "DELETE from db_timelog WHERE id=".$_GET['delete_timelog']);
        echo "<script>window.history.pushState('', '', window.location.pathname);</script>";
    }

    if(isset($_GET['clone_id']) && !empty($_GET['clone_id']) ){
        $fetch_timelog = mysqli_fetch_assoc(mysqli_query($conn, "SELECT * from db_timelog WHERE id=".$_GET['clone_id']));
        mysqli_query($conn, "INSERT INTO db_timelog(task_details, start_time, end_time, task_date, project_id, user_id, status) VALUES('".$fetch_timelog['task_details']."', '".$fetch_timelog['start_time']."','".$fetch_timelog['end_time']."', '".date("Y-m-d h:i:s")."', '".$fetch_timelog['project_id']."', '".$fetch_timelog['user_id']."', 'pending approval')");
        $last_id = mysqli_insert_id($conn);

         // Add entry in activity table.
        $get_project_name = mysqli_fetch_assoc(mysqli_query($conn, "SELECT * FROM db_projects WHERE id=".$fetch_timelog['project_id']));
        if(!empty($get_project_name['manager_id'])){

            $title = "Added time by ".$show_name." for project ".$get_project_name['name'];
            $desc = "<p><b>Start Time:</b>".$fetch_timelog['start_time']."</p><p><b>End Time:</b>".$fetch_timelog['end_time']."</p>";

            mysqli_query($conn, "INSERT INTO db_user_activity(title, description, created_by, to_user_id, date_time) VALUES('$title', '','".$_SESSION['loggedin_user']."', '".$get_project_name['manager_id']."', '".date("Y-m-d h:i:s")."')");
            $u_info = get_user_by_id($get_project_name['manager_id']);
            
            if(isset($u_info['email']) && !empty($u_info['email'])){
                send_zoho_mail($u_info['email'],'$title',"Hello ".ucwords($u_info['full_name']).",<br><br> $title<br>$desc <br> You can take action by clicking on <a target='_blank' href='".$site_url."?approve_from_mail=".$last_id."&pass_uid=".$get_project_name['manager_id']."'>approve</a> or <a target='_blank' href='".$site_url."?reject_from_mail=".$last_id."&pass_uid=".$get_project_name['manager_id']."'>reject</a> <br><br> Regards,<br> Timesheethub.");
            }
            
        }
        echo "<script>window.history.pushState('', '', window.location.pathname);</script>";
    }

    if(isset($_POST['approve_bulk']) && !empty($_POST['approve_bulk'])){
        foreach($_POST['approve_bulk'] as $ab){
            
            $old_log = get_log_array($ab);
            array_push($old_log, array('user_id'=>$_SESSION['loggedin_user'],'action'=>'Approved','date_time'=>strtotime('now')));
            mysqli_query($conn, "UPDATE db_timelog SET status='approved', log='".serialize($old_log)."' WHERE id=".$ab);  

            $get_timelog = mysqli_fetch_assoc(mysqli_query($conn, "SELECT * FROM db_timelog WHERE id=".$ab));
            if(!empty($get_timelog['project_id'])){

                $get_project_name = mysqli_fetch_assoc(mysqli_query($conn, "SELECT * FROM db_projects WHERE id=".$get_timelog['project_id']));

                $title = "Approved timelog by ".$show_name." for project ".$get_project_name['name'];
                // Add entry in activity table.
                mysqli_query($conn, "INSERT INTO db_user_activity(title, description, created_by, to_user_id, date_time) VALUES('$title', '','".$_SESSION['loggedin_user']."', '".$get_timelog['user_id']."', '".date("Y-m-d h:i:s")."')");
                // Send mail to related user
                if(!empty(get_user_by_id($get_timelog['user_id']))){
                    $mail_to = get_user_by_id($get_timelog['user_id']);
                    send_zoho_mail($mail_to['email'],$title,"Hello ".ucwords($mail_to['full_name']).",<br><br> $title <br><br> Regards,<br> Timesheethub.");
                }

            }
        }
      
    }
    
    if(isset($_GET['approve']) && !empty($_GET['approve'])){
    
        $old_log = get_log_array($_GET['approve']);
        array_push($old_log, array('user_id'=>$_SESSION['loggedin_user'],'action'=>'Approved','date_time'=>strtotime('now')));

        mysqli_query($conn, "UPDATE db_timelog SET status='approved', log='".serialize($old_log)."' WHERE id=".$_GET['approve']);

        
        $get_timelog = mysqli_fetch_assoc(mysqli_query($conn, "SELECT * FROM db_timelog WHERE id=".$_GET['approve']));
        if(!empty($get_timelog['project_id'])){

            $get_project_name = mysqli_fetch_assoc(mysqli_query($conn, "SELECT * FROM db_projects WHERE id=".$get_timelog['project_id']));

            $title = "Approved timelog by ".$show_name." for project ".$get_project_name['name'];
            // Add entry in activity table.
            mysqli_query($conn, "INSERT INTO db_user_activity(title, description, created_by, to_user_id, date_time) VALUES('$title', '','".$_SESSION['loggedin_user']."', '".$get_timelog['user_id']."', '".date("Y-m-d h:i:s")."')");
            // Send mail to related user
            if(!empty(get_user_by_id($get_timelog['user_id']))){
                $mail_to = get_user_by_id($get_timelog['user_id']);
                send_zoho_mail($mail_to['email'],$title,"Hello ".ucwords($mail_to['full_name']).",<br><br> $title <br><br> Regards,<br> Timesheethub.");
            }

        }

        echo "<script>window.history.pushState('', '', window.location.pathname);</script>";
    }
    
    if(isset($_POST['reject_bulk']) && !empty($_POST['reject_bulk'])){
        foreach($_POST['reject_bulk'] as $rb){
            $old_log = get_log_array($rb);
            array_push($old_log, array('user_id'=>$_SESSION['loggedin_user'],'action'=>'Rejected','date_time'=>strtotime('now')));
            mysqli_query($conn, "UPDATE db_timelog SET status='rejected', log='".serialize($old_log)."' WHERE id=".$rb);  
            
            $get_timelog = mysqli_fetch_assoc(mysqli_query($conn, "SELECT * FROM db_timelog WHERE id=".$rb));
            if(!empty($get_timelog['project_id'])){

                $get_project_name = mysqli_fetch_assoc(mysqli_query($conn, "SELECT * FROM db_projects WHERE id=".$get_timelog['project_id']));

                $title = "Rejected timelog by ".$show_name." for project ".$get_project_name['name'];
                // Add entry in activity table.
                mysqli_query($conn, "INSERT INTO db_user_activity(title, description, created_by, to_user_id, date_time) VALUES('$title', '','".$_SESSION['loggedin_user']."', '".$get_timelog['user_id']."', '".date("Y-m-d h:i:s")."')");
                // Send mail to related user
                if(!empty(get_user_by_id($get_timelog['user_id']))){
                    $mail_to = get_user_by_id($get_timelog['user_id']);
                    send_zoho_mail($mail_to['email'],$title,"Hello ".ucwords($mail_to['full_name']).",<br><br> $title <br><br> Regards,<br> Timesheethub.");
                }

            }
        }
      
    }

    if(isset($_GET['reject']) && !empty($_GET['reject'])){
        
        $old_log = get_log_array($_GET['reject']);
        array_push($old_log, array('user_id'=>$_SESSION['loggedin_user'],'action'=>'Rejected','date_time'=>strtotime('now')));
        
        mysqli_query($conn, "UPDATE db_timelog SET status='rejected', log='".serialize($old_log)."' WHERE id=".$_GET['reject']);

        
        $get_timelog = mysqli_fetch_assoc(mysqli_query($conn, "SELECT * FROM db_timelog WHERE id=".$_GET['reject']));
        if(!empty($get_timelog['project_id'])){

            $get_project_name = mysqli_fetch_assoc(mysqli_query($conn, "SELECT * FROM db_projects WHERE id=".$get_timelog['project_id']));

            $title = "Rejected timelog by ".$show_name." for project ".$get_project_name['name'];
            // Add entry in activity table.
            mysqli_query($conn, "INSERT INTO db_user_activity(title, description, created_by, to_user_id, date_time) VALUES('$title', '','".$_SESSION['loggedin_user']."', '".$get_timelog['user_id']."', '".date("Y-m-d h:i:s")."')");
            // Send mail to related user
            if(!empty(get_user_by_id($get_timelog['user_id']))){
                $mail_to = get_user_by_id($get_timelog['user_id']);
                send_zoho_mail($mail_to['email'],'$title',"Hello ".ucwords($mail_to['full_name']).",<br><br> $title <br><br> Regards,<br> Timesheethub.");
            }

        }

        echo "<script>window.history.pushState('', '', window.location.pathname);</script>";
    }



    /******** Timelog main Query Started ********/
    $start = 0;
    $limit = 2;
    if(isset($_GET['next_week']) && !empty($_GET['next_week'])){
        $start = $_GET['next_week']*2;
    }
    if($emp_list['type'] == 'admin'){
         $query = "SELECT GROUP_CONCAT(id SEPARATOR ',') AS ids, WEEK(task_date,1) AS Week, YEAR(task_date) AS Year, COUNT(*) AS Total FROM db_timelog GROUP BY Year, Week order by Year desc, Week desc limit  $start, $limit";
            
        if(!empty($_GET['filter_proj']) && !empty($_GET['filter_date'])){
                $pass_date = explode(' - ', $_GET['filter_date']);
                $query = "SELECT GROUP_CONCAT(id SEPARATOR ',') AS ids, WEEK(task_date,1) AS Week, YEAR(task_date) AS Year, COUNT(*) AS Total FROM db_timelog where cast(task_date as date) >= DATE('".$pass_date[0]." 00:00:00') and cast(task_date as date) <=  DATE('".$pass_date[1]." 00:00:00') and project_id=".$_GET['filter_proj']." GROUP BY Year, Week order by Year desc, Week desc limit $start, $limit";
        } elseif (!empty($_GET['filter_proj'])) {
                $query = "SELECT GROUP_CONCAT(id SEPARATOR ',') AS ids, WEEK(task_date,1) AS Week, YEAR(task_date) AS Year, COUNT(*) AS Total FROM db_timelog where project_id=".$_GET['filter_proj']." GROUP BY Year, Week order by Year desc, Week desc limit $start, $limit";
        } elseif (!empty($_GET['filter_date'])) {
                $pass_date = explode(' - ', $_GET['filter_date']);
                $query = "SELECT  GROUP_CONCAT(id SEPARATOR ',') AS ids, WEEK(task_date,1) AS Week, YEAR(task_date) AS Year, COUNT(*) AS Total FROM db_timelog where cast(task_date as date) >= DATE('".$pass_date[0]." 00:00:00') and cast(task_date as date) <=  DATE('".$pass_date[1]." 00:00:00') GROUP BY Year, Week order by Year desc, Week desc limit $start, $limit";
        }

        /*$query = "select * from db_timelog ORDER BY id DESC";

        if(!empty($_GET['filter_proj']) && !empty($_GET['filter_date'])){
             $pass_date = explode(' - ', $_GET['filter_date']);
             $query = "select * from db_timelog where task_date >= DATE('".$pass_date[0]." 00:00:00') and task_date <=  DATE('".$pass_date[1]." 00:00:00') and project_id=".$_GET['filter_proj']." ORDER BY id DESC";
        } elseif (!empty($_GET['filter_proj'])) {
            $query = "select * from db_timelog where project_id=".$_GET['filter_proj']." ORDER BY id DESC";
        } elseif (!empty($_GET['filter_date'])) {
            $pass_date = explode(' - ', $_GET['filter_date']);
            $query = "select * from db_timelog where task_date >= DATE('".$pass_date[0]." 00:00:00') and task_date <=  DATE('".$pass_date[1]." 00:00:00') ORDER BY id DESC";
        }*/
       
        $all_timelog = mysqli_query($conn, $query);
        $all_proj = mysqli_fetch_all(mysqli_query($conn, "select project_id from db_timelog group by project_id"), MYSQLI_ASSOC);

     }  elseif ($emp_list['type'] == 'manager') {

           $all_projects = mysqli_query($conn, "SELECT * FROM db_projects WHERE manager_id=".$_SESSION['loggedin_user']);
           $my_projects = array();
            while($row = mysqli_fetch_array($all_projects)){
                array_push($my_projects, $row['id']);
            }
            $query = "select * from db_timelog where project_id in(".implode(',',$my_projects).") ORDER BY id DESC";
            
            /*if(!empty($_GET['filter_proj']) && !empty($_GET['filter_date'])){
             $pass_date = explode(' - ', $_GET['filter_date']);
             $query = "select * from db_timelog where task_date >= DATE('".$pass_date[0]." 00:00:00') and task_date <=  DATE('".$pass_date[1]." 00:00:00') and project_id=".$_GET['filter_proj']." ORDER BY id DESC";
            } elseif (!empty($_GET['filter_proj'])) {
               $query = "select * from db_timelog where project_id=".$_GET['filter_proj']." ORDER BY id DESC";
            } elseif (!empty($_GET['filter_date'])) {
                $pass_date = explode(' - ', $_GET['filter_date']);
                $query = "select * from db_timelog where task_date >= DATE('".$pass_date[0]." 00:00:00') and task_date <=  DATE('".$pass_date[1]." 00:00:00') and project_id in(".implode(',',$my_projects).") ORDER BY id DESC";
            }*/
            $query = "SELECT GROUP_CONCAT(id SEPARATOR ',') AS ids, WEEK(task_date,1) AS Week, YEAR(task_date) AS Year, COUNT(*) AS Total FROM db_timelog where project_id in(".implode(',',$my_projects).") GROUP BY Year, Week order by Year desc, Week desc limit $start, $limit";
            
                    if(!empty($_GET['filter_proj']) && !empty($_GET['filter_date'])){
                        $pass_date = explode(' - ', $_GET['filter_date']);
                        $query = "SELECT GROUP_CONCAT(id SEPARATOR ',') AS ids, WEEK(task_date,1) AS Week, YEAR(task_date) AS Year, COUNT(*) AS Total FROM db_timelog where cast(task_date as date) >= DATE('".$pass_date[0]." 00:00:00') and cast(task_date as date) <=  DATE('".$pass_date[1]." 00:00:00') and project_id=".$_GET['filter_proj']." GROUP BY Year, Week order by Year desc, Week desc limit $start, $limit";
                    } elseif (!empty($_GET['filter_proj'])) {
                            $query = "SELECT GROUP_CONCAT(id SEPARATOR ',') AS ids, WEEK(task_date,1) AS Week, YEAR(task_date) AS Year, COUNT(*) AS Total FROM db_timelog where project_id=".$_GET['filter_proj']." GROUP BY Year, Week order by Year desc, Week desc limit $start, $limit";
                    } elseif (!empty($_GET['filter_date'])) {
                            $pass_date = explode(' - ', $_GET['filter_date']);
                            $query = "SELECT GROUP_CONCAT(id SEPARATOR ',') AS ids, WEEK(task_date,1) AS Week, YEAR(task_date) AS Year, COUNT(*) AS Total FROM db_timelog where cast(task_date as date) >= DATE('".$pass_date[0]." 00:00:00') and cast(task_date as date) <=  DATE('".$pass_date[1]." 00:00:00') and project_id in(".implode(',',$my_projects).") GROUP BY Year, Week order by Year desc, Week desc limit $start, $limit";
                    }
           // echo $query;

            $all_timelog = mysqli_query($conn, $query);
            if($all_timelog->num_rows > 0){
                $all_proj = mysqli_fetch_all(mysqli_query($conn, "select project_id from db_timelog where project_id in(".implode(',',$my_projects).") group by project_id"), MYSQLI_ASSOC);
            }
            
        
     } else {

        $emp_ids = $_SESSION['loggedin_user'];
        if($emp_list['type'] == 'company'){
           $get_emp_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($get_emp_ids) && isset($get_emp_ids['ids'])){
                $emp_ids = $get_emp_ids['ids'];
           }
        }

        $query = "SELECT GROUP_CONCAT(id SEPARATOR ',') AS ids,WEEK(task_date,1) AS Week, YEAR(task_date) AS Year, COUNT(*) AS Total FROM db_timelog where user_id in(".$emp_ids.") GROUP BY Year, Week order by Year desc, Week desc limit  $start, $limit";


            
        if(!empty($_GET['filter_proj']) && !empty($_GET['filter_date'])){
                $pass_date = explode(' - ', $_GET['filter_date']);
                $query = "SELECT GROUP_CONCAT(id SEPARATOR ',') AS ids, WEEK(task_date,1) AS Week, YEAR(task_date) AS Year, COUNT(*) AS Total FROM db_timelog where cast(task_date as date) >= DATE('".$pass_date[0]." 00:00:00') and cast(task_date as date) <=  DATE('".$pass_date[1]." 00:00:00') and project_id=".$_GET['filter_proj']." and user_id in(".$emp_ids.") GROUP BY Year, Week order by Year desc, Week desc limit $start, $limit";
        } elseif (!empty($_GET['filter_proj'])) {
                $query = "SELECT GROUP_CONCAT(id SEPARATOR ',') AS ids, WEEK(task_date,1) AS Week, YEAR(task_date) AS Year, COUNT(*) AS Total FROM db_timelog where project_id=".$_GET['filter_proj']." and user_id in(".$emp_ids.") GROUP BY Year, Week order by Year desc, Week desc limit $start, $limit";
        } elseif (!empty($_GET['filter_date'])) {
                $pass_date = explode(' - ', $_GET['filter_date']);
                $query = "SELECT GROUP_CONCAT(id SEPARATOR ',') AS ids, WEEK(task_date,1) AS Week, YEAR(task_date) AS Year, COUNT(*) AS Total FROM db_timelog where cast(task_date as date) >= DATE('".$pass_date[0]." 00:00:00') and cast(task_date as date) <=  DATE('".$pass_date[1]." 00:00:00') and user_id in(".$emp_ids.")  GROUP BY Year, Week order by Year desc, Week desc limit $start, $limit";
        }

       /* $query = "select * from db_timelog where user_id=".$_SESSION['loggedin_user']." ORDER BY id DESC";
    
        if(!empty($_GET['filter_proj']) && !empty($_GET['filter_date'])){
             $pass_date = explode(' - ', $_GET['filter_date']);
             $query = "select * from db_timelog where task_date >= DATE('".$pass_date[0]." 00:00:00') and task_date <=  DATE('".$pass_date[1]." 00:00:00')  and user_id=".$_SESSION['loggedin_user']." and project_id=".$_GET['filter_proj']." ORDER BY id DESC";
            } elseif (!empty($_GET['filter_proj'])) {
               $query = "select * from db_timelog where project_id='".$_GET['filter_proj']."' and user_id=".$_SESSION['loggedin_user']." ORDER BY id DESC";
            } elseif (!empty($_GET['filter_date'])) {
                $pass_date = explode(' - ', $_GET['filter_date']);
                $query = "select * from db_timelog where task_date >= DATE('".$pass_date[0]." 00:00:00') and task_date <=  DATE('".$pass_date[1]." 00:00:00') and user_id=".$_SESSION['loggedin_user']." ORDER BY id DESC";
            }*/

        $all_timelog = mysqli_query($conn, $query);
        $all_proj = mysqli_fetch_all(mysqli_query($conn, "select project_id from db_timelog where user_id=".$_SESSION['loggedin_user']." group by project_id"), MYSQLI_ASSOC);
        
     }
     //print_r($all_timelog);
                                           
?>

<!-- Body: Body -->       
    <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">Timelog</h3>
                            <div class="inline-filter">
                                <select class="project_filter">
                                    <option value=""> -- Select Project -- </option>
                                    <?php 
                                    if(!empty($all_projects_arr)){
                                        foreach($all_projects_arr as $single_pro){
                                           // $fetch_pro = mysqli_fetch_assoc(mysqli_query($conn, "SELECT * FROM db_projects WHERE id=".$single_pro['project_id']));
                                            $selected_proj = ($_GET['filter_proj'] == $single_pro['id']) ? "selected" : "";
                                           // if(!empty($fetch_pro)){
                                                echo '<option value="'.$single_pro['id'].'" '.$selected_proj.'>'.$single_pro['name'].'</option>';
                                            //}
                                            
                                        }
                                    }
                                    ?>

                                </select>
                                <?php 
                                    if($emp_list['type'] == 'manager' || $emp_list['type'] == 'admin' || $emp_list['type'] == 'company'){
                                        echo "<select class='select_emp' name='select_emp'><option value=''> -- Select Employee -- </option>";
                                        
                                        if($emp_list['type'] == 'manager'){
                                            $pro_query = mysqli_query($conn, "SELECT * FROM db_projects WHERE manager_id=".$_SESSION['loggedin_user']);
                                            $all_emps = array();
                                            while ($p_row = mysqli_fetch_array($pro_query)) {
                                                $emp_row = unserialize($p_row['employee_ids']);
                                                if(!empty($emp_row)){
                                                    //array_merge($all_emps, array_column($emp_row, 'employe_id'));
                                                    foreach(array_column($emp_row, 'employe_id') as $s){
                                                        array_push($all_emps, $s);
                                                    }
                                                }
                                            }
                                            $all_emps = array_unique($all_emps);
                                            
                                            foreach($all_emps as $ae){
                                                $sel = (isset($_GET['filter_emp']) && $_GET['filter_emp'] == $ae ) ? "selected" : "";
                                                echo '<option value="'.$ae.'" '.$sel.'>'.get_user_by_id($ae)['full_name'].'</option>';
                                            }

                                        } elseif($emp_list['type'] == 'company'){
                                            $get_managers = mysqli_fetch_array(mysqli_query($conn, "SELECT GROUP_CONCAT(id SEPARATOR ',') AS ids FROM db_users WHERE type='manager' and company_name='".$_SESSION['loggedin_user']."' "));
                                            $pro_query = mysqli_query($conn, "SELECT * FROM db_projects WHERE manager_id in(".$get_managers[ids].")");
                                            $all_emps = array();
                                            while ($p_row = mysqli_fetch_array($pro_query)) {
                                                $emp_row = unserialize($p_row['employee_ids']);
                                                if(!empty($emp_row)){
                                                    //array_merge($all_emps, array_column($emp_row, 'employe_id'));
                                                    foreach(array_column($emp_row, 'employe_id') as $s){
                                                        array_push($all_emps, $s);
                                                    }
                                                }
                                            }
                                            $all_emps = array_unique($all_emps);
                                            
                                            foreach($all_emps as $ae){
                                                $sel = (isset($_GET['filter_emp']) && $_GET['filter_emp'] == $ae ) ? "selected" : "";
                                                echo '<option value="'.$ae.'" '.$sel.'>'.get_user_by_id($ae)['full_name'].'</option>';
                                            }

                                        } else {
                                            $emp_query = mysqli_query($conn, "SELECT * FROM  db_users WHERE type='employee'");
                                            while($get_emp = mysqli_fetch_array($emp_query)){
                                                echo '<option value="'.$get_emp['id'].'">'.$get_emp['full_name'].'</option>';
                                            }

                                        }
                                        echo "</select>";
                                    }
                                ?>
                                <input type="text" name="daterange" value="" placeholder="Filter By Date" autocomplete="off" style="width: 192px;" />
                                <button class='btn btn-dark clear_filter' style="display:none;">Clear Filter</button>
                            </div>
                            <div class="col-auto d-flex w-sm-100 mt-2 mt-sm-0">
                    
                                
                            </div>
                            </div>
                        </div>
                    </div> <!-- Row end  -->
                    <div class="row clearfix g-3">
                    <div class="col-sm-12">
                        <div class="card mb-3">
                            <div class="card-body timelog-body">
                                <?php  
                                /*
                                    // if ($emp_list['type'] != 'manager') {
                                ?>
                                <!-- <table id="myProjectTable" class="table table-hover align-middle mb-0" style="width:100%; display: none;">
                                    <thead>
                                        <tr>
                                            <th>Date</th>
                                            <th>Project</th>
                                            <th>Start Time</th>
                                            <th>End Time</th>
                                            <th>Worked</th>
                                            <th>Task Details</th>
                                            <th>Status</th>
                                            <th>Actions</th>
                                        </tr>
                                    </thead>
                                    <tbody>
                                        <?php 

                                            if(!empty($all_timelog)){
                                                while($res = mysqli_fetch_array($all_timelog)):

                                                    $pro_name = '-';
                                                    $action_html = '-';
                                                    if ($emp_list['type'] == 'manager') {
                                                        
                                                        if($res['status'] == 'pending approval'){
                                                            $action_html = '<button type="button" class="btn btn-success approve-btn action-btn" data-id="'.$res['id'].'" data-bs-toggle="modal" data-bs-target="#approve_req">Approve</button> <button type="button" class="btn btn-danger reject-btn action-btn" data-id="'.$res['id'].'" data-bs-toggle="modal" data-bs-target="#reject_req">Reject</button>';
                                                        }
                                                        
                                                    } else {
                                                        $action_html = '<a href="?clone_id='.$res['id'].'"><button type="button" class="btn btn-outline-secondary clone-btn" data-id="'.$res['id'].'" title="Clone"><i class="icofont-ui-copy text-success" ></i></button></a>
                                                            <button type="button" title="Delete" class="btn btn-outline-secondary deleterow" data-id="'.$res['id'].'" data-bs-toggle="modal" data-bs-target="#deleteproject"><i class="icofont-ui-delete text-danger"></i></button>';
                                                    }
                                                    if(!empty($res['project_id'])){
                                                        $get_project_name = mysqli_fetch_assoc(mysqli_query($conn, "SELECT * FROM db_projects WHERE id=".$res['project_id']));
                                                        $pro_name = $get_project_name['name'];
                                                    }
                                                    if(!empty($res['task_id'])){
                                                         $get_task_name = mysqli_fetch_assoc(mysqli_query($conn, "SELECT * FROM db_tasks WHERE id=".$res['task_id']));
                                                         $pro_name .= '<br><p class="task_name"><i class="icofont-long-arrow-right"></i>'.$get_task_name['name']."</p>";
                                                    }
                                                    
                                                    
                                                    $difference = '-';
                                                    if(!empty($res['start_time']) && !empty($res['end_time'])){
                                                        $time1 = strtotime($res['start_time']);
                                                        $time2 = strtotime($res['end_time']);
                                                        $elapsed = $time2 - $time1;
                                                        $difference =  date("H", $elapsed)."Hrs ".date("i", $elapsed)."min";
                                                    }
                                                    if(!empty($res['total_time'])){
                                                        $ex         = explode(':', $res['total_time']);
                                                        $difference = $ex[0]."Hrs ".$ex[1]."min";
                                                    }
                                                    
                                                echo '<tr>
                                                   <td>
                                                       '.date('d/m/Y', strtotime($res['task_date'])).'
                                                   </td>
                                                   <td>
                                                       '.$pro_name.'
                                                   </td>
                                                   <td>
                                                       '.$res['start_time'].'
                                                   </td>
                                                   <td>
                                                        '.$res['end_time'].'
                                                   </td>
                                                   <td>
                                                        '.$difference.'
                                                   </td>
                                                   <td>
                                                        '.$res['task_details'].'
                                                   </td>
                                                    <td>
                                                        '.$res['status'].'
                                                   </td>
                                                   
                                                    <td>
                                                        <div class="btn-group" role="group" aria-label="Basic outlined example">

                                                            '.$action_html.'
                                                        </div>
                                                    </td>
                                                </tr>';
                                            endwhile;
                                            }
                                            
                                        ?>
                                        
                                    </tbody>
                                </table> -->
                                <?php 
                                  //  } else { */
                                 //$qry = mysqli_query($conn, "SELECT * FROM  db_timelog_change_request where status in(1) order by date_time desc");
                                 if($emp_list['type'] == 'admin') {
                                    $qry = mysqli_query($conn, "SELECT * FROM db_timelog_change_request where status in(1) order by date_time desc");
                                    } elseif($emp_list['type'] == 'manager'){
                                        // Default Query
                                        $qry = mysqli_query($conn, "SELECT * FROM db_timelog_change_request where status in(1) and timelog_id in(0) order by date_time desc");

                                    $all_projects = mysqli_query($conn, "SELECT * FROM db_projects WHERE manager_id=".$_SESSION['loggedin_user']);
                                    $my_projects = array();
                                      while($row = mysqli_fetch_array($all_projects)){
                                          array_push($my_projects, $row['id']);
                                      }
                                      if(!empty($my_projects)){
                                         $get_man_timelog = mysqli_fetch_assoc( mysqli_query($conn,"SELECT GROUP_CONCAT(id SEPARATOR ',') AS ids FROM db_timelog where project_id in(".implode(',',$my_projects).")"));
                                         if(isset($get_man_timelog['ids']) && !empty($get_man_timelog['ids'])){
                                            $qry = mysqli_query($conn, "SELECT * FROM db_timelog_change_request where status in(1) and timelog_id in(".$get_man_timelog['ids'].") order by date_time desc");
                                         }

                                      }
                           
            
                           
                            } elseif($emp_list['type'] == 'company'){
                                $qry = mysqli_query($conn, "SELECT * FROM db_timelog_change_request where status in(1) and timelog_id in(0) order by date_time desc");

                                $all_users = mysqli_query($conn, "SELECT * FROM db_users WHERE company_name=".$_SESSION['loggedin_user']);
                                $my_users = array();
                                while($row = mysqli_fetch_array($all_users)){
                                      array_push($my_users, $row['id']);
                                }
                                if(!empty($my_users)){
                                     $get_man_timelog = mysqli_fetch_assoc( mysqli_query($conn,"SELECT GROUP_CONCAT(id SEPARATOR ',') AS ids FROM db_timelog where user_id in(".implode(',',$my_users).")"));
                                     if(isset($get_man_timelog['ids']) && !empty($get_man_timelog['ids'])){
                                        $qry = mysqli_query($conn, "SELECT * FROM db_timelog_change_request where status in(1) and timelog_id in(".$get_man_timelog['ids'].") order by date_time desc");
                                       // echo "SELECT * FROM db_timelog_change_request where status in(1) and timelog_id in(".$get_man_timelog['ids'].") order by date_time desc";
                                        //print_r($get_man_timelog);
                                     }

                                }
                            }
                           
                                ?>
                                <table class="manager_tbl" style="width: 100%;">
                                    <thead><tr><td colspan="7" style="text-align: right;padding-bottom: 0;"><a class="view_all_req" href="view_request.php">View Requests(<?= $qry->num_rows; ?>)</a></td></tr></thead>
                                    <?php 
                                    // $main_query = "SELECT WEEK(task_date) AS Week, YEAR(task_date) AS Year, COUNT(*) AS Total FROM db_timelog where project_id in(".implode(',',$my_projects).") GROUP BY Year, Week order by Year desc, Week desc";
                                    
                                        
                                        $q = mysqli_query( $conn, $query);
                                        if($q->num_rows == 0){
                                            echo "<tbody><tr><td><p class='no_rec'> No Record Found</p></td></tr></tbody>";

                                        } else {
                                        while( $raw = mysqli_fetch_assoc($q) ){
                                            
                                        $week_info = getStartAndEndDate($raw['Week'], $raw['Year'], 'Y-m-d');
                                        /*if ($emp_list['type'] == 'employee') {
                                            $get_week_data = mysqli_query($conn, "SELECT * FROM db_timelog where task_date >= DATE('".$week_info[0]." 00:00:00') and task_date <=  DATE('".$week_info[1]." 00:00:00') and user_id=".$_SESSION['loggedin_user']);
                                        } else {
                                            $get_week_data = mysqli_query($conn, "SELECT * FROM db_timelog where task_date >= DATE('".$week_info[0]." 00:00:00') and task_date <=  DATE('".$week_info[1]." 00:00:00')");
                                        }*/
                                        $get_week_data = explode(',', $raw['ids']);

                                        //$get_week_data = mysqli_query($conn, "SELECT * FROM db_timelog where task_date >= DATE('".$week_info[0]." 00:00:00') and task_date <=  DATE('".$week_info[1]." 00:00:00') and user_id=".$_SESSION['loggedin_user']);
                                        if(!empty($get_week_data)){
                                            $week_format = getStartAndEndDate($raw['Week'], $raw['Year'], 'M d');
                                            echo '<tbody><tr class="start_tr" data-week="">
                                                        <th colspan="8">'.$week_format[0].' - '.$week_format[1].'</th>
                                                    </tr>
                                                    <tr class="top-bar-timelog">';
                                                    if($emp_list['type'] == 'manager' || $emp_list['type'] == 'admin' || $emp_list['type'] == 'company') {
                                                        echo '<th class="first_checkbox" data-w="'.$raw['Week'].'"><input type="checkbox" class="select_all_week_day" value="'.$raw['Week'].'"></th>';
                                                    }
                                                            echo '<th>Date</th>
                                                            <th>Name</th>
                                                            <th>Description</th>
                                                            <th>Project</th>
                                                            <th style="display:none;">Start time</th>
                                                            <th style="display:none;">End time</th>
                                                            <th>Worked</th>
                                                            <th>Manager</th>
                                                            
                                                            <th>Status</th>
                                                            <th>Log</th>
                                                    </tr>';
                                                    $has_rejected = 0;
                                                    $approved_count = 0;
                                                    $reject_count = 0;
                                                    $pending_count = 0;
                                           // while ( $inner_raw = mysqli_fetch_assoc($get_week_data) ) {
                                                foreach($get_week_data as $single_entry){
                                                    $inner_raw = mysqli_fetch_assoc(mysqli_query($conn, "SELECT * from db_timelog WHERE id=".$single_entry));
                                                   
                                                    $pro_name = '-';
                                                    $man_name = '-';
                                                    
                                                   
                                                    if($emp_list['type'] == 'manager'){
                                                        if(!isset($all_projects_arr[$inner_raw['project_id']])){
                                                            continue;
                                                        }
                                                    }
                                            
                                                    if(!empty($inner_raw['project_id'])){
                                                        $get_project_name = mysqli_fetch_assoc(mysqli_query($conn, "SELECT * FROM db_projects WHERE id=".$inner_raw['project_id']));
                                                        $pro_name = $get_project_name['name'];
                                                        $m_info = get_user_by_id($get_project_name['manager_id']);
                                                        $man_name = $m_info['full_name'];
                                                        if(isset($_GET['filter_proj']) && !empty($_GET['filter_proj'])){
                                                            if($inner_raw['project_id'] != $_GET['filter_proj']){
                                                                continue;
                                                            }
                                                           
                                                        }
                                                    }

                                                    if(isset($_GET['filter_emp']) && !empty($_GET['filter_emp']) && $_GET['filter_emp'] != $inner_raw['user_id']){
                                                        continue;
                                                    }


                                                    if(!empty($inner_raw['task_id'])){
                                                         $get_task_name = mysqli_fetch_assoc(mysqli_query($conn, "SELECT * FROM db_tasks WHERE id=".$inner_raw['task_id']));
                                                         $pro_name .= '<br><p class="task_name"><i class="icofont-long-arrow-right"></i>'.$get_task_name['name']."</p>";
                                                    }
                                                    
                                                   
                                                    $difference = '-';
                                                    if(!empty($inner_raw['start_time']) && !empty($inner_raw['end_time'])){
                                                        $time1 = strtotime($inner_raw['start_time']);
                                                        $time2 = strtotime($inner_raw['end_time']);
                                                        $elapsed = $time2 - $time1;
                                                        $difference =  date("H", $elapsed)."Hrs ".date("i", $elapsed)."min";
                                                    }
                                                    if(!empty($inner_raw['total_time'])){
                                                        $ex         = explode(':', $inner_raw['total_time']);
                                                        $difference = $ex[0]."Hrs ".$ex[1]."min";
                                                    }
                                                    echo '<tr data-week-no="'.$raw['Week'].'" data-year="'.$raw['Year'].'" data-id="'.$inner_raw['id'].'">';

                                                    if($emp_list['type'] == 'manager' || $emp_list['type'] == 'admin' || $emp_list['type'] == 'company') {
                                                        if($inner_raw['status'] == 'pending approval'){
                                                        echo '<td class="first_checkbox" data-w="'.$raw['Week'].'"><input type="checkbox" class="select_single_day" value="'.$inner_raw['id'].'"></td>';
                                                        } else {
                                                            echo '<td class="first_checkbox"></td>';
                                                        }
                                                    }

                                                    $by_name = '';
                                                    $get_u = mysqli_query($conn, "SELECT * FROM db_users WHERE id=".$inner_raw['user_id']);
                                                    if($get_u->num_rows > 0){
                                                        $by_name = mysqli_fetch_assoc($get_u)['full_name'];
                                                    }

                                                    

            

        
                                                        echo '<td tabindex="0" class="">
                                                                       '.date('d/m/Y', strtotime($inner_raw['task_date'])).'
                                                            </td>
                                                            
                                                            <td>
                                                                '.$by_name.'
                                                            </td> 
                                                            <td style="width:20%">'.$inner_raw['task_details'].'</td>
                                                            <td>
                                                                      '.$pro_name.'
                                                                   </td>
                                                                   <td style="display:none;">
                                                                       '.$inner_raw['start_time'].'
                                                                   </td>
                                                                   <td style="display:none;">
                                                                        '.$inner_raw['end_time'].'
                                                                   </td>
                                                                   <td>
                                                                        '.$difference.'
                                                                   </td>
                                                                   <td class=" dt-body-right">
                                                                        '.$man_name.'
                                                                   </td>
                                                                   
                                                                    <td>
                                                                        '.$inner_raw['status'].'
                                                                   </td> 
                                                                   <td>
                                                                        <a class="v_log" data-id="'.$inner_raw['id'].'">View Log</a>
                                                                   </td> 
                                            
                                                
                                                    </tr>';
                                                    if($inner_raw['status'] == 'rejected' || $inner_raw['status'] == 'pending approval'){
                                                        $has_rejected = 1;
                                                    }

                                                    if( $inner_raw['status'] == 'approved'){
                                                        $approved_count++;
                                                    }
                                                    if($inner_raw['status'] == 'rejected'){
                                                        $reject_count++;
                                                    }
                                                    if($inner_raw['status'] == 'pending approval'){
                                                        $pending_count++;
                                                    }

                                            }
                                            if($emp_list['type'] == 'manager' || $emp_list['type'] == 'admin' || $emp_list['type'] == 'company') {
                                                echo '<tr class="last_tr"><th colspan="9"><button class="resubmit-btn manager" data-week-no="'.$raw['Week'].'" data-year="'.$raw['Year'].'">Edit Timelog</button></th></tr>';
                                               // if($get_week_data->num_rows != $approved_count ||  $emp_list['type'] == 'admin' ):
                                                 if($pending_count > 0 ||  $emp_list['type'] == 'admin' ):

                                                    echo '<tr class="last_tr"><th colspan="9">';
                                                    
                                                    echo '<button class="approve-btn-all" data-week-no="'.$raw['Week'].'">Approve All</button> <button class="approve-btn" data-week-no="'.$raw['Week'].'" style="display:none;">Approve Selcted</button><button class="reject-btn" data-week-no="'.$raw['Week'].'" style="display:none;">Reject Selcted</button>
                                                        <button class="reject-btn-all" data-week-no="'.$raw['Week'].'">Reject All</button>';
                                                   

                                                        echo '<button class="customize-btn-all" data-week-no="'.$raw['Week'].'">Customize</button> 
                                                       </th></tr>';
                                               endif;
                                            } else {
                                                if($has_rejected == 1 && $emp_list['type'] != 'admin'){
                                                    echo '<tr class="last_tr"><th colspan="9"><button class="resubmit-btn" data-week-no="'.$raw['Week'].'" data-year="'.$raw['Year'].'">Resubmit Timelog</button></th></tr>';
                                                }
                                                
                                            }
                                        echo "</tbody>";
                                        }
                                        
                                    }
                                        
                                    ?>
                                    
                                    
                                <?php } ?>
                                </table>

                                
                                <?php
                                        $next_p = 1;
                                        if(isset($_GET['next_week']) && !empty($_GET['next_week'])){
                                            $next_p = $_GET['next_week']+1;
                                        }
                                        if($q->num_rows != 0){
                                            echo "<div class='load_more_div'><button class='btn load_more_btn' data-value='".$next_p."'>Load More</button></div>";
                                        } 

                                    //}
                                ?>




                            </div>
                        </div>
                    </div>
                    </div><!-- Row End -->
                </div>
            </div>
            <?php 
                 $full_row = '<tr><td><select class="form-select sel_project" aria-label="Default select Project Category" name="project_id[]" required="">\
                            <option value="">Select Project Name</option>\ ';
                            
                foreach($all_projects_arr as $single_pro){
                  $full_row .= '<option value="'.$single_pro['id'].'" data-main>'.$single_pro['name'].'</option>'; 
                  $qu = mysqli_query($conn, "SELECT * FROM db_tasks WHERE project_id=".$single_pro['id']);

                  $arr = unserialize($single_pro['employee_ids']);

                  if($qu->num_rows > 0){
                    while($task_row = mysqli_fetch_array($qu)){
                        

                        if($emp_list['type'] == 'employee' && !array_search($_SESSION['loggedin_user'], array_column($arr, 'employe_id')) && !in_array($_SESSION['loggedin_user'], unserialize($task_row['emplyee_id']))){
                            continue;
                        }
                      $full_row .= '<option value="'.$single_pro['id'].'" data-task-id="'.$task_row['id'].'">&nbsp;&nbsp;&nbsp;'.$task_row['name'].'</option>\ ';
                    }
                  }
                }
                                                
                $full_row .= '</select><input type="hidden" name="hidden_task_id[]" class="hidden_task_id" value="" ></td>\
                        <td><input type="text" class="add_day_time" name="week_first_day[]" data-value="" placeholder="hh:ii:ss" autocomplete="off"></td>\
                        <td><input type="text" class="add_day_time" name="week_second_day[]" data-value="" placeholder="hh:ii:ss" autocomplete="off"></td>\
                        <td><input type="text" class="add_day_time" name="week_third_day[]" data-value="" placeholder="hh:ii:ss" autocomplete="off"></td>\
                        <td><input type="text" class="add_day_time" name="week_fourth_day[]" data-value="" placeholder="hh:ii:ss" autocomplete="off"></td>\
                        <td><input type="text" class="add_day_time" name="week_fifth_day[]" data-value="" placeholder="hh:ii:ss" autocomplete="off"></td>\
                        <td><input type="text" class="add_day_time" name="week_six_day[]" data-value="" placeholder="hh:ii:ss" autocomplete="off"></td>\
                        <td><input type="text" class="add_day_time" name="week_seven_day[]" data-value="" placeholder="hh:ii:ss" autocomplete="off"></td>\
                        <td class="last_td"><span class="time">00:00:00</span><sapn class="close_td">X</span></td></tr>\ ';
                        echo '<script>var full_row = \''.$full_row.'\'; </script>';
            ?>
             <div class="modal fade timelog-modal" id="addemp" tabindex="-1"  aria-hidden="true">
                <div class="modal-dialog modal-dialog-centered modal-lg modal-dialog-scrollable">
                    <div class="modal-content">
                        <div class="modal-header">
                            <h5 class="modal-title  fw-bold" id="createprojectlLabel"> Add Timelog</h5>
                            <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
                        </div>
                        <div class="modal-body" style="padding-top: 30px;"> 
                        
                        <form name="f1" method="POST" enctype="multipart/form-data">
                            <div class="date_div">
                                    <span class="time_info"><i class="icofont-info-circle"></i> Time in 24 hours formate</span>
                                <input type="text" name="select_range" class="top_range"></div>
                                <table class="add_time_tbl">
                                    <thead>
                                        <tr>
                                            <th class="col-span-4"><div class="project_div"><span>Projects</span></div></th>
                                            <th><span class="show_week_date">Mo,</span><input type="hidden" name="hidden_first_week"></th>
                                            <th><span class="show_week_date">Tu,</span><input type="hidden" name="hidden_second_week"></th>
                                            <th><span class="show_week_date">We,</span><input type="hidden" name="hidden_third_week"></th>
                                            <th><span class="show_week_date">Th,</span><input type="hidden" name="hidden_forth_week"></th>
                                            <th><span class="show_week_date">Fr,</span><input type="hidden" name="hidden_fifth_week"></th>
                                            <th><span class="show_week_date">Sa,</span><input type="hidden" name="hidden_six_week"></th>
                                            <th><span class="show_week_date">Su,</span><input type="hidden" name="hidden_seven_week"></th>
                                            <th><span>Total:</span></th>
                                        </tr>
                                    </thead>
                                    <tbody>
                                        <tr>
                                            <td><select class="form-select sel_project" aria-label="Default select Project Category" name="project_id[]" required="">
                                                <option value="">Select Project Name</option>
                                                <?php
                                                foreach($all_projects_arr as $single_pro){
                                                  echo '<option value="'.$single_pro['id'].'" data-main>'.$single_pro['name'].'</option>'; 
                                                  $qu = mysqli_query($conn, "SELECT * FROM db_tasks WHERE project_id=".$single_pro['id']);
                                                   $arr = unserialize($single_pro['employee_ids']);
                                                
                                                  if($qu->num_rows > 0){
                                                    while($task_row = mysqli_fetch_array($qu)){
                                                        if($emp_list['type'] == 'employee' && !array_search($_SESSION['loggedin_user'], array_column($arr, 'employe_id')) && !in_array($_SESSION['loggedin_user'], unserialize($task_row['emplyee_id']))){
                                                                continue;
                                                            }
                                                      echo '<option value="'.$single_pro['id'].'" data-task-id="'.$task_row['id'].'">&nbsp;&nbsp;&nbsp;'.$task_row['name'].'</option>';
                                                    }
                                                  }
                                                }
                                                ?>
                                        </select><input type="hidden" name="hidden_task_id[]" class="hidden_task_id" value=""></td>
                                            <td><input type="text" class="add_day_time" name="week_first_day[]" data-value="" placeholder="hh:ii:ss" autocomplete="off"></td>
                                            <td><input type="text" class="add_day_time" name="week_second_day[]" data-value="" placeholder="hh:ii:ss" autocomplete="off"></td>
                                            <td><input type="text" class="add_day_time" name="week_third_day[]" data-value="" placeholder="hh:ii:ss" autocomplete="off"></td>
                                            <td><input type="text" class="add_day_time" name="week_fourth_day[]" data-value="" placeholder="hh:ii:ss" autocomplete="off"></td>
                                            <td><input type="text" class="add_day_time" name="week_fifth_day[]" data-value="" placeholder="hh:ii:ss" autocomplete="off"></td>
                                            <td><input type="text" class="add_day_time" name="week_six_day[]" data-value="" placeholder="hh:ii:ss" autocomplete="off"></td>
                                            <td><input type="text" class="add_day_time" name="week_seven_day[]" data-value="" placeholder="hh:ii:ss" autocomplete="off"></td>
                                            <td class="last_td"><span class="time">00:00:00</span><sapn class="close_td">X</span></td>
                                        </tr>
                                    </tbody>
                                    <tfoot>
                                         <tr>
                                            <td>Total:</td>
                                            <td>00:00:00</td>
                                            <td>00:00:00</td>
                                            <td>00:00:00</td>
                                            <td>00:00:00</td>
                                            <td>00:00:00</td>
                                            <td>00:00:00</td>
                                            <td>00:00:00</td>
                                            <td></td>

                                        </tr>
                                    </tfoot>
                                </table>
                                <button type="button" class="add_new_pro"><i class="icofont-plus-circle"></i> Add new row</button>
                                <div class="deadline-form">
                          
                            <input type="submit" name="save_time" class="save_time" style="display: none;">
                           
                            </form>
                        </div>
                     <div class="modal-footer">
                            <!-- <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Done</button> -->
                            <button type="submit" class="btn btn-primary" name="submit" value="submit" onclick="$('.save_time').click();">Submit Timelog</button>
                            <button type="button" class="btn btn-primary clear-btn">Clear</button>

                        </div> 
                    </div>  
                </div>
            </div>
        </div>

        <div class="modal fade timelog-modal" id="view_emp" tabindex="-1"  aria-hidden="true">
                <div class="modal-dialog modal-dialog-centered modal-lg modal-dialog-scrollable">
                    <div class="modal-content">
                        <div class="modal-header">
                            <h5 class="modal-title  fw-bold" id="createprojectlLabel"> Edit Timelog</h5>
                            <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
                        </div>
                        <div class="modal-body" style="padding-top: 30px;"> 
                        
                        <form name="f1" method="POST" enctype="multipart/form-data">
                            <div class="date_div">
                                    <span class="time_info"><i class="icofont-info-circle"></i> Time in 24 hours formate</span>
                                <input type="text" name="select_range" class="top_range" style="display:none;"></div>
                                <table class="add_time_tbl">
                                    <thead>
                                        <tr>
                                            <th class="col-span-4"><div class="project_div"><span>Projects</span></div></th>
                                            <th><span class="show_week_date">Mo,</span><input type="hidden" name="hidden_first_week"></th>
                                            <th><span class="show_week_date">Tu,</span><input type="hidden" name="hidden_second_week"></th>
                                            <th><span class="show_week_date">We,</span><input type="hidden" name="hidden_third_week"></th>
                                            <th><span class="show_week_date">Th,</span><input type="hidden" name="hidden_forth_week"></th>
                                            <th><span class="show_week_date">Fr,</span><input type="hidden" name="hidden_fifth_week"></th>
                                            <th><span class="show_week_date">Sa,</span><input type="hidden" name="hidden_six_week"></th>
                                            <th><span class="show_week_date">Su,</span><input type="hidden" name="hidden_seven_week"></th>
                                            <th><span>Total:</span></th>
                                        </tr>
                                    </thead>
                                    <tbody>
                                        <?php  
                                        if(isset($_POST['resubmit_ids']) &&  !empty($_POST['resubmit_ids'])){
                                            $qr = mysqli_query($conn, "SELECT * FROM db_timelog where id in (".implode(",",$_POST['resubmit_ids']).") GROUP BY id, project_id HAVING COUNT(project_id)");
                                            $is_all_edit = $_POST['is_editable'];
                                            $resubmit_task_ids = array();
                                           
                                            if($qr->num_rows > 0){
                                                while($sr = mysqli_fetch_array($qr)){
                                                    if(is_null($sr['task_id']) || empty($sr['task_id'])){ 
                                                       if(!is_array($resubmit_project_list[$sr['task_id']])){ $resubmit_project_list[$sr['task_id']] = array(); }
                                                       array_push($resubmit_project_list[$sr['task_id']], $sr);
                                                       //$resubmit_project_list[$sr['task_id']] = $sr;
                                                    } else {
                                                       if(!is_array($resubmit_task_list[$sr['task_id']])){ $resubmit_task_list[$sr['task_id']] = array(); }
                                                       array_push($resubmit_task_list[$sr['task_id']], $sr);
                                                       //$resubmit_task_list[$sr['task_id']] = $sr;
                                                    }
                                               }
                                              
                                               if(!empty($resubmit_project_list)){
                                                   $main_tasks = array();
                                                  
                                                   foreach($resubmit_project_list as $k => $inner_projects):
                                                       
                                                   $get_week_format = getStartAndEndDate($_POST['resubmit_week'], $_POST['resubmit_year'], 'Y-m-d');
                                                   $start_of_week = $get_week_format[0];

                                                   $first_v    = '';   $first_e    = 'disabled';  $first_h    = ''; 
                                                   $second_v   = '';   $second_e   = 'disabled';  $second_h   = '';
                                                   $third_v    = '';   $third_e    = 'disabled';  $third_h    = '';
                                                   $fourth_v   = '';   $fourth_e   = 'disabled';  $fourth_h   = '';
                                                   $fifth_v    = '';   $fifth_e    = 'disabled';  $fifth_h    = '';
                                                   $six_v      = '';   $six_e      = 'disabled';  $six_h      = ''; 
                                                   $seven_v    = '';   $seven_e    = 'disabled';  $seven_h    = '';  


                                                   foreach($inner_projects as $sr):
                                                       
                                                      

                                                       if($start_of_week == date("Y-m-d",strtotime($sr['task_date'])) && $k == $sr['task_id'] ){
                                                           $first_v = $sr['total_time'];
                                                           $first_e = ($sr['status'] != 'approved' || $is_all_edit == 1) ? "" : "disabled";
                                                           $first_h = "<input type='hidden' name='hidden_week_first_day[]' value='".$sr['id']."'>";
                                                           
                                                       } 
                                                       $first_day_td = '<input type="text" name="week_first_day[]" class="add_day_time" placeholder="hh:mm:ss" autocomplete="off" value="'.$first_v.'" '.$first_e.'>'.$first_h; // First Day Input

                                                       if(date('Y-m-d', strtotime($start_of_week . ' +1 day')) == date("Y-m-d",strtotime($sr['task_date'])) && $k == $sr['task_id']){
                                                           $second_v = $sr['total_time'];
                                                           $second_e = ($sr['status'] != 'approved' || $is_all_edit == 1) ? "" : "disabled";
                                                           $second_h = "<input type='hidden' name='hidden_week_second_day[]' value='".$sr[date('Y-m-d', strtotime($start_of_week . ' +1 day'))]['id']."'>";
                                                       } 
                                                       $second_day_td = '<input type="text" name="week_second_day[]" class="add_day_time" placeholder="hh:mm:ss" autocomplete="off" value="'.$second_v.'" '.$second_e.'>'.$second_h; // Second Day Input

                                                       if(date('Y-m-d', strtotime($start_of_week . ' +2 day')) == date("Y-m-d",strtotime($sr['task_date'])) && $k == $sr['task_id']){
                                                           $third_v = $sr['total_time'];
                                                           $third_e = ($sr['status'] != 'approved' || $is_all_edit == 1) ? "" : "disabled";
                                                           $third_h = "<input type='hidden' name='hidden_week_third_day[]' value='".$sr['id']."'>".$third_h;
                                                       } 
                                                       $third_day_td = '<input type="text" name="week_third_day[]" class="add_day_time" placeholder="hh:mm:ss" autocomplete="off" value="'.$third_v.'" '.$third_e.'>'.$third_h;  // Third Day Input

                                                       if(date('Y-m-d', strtotime($start_of_week . ' +3 day')) == date("Y-m-d",strtotime($sr['task_date'])) && $k == $sr['task_id']){
                                                           $fourth_v = $sr['total_time'];
                                                           $fourth_e = ($sr['status'] != 'approved' || $is_all_edit == 1) ? "" : "disabled";
                                                           $fourth_h = "<input type='hidden' name='hidden_week_fourth_day[]' value='".$sr['id']."'>";
                                                       } 
                                                       $fourth_day_td = '<input type="text" name="week_fourth_day[]" class="add_day_time" placeholder="hh:mm:ss" autocomplete="off" value="'.$fourth_v.'" '.$fourth_e.'>'.$fourth_h;  // Forth Day Input

                                                       if(date('Y-m-d', strtotime($start_of_week . ' +4 day')) == date("Y-m-d",strtotime($sr['task_date'])) && $k == $sr['task_id']){
                                                           $fifth_v = $sr['total_time'];
                                                           $fifth_e = ($sr['status'] != 'approved' || $is_all_edit == 1) ? "" : "disabled";
                                                           $fifth_h = "<input type='hidden' name='hidden_week_fifth_day[]' value='".$sr['id']."'>";
                                                       } 
                                                       
                                                       $fifth_day_td = '<input type="text" name="week_fifth_day[]" class="add_day_time" placeholder="hh:mm:ss" autocomplete="off" value="'.$fifth_v.'" '.$fifth_e.'>'.$fifth_h; // Fifth Day Input

                                                       if(date('Y-m-d', strtotime($start_of_week . ' +5 day')) == date("Y-m-d",strtotime($sr['task_date'])) && $k == $sr['task_id']){
                                                           $six_v = $sr['total_time'];
                                                           $six_e = ($sr['status'] != 'approved' || $is_all_edit == 1) ? "" : "disabled";
                                                           $six_h = "<input type='hidden' name='hidden_week_six_day[]' value='".$sr['id']."'>";
                                                       } 
                                                       $six_day_td = '<input type="text" name="week_six_day[]" class="add_day_time" placeholder="hh:mm:ss" autocomplete="off" value="'.$six_v.'" '.$six_e.'>'.$six_h; // Six Day Input

                                                       if(date('Y-m-d', strtotime($start_of_week . ' +6 day')) == date("Y-m-d",strtotime($sr['task_date'])) && $k == $sr['task_id']){
                                                           $seven_v = $sr['total_time'];
                                                           $seven_e = ($sr['status'] != 'approved' || $is_all_edit == 1) ? "" : "disabled";
                                                           $seven_h = "<input type='hidden' name='hidden_week_seven_day[]' value='".$sr['id']."'>";
                                                       } 
                                                       $seven_day_td = '<input type="text" name="week_seven_day[]" class="add_day_time" placeholder="hh:mm:ss" autocomplete="off" value="'.$seven_v.'" '.$seven_e.'>'.$seven_h; // Seven Day Input

                                               
                                                   endforeach;

                                                   echo '<tr>
                                                       <td><select class="form-select sel_project" aria-label="Default select Project Category" name="project_id[]" required="" disabled>
                                                           <option value="">Select Project Name</option>';
                                                           if($sr['task_id'] == 0 && !empty($sr['project_id'])){
                                                               $get_pro = mysqli_fetch_assoc(mysqli_query($conn,"SELECT * from db_projects WHERE id=".$sr['project_id']));
                                                               echo '<option value="'.$sr['project_id'].'" data-main selected>'.$get_pro['name'].'</option>';   

                                                           } else {
                                                               if(!empty($sr['task_id'])){
                                                                   $get_task = mysqli_fetch_assoc(mysqli_query($conn, "SELECT * from db_tasks WHERE id=".$sr['task_id']));
                                                                  echo '<option value="'.$get_task['project_id'].'" data-task-id="'.$sr['task_id'].'" selected>&nbsp;&nbsp;&nbsp;'.$get_task['name'].'</option>'; 
                                                               }
                                                           }
                                                           foreach($all_projects_arr as $single_pro){
                                                               $selected_pr = ($sr['task_id'] == 0 && $single_pro['id'] == $sr['project_id'] ) ? "selected" : "";
                                                             echo '<option value="'.$single_pro['id'].'" data-main '.$selected_pr.'>'.$single_pro['name'].'</option>'; 
                                                             $qu = mysqli_query($conn, "SELECT * FROM db_tasks WHERE project_id=".$single_pro['id']);
                                                             
                                                             if($qu->num_rows > 0){
                                                               while($task_row = mysqli_fetch_array($qu)){
                                                                   $selected_ts = ($sr['task_id'] != 0 && $task_row['id'] == $sr['task_id'] ) ? "selected" : "";
                                                                 echo '<option value="'.$single_pro['id'].'" data-task-id="'.$task_row['id'].'" '.$selected_ts.'>&nbsp;&nbsp;&nbsp;'.$task_row['name'].'</option>';
                                                               }
                                                             }
                                                           }

                                                           

                                                          
                                                       echo '
                                                   </select><input type="hidden" name="hidden_task_id[]" class="hidden_task_id" value=""></td>
                                                       <td>'.$first_day_td.'</td>
                                                       <td>'.$second_day_td.'</td>
                                                       <td>'.$third_day_td.'</td>
                                                       <td>'.$fourth_day_td.'</td>
                                                       <td>'.$fifth_day_td.'</td>
                                                       <td>'.$six_day_td.'</td>
                                                       <td>'.$seven_day_td.'</td>
                                                       <td class="last_td"><span class="time">00:00:00</span><sapn class="close_td">X</span></td>
                                                   </tr>';
                                                   endforeach;
                                               }

                                               if(!empty($resubmit_task_list)){
                                                   $main_tasks = array();
                                                   foreach($resubmit_task_list as $k => $inner_tasks):
                                                       $first_v    = '';   $first_e    = 'disabled';  $first_h    = ''; 
                                                       $second_v   = '';   $second_e   = 'disabled';  $second_h   = '';
                                                       $third_v    = '';   $third_e    = 'disabled';  $third_h    = '';
                                                       $fourth_v   = '';   $fourth_e   = 'disabled';  $fourth_h   = '';
                                                       $fifth_v    = '';   $fifth_e    = 'disabled';  $fifth_h    = '';
                                                       $six_v      = '';   $six_e      = 'disabled';  $six_h      = ''; 
                                                       $seven_v    = '';   $seven_e    = 'disabled';  $seven_h    = '';  
                                                       $get_week_format = getStartAndEndDate($_POST['resubmit_week'], $_POST['resubmit_year'], 'Y-m-d');
                                                       $start_of_week = $get_week_format[0];

                                                       foreach($inner_tasks as $sr):
                                                           //$main_tasks[date("Y-m-d",strtotime($sr['task_date']))] = $sr;
                                                          

                                                  
                                                 // print_r($main_tasks);
                                                 //echo "<pre>";  print_r($sr); echo "</pre>";
                                                 if($start_of_week == date("Y-m-d",strtotime($sr['task_date'])) && $k == $sr['task_id'] ){
                                                   $first_v = $sr['total_time'];
                                                   $first_e = ($sr['status'] != 'approved' || $is_all_edit == 1) ? "" : "disabled";
                                                   $first_h = "<input type='hidden' name='hidden_week_first_day[]' value='".$sr['id']."'>";
                                                   
                                               } 
                                               $first_day_td = '<input type="text" name="week_first_day[]" class="add_day_time" placeholder="hh:mm:ss" autocomplete="off" value="'.$first_v.'" '.$first_e.'>'.$first_h; // First Day Input

                                               if(date('Y-m-d', strtotime($start_of_week . ' +1 day')) == date("Y-m-d",strtotime($sr['task_date'])) && $k == $sr['task_id']){
                                                   $second_v = $sr['total_time'];
                                                   $second_e = ($sr['status'] != 'approved' || $is_all_edit == 1) ? "" : "disabled";
                                                   $second_h = "<input type='hidden' name='hidden_week_second_day[]' value='".$sr[date('Y-m-d', strtotime($start_of_week . ' +1 day'))]['id']."'>";
                                               } 
                                                   $second_day_td = '<input type="text" name="week_second_day[]" class="add_day_time" placeholder="hh:mm:ss" autocomplete="off" value="'.$second_v.'" '.$second_e.'>'.$second_h; // Second Day Input

                                                   if(date('Y-m-d', strtotime($start_of_week . ' +2 day')) == date("Y-m-d",strtotime($sr['task_date'])) && $k == $sr['task_id']){
                                                       $third_v = $sr['total_time'];
                                                       $third_e = ($sr['status'] != 'approved' || $is_all_edit == 1) ? "" : "disabled";
                                                       $third_h = "<input type='hidden' name='hidden_week_third_day[]' value='".$sr['id']."'>".$third_h;
                                                   } 
                                                   $third_day_td = '<input type="text" name="week_third_day[]" class="add_day_time" placeholder="hh:mm:ss" autocomplete="off" value="'.$third_v.'" '.$third_e.'>'.$third_h;  // Third Day Input

                                                   if(date('Y-m-d', strtotime($start_of_week . ' +3 day')) == date("Y-m-d",strtotime($sr['task_date'])) && $k == $sr['task_id']){
                                                       $fourth_v = $sr['total_time'];
                                                       $fourth_e = ($sr['status'] != 'approved' || $is_all_edit == 1) ? "" : "disabled";
                                                       $fourth_h = "<input type='hidden' name='hidden_week_fourth_day[]' value='".$sr['id']."'>";
                                                   } 
                                                   $fourth_day_td = '<input type="text" name="week_fourth_day[]" class="add_day_time" placeholder="hh:mm:ss" autocomplete="off" value="'.$fourth_v.'" '.$fourth_e.'>'.$fourth_h;  // Forth Day Input

                                                   if(date('Y-m-d', strtotime($start_of_week . ' +4 day')) == date("Y-m-d",strtotime($sr['task_date'])) && $k == $sr['task_id']){
                                                       $fifth_v = $sr['total_time'];
                                                       $fifth_e = ($sr['status'] != 'approved' || $is_all_edit == 1) ? "" : "disabled";
                                                       $fifth_h = "<input type='hidden' name='hidden_week_fifth_day[]' value='".$sr['id']."'>";
                                                   } 
                                                   
                                                   $fifth_day_td = '<input type="text" name="week_fifth_day[]" class="add_day_time" placeholder="hh:mm:ss" autocomplete="off" value="'.$fifth_v.'" '.$fifth_e.'>'.$fifth_h; // Fifth Day Input

                                                   if(date('Y-m-d', strtotime($start_of_week . ' +5 day')) == date("Y-m-d",strtotime($sr['task_date'])) && $k == $sr['task_id']){
                                                       $six_v = $sr['total_time'];
                                                       $six_e = ($sr['status'] != 'approved' || $is_all_edit == 1) ? "" : "disabled";
                                                       $six_h = "<input type='hidden' name='hidden_week_six_day[]' value='".$sr['id']."'>";
                                                   } 
                                                   $six_day_td = '<input type="text" name="week_six_day[]" class="add_day_time" placeholder="hh:mm:ss" autocomplete="off" value="'.$six_v.'" '.$six_e.'>'.$six_h; // Six Day Input

                                                   if(date('Y-m-d', strtotime($start_of_week . ' +6 day')) == date("Y-m-d",strtotime($sr['task_date'])) && $k == $sr['task_id']){
                                                       $seven_v = $sr['total_time'];
                                                       $seven_e = ($sr['status'] != 'approved' || $is_all_edit == 1) ? "" : "disabled";
                                                       $seven_h = "<input type='hidden' name='hidden_week_seven_day[]' value='".$sr['id']."'>";
                                                   } 
                                                   $seven_day_td = '<input type="text" name="week_seven_day[]" class="add_day_time" placeholder="hh:mm:ss" autocomplete="off" value="'.$seven_v.'" '.$seven_e.'>'.$seven_h; // Seven Day Input

                                                   
                                               endforeach;
                                               echo '<tr>
                                                       <td><select class="form-select sel_project" aria-label="Default select Project Category" name="project_id[]" required="" disabled>
                                                           <option value="">Select Project Name</option>';
                                                           if($sr['task_id'] == 0 && !empty($sr['project_id'])){
                                                               $get_pro = mysqli_fetch_assoc(mysqli_query($conn,"SELECT * from db_projects WHERE id=".$sr['project_id']));
                                                               echo '<option value="'.$sr['project_id'].'" data-main selected>'.$get_pro['name'].'</option>';   

                                                           } else {
                                                               if(!empty($sr['task_id'])){
                                                                   $get_task = mysqli_fetch_assoc(mysqli_query($conn, "SELECT * from db_tasks WHERE id=".$sr['task_id']));
                                                                  echo '<option value="'.$get_task['project_id'].'" data-task-id="'.$sr['task_id'].'" selected>&nbsp;&nbsp;&nbsp;'.$get_task['name'].'</option>'; 
                                                               }
                                                           }
                                                           foreach($all_projects_arr as $single_pro){
                                                               $selected_pr = ($sr['task_id'] == 0 && $single_pro['id'] == $sr['project_id'] ) ? "selected" : "";
                                                             echo '<option value="'.$single_pro['id'].'" data-main '.$selected_pr.'>'.$single_pro['name'].'</option>'; 
                                                             $qu = mysqli_query($conn, "SELECT * FROM db_tasks WHERE project_id=".$single_pro['id']);
                                                             
                                                             if($qu->num_rows > 0){
                                                               while($task_row = mysqli_fetch_array($qu)){
                                                                   $selected_ts = ($sr['task_id'] != 0 && $task_row['id'] == $sr['task_id'] ) ? "selected" : "";
                                                                 echo '<option value="'.$single_pro['id'].'" data-task-id="'.$task_row['id'].'" '.$selected_ts.'>&nbsp;&nbsp;&nbsp;'.$task_row['name'].'</option>';
                                                               }
                                                             }
                                                           }

                                                           

                                                          
                                                       echo '
                                                   </select><input type="hidden" name="hidden_task_id[]" class="hidden_task_id" value=""></td>
                                                       <td>'.$first_day_td.'</td>
                                                       <td>'.$second_day_td.'</td>
                                                       <td>'.$third_day_td.'</td>
                                                       <td>'.$fourth_day_td.'</td>
                                                       <td>'.$fifth_day_td.'</td>
                                                       <td>'.$six_day_td.'</td>
                                                       <td>'.$seven_day_td.'</td>
                                                       <td class="last_td"><span class="time">00:00:00</span><sapn class="close_td">X</span></td>
                                                   </tr>';
                                               endforeach;
                                               }
                                                   
                                                  
                                                   
                                           }  
                                        }
                                        ?>
                                        
                                    </tbody>
                                    <tfoot>
                                         <tr>
                                            <td>Total:</td>
                                            <td>00:00:00</td>
                                            <td>00:00:00</td>
                                            <td>00:00:00</td>
                                            <td>00:00:00</td>
                                            <td>00:00:00</td>
                                            <td>00:00:00</td>
                                            <td>00:00:00</td>
                                            <td></td>

                                        </tr>
                                    </tfoot>
                                </table>
                                <button type="button" class="add_new_pro" style="display:none;"><i class="icofont-plus-circle"></i> Add new row</button>
                                <div class="deadline-form">
                          
                            <input type="submit" name="update_time" class="update_time" style="display: none;">
                           
                            </form>
                        </div>
                     <div class="modal-footer">
                            <!-- <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Done</button> -->
                            <button type="submit" class="btn btn-primary" name="submit" value="submit" onclick="$('.update_time').click();">Submit Timelog</button>
                            <button type="button" class="btn btn-primary clear-btn">Clear</button>

                        </div> 
                    </div>  
                </div>
            </div>
        </div>
            <!-- Modal  Delete Folder/ File-->
            <div class="modal fade" id="deleteproject" tabindex="-1"  aria-hidden="true">
                <div class="modal-dialog modal-dialog-centered modal-md modal-dialog-scrollable">
                <div class="modal-content">
                    <div class="modal-header">
                        <h5 class="modal-title  fw-bold" id="deleteprojectLabel"> Delete item Permanently?</h5>
                        <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
                    </div>
                    <div class="modal-body justify-content-center flex-column d-flex">
                        <i class="icofont-ui-delete text-danger display-2 text-center mt-2"></i>
                        <p class="mt-4 fs-5 text-center">You can only delete this item Permanently</p>
                    </div>
                    <div class="modal-footer">
                        <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Cancel</button>
                       <a href="#" class="del_anchor"> <button type="button" class="btn btn-danger color-fff">Delete</button></a>
                    </div>
                </div>
                </div>
            </div>


            <!-- Model for approve request --->
            <div class="modal fade" id="approve_req" tabindex="-1"  aria-hidden="true">
                <div class="modal-dialog modal-dialog-centered modal-md modal-dialog-scrollable">
                <div class="modal-content">
                    <div class="modal-header">
                        <h5 class="modal-title  fw-bold" id="deleteprojectLabel"> Approve this timelog?</h5>
                        <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
                    </div>
                    <div class="modal-body justify-content-center flex-column d-flex">
                        <i class="icofont-clock-time text-primary display-2 text-center mt-2"></i>
                        <p class="mt-4 fs-5 text-center">You can only approve this timelog.</p>
                    </div>
                    <div class="modal-footer">
                        <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Cancel</button>
                       <a href="#" class="approve_anchor"> <button type="button" class="btn btn-danger color-fff">Proceed</button></a>
                    </div>
                </div>
                </div>
            </div>
            <!-- Model for approve request --->
            <div class="modal fade" id="reject_req" tabindex="-1"  aria-hidden="true">
                <div class="modal-dialog modal-dialog-centered modal-md modal-dialog-scrollable">
                <div class="modal-content">
                    <div class="modal-header">
                        <h5 class="modal-title  fw-bold" id="deleteprojectLabel"> Reject this timelog?</h5>
                        <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
                    </div>
                    <div class="modal-body justify-content-center flex-column d-flex">
                        <i class="icofont-clock-time text-danger display-2 text-center mt-2"></i>
                        <p class="mt-4 fs-5 text-center">You can only reject this timelog.</p>
                    </div>
                    <div class="modal-footer">
                        <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Cancel</button>
                       <a href="#" class="reject_anchor"> <button type="button" class="btn btn-danger color-fff">Procced</button></a>
                    </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>



            <!-- Model for View Log --->
            <div class="modal fade " id="view_log" tabindex="-1"  aria-hidden="true">
                <div class="modal-dialog modal-dialog-centered modal-md modal-dialog-scrollable">
                <div class="modal-content">
                    <div class="modal-header">
                        <h5 class="modal-title  fw-bold" id="deleteprojectLabel"> View Log</h5>
                        <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
                    </div>
                    <div class="modal-body justify-content-center d-flex">
                       <table class="viewlog-tbl" style="width: 100%;">
                           <thead>
                               <tr class="top-bar-log">
                                   <th>No.</th>
                                   <th>Date</th>
                                   <th>Description</th>
                               </tr>
                           </thead>

                           <tbody class="tbody_view-log">
                               
                                <?php 

                                if(isset($_POST['pass_task_id']) && !empty($_POST['pass_task_id'])){
                                    //date_default_timezone_set($_POST['time_zone']);
                                    //date_default_timezone_set('Europe/London')

                                    $log_view = get_log_array($_POST['pass_task_id']);
                                    $n=1;
                                    $log_details = mysqli_fetch_assoc(mysqli_query($conn, "SELECT * FROM db_timelog where id=".$_POST['pass_task_id']));
                                        

                                    $u_info = get_user_by_id($log_details['user_id']);

                                    $datetime = new DateTime();
                                    $datetime->setTimestamp(strtotime($log_details['task_date']));
                                    $la_time = new DateTimeZone($_POST['time_zone']);
                                    $datetime->setTimezone($la_time);
                                    

                                    echo '<tr><td class="td_view-log">1</td><td class="td_view-log">'.$datetime->format('Y-m-d h:i A').'</td><td class="td_view-log">Created By '.$u_info['type'].' '.$u_info['full_name'].' </td></tr>'; 

                                    if(!empty($log_view)){
                                        

                                        foreach($log_view as $single){
                                            $n++;
                                            $datetime_1 = new DateTime();
                                            $datetime_1->setTimestamp($single['date_time']);
                                            
                                            $la_time = new DateTimeZone($_POST['time_zone']);
                                            $datetime_1->setTimezone($la_time);
                                            $u_info = get_user_by_id($single['user_id']);
                                           echo '<tr><td class="td_view-log">'.$n.'</td><td class="td_view-log">'.$datetime_1->format('Y-m-d h:i A').'</td><td class="td_view-log">'.$single['action'].' By '.$u_info['type'].' '.$u_info['full_name'].' </td></tr>'; 
                                        }
                                    }
                                    
                                } else {
                                    echo '<tr><td colspan="3"> <center>No Records Found</center></td></tr>';
                                }

                                ?>
                                
                                
                               
                           </tbody>
                       </table>
                    </div>
                    <div class="modal-footer">
                       
                    </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> -->


            <!--Change Request Popup Button Start-->
            <div class="modal fade" id="view_log" tabindex="-1"  aria-hidden="true">
              <div class="modal-dialog modal-dialog-centered modal-md modal-dialog-scrollable">
                <div class="modal-content">
                    <div class="modal-header">
                        <h5 class="modal-title  fw-bold" id="deleteprojectLabel"> View Log</h5>
                        <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
                    </div>
                    <div class="modal-body justify-content-center d-flex">
                       <table class="viewlog-tbl" style="width: 100%;">
                           <thead>
                               <tr class="top-bar-log">
                                   <th>No.</th>
                                   <th>Date</th>
                                   <th>Description</th>
                               </tr>
                           </thead>

                           <tbody class="tbody_view-log">
                           <section class="popup">
                              <div class="popup__content">
                                <div class="close">
                                  <span></span>
                                  <span></span>
                                </div>
                                hello my name is popup
                              </div>
                           </section>                              
                                
                           </tbody>
                       </table>
                    </div>
                </div>
              </div>
            </div>

        <!--Change Request Popup Button Start-->

<?php 
include("footer.php"); 
?>

<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" />
<style type="text/css">
    .viewlog-tbl th {
        background: #163339;
        color: #fff;
        padding: 12px 6px !important;
    }
    a.v_log {
    cursor: pointer;
    text-decoration: underline;
    }
    .top-bar-log{
    background: #163339;
    color: #fff;
    padding: 12px 8px !important;
    }
    #view_log td.td_view-log {
        padding: 10px 10px;
    }
    table.manager_tbl tr td {
        border-top: 1px solid #f0f0f0;
        padding: 22px 6px;
    }
    tr.last_tr {
            text-align: right;
            border-top: 1px solid #f0f0f0;
    }
    table.manager_tbl tr th {
        padding: 22px 6px;
    }
    button.approve-btn, button.approve-btn-all {
        background: #61a10b;
        padding: 10px 15px;
        color: #fff;
        border: 1px solid #61a10b;
        border-radius: 6px;
        font-weight: 600;
        margin-right: 12px;
        transition: all 0.5s;
    }
    button.approve-btn:hover, button.approve-btn-all:hover {
        background: transparent;
        color: #61a10b;
    }
    button.reject-btn, button.reject-btn-all {
        background: #cb0012;
        color: #fff;
        border: 1px solid #cb0012;
        padding: 10px 15px;
        border-radius: 6px;
        font-weight: 600;
        transition: all 0.5s;
        margin-right: 12px;
    }
    button.customize-btn-all {
        background: #cea254;
        color: #fff;
        border: 1px solid #cea254;
        padding: 10px 15px;
        border-radius: 6px;
        font-weight: 600;
        transition: all 0.5s;
    }
    button.customize-btn-all:hover{
        background:transparent;
        color: #cea254;
    }
    button.reject-btn:hover, button.reject-btn-all:hover{
        background:transparent;
        color: #cb0012;
    }
    button.btn.load_more_btn {
    background: #163339;
    color: #fff;
    padding: 10px 30px;
    border-radius: 6px;
    }
    table.manager_tbl tr:hover td {
    background: #f0f0f0;
    }
    tr.start_tr:nth-child(1) {
    border: none;
}
tr.top-bar-timelog th {
    background: #163339;
    color: #fff;
    padding: 12px 6px !important;
}
tr.start_tr {
    border-top: 1px solid #f0f0f0;
}
    .load_more_div {
        text-align: center;
        margin-bottom: 20px;
    }
    tr.start_tr th {
        padding-bottom: 16px !important;
        font-size: 18px;
    }
    button.btn.btn-dark.clear_filter {
        font-size: 12px;
        vertical-align: top;
        margin-left: 10px;
    }
    p.task_name i {
        margin-right: 3px;
    }
    p.task_name {
        margin-bottom: 0;
    }
    sapn.close_td {
        margin-left: 10px;
    }
    .action-btn, .action-btn:hover{
        color: white;
    }
    select.project_filter {
        margin-left: 0px !important;
    }
    .inline-filter input{
        margin-right: 0px !important;
    }
    button.btn.btn-success.approve-btn{
        margin-right: 10px;
    }
    .inline-filter input, select.project_filter, select.select_emp {
        height: 35px;
        border-color: var(--border-color);
        background-color: var(--card-color);
        border: 1px solid #ced4da;
        outline: none;
        border-radius: 0.25rem;
        margin: 0px 5px;
    }
    .inline-filter input:focus, select.project_filter:focus {
        box-shadow: 0 0 10px rgb(33 37 41 / 15%);
        background-color: var(--card-color);
        border-color: var(--primary-color);
    }
    .spinner-border.float-right {
        position: fixed;
        top: 45%;
        right: 50%;
        z-index: 999999;
    }
    .add_new_pro i.icofont-plus-circle {
        padding-right: 5px;
    }
    .daterangepicker.show-ranges .drp-calendar, .daterangepicker.show-ranges .drp-buttons {
        display: block;
    }
    .daterangepicker.ltr.show-ranges.opensright {
        z-index: 999999;
    }
    option[data-main] {
        font-weight: 600;
        color: #212529;
    }
    .add_day_time {
        width: 90px;
        border: 1px solid #ced4da;
        height: 38px;
        outline: none;
        padding: 8px;
        border-radius: 4px;
    }
    .modal-header {
        padding: 15px 20px;
    }
    .timelog-modal .modal-dialog {
        max-width: 1120px;
        width: 100%;
        padding: 0 10px;
        margin: 0 auto;
    }
    button.add_new_pro {
        border: none;
        background: #163339;
        color: #fff;
        padding: 7px 12px;
        border-radius: 4px;
    }
    input.top_range {
        max-width: 194px;
        width: 100%;
        padding: 4px;
    }
    table.add_time_tbl tfoot tr td {
        padding: 13px 10px;
        font-weight: 500;
    }
    .timelog-modal form {
        padding-bottom: 16px;
    }
    input.top_range {
        margin-bottom: 20px;
        outline: none;
    }
    select.form-select.sel_project {
        width: 200px;
        border: 1px solid #ced4da;
        margin-left: 10px;
    }
    .add_time_tbl tbody tr:first-child td {
        padding-top: 10px;
    }
    .add_time_tbl tbody tr:last-child td {
        padding-bottom: 10px;
    }
    .add_time_tbl thead, .add_time_tbl tfoot {
        background-color: #16333917;
        color: #163339;
    }
    .modal-dialog-scrollable .modal-body {
        padding-left: 23px;
        padding-right: 23px;
    }
    .add_time_tbl th.col-span-4 {
        padding: 13px 10px;
    }
    .project_div span, span.show_week_date {
        font-weight: 500;
        font-size: 14px;
    }
    table.add_time_tbl {
        border: 1px solid #163339;
        margin-bottom: 20px;
        width: 100%;
    }
    .add_time_tbl tbody tr {
        height: 55px;
    }   
    .date_div {
        justify-content: flex-end;
        align-items: baseline;
        display: flex;
    }
    span.time_info {
            padding-right: 10px;
    }
     sapn.close_td{
        cursor: pointer;
     }
     @media(max-width: 992px){
        div#myProjectTable_wrapper .col-sm-12 {
            overflow: hidden;
            overflow-x: scroll;
        }
        table.manager_tbl {
        max-width: 1200px;
    }
    .card-body {
    overflow: hidden;
    overflow-x: scroll;
}
     }
    @media(max-width:425px){
        .inline-filter, .inline-filter input, select.project_filter  {
        width: 100%;
    }
        .inline-filter input[type="text"] {
        margin-left: 0;
        margin-top: 6px;
    }
    }

    button.resubmit-btn {
        background: #163339;
        color: #fff;
        padding: 10px 30px;
        border-radius: 6px;
    }
    th.first_checkbox, td.first_checkbox {
        display: none;
    }
    .modal-dialog-scrollable .modal-content {
        max-height:100%;
        overflow: hidden;
        /*height: 100%;*/
    }
    tbody.tbody_view-log tr:nth-child(even) {
        background: rgb(22 51 57 / 10%);
    }
    table.manager_tbl .cr_btn {
        display: block;
        border: 1px solid;
        color: white;
        background: #cea254;
        border-radius: 5px;
        padding: 4px;
        font-size: 14px;
    }
    

</style>
<script type="text/javascript">
    function isNumeric(str) {
      if (typeof str != "string") return false // we only process strings!  
      return !isNaN(str) && // use type coercion to parse the _entirety_ of the string (`parseFloat` alone does not do this)...
             !isNaN(parseFloat(str)) // ...and ensure strings of whitespace fail
    }
    function addLeadingZeros(num, totalLength) {
      return String(num).padStart(totalLength, '0');
    }
    function apply_custom_filter(){
        var selected_proj = $(".project_filter").val();
        var selected_date = $('input[name="daterange"]').val();
        var selected_emp  = $(".select_emp").val();
        $(".spinner-border").show();
        $.ajax({
            type:"get",
            url:"?filter_proj="+selected_proj+"&filter_date="+selected_date+"&filter_emp="+selected_emp,
            success:function(res){
                $(".spinner-border").hide();
                if(selected_proj != '' &&  selected_date != '' && selected_emp != ''){
                    window.history.pushState('', '', "?filter_proj="+selected_proj+"&filter_date="+selected_date+"&filter_emp="+selected_emp);
                    $(".clear_filter").show();
                } else if(selected_proj != '' &&  selected_date != '') {
                    window.history.pushState('', '', "?filter_proj="+selected_proj+"&filter_date="+selected_date);
                    $(".clear_filter").show();
                } else if(selected_proj != '' &&  selected_emp != '') {
                    window.history.pushState('', '', "?filter_proj="+selected_proj+"&filter_emp="+selected_emp);
                    $(".clear_filter").show();
                } else if(selected_date != '' &&  selected_emp != '') {
                    window.history.pushState('', '', "?filter_date="+selected_date+"&filter_emp="+selected_emp);
                    $(".clear_filter").show();
                } else if(selected_proj != '') {
                    window.history.pushState('', '', "?filter_proj="+selected_proj);
                    $(".clear_filter").show();
                } else if(selected_date != '') {
                    window.history.pushState('', '', "?filter_date="+selected_date);
                    $(".clear_filter").show();
                } else if(selected_emp != '') {
                    window.history.pushState('', '', "?filter_emp="+selected_emp);
                    $(".clear_filter").show();
                } else {
                    window.history.pushState('', '', window.location.pathname);
                    $(".clear_filter").hide();
                }
                if($('.manager_tbl').length){
                        $('.manager_tbl').html($(res).find('.manager_tbl').html());
                } else {
                    $('#myProjectTable').html($(res).find('#myProjectTable').html());
                     // Use $("#dailyNews").DataTable().destroy() for DataTables 1.10.x
                    $("#myProjectTable").dataTable().fnDestroy()

                    $("#myProjectTable").dataTable({});
                }


                if($(res).find(".load_more_btn").length){
                    $(".load_more_btn").show();
                }
                $("table.manager_tbl tbody").each(function(){
                       if($(this).find("td").length == 0){
                           $(this).hide();
                       } else {
                           $(this).show();
                       }

                });
            }
        });
    }
    function total_of_time(curr)
    { 
        var cur_index = $(curr).closest("td").index();
        var vert_count = 0;
        var hori_count = 0;

        const vert_durations = [];
        const hori_durations = [];

        const vert_result = moment.duration();
        const hori_result = moment.duration();




        $(curr).closest("tr").find("td").each(function(){
            
            if($(this).find("input").val() != undefined){
              // vert_durations.push($(this).find("input").val());
                //vert_count += parseInt($(this).find("input").val().replaceAll(":",""));
                vert_result.add(moment.duration($(this).find("input").val()));
               
                $(curr).closest("tr").find("span.time").text(addLeadingZeros(parseInt(vert_result.asHours()),2)+":"+moment.utc(vert_result.asMilliseconds()).format("mm:ss"));
              
            }     
        });
        /*const totalDurations_top = vert_durations.slice(1)
 .reduce((prev, cur) => moment.duration(cur).add(prev),
  moment.duration(vert_durations[0])); 

        $(curr).closest("tr").find("span.time").text(moment.utc(totalDurations_top.asMilliseconds()).format("HH:mm:ss"));*/

        $(curr).closest("tbody").find("tr").each(function(){

                if($(this).find("td").eq(cur_index).find("input").val() != undefined){
                    // hori_durations.push($(this).find("td").eq(cur_index).find("input").val());
                    
                    // hori_count += parseInt($(this).find("td").eq(cur_index).find("input").val().replaceAll(":",""));
                
                    hori_result.add(moment.duration($(this).find("td").eq(cur_index).find("input").val()));
                    $(curr).closest("table").find("tfoot td").eq(cur_index).text(addLeadingZeros(parseInt(hori_result.asHours()),2)+":"+moment.utc(hori_result.asMilliseconds()).format("mm:ss"));
                   
                }
             
        });
        /*/const totalDurations = hori_durations.slice(1)
 .reduce((prev, cur) => moment.duration(cur).add(prev),
  moment.duration(hori_durations[0]));       
        $("table.add_time_tbl tfoot td").eq(cur_index).text(moment.utc(totalDurations.asMilliseconds()).format("HH:mm:ss"));*/  
    }
    function secondsToHms(d) {
        d = Number(d);
        var h = Math.floor(d / 3600);
        var m = Math.floor(d % 3600 / 60);
        var s = Math.floor(d % 3600 % 60);

        var hDisplay = h > 0 ? ((h < 10) ? ("0" + h) : h) + ":" : "00:";
        var mDisplay = m > 0 ? ((m < 10) ? ("0" + m) : m) + ":" : "00:";
        var sDisplay = s > 0 ? ((s < 10) ? ("0" + s) : s) : "00";
        return hDisplay + mDisplay + sDisplay; 
    }
    function convert_number_to_time($val){
       var whole_string = '';
        
        if($val.length <= 4){
            var remains = 4 -$val.length;
            for(var m=0; m < remains; m++){ whole_string += '0'; }
            whole_string += $val+"00";
            
        } else {
            if($val.length == 5){  whole_string = $val+"0"; } else { whole_string = $val; }
        }
        
        if(whole_string == ''){
            return false;
        }
        
        if(String(whole_string).length<6){
            var remains_1 = 6 -String(whole_string).length;
            var extra = '';
            for(var j=0; j < remains_1; j++){ extra += '0'; }  
             whole_string =  extra+whole_string;
        }
    
        var new_str = String(whole_string).match(/.{0,2}/g).join(":");
       
        if(new_str[8] == ':'){
            new_str =  new_str.substring(0,8);
        }

        return new_str;
    }

    $(document).ready(function(){
        $('input[name="daterange"]').daterangepicker({locale: {
            format: 'YYYY-MM-DD'
        }});
       

            var start = moment().startOf('isoWeek');
            var end = moment().endOf('isoWeek');
            <?php
                if(!isset($_GET['filter_date'])){
                     echo '$("input[name=\'daterange\']").val("");';
                }
                if(isset($_GET['filter_date']) && !empty($_GET['filter_date'])){
                    $ex_date = explode(" - ", $_GET['filter_date']);
                    echo 'apply_custom_filter(); start = "'.$ex_date[0].'"; end = "'.$ex_date[1].'"; ';
                } elseif(isset($_GET['filter_proj']) && !empty($_GET['filter_proj'])){
                    echo 'apply_custom_filter();';
                }  elseif(isset($_GET['filter_emp']) && !empty($_GET['filter_emp'])){
                    echo 'apply_custom_filter();';
                } else {
                    echo '$("input[name=\'daterange\']").val("");';
                }

            ?>


            function cb(start, end) {
               // $('#reportrange span').html(start.format('MMMM D, YYYY') + ' - ' + end.format('MMMM D, YYYY'));
               //start.format('MMMM D, YYYY') + ' - ' + end.format('MMMM D, YYYY');
               //$('input.top_range').html(moment(start, "YYYY-MM-DD").startOf('isoWeek').format('MMMM D, YYYY') + ' - ' + moment(start, "YYYY-MM-DD").endOf('isoWeek').format('MMMM D, YYYY'));

                for(var n = 0; n<=6; n++){
                    $(".show_week_date").eq(n).text(moment(start).add(n,'days').format('dd')+', '+moment(start).add(n,'days').format('MMM')+" "+moment(start).add(n,'days').format('DD'));
                    $(".show_week_date").eq(n).next("input").val(moment(start).add(n,'days').format('YYYY-MM-DD'));
                }
               
            }

            $('input.top_range').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().subtract(6, 'days'), moment()],
                }
            }, cb);

            cb(start, end);

        
        
        if($("#myProjectTable").hasClass("dataTable")){
            $("#myProjectTable").dataTable().fnDestroy();
            $("#myProjectTable").dataTable({"order": []});
        }
        
    });
    $(document).on("click", ".clear_filter", function(){
        $(".spinner-border").show();
        $("input[name='daterange']").val("");
        $("select.project_filter").val("");
        //$("select.project_filter").change();
        $(this).hide();
        window.history.pushState('', '', window.location.pathname);
        window.location.href = window.location.pathname;

        $.get(window.location.pathname, function(res){
             $(".spinner-border").hide();
            if($('.manager_tbl').length){
                    $('.manager_tbl').html($(res).find('.manager_tbl').html());
            } else {
                $('#myProjectTable').html($(res).find('#myProjectTable').html());
                 // Use $("#dailyNews").DataTable().destroy() for DataTables 1.10.x
                $("#myProjectTable").dataTable().fnDestroy()

                $("#myProjectTable").dataTable({});   
            }
            if($(res).find(".load_more_btn").length){
                $(".load_more_btn").show();
            }
            

        });
    });
    $(document).on("click", ".deleterow", function(){
       $('.del_anchor').attr("href", "?delete_timelog="+$(this).attr('data-id'));
    });
    $(document).on("click", ".approve-btn", function(){
       $('.approve_anchor').attr("href", "?approve="+$(this).attr('data-id'));
    });
    $(document).on("click", ".reject-btn", function(){
       $('.reject_anchor').attr("href", "?reject="+$(this).attr('data-id'));
    });
    $(document).on("click", ".add_new_pro", function(){
        $('table.add_time_tbl tbody').append(full_row);
    });

    $(document).on("change", ".project_filter", function(){
        apply_custom_filter();

    });
    // $(document).on("click", ".clone-btn", function(){

    // });
    $('input[name="daterange"]').on('apply.daterangepicker', function(ev, picker) {
       apply_custom_filter();
    });
    $(document).on("click", ".approve-btn-all", function(){
        var selected_week = $(this).attr("data-week-no");
        if(confirm("Are you sure, You want to approve all 'Pending' timelog?")){
            $(".spinner-border").show();
            var all_selected = $("tr[data-week-no='"+selected_week+"'] input").map(function(){ return $(this).val();}).get();
            $.ajax({
                type:"post",
                url:window.location.href,
                data:{approve_bulk:all_selected},
                success:function(res){
                    $(".spinner-border").hide();
                    location.reload();
                
                    }
            });
        }
    });

    $(document).on("click", ".reject-btn-all", function(){
        var selected_week = $(this).attr("data-week-no");
        if(confirm("Are you sure, you want to reject all 'Pending' timelog?")){
            $(".spinner-border").show();
            var all_selected = $("tr[data-week-no='"+selected_week+"'] input").map(function(){ return $(this).val();}).get();
            $.ajax({
                type:"post",
                url:window.location.href,
                data:{reject_bulk:all_selected},
                success:function(res){
                    $(".spinner-border").hide();
                    location.reload();
                }
            });
        }
    });
    $(document).on("click", ".customize-btn-all", function(){
        $(this).toggleClass('open');
        var dw_no = $(this).attr('data-week-no');
        if($(this).hasClass('open')){
            $(this).closest("th").find(".approve-btn-all").hide();
            $(this).closest("th").find(".reject-btn-all").hide();
            $(this).closest("th").find(".approve-btn").show();
            $(this).closest("th").find(".reject-btn").show();
            $('.first_checkbox[data-w="'+dw_no+'"]').show();
            $(this).text("Close Customize");
            $(this).closest("th").attr("colspan","10");
            $(this).closest("tr").prev(".last_tr").find('th').attr("colspan","10");
        } else {
            $(this).closest("th").find(".approve-btn-all").show();
            $(this).closest("th").find(".reject-btn-all").show();
            $(this).closest("th").find(".approve-btn").hide();
            $(this).closest("th").find(".reject-btn").hide();
            $('.first_checkbox[data-w="'+dw_no+'"]').hide();
            $(this).text("Customize");
            $(this).closest("th").attr("colspan","9");
            $(this).closest("tr").prev(".last_tr").find('th').attr("colspan","9");
        }
        

    });

    $(document).on("click", "sapn.close_td", function(){
        if($(".add_time_tbl tbody tr").length > 1){
            if(confirm("Are you sure?")){
              $(this).closest("tr").remove(); 

            }
        }
    });

    $(document).on("change", "select.form-select.sel_project", function(){
        if($(this).find("option[data-task-id]:selected").length){
            $(this).next(".hidden_task_id").val($(this).find("option:selected").attr("data-task-id"));
        }
    });
    
    $(document).on("blur", ".add_day_time", function(){
       if($(this).val().indexOf(':')> -1 ){
            var seprate_time = $(this).val().split(":");
            var full_time = "";
            if(!isNumeric(seprate_time[0])){
                seprate_time[0] = '00';
            }
            if(seprate_time[0]>=24){
                seprate_time[0] = 24;
            }
            full_time += seprate_time[0]+":";

            if(!isNumeric(seprate_time[1])){
                seprate_time[1] = '00';
            }
            if(seprate_time[1]>=60){
                seprate_time[1] = '00';
            }
            full_time += seprate_time[1]+":";

            if(!isNumeric(seprate_time[2])){
                seprate_time[2] = '00';
            }
            if(seprate_time[2]>=60){
                seprate_time[2] = '00';
            }
            full_time += seprate_time[2];
            $(this).val(full_time);
            //if($(this).val().replaceAll(":","") > 0){
                 total_of_time(this);
            //}
            return false;
        }


    if(!isNumeric($(this).val()) || $(this).val() <= 0){
        $(this).attr('data-value', $(this).val());
       $(this).val('');
        total_of_time(this);
    } else {
        var converted_str = convert_number_to_time($(this).val());
        $(this).val(converted_str);
    }

     if($(this).val().indexOf(':')> -1 ){
        var seprate_time = $(this).val().split(":");
        var full_time = "";
        if(seprate_time[0]>=24){
            seprate_time[0] = 24;
        }
        full_time += seprate_time[0]+":";

        if(seprate_time[1]>=60){
            seprate_time[1] = '00';
        }
        full_time += seprate_time[1]+":";
        if(seprate_time[2]>=60){
            seprate_time[2] = '00';
        }
        full_time += seprate_time[2];
        $(this).val(full_time);
        //if($(this).val().replaceAll(":","") > 0){
             total_of_time(this);
        //}

    }
   
    //if($(this).val().replaceAll(":","") > 0){
         total_of_time(this);
    //}
});
    $(document).on("click", ".select_all_week_day", function(){
        var sel_week = $(this).val();
        if($(this).prop("checked")){
            $("tr[data-week-no='"+sel_week+"'] input").prop("checked", true);
        } else {
            $("tr[data-week-no='"+sel_week+"'] input").prop("checked", false);
        }
        
    });
    $(document).on("click", ".load_more_btn", function(){
        var next_page = $(this).attr("data-value");
        $(".spinner-border").show();
        $.ajax({
            type:"get",
            url:window.location.href,
            data:{next_week:next_page},
            success:function(res){
                
                $(".spinner-border").hide();
                if($(res).find(".load_more_btn").length){
                    $(".load_more_btn").show();
                    $(".manager_tbl").append($(res).find(".manager_tbl").html());  
                    $(".load_more_btn").attr("data-value", $(res).find(".load_more_btn").attr("data-value"));
                } else {
                    $(".load_more_btn").hide();
                }
                $("table.manager_tbl tbody").each(function(){
                       if($(this).find("td").length == 0){
                           $(this).hide();
                       } else {
                           $(this).show();
                       }
                });
            }
        })
    });
    $(document).on("click", ".approve-btn", function(){
        var selected_week = $(this).attr("data-week-no");

        if($("tr[data-week-no='"+selected_week+"'] input:checked").length == 0){
            alert("Please Select timelog entry.");
        } else {
            if(confirm("Are You Sure, you want to approve selected timelog?")){
        
                $(".spinner-border").show();
                var all_selected = $("tr[data-week-no='"+selected_week+"'] input:checked").map(function(){ return $(this).val();}).get();
                $.ajax({
                    type:"post",
                    url:window.location.href,
                    data:{approve_bulk:all_selected},
                    success:function(res){
                        
                        $(".spinner-border").hide();
                        location.reload();
                        /*if($(res).find(".load_more_btn").length){
                            $(".load_more_btn").show();
                            $(".manager_tbl").append($(res).find(".manager_tbl").html());  
                            $(".load_more_btn").attr("data-value", $(res).find(".load_more_btn").attr("data-value"));
                        } else {
                            $(".load_more_btn").hide();
                        }*/
                    }
                })

            
            }

        }

    });
    $(document).on("click", ".reject-btn", function(){
        var selected_week = $(this).attr("data-week-no");

        if($("tr[data-week-no='"+selected_week+"'] input:checked").length == 0){
            alert("Please Select timelog entry.");
        } else {
            if(confirm("Are You Sure, you want to reject selected timelog?")){
                $(".spinner-border").show();
                var all_selected = $("tr[data-week-no='"+selected_week+"'] input:checked").map(function(){ return $(this).val();}).get();
                $.ajax({
                    type:"post",
                    url:window.location.href,
                    data:{reject_bulk:all_selected},
                    success:function(res){
                        
                        $(".spinner-border").hide();
                        location.reload();
                        /*if($(res).find(".load_more_btn").length){
                            $(".load_more_btn").show();
                            $(".manager_tbl").append($(res).find(".manager_tbl").html());  
                            $(".load_more_btn").attr("data-value", $(res).find(".load_more_btn").attr("data-value"));
                        } else {
                            $(".load_more_btn").hide();
                        }*/
                    }
                })

            }

        }

    });

    $(document).on("click", ".resubmit-btn", function(){
        $(".spinner-border").show();
        
        var res_week = $(this).attr("data-week-no");
        var res_year = $(this).attr("data-year");

        var res_ids = $("tr[data-week-no='"+res_week+"']").map(function(){ return $(this).attr("data-id");}).get();
        var is_editable = ($(this).hasClass('manager')) ? 1 : 0;

        $.ajax({
            type:"post",
            url:window.location.pathname,
            data:{resubmit_time:1,resubmit_ids:res_ids, resubmit_week:res_week, resubmit_year:res_year,is_editable:is_editable},
            success:function(res1){
                $("#view_emp").html($(res1).find("#view_emp").html());
                $(".spinner-border").hide();
                $("#view_emp").modal("show");
                
                start = moment().day("monday").week(parseInt(res_week));
                for(var n = 0; n<=6; n++){
                    $("#view_emp .show_week_date").eq(n).text(moment(start).add(n,'days').format('dd')+', '+moment(start).add(n,'days').format('MMM')+" "+moment(start).add(n,'days').format('DD'));
                    $("#view_emp .show_week_date").eq(n).next("input").val(moment(start).add(n,'days').format('YYYY-MM-DD'));
                }
                setTimeout(function(){
                        $("#view_emp table tbody tr").eq(0).find("input.add_day_time").blur();
                },200);
               

            }
        })
    });


    $(document).on("click",".v_log", function(){
        $(".spinner-border").show();
         
          var pass_task_id = $(this).attr("data-id");
          var time_zone = Intl.DateTimeFormat().resolvedOptions().timeZone;
          $.ajax({
            type:"post",
            url:window.location.pathname,
            data:{get_log_info:1,pass_task_id:pass_task_id, time_zone:time_zone},
            success:function(res_1){
                $('.tbody_view-log').html($(res_1).find('.tbody_view-log').html());
                $("#view_log").modal('show');
                $(".spinner-border").hide();
            }
          })
    });


    $(document).on("change",".select_emp", function(){
        apply_custom_filter();
    });
    jQuery(document).on("click", "button.clear-btn", function(){
            jQuery(this).closest(".modal-content").find("input").val('');
            jQuery(this).closest(".modal-content").find("textarea").val("");
            jQuery(this).closest(".modal-content").find("select").val('').change();
    });

    jQuery(document).on("click",".cr_btn", function(){

    });

</script>