<?php

class User {

  private $_conn = null;
  private $_res = null;

	public function __construct($conn){
		$this->_conn = $conn;
	}

  public function registerUser($user){

    $query = $this->_conn->query("SELECT id FROM users WHERE `email` = '".$user['email']."'");

    if($query->num_rows == 1){
      
        $this->_res = ['status'=>'error', 'message'=>' :: Email address is regieterd already, Please try with another email ', 'data'=> null];
    
    }else{
        //register user 
        $password = md5($user['password']);
        $reg_string = "INSERT INTO users (`titleId`, `fname`, `lname`, `email`,`password`, `telephone`, `userTypeId`,`barristerId`, `designationId`) VALUES('".$user['titleId']."', '".$user['fname']."', '".$user['lname']."', '".$user['email']."', '".$password."', '".$user['telephone']."', '".$user['userTypeId']."','".$user['barristerId']."', '".$user['designationId']."')";
        $query_insert = $this->_conn->query($reg_string);
        if($query_insert){
            $this->_res = ['status'=>'ok', 'message'=>' :: User saved, Thanks', 'data'=>null];
        }else{
          $this->_res = ['status'=>'error', 'message'=>' :: Can not save user!', 'data'=>$reg_string];
        }

    }

    return $this->_res;

  }

  public function getUsers($filter){

    $query_string = "SELECT `users`.`id`, CONCAT(`titles`.`name`, ' ', `users`.`fname`, ' ',`users`.`lname`) as fullname, `users`.`email`, `users`.`telephone`, `designations`.`name` as designation, `userTypes`.`name` as userType,  `users`.`lastLogin`, `users`.`active` FROM users, titles, designations, userTypes WHERE `users`.`titleId` = `titles`.`id` AND `users`.`designationId` = `designations`.`id` AND `users`.`userTypeId` = `userTypes`.`id`";
    if($filter['active'] != "all"){
      $query_string .= " AND `users`.`active` = '".$filter['active']."' ";
    }

    $query_string .= " ORDER BY id DESC ";

    $query = $this->_conn->query($query_string);

    if($query->num_rows > 0){
      $data = [];
      $counter = 1;

      while($row = $query->fetch_assoc()){
        $row['index'] = $counter;
        if($row['active'] == 1){ 
          $row['statusText'] = "Active"; 
          $row['statusColor'] = "primary"; 
        }else { 
          $row['statusText'] = "Inactive"; 
          $row['statusColor'] = "danger"; 
        }

        $data[] = $row;
        $counter ++;
      }

      $this->_res = ['status'=>'ok', 'message'=>'', 'data'=>$data];

    }else{
      $this->_res = ['status'=>'error', 'message'=>' :: No user found', 'data'=>$query_string];
    }

    return $this->_res;

  }

  public function getUser($id){

    $query = $this->_conn->query("SELECT `users`.*, CONCAT(`titles`.`name`, ' ', `users`.`fname`, ' ',`users`.`lname`) as fullname, `designations`.`name` as designation, `userTypes`.`name` as userType FROM users, titles, designations, userTypes WHERE `users`.`id` = '".$id."' AND `users`.`designationId` = `designations`.`id` AND `users`.`titleId` = `titles`.`id` AND `users`.`userTypeId` = `userTypes`.`id`");
    if($query->num_rows > 0){
      $row = $query->fetch_assoc();
      if($row['status'] == '0'){
        $row['statusText'] = ' Inactive ';
      }else{
        $row['statusText'] = ' Active ';
      }

      $row['permission'] = json_decode($row['permission']);

      $this->_res = ['status'=>'ok', 'message'=>'', 'data'=>$row];
    }else{
      $this->_res = ['status'=>'error', 'message'=>' :: No user found!', 'data'=>null];
    } 
    return $this->_res;
  }


  public function updateUser($id, $data){

    $query = $this->_conn->query("SELECT `password` FROM `users` WHERE `id` = '".$id."'");
    
    if($query->num_rows == 1){
      $row_user = $query->fetch_assoc();
      if($row_user['password'] == $data['password']){
        $update_string = "UPDATE users SET `titleId` = '".$data['titleId']."', `fname`='".$data['fname']."', `lname` = '".$data['lname']."', `email` = '".$data['email']."', `telephone` = '".$data['telephone']."',  `userTypeId` = '".$data['userTypeId']."',  `barristerId` = '".$data['barristerId']."', `designationId` = '".$data['designationId']."',  `active` = '".$data['active']."' WHERE id = '".$id."' "; 
      }else{
        $password = md5($data['password']);
        $update_string = "UPDATE users SET `titleId` = '".$data['titleId']."', `fname`='".$data['fname']."', `lname` = '".$data['lname']."', `email` = '".$data['email']."', `telephone` = '".$data['telephone']."',  `userTypeId` = '".$data['userTypeId']."',  `barristerId` = '".$data['barristerId']."', `designationId` = '".$data['designationId']."', `password` = '".$password."', `active` = '".$data['active']."' WHERE id = '".$id."' ";
      
      }

      $query_update = $this->_conn->query($update_string); 
      
      if($query_update){
        $this->_res = ['status'=>'ok', 'message'=>' :: User updated, Thanks', 'data'=>null];
      }else{
        $this->_res = ['status'=>'error', 'message'=>' :: Can not update user details!', 'data'=>$update_string];
      }
    }else{
      $this->_res = ['status'=>'error', 'message'=>' :: No user found!', 'data'=>null];
    }

    return $this->_res;
    
  }

  public function updatePermission($id, $permission){
    $query = $this->_conn->query("SELECT fname FROM users WHERE id = '".$id."'");
    
    if($query->num_rows == 1){
      $permission = json_encode($permission);
      $query_update = $this->_conn->query("UPDATE users SET `permission` = '".$permission."' WHERE id = '".$id."' ");
      
      if($query_update){
        $this->_res = ['status'=>'ok', 'message'=>' :: User permission updated, Thanks', 'data'=>null];
      }else{
        $this->_res = ['status'=>'error', 'message'=>' :: Can not update user permission!', 'data'=>null];
      }
    }else{
      $this->_res = ['status'=>'error', 'message'=>' :: No user found!', 'data'=>null];
    }

    return $this->_res;
  }

  public function deleteUser($id){

    $query_check = $this->_conn->query("SELECT * FROM users WHERE id = '".$id."'");
    
    if($query_check->num_rows == 1){
      $query_delete = $this->_conn->query("DELETE FROM users WHERE id = '".$id."'");

      if($query_delete){
        $this->_res = ['status' => 'ok', 'message'=>' :: User has been deleted nicely, Thanks', 'data'=>null];
      }else{
        $this->_res = ['status' => 'error', 'message'=>' :: Can not delete users!', 'data'=>null];
      }

    }else {
      $this->_res = ['status' => 'error', 'message'=>' :: User not found!', 'data'=>null];
    }
    return $this->_res;
  }


  public function tryLogin($user){

    $userPassword = md5($user['password']);
    $string= "SELECT `users`.`id`, `titles`.`name` as title, `users`.`fname`, `users`.`lname`, `users`.`active`,`users`.`userTypeId`, `users`.`barristerId`, `users`.`permission` FROM users, titles WHERE `users`.`email` = '".$user['email']."' AND `users`.`password` = '".$userPassword."' AND `users`.`titleId` = `titles`.`id`";
    $query = $this->_conn->query($string);

    if($query->num_rows == 1){
      $row = $query->fetch_object();
      if($row->active == 0){
        $this->_res = ['status'=> 'error', 'message'=>' :: Your account is not activated. Please contact system administrator !', 'data'=>null];
      }else{
        $data = [];
        $data['userId'] = $row->id;
        //update last login 
        // $dateNow = date('Y-m-d h:i:sa');
        // $this->_conn->query("UPDATE `users` SET `lastLogin` = '".$dateNow."' WHERE `id` = '".$row->id."'");
        $data['userName'] = $row->title." ".$row->fname." ".$row->lname;
        $data['permission'] = json_decode($row->permission);
        $data['userToken'] = $this->encryptDecrypt('encrypt', $row->id);
        $data['validToken'] = $this->encryptDecrypt('encrypt', $user['password']);
        $userType = [];
        $userType['userTypeId'] = $row->userTypeId;
        $userType['barristerId'] = $row->barristerId;
        $data['userType'] = $userType;

        $this->_res = ['status'=>'ok', 'message'=>' :: Login successful. Welcome to Phantom Pro.', 'data'=>$data];

      }

    }else{
      $this->_res = ['status'=>'error', 'message'=>' :: Login details is not valid!', 'data'=>$string];      
    }

    return $this->_res;

  }

  public function checkLanding($userId){

    $query = $this->_conn->query("SELECT `permission`, `active`, `userTypeId`, `barristerId` FROM `users` WHERE `id` = '".$userId."'");
    if($query->num_rows == 1){
      $row_user = $query->fetch_assoc();
      if($row_user['active'] == '0'){
        $this->_res = ['status'=>'error', 'message'=>'Your account is not active, Please contact admin!', 'data'=>null];
      }else{
        $data = [];
        $permission = json_decode($row_user['permission']);
        $data['permission'] = $permission;
        $userType = [];
        $userType['userTypeId'] = $row_user['userTypeId'];
        $userType['barristerId'] = $row_user['barristerId'];
        $data['userType'] = $userType;

        $this->_res = ['status'=>'ok', 'message'=>'', 'data'=>$data];
      }
      
    }else{
      $this->_res = ['status'=>'error', 'message'=>'No user found!', 'data'=>null];
    }

    return $this->_res;
  }

  public function encryptDecrypt($action, $string) {
        $output = false;
        $encrypt_method = "AES-256-CBC";
        $secret_key = '2FcKRSN39nUdVj8';
        $secret_iv = 'SWbMG88Spu2PP6XeA2';
        // hash
        $key = hash('sha256', $secret_key);
        
        // iv - encrypt method AES-256-CBC expects 16 bytes - else you will get a warning
        $iv = substr(hash('sha256', $secret_iv), 0, 16);
        if ( $action == 'encrypt' ) {
            $output = openssl_encrypt($string, $encrypt_method, $key, 0, $iv);
            $output = base64_encode($output);
        } else if( $action == 'decrypt' ) {
            $output = openssl_decrypt(base64_decode($string), $encrypt_method, $key, 0, $iv);
        }
        return $output;
    }

    function getToken($length) {
        $length = intval($length, 10);
        $output = '';
        for ($i = 0; $i < $length; $i++) {
            $output .= mt_rand(0, 9);
        }
        return $output;
    }



}



?>