<?php
   include("header.php");
 /* 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(isset($_GET['accept_request']) && !empty($_GET['accept_request'])){
      $get_request = mysqli_fetch_assoc(mysqli_query($conn, "SELECT * FROM db_timelog_change_request WHERE id=".$_GET['accept_request']));
      $old_log_data = get_log_array($get_request['timelog_id']);
      array_push($old_log_data, array('user_id'=>$_SESSION['loggedin_user'],'action'=>'Change Request accepted','date_time'=>strtotime('now')));
            
         
   	mysqli_query($conn, "UPDATE db_timelog SET change_request=2,status='rejected', log='".serialize($old_log_data)."' where id=".$get_request['timelog_id']);
      mysqli_query($conn, "UPDATE db_timelog_change_request SET status=2 where id=".$_GET['accept_request']);

   	$get_timelog = mysqli_fetch_assoc(mysqli_query($conn, "SELECT * FROM db_timelog WHERE id=".$get_request['timelog_id']));

   	mysqli_query($conn, "INSERT into db_user_activity(title,created_by,to_user_id,date_time) VALUES('Your change request has been approved by ".get_user_by_id($_SESSION['loggedin_user'])['full_name']."','".$_SESSION['loggedin_user']."','".$get_timelog['user_id']."','".date('Y-m-d H:i:s')."')");
      $u_info = get_user_by_id($get_timelog['user_id']);

      $get_pro = mysqli_fetch_assoc(mysqli_query($conn, "SELECT * FROM db_projects WHERE id=".$get_timelog['project_id'])); 
      $get_task = mysqli_fetch_assoc(mysqli_query($conn, "SELECT * FROM db_tasks WHERE id=".$get_timelog['task_id']));
            
      send_zoho_mail($u_info['email'],'Your Change Request has been Approved ',"Hello ".ucwords($u_info['full_name']).",<br><br> Your change request has been approved by ".get_user_by_id($_SESSION['loggedin_user'])['full_name']."<br><br> Below are the details of your timelog:<br> <b>Project:</b> ".$get_pro['name']."<br> <b>Task:</b> ".$get_task['name']."<br> <b>Total Time:</b> ".$get_timelog['total_time']." <br> <b>Request:</b> ".$get_timelog['change_request_txt'].". <br><br> Regards,<br> Timesheethub.");
            
   	echo "<script>window.history.replaceState(null, null, window.location.pathname);</script>";
   }
   if(isset($_GET['decline_request']) && !empty($_GET['decline_request'])){
      $get_request = mysqli_fetch_assoc(mysqli_query($conn, "SELECT * FROM db_timelog_change_request WHERE id=".$_GET['decline_request']));

       $old_log_data = get_log_array($get_request['timelog_id']);

      array_push($old_log_data, array('user_id'=>$_SESSION['loggedin_user'],'action'=>'Change Request declined','date_time'=>strtotime('now')));

   	mysqli_query($conn, "UPDATE db_timelog SET change_request=3, log='".serialize($old_log_data)."' where id=".$get_request['timelog_id']);
      mysqli_query($conn, "UPDATE db_timelog_change_request SET status=3 where id=".$_GET['decline_request']);
   	
      $get_timelog = mysqli_fetch_assoc(mysqli_query($conn, "SELECT * FROM db_timelog WHERE id=".$get_request['timelog_id'])); 

   	mysqli_query($conn, "INSERT into db_user_activity(title,created_by,to_user_id,date_time) VALUES('Your change request has been declined by ".get_user_by_id($_SESSION['loggedin_user'])['full_name']."','".$_SESSION['loggedin_user']."','".$get_timelog['user_id']."','".date('Y-m-d H:i:s')."')");
      $u_info = get_user_by_id($get_timelog['user_id']);

      $get_pro = mysqli_fetch_assoc(mysqli_query($conn, "SELECT * FROM db_projects WHERE id=".$get_timelog['project_id'])); 
      $get_task = mysqli_fetch_assoc(mysqli_query($conn, "SELECT * FROM db_tasks WHERE id=".$get_timelog['task_id']));
            
      send_zoho_mail($u_info['email'],'Your Change Request has been Declined ',"Hello ".ucwords($u_info['full_name']).",<br><br> Your change request has been declined by ".get_user_by_id($_SESSION['loggedin_user'])['full_name']."<br><br> Below are the details of your timelog:<br> <b>Project:</b> ".$get_pro['name']."<br> <b>Task:</b> ".$get_task['name']."<br> <b>Total Time:</b> ".$get_timelog['total_time']." <br> <b>Request:</b> ".$get_timelog['change_request_txt'].". <br><br> Regards,<br> Timesheethub.");
        
   	echo "<script>window.history.replaceState(null, null, window.location.pathname);</script>";
   }
   ?>
<div class="body d-flex py-lg-3 py-md-2">
   <div class="container-xxl">
      <div class="row">
         <div class="col-sm-12">
            <div class="card mb-3">
               <div class="timelog-d">
                  <table class="manager_tbl">
                     <tbody>
                        <tr class="top-timelog">
                           <th>Date</th>
                           <th>Project</th>
                           <th>Worked</th>
                           <th>Employee</th>
                           <th>Description</th>
                           <th>Actions</th>
                        </tr>
                        <?php 
                        if($emp_list['type'] == 'admin') {
                           $qry = mysqli_query($conn, "SELECT * FROM db_timelog_change_request where status in(1,2,3) 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,2,3) 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,2,3) 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,2,3) 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,2,3) and timelog_id in(".$get_man_timelog['ids'].") order by date_time desc");
                                 }

                              }
                        }
                           
                           if($qry->num_rows==0){
                           	echo "<tr><td colspan='4'><ceter>No Records Found.</center></td></tr>";
                           } else {
                           
                           	while($row = mysqli_fetch_assoc($qry)){
                                 $pro_name = '-';
                                 $fetch_timelog = mysqli_fetch_assoc(mysqli_query($conn, "SELECT * FROM db_timelog WHERE id=". $row['timelog_id']));
                           
                                  if(!empty($fetch_timelog['project_id'])){
                                      $get_project_name = mysqli_fetch_assoc(mysqli_query($conn, "SELECT * FROM db_projects WHERE id=".$fetch_timelog['project_id']));
                                      $pro_name   = $get_project_name['name'];
                                  }

                                                   
                                  if(!empty($fetch_timelog['task_id'])){
                                       $get_task_name = mysqli_fetch_assoc(mysqli_query($conn, "SELECT * FROM db_tasks WHERE id=".$fetch_timelog['task_id']));
                                       $pro_name .= '<br><p class="task_name"><i class="icofont-long-arrow-right"></i>'.$get_task_name['name']."</p>";
                                  }

                                  $by_name = '';
                                  $get_u = mysqli_query($conn, "SELECT * FROM db_users WHERE id=".$fetch_timelog['user_id']);
                                  if($get_u->num_rows > 0){
                                      $by_name = mysqli_fetch_assoc($get_u)['full_name'];
                                  }
                                                    
                                 $tr_class = '';
                                 if($row['status'] == 2){
                                    $tr_class = 'accepted_tr';
                                 } else if($row['status'] == 3){ 
                                     $tr_class = 'decline_tr';
                                 }
                                 $get_data = mysqli_fetch_assoc(mysqli_query($conn,"SELECT * FROM db_timelog where id=".$row['timelog_id']));

                           		echo '<tr class="'.$tr_class.'">
                           				<td>'.$row['date_time'].'</td>
                                       <td>'.$pro_name.'</td>
                           				<td>'.$get_data['total_time'].'</td>
                                       <td>'.$by_name.'</td>
                           				<td>'.$row['request_txt'].'</td>
                           				<td>';
                   				if($row['status'] == 1){
                   					echo '<button class="accept_btn" data-id="'.$row['id'].'">Accept</button> | 
                   					<button class="decline_btn" data-id="'.$row['id'].'">Decline</button>';	
                   				} else if($row['status'] == 2){
                   					echo '<span class="accept">Accepted</span>';
                   				} else if($row['status'] == 3){
							echo '<span class="decline">Declined</span>';
                   				}
                           				
                           				echo '</td>
                           			</tr>';
                           	}
                           
                           }
                           ?>
                     </tbody>
                  </table>
               </div>
            </div>
         </div>
      </div>
   </div>
</div>
<?php
   include("footer.php"); 
   ?>

<style>
   .timelog-d {
      flex: 1 1 auto;
      padding: 1rem 1rem;
   }
   .timelog-d table.manager_tbl {
      width: 100%;
   }
   .timelog-d table.manager_tbl tr.top-timelog th {
      background: #163339;
      color: #fff;
      padding: 12px 6px !important;
   }
   .timelog-d table.manager_tbl td{
      border-top: 1px solid #f0f0f0;
      padding: 22px 6px;
   }
   /*.timelog-d table.manager_tbl tr:hover td {
      background:#f0f0f0;
   }*/
   button.accept_btn {
      padding: 6px 35px;
      border: 1px solid green;
      background-color: green;
      color: #fff;
      border-radius: 4px;
      transition: all 0.4s ease-in-out;
   }
   button.accept_btn:hover {
      background-color: #fff;
      color: green;
   }
   button.decline_btn {
      padding: 6px 35px;
      border: 1px solid red;
      background-color: red;
      color: #fff;
      border-radius: 4px;
      transition: all 0.4s ease-in-out;
   }
   button.decline_btn:hover {
      background-color: #fff;
      color: red;
   }
   tr.accepted_tr {
    background-color: rgb(0 128 0 / 25%);
    color: #000;
   }
   tr.decline_tr {
    background-color: rgb(255 0 0 / 25%);
    color: #000;
   }
</style>
<script type="text/javascript">
$(document).on("click", ".accept_btn", function(){
	var pass_id = $(this).attr("data-id");
	if(confirm("Are you sure want to Accept request?")){
		window.location.href = "?accept_request="+pass_id;
	}
});
$(document).on("click", ".decline_btn", function(){
	var pass_id = $(this).attr("data-id");
	if(confirm("Are you sure want to Decline request?")){
		window.location.href = "?decline_request="+pass_id;
	}
});
</script>