<?php

defined('BASEPATH') OR exit('No direct script access allowed');

// This can be removed if you use __autoload() in config.php OR use Modular Extensions
/** @noinspection PhpIncludeInspection */
require APPPATH . 'libraries/REST_Controller.php';

class User extends REST_Controller {

  function __construct()
  {
    // Construct the parent class
    parent::__construct();
    header('Content-type: application/json');
    header('Access-Control-Allow-Origin: *');
    header("Access-Control-Allow-Headers: X-API-KEY, Origin, X-Requested-With, Content-Type, Accept, Access-Control-Request-Method");
    header("Access-Control-Allow-Methods: GET, POST, PUT, DELETE");
    $method = $_SERVER['REQUEST_METHOD'];
    if($method == "OPTIONS") {
      die();
    }
    ini_set('max_execution_time', 5000);
    ini_set("memory_limit", "-1");
    ini_set("allow_url_fopen", "1");


    //      Load Models
    $this->load->model('User_model','User');
    $this->load->model('Attendance_model','Attendance');
    $this->load->model('Daily_tasks_model', 'Daily_tasks');
    $this->load->model('Daily_reports_model', 'Daily_reports');
    $this->load->library('Accounts_management','accounts_management');
    $this->load->model('Purchase_order_model', 'Purchase_order');
    $this->load->model('Purchase_request_model', 'Purchase_request');
    $this->load->model('Employees_model', 'Employee');

  }
  //  Get Project List
  public function details_get()
  {
    $id = $this->get('user_id');
    if($id !== NULL) {
      $user_data = $this->User->select_user("",array("u.user_id"=>$id),true);
      $employee_data	= $this->Employee->select_employee("e.*",array("e.user_id"=>$id));
      if($user_data->num_rows()==1 && $employee_data->num_rows() == 1){
        if($user_data->row()->acc_status==0 || $user_data->row()->delete_status==1){
          $acc_status = 0;
        }else{
          $acc_status = 1;
        }
        if($employee_data->row()->photo!=''){
          $photo = base_url().'uploads/employees/'.$row->photo;
        }else{
          $photo = base_url().'uploads/employees/default.png';
        }
        $message = [
          'status' => TRUE,
          'user_id' => (int)$user_data->row()->user_id,
          'name' => $user_data->row()->user_alias,
          'email' => $user_data->row()->username,
          'phone' => $user_data->row()->phone_no,
          'branch_id' => $user_data->row()->branch_id,
          'photo' => $photo,
          'acc_status' => $acc_status,
          'user_type' => $user_data->row()->role_name,
          'address' => $user_data->row()->address,
          'phone' => $user_data->row()->phone_no,
          'dob' => ($user_data->row()->dob!='0000-00-00')?date("d-m-Y",strtotime($user_data->row()->dob)):"",
          'joined_date' => ($user_data->row()->joined_date!='0000-00-00')?date("d-m-Y",strtotime($user_data->row()->joined_date)):"",
          'duty_start_time' => date("h:i A",strtotime($user_data->row()->duty_start_time)),
          'duty_end_time' => date("h:i A",strtotime($user_data->row()->duty_end_time)),
          'employee_code' => $user_data->row()->employee_code,
          'role_title' => $user_data->row()->role_title,
          'message' => 'User Details Retrieved Successfully'
        ];
        if($message['user_type']=='supervisor' || $message['user_type']=='sales_staff'){
          $message['project_access'] = 1;
        }else{
          $message['project_access'] = 1;
        }

        // Check Attendance Today
        $attendance = $this->Attendance->select_attendance('*',array("uat.user_id"=>$id,"uat.attendance_date"=>date('Y-m-d'),"uat.delete_status"=>0));
        $message['project_access_without_duty_sign'] = $user_data->row()->project_access_without_duty_sign;
        $message['attendance_marked'] = 0;
        $message['attendance_status'] = 0;
        $message['signed_in_status'] = 0;
        $message['signed_off_status'] = 0;
        $message['signed_in_remarks'] = '';
        $message['signed_off_remarks'] = '';
        if($attendance->num_rows()>0){
          $attendance = $attendance->row();
          $message['attendance_marked'] = 1;
          $message['attendance_status'] = $attendance->attendance_status;
          if($attendance->signed_in_time!='00:00:00'){
            $message['signed_in_status'] = 1;
            if(date('H:i',strtotime($attendance->signed_in_time)) > date('H:i',strtotime($user_data->row()->duty_start_time))){
              $signed_in_time_1 = new DateTime(date('Y-m-d') . ' ' . date("h:i:s A", strtotime($attendance->signed_in_time)));
              $duty_start_time_1 = new DateTime(date('Y-m-d') . ' ' . date("h:i:s A", strtotime($user_data->row()->duty_start_time)));
              $late_in = $signed_in_time_1->diff($duty_start_time_1);
              $late_in = $late_in->format('%H') . " h : " . $late_in->format('%I')." m";
              $message['signed_in_remarks'] ="Signed In Late (".$late_in.") Today";
            }elseif(date('H:i',strtotime($attendance->signed_in_time)) < date('H:i',strtotime($user_data->row()->duty_start_time))){
              $signed_in_time_12 = new DateTime(date('Y-m-d') . ' ' . date("h:i:s A", strtotime($attendance->signed_in_time)));
              $duty_start_time_12 = new DateTime(date('Y-m-d') . ' ' . date("h:i:s A", strtotime($user_data->row()->duty_start_time)));
              $early_in = $signed_in_time_12->diff($duty_start_time_12);
              $early_in = $early_in->format('%H') . " h : " . $early_in->format('%I')." m";
              $message['signed_in_remarks'] ="Signed In Early (".$early_in.") Today";
            }else{
              $message['signed_in_remarks'] ="Signed In On Time Today";
            }
          }
          if($attendance->signed_off_time!='00:00:00'){
            $message['signed_off_status'] = 1;
            if(date('H:i',strtotime($attendance->signed_off_time)) > date('H:i',strtotime($user_data->row()->duty_end_time))){
              $signed_off_time_1 = new DateTime(date('Y-m-d') . ' ' . date("h:i:s A", strtotime($attendance->signed_off_time)));
              $duty_end_time_1 = new DateTime(date('Y-m-d') . ' ' . date("h:i:s A", strtotime($user_data->row()->duty_end_time)));
              $late_out = $signed_off_time_1->diff($duty_end_time_1);
              $late_out = $late_out->format('%H') . " h : " . $late_out->format('%I')." m";
              $message['signed_off_remarks'] ="Signed Off Late (".$late_out.") Today";
            }elseif(date('H:i',strtotime($attendance->signed_off_time)) < date('H:i',strtotime($user_data->row()->duty_end_time))){
              $signed_off_time_12 = new DateTime(date('Y-m-d') . ' ' . date("h:i:s A", strtotime($attendance->signed_off_time)));
              $duty_end_time_12 = new DateTime(date('Y-m-d') . ' ' . date("h:i:s A", strtotime($user_data->row()->duty_end_time)));
              $early_out = $signed_off_time_12->diff($duty_end_time_12);
              $early_out = $early_out->format('%H') . " h : " . $early_out->format('%I')." m";
              $message['signed_off_remarks'] ="Signed Off Early (".$early_out.") Today";
            }else{
              $message['signed_off_remarks'] ="Signed Off On Time Today";
            }
          }
        }else{
          // Check Previous Day Attendance Before 12 Hour
          $this->db->where("CONCAT(uat.attendance_date,' ',signed_in_time) >= now() - INTERVAL 12 HOUR");
          $attendance = $this->Attendance->select_attendance('*',array("uat.user_id"=>$id,"uat.attendance_date"=>date('Y-m-d',strtotime("-1 day")),"uat.delete_status"=>0));
          $message['project_access_without_duty_sign'] = $user_data->row()->project_access_without_duty_sign;
          $message['attendance_marked'] = 0;
          $message['attendance_status'] = 0;
          $message['signed_in_status'] = 0;
          $message['signed_off_status'] = 0;
          if($attendance->num_rows()>0){
            $attendance = $attendance->row();
            $message['attendance_marked'] = 1;
            $message['attendance_status'] = $attendance->attendance_status;
            if($attendance->signed_in_time!='00:00:00'){
              $message['signed_in_status'] = 1;
            }
            if($attendance->signed_off_time!='00:00:00'){
              $message['signed_off_status'] = 1;
            }
          }
        }
        $message['projectwise_sign'] = $user_data->row()->projectwise_sign;
        $message['projectwise_sign_in_status'] = 0;
        $message['projectwise_sign_in_project_id'] = 0;
        if($message['projectwise_sign']==1){
          // Check Project Wise Attendance Attendance Today
          $projectwise_attendance = $this->Attendance->select_attendance_projectwise('*',array("uat.user_id"=>$user_data->row()->user_id,"uat.attendance_date"=>date('Y-m-d'),"uat.delete_status"=>0,"uat.signed_off_time"=>"00:00:00"),array("uat.attendance_id","desc"),1);
          if($projectwise_attendance->num_rows()==1){
            $projectwise_attendance = $projectwise_attendance->row();
            $message['projectwise_sign_in_status'] = 1;
            $message['projectwise_sign_in_project_id'] = $projectwise_attendance->project_id;
            $message['projectwise_sign_in_project_name'] = $projectwise_attendance->work_name;
          }
        }
        $this->set_response($message, REST_Controller::HTTP_OK); // 200
      }else{
        $message = [
          'status' => FALSE,
          'message' => 'User Not Found'
        ];
        $this->response($message, REST_Controller::HTTP_BAD_REQUEST); // BAD_REQUEST (400) being the HTTP response code
      }
    }else{
      $message = [
        'status' => FALSE,
        'message' => 'User ID Required'
      ];
      $this->response($message, REST_Controller::HTTP_BAD_REQUEST); // BAD_REQUEST (400) being the HTTP response code
    }
  }
  public function transaction_summary_get()
  {
    $id = $this->get('user_id');
    if($id !== NULL) {
      $account_head_data = $this->Account->select_account_heads("",array("e.user_id"=>$id),'user');
      if($account_head_data->num_rows()==1){
        $message = [
          'status' => TRUE,
          'message' => 'User Transaction Details Retrieved Successfully'
        ];
        $user_account_id = $account_head_data->row()->acc_head_id;
        $message = $this->accounts_management->calculate_user_summary($user_account_id);
        $message['user_commission_show_status'] = (int)$this->config->item('User_project_commission_payment');

        $employee_data	= $this->Employee->select_employee("e.*",array("e.user_id"=>$id));
        if ($employee_data->num_rows() == 1) {
          // Leave Applications
          $leave_application_where['la.employee_id'] = $employee_data->row()->employee_id;
          $leave_application_where['la.leave_date_from >='] = date('Y-m-d');
          $leave_applications	= $this->Employee->select_employee_leave_applications("la.*,u.user_alias,e.civil_id,e.employee_name,ed.department_name,e.phone_no,e.user_designation",$leave_application_where,'','',1);
          $message['leave_application_count'] = $leave_applications->num_rows();
          if($leave_applications->num_rows()==1){
            $leave_applications = $leave_applications->row();
            if($leave_applications->approval_status_1==1){
              $approval_status = 'Approved';
            }elseif($leave_applications->approval_status_1==2){
              $approval_status = 'Rejected';
            }else{
              $approval_status = 'Pending';
            }
            $message['leave_date'] = date('d-m-Y',strtotime($leave_applications->leave_date_from));
            $message['leave_approval_status'] = $approval_status;
            $message['leave_approval_remarks'] = $leave_applications->approved_remarks_1;
          }
        }

        $this->set_response($message, REST_Controller::HTTP_OK); // 200
      }else{
        $message = [
          'status' => FALSE,
          'message' => 'User Details Not Found'
        ];
        $this->response($message, REST_Controller::HTTP_BAD_REQUEST); // BAD_REQUEST (400) being the HTTP response code
      }
    }else{
      $message = [
        'status' => FALSE,
        'message' => 'User ID Required'
      ];
      $this->response($message, REST_Controller::HTTP_BAD_REQUEST); // BAD_REQUEST (400) being the HTTP response code
    }
  }
  //  Update Firebase Token
  public function firebase_token_post()
  {
    if($this->post('user_id')!=''){
      $data['u.user_id'] = $this->post('user_id');
      $data['firebase_token'] = $this->post('firebase_token');
      $user_data = $this->User->select_user("",array("firebase_token"=> $data['firebase_token']),true);
      if($user_data->num_rows()>0){
        foreach ($user_data->result() as $row):
          $data2['user_id'] = $row->user_id;
          $data2['firebase_token'] = "";
          $result2 = $this->User->update_user($data2);
        endforeach;
      }
      $result = $this->User->update_user($data);
      $message = [
        'status' => TRUE,
        'message' => 'Token Updated Successfully'
      ];
      $this->set_response($message, REST_Controller::HTTP_OK); // 200
    }else{
      $message = [
        'status' => FALSE,
        'message' => 'User ID Required'
      ];
      $this->response($message, REST_Controller::HTTP_BAD_REQUEST); // BAD_REQUEST (400) being the HTTP response code
    }
  }
  //  Get Notifications
  public function notifications_get()
  {
    if($this->get('user_id')!='' && $this->get('user_id') !== NULL){
      $message = array();
      $j = 0;
      $user_details = $this->User->select_user("",array("u.user_id"=>$this->get('user_id')),true);

      // Check Daily Task Pending
      $task_where['dt.user_id'] = $this->get('user_id');
      $task_where['task_status !='] = 1;
      // $task_where['task_due_date <'] = date('Y-m-d');
      if($this->get('work_id')!='' && $this->get('work_id') !== NULL){
        $task_where['dt.work_id'] = $this->get('work_id');
      }
      $tasks	= $this->Daily_tasks->select("dt.*,u2.user_alias as created_user,u1.user_alias as assigned_to,wc.work_id,wc.work_name",$task_where);
      foreach ($tasks->result() as $row):
        $message[$j]['notification_type'] = 'daily_task';
        $message[$j]['reference_id'] = $row->task_id;
        $message[$j]['reference_type'] = 'task_id';
        $message[$j]['work_id'] = $row->work_id;
        $message[$j]['title'] = $row->task_title;
        $message[$j]['message'] = "You Have Some Overdue Pending Tasks in ".$row->work_name.".";
        $message[$j]['notification_date'] = date("d-m-Y");
        $j++;
      endforeach;

      // Select Purchase Request Notifications if User=Project Engineer
      if($user_details->num_rows()==1 && $user_details->row()->user_role==15){ //Project Engneer
        $request_where['pr.approval_status_1'] = 0;
        if($this->get('work_id')!='' && $this->get('work_id') !== NULL){
          $request_where['sl.work_id'] = $this->get('work_id');
        }
        $purchase_requests	= $this->Purchase_request->select_purchase_request("pr.*,wc.work_name,u.user_alias,sl.location_name,sl.work_id,sl.location_type,sl.work_id as location_work_id",$request_where);
        foreach ($purchase_requests->result() as $row):
          $message[$j]['notification_type'] = 'purchase_request';
          $message[$j]['reference_id'] = $row->request_id;
          $message[$j]['reference_type'] = 'request_id';
          $message[$j]['work_id'] = $row->work_id;
          $message[$j]['title'] = "";
          $message[$j]['message'] = "You Have a Pending Purchase Request Approval (Created By ".$row->user_alias.") in ".$row->work_name.".";
          $message[$j]['notification_date'] = date("d-m-Y");
          $j++;
        endforeach;
      }

      if (sizeof($message) > 0) {
        $json_data['data'] = $message;
        $json_data['count'] = sizeof($message);
        $this->set_response($json_data, REST_Controller::HTTP_OK); // OK (200) being the HTTP response code
      } else {
        $message = [
          'status' => FALSE,
          'message' => 'No Notifications Found'
        ];
        $this->response($message, REST_Controller::HTTP_BAD_REQUEST); // 400
      }
    }else{
      $message = [
        'status' => FALSE,
        'message' => 'User ID Required'
      ];
      $this->response($message, REST_Controller::HTTP_BAD_REQUEST); // BAD_REQUEST (400) being the HTTP response code
    }
  }
  public function activities_get()
  {
    if($this->get('user_id')!='' && $this->get('user_id') !== NULL){
      $message = array();
      $j = 0;
      $user_details = $this->User->select_user("",array("u.user_id"=>$this->get('user_id')),true);

      // Check Daily Task Pending
      // $data["STR_TO_DATE(ua.activity_date,'%Y-%m-%d') <="]= date('Y-m-d', strtotime($this->get('end_date')));
      // $data["STR_TO_DATE(ua.activity_date,'%Y-%m-%d') >="]= date('Y-m-d', strtotime($this->get('start_date')));
      $data['ua.user_id'] = $this->get('user_id');
      $activities	= $this->User->select_activities("",$data);
      foreach ($activities->result() as $row):
        $reference = "";
        if($row->reference_id!=0){
          $reference = " (#" . $row->reference_id . ")";
        }
        $message[$j]['date'] = date('d-m-Y h:i A', strtotime($row->activity_date));
        $message[$j]['activity_through'] = ucwords(str_replace("_","",$row->activity_through));
        $message[$j]['activity_description'] = $row->activity_description;
        $message[$j]['details'] = $row->activity_type . $reference;
        $j++;
      endforeach;

      if (sizeof($message) > 0) {
        $json_data['data'] = $message;
        $json_data['count'] = sizeof($message);
        $this->set_response($json_data, REST_Controller::HTTP_OK); // OK (200) being the HTTP response code
      } else {
        $message = [
          'status' => FALSE,
          'message' => 'No Activities Found'
        ];
        $this->response($message, REST_Controller::HTTP_BAD_REQUEST); // 400
      }
    }else{
      $message = [
        'status' => FALSE,
        'message' => 'User ID Required'
      ];
      $this->response($message, REST_Controller::HTTP_BAD_REQUEST); // BAD_REQUEST (400) being the HTTP response code
    }
  }
  //  Change Password
  public function change_password_post()
  {
    $data['user_id'] = $this->post('user_id');
    $current_pass_posted = $this->post('current_password');
    $new_pss = $this->post('new_password');
    $new_pass_confirm = $this->post('new_password_confirm');

    if($current_pass_posted!='' && $new_pss!='' && $new_pass_confirm!='') {
      $user=$this->User->select_user("",array("user_id"=>$data['user_id']));
      if($user->num_rows()==1) {
        $current_password = $user->row()->password;
        if($current_password==$current_pass_posted)
        {
          if($new_pss==$new_pass_confirm)
          {
            $data['password']=$new_pss;
            $result = $this->User->update_user($data);
            if($result == 1){
              $message = [
                'status' => TRUE,
                'message' => 'Password Changed Successfully'
              ];
              $this->response($message, REST_Controller::HTTP_CREATED); // OK (200) being the HTTP response code
            }else{
              $message = [
                'status' => FALSE,
                'message' => 'There Has Been Some Error Occurred'
              ];
              $this->response($message, REST_Controller::HTTP_BAD_REQUEST); // BAD_REQUEST (400) being the HTTP response code
            }
          }else {
            $message = [
              'status' => FALSE,
              'message' => 'New Password and Confirmation Password are Not Matching'
            ];
            $this->response($message, REST_Controller::HTTP_BAD_REQUEST); // BAD_REQUEST (400) being the HTTP response code
          }
        }
        else {
          $message = [
            'status' => FALSE,
            'message' => 'Current Password Provided is Not Matching to Existing Password'
          ];
          $this->response($message, REST_Controller::HTTP_BAD_REQUEST); // BAD_REQUEST (400) being the HTTP response code
        }
      }
      else {
        $message = [
          'status' => FALSE,
          'message' => 'User Not Found with Provided ID'
        ];
        $this->response($message, REST_Controller::HTTP_BAD_REQUEST); // NOT_FOUND (404) being the HTTP response code
      }
    } else {
      $message = [
        'status' => FALSE,
        'message' => 'Passwords are Required'
      ];
      $this->response($message, REST_Controller::HTTP_BAD_REQUEST); // BAD_REQUEST (400) being the HTTP response code
    }

  }

  public function test_firebase_get(){
    $users = $this->User->select_user("",array("firebase_token !="=>""))->result();
    foreach($users as $key=>$value){
      $firebase_data['token'] = $value->firebase_token;
      $firebase_data['title'] = "Hai Test!";
      $firebase_data['message'] = "Hello this is testing";
      $firebase_result = $this->User->push_firebase($firebase_data);

      $notification_data['user_id'] = $value->user_id;
      $notification_data['token'] = $value->firebase_token;
      $notification_data['firebase_sent_status'] = $firebase_result->success;
      $notification_data['firebase_multicast_id'] = $firebase_result->multicast_id;
      if ($notification_data['firebase_sent_status'] == 1) {
        $notification_data['firebase_message_id'] = $firebase_result->success;
      }
      print_r($notification_data);
    }
  }

  public function create_leave_application_post()
  {
    if($this->post('user_id')!='' && $this->post('leave_date')){
      $employee_data	= $this->Employee->select_employee("e.*",array("e.user_id"=>$this->post('user_id')));
      if ($employee_data->num_rows() == 1) {
        $data['employee_id'] = $employee_data->row()->employee_id;
        $data['leave_date_from'] = date('Y-m-d',strtotime($this->post('leave_date')));
        $data['leave_date_to'] = date('Y-m-d',strtotime($this->post('leave_date')));
        $data['no_of_days'] = 1;
        $data['leave_type'] = 1;
        $data['leave_reason'] = $this->post('reason');
        $data['created_date'] = date('Y-m-d H:i:s');
        $data['created_by'] = $this->post('user_id');
        $result = $this->Employee->create_employee_leave_applications($data);
        if($result['status'] == 1) {
          $message = [
            'status' => TRUE,
            'message' => 'Leave Application Submitted Successfully'
          ];
          $this->set_response($message, REST_Controller::HTTP_CREATED); // CREATED (201) being the HTTP response code
        }else {
          $message = [
            'status' => FALSE,
            'message' => 'There Has Been Some Error Occurred'
          ];
          $this->response($message, REST_Controller::HTTP_BAD_REQUEST); // NOT_FOUND (400) being the HTTP response code
        }
      }else {
        $message = [
          'status' => FALSE,
          'message' => 'There Has Been Some Error Occurred'
        ];
        $this->response($message, REST_Controller::HTTP_BAD_REQUEST); // NOT_FOUND (400) being the HTTP response code
      }
    }else{
      $message = [
        'status' => FALSE,
        'message' => 'User ID, Leave Date are Required'
      ];
      $this->response($message, REST_Controller::HTTP_BAD_REQUEST); // BAD_REQUEST (400) being the HTTP response code
    }
  }
  public function select_leave_application_get()
  {
    if($this->get('user_id')!="" && $this->get('user_id') !== NULL) {

      $data=array();
      $user_id = $this->get('user_id');
      $employee_data	= $this->Employee->select_employee("e.*",array("e.user_id"=>$user_id));
      if ($employee_data->num_rows() == 1) {
        $data['la.employee_id'] = $employee_data->row()->employee_id;
        $data['la.leave_date_from >='] = date('Y-m-d');
        $leave_applications	= $this->Employee->select_employee_leave_applications("la.*,u.user_alias,e.civil_id,e.employee_name,ed.department_name,e.phone_no,e.user_designation",$data);
        if ($leave_applications->num_rows() > 0) {
          $message = array();
          $j = 0;
          foreach ($leave_applications->result() as $row):
            if($row->approval_status_1==1){
              $approval_status = 'Approved';
            }elseif($row->approval_status_1==2){
              $approval_status = 'Rejected';
            }else{
              $approval_status = 'Pending';
            }
            $message[$j]['application_id'] = $row->application_id;
            $message[$j]['leave_date'] = date('d-m-Y',strtotime($row->leave_date_from));
            $message[$j]['reason'] = $row->leave_reason;
            $message[$j]['created_date'] = date('d-m-Y',strtotime($row->created_date));
            $message[$j]['approval_status'] = $approval_status;
            $message[$j]['approval_remarks'] = $row->approved_remarks_1;

            $j++;
          endforeach;
          $json_data['status'] = TRUE;
          $json_data['data'] = $message;
          $this->set_response($json_data, REST_Controller::HTTP_OK); // OK (200) being the HTTP response code
        } else {
          $message = [
            'status' => FALSE,
            'message' => 'No Leave Applications Found'
          ];
          $this->response($message, REST_Controller::HTTP_BAD_REQUEST); // 400
        }
      }else{
        $message = [
          'status' => FALSE,
          'message' => 'Some Error Occurred'
        ];
        $this->response($message, REST_Controller::HTTP_BAD_REQUEST); // 400
      }
    }else{
      $message = [
        'status' => FALSE,
        'message' => 'Required Parameters Missing . User ID Required'
      ];
      $this->response($message, REST_Controller::HTTP_BAD_REQUEST); // BAD_REQUEST (400) being the HTTP response code
    }
  }
}
