<?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 Login extends REST_Controller {

  function __construct()
  {
    parent::__construct();
    // Construct the parent class
    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('App_model', 'App');
    $this->load->model('Client_model', 'Client');
    $this->load->model('Attendance_model', 'Attendance');
  }
  public function index_post()
  {
    //     Default Method
    $this->login_post();
  }

  //  User Login
  public function login_post()
  {
    // $param = $this->post('param');
    $data['username'] = $this->post('username');
    $data['password'] = $this->post('password');
    $type='company';//default
    if($this->post('type')){
      $type= $this->post('type');
    }
    $data['mobile_app_access'] = 1;
    if($data['username']!='' && $data['password']!='') {
      if($type=='company'){
        // Process Login
        $result = $this->User->select_user("",$data);
        // Let's check if there are any results
        if ($result->num_rows() == 1) {
          // If there is a user, then create session data
          $row = $result->row();
          if($row->acc_status==1){
            $message = [
              'status' => TRUE,
              'user_id' => $row->user_id, // Automatically generated by the model
              'user_alias' => $row->user_alias,
              'user_type' => $row->role_name,
              'acc_status' => 1,
              'message' => 'Logged In Successfully'
            ];
            if($row->role_name=='general_manager'){
              $message['user_type'] = 'supervisor';
            }
            if($message['user_type']=='supervisor' || $message['user_type']=='sales_staff'){
              $message['project_access'] = 1;
            }else{
              $message['project_access'] = 1;
            }

            // Check Attendance Today
            // $this->db->where("CONCAT(uat.attendance_date,' ',signed_in_time) >= now() - INTERVAL 1 DAY");
            $attendance = $this->Attendance->select_attendance('*',array("uat.user_id"=>$row->user_id,"uat.attendance_date"=>date('Y-m-d'),"uat.delete_status"=>0));
            $message['project_access_without_duty_sign'] = $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;
              }
            }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"=>$row->user_id,"uat.attendance_date"=>date('Y-m-d',strtotime("-1 day")),"uat.delete_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'] = $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"=>$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;
              }
            }

            ##storing Last Login Details
            $data2['last_login'] = date('Y-m-d, h:i:s');
            $data2['user_id'] = $row->user_id;
            $this->User->update_user($data2);

            $this->response($message, REST_Controller::HTTP_OK); // OK (200) being the HTTP response code
          }else {
            $message = [
              'status' => FALSE,
              'message' => 'Your Account Has been Suspented!'
            ];
            $this->response($message, REST_Controller::HTTP_BAD_REQUEST); // BAD_REQUEST (400) being the HTTP response code
          }

        } else {
          $message = [
            'status' => FALSE,
            'message' => 'Invalid Login Credentials'
          ];
          $this->response($message, REST_Controller::HTTP_BAD_REQUEST); // BAD_REQUEST (400) being the HTTP response code
        }
      }elseif($type=='client'){
        $client_data['client_email'] = $data['username'];
        $client_data['client_password'] = $data['password'];
        $result = $this->Client->select_client("",$client_data);
        if ($result->num_rows() == 1) {
          // If there is a user, then create session data
          $row = $result->row();
          $message = [
            'status' => TRUE,
            'user_id' => $row->client_id, // Automatically generated by the model
            'user_alias' => $row->client_name,
            'user_type' => 'client',
            'message' => 'Logged In Successfully'
          ];
          $this->response($message, REST_Controller::HTTP_OK); // OK (200) being the HTTP response code
        } else {
          $message = [
            'status' => FALSE,
            'message' => 'Invalid Login Credentials'
          ];
          $this->response($message, REST_Controller::HTTP_BAD_REQUEST); // BAD_REQUEST (400) being the HTTP response code
        }
      }else {
        $message = [
          'status' => FALSE,
          'message' => 'Error Occurred'
        ];
        $this->response($message, REST_Controller::HTTP_BAD_REQUEST); // BAD_REQUEST (400) being the HTTP response code
      }
    } else {
      $message = [
        'status' => FALSE,
        'message' => 'Username and Password are Required'
      ];

      $this->response($message, REST_Controller::HTTP_BAD_REQUEST); // BAD_REQUEST (400) being the HTTP response code
    }

  }

  //  Get App Updation Details
  public function app_update_get($type=""){

    $data = array();
    if($type!=""){
      $data['updation_type'] = $type;
    }
    if($this->get('app')!="" && $this->get('app') !== NULL){
      $data['app'] = $this->get('app');
    }else{
      $data['app'] = 'android_native';
    }
    $res = $this->App->select_update($data);
    if ($res->num_rows() >0) {
      $message = array();
      $j=0;
      foreach ($res->result() as $row):

        $message['id'] = $row->data_id;
        $message['updation_status'] = (int)$row->updation_status;
        $message['updation_type'] = $row->updation_type;
        $message['updation_link'] = $row->updation_link;

      endforeach;
      $this->set_response($message, REST_Controller::HTTP_OK); // OK
    } else {
      $message = [
        'status' => FALSE,
        'message' => 'No Update Found'
      ];
      $this->response($message, REST_Controller::HTTP_BAD_REQUEST); // NOT_FOUND (400) being the HTTP response code
    }
  }
}
