<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');

class Login extends Public_Controller {

    function __construct() {
        parent::__construct();
		$this->load->helper('form');
	}

	function index() {
		if($this->session->userdata('userLevel') == 1){
			redirect('admin/dashboard', 'refresh');
        }else {
            $this->template
            		->set('template', 'main')
                    ->set('view', 'pages/mtLogin')
            		->render();
		}
	}

    function verifyLogin() {

        $this->load->model('login_model');
		$this->load->library('form_validation');
		$this->form_validation->set_rules('email', 'שם משתמש', 'trim|required|xss_clean');
		$this->form_validation->set_rules('password', 'הסיסמה', 'trim|required|xss_clean|callback_check_database');
        $this->form_validation->set_error_delimiters('<div class="alert alert-mini alert-danger margin-bottom-30">', '</div>');

		if($this->form_validation->run() == FALSE) {
            $this->form_validation->set_message('check_database', 'שם משתמש או סיסמה שגויים!');
            $this->index();
		} else {
            if($this->session->userdata('userLevel') == 1){
                $user_data = array(
                        'customerId'    => getUserId(),
                        'ip_address'    => $_SERVER['REMOTE_ADDR'],
                        'session_date'  => date('Y-m-d H:i:s'),
                        'isAdmin'       => 1
                    );
                $this->general_model->insertRow('customers_online', $user_data);
			    redirect('admin/dashboard', 'refresh');
            }
		}
	}

    function verifyLoginAjax() {
        $this->load->model('login_model');
		$this->load->library('form_validation');
		$this->form_validation->set_rules('email', 'שם משתמש', 'trim|required|xss_clean');
		$this->form_validation->set_rules('password', 'הסיסמה', 'trim|required|xss_clean|callback_check_database');
        $this->form_validation->set_error_delimiters('<div class="alert alert-mini alert-danger margin-bottom-30">', '</div>');
		if($this->form_validation->run() == FALSE) {
		    if (!empty($_SERVER['HTTP_CLIENT_IP'])) {
              $ip = $_SERVER['HTTP_CLIENT_IP'];
		    }else if (!empty($_SERVER['HTTP_X_FORWARDED_FOR'])) {
              $ip = $_SERVER['HTTP_X_FORWARDED_FOR'];
            } else {
              $ip = $_SERVER['REMOTE_ADDR'];
            }
            $bytes = openssl_random_pseudo_bytes(16);
			echo json_encode(array('result' => false, 'ip' => $ip, 'request_id' => md5($bytes), 'msg' => 'שם משתמש או סיסמה שגויים!'));
		} else {
			echo json_encode(array('result' => true, 'msg' => ''));
		}
	}
    
    function auth(){
        
        if( isset($_SESSION['userId']) && !empty($_SESSION['userId'])
        && isset($_SESSION['customerId']) && !empty($_SESSION['customerId'])
        && isset($_SESSION['browser']) && !empty($_SESSION['browser'])
        && isset($_SESSION['ip_address']) && !empty($_SESSION['ip_address'])
        && isset($_SESSION['code_tries']) && !empty($_SESSION['code_tries'])
        && $_SESSION['code_tries'] <= 5 && isset($_POST['code']) && !empty($_POST['code']) ){
            $_SESSION['code_tries'] = $_SESSION['code_tries'] + 1;
            $userId         = strip_tags(mysqli_real_escape_string($this->db->conn_id, trim($_SESSION['userId'])));
            $customerId     = strip_tags(mysqli_real_escape_string($this->db->conn_id, trim($_SESSION['customerId'])));
            $browser        = strip_tags(mysqli_real_escape_string($this->db->conn_id, trim($_SESSION['browser'])));
            $ip_address     = strip_tags(mysqli_real_escape_string($this->db->conn_id, trim($_SESSION['ip_address'])));
            $code           = strip_tags(mysqli_real_escape_string($this->db->conn_id, trim($_POST['code'])));
            $session_hash   = $userId . $customerId . $_SERVER['HTTP_USER_AGENT'] . $_SERVER['REMOTE_ADDR'];
            $hashed_sess    = hash('sha256', $session_hash);
            $nowDate        = date('Y-m-d H:i:s', strtotime('NOW'));
            $endDate        = date('Y-m-d H:i:s', strtotime('+10 Minutes'));
            $this->db->select('userId, customerId');
    		$this->db->from('customers_session');
            $this->db->where('userId = ' . "'$userId'");
    		$this->db->where('customerId = ' . "'" . $customerId . "'");
    		$this->db->where('session = ' . "'" . $hashed_sess . "'");
    		$this->db->where('is_used = ' . "'0'");
    		$this->db->where('code = ' . "'" . hash('sha256', $code) . "'");
    		$this->db->where('expires BETWEEN ' . "'" . $nowDate . "'" . 'AND' . "'" . $endDate . "'");
    		$this->db->order_by('id', 'DESC');
    		$this->db->limit(1);
            $queryU = $this->db->get();
            if($queryU -> num_rows() == 1) {
                $error      = false;
                $error_code = 0;
		        $user = $queryU->row();
		        $current_user = $this->general_model->getRowById('users', 'userId', $user->userId);
		        $sessionArray = array(
    				'userLevel' => (string)$current_user->userLevel,
                    'userData' => $current_user
    			);
                $this->session->set_userdata($sessionArray);
		        if($current_user->userLevel == 1){
		            redirect('admin/dashboard', 'refresh');
		        }else if($current_user->userLevel == 3){
		            redirect('app/welcome', 'refresh');
                }else if($current_user->userLevel == 4){
                    redirect('agent/dashboard', 'refresh');
                }else{
                    $error      = true;
                    $error_code = 150;
                }
    		}else {
    			$error      = true;
                $error_code = 401;
    		}
        }else{
            if(isset($_SESSION['code_tries'])){
                if( $_SESSION['code_tries'] > 5 ){
                    redirect('login', 'refresh');
                }else{
                    $_SESSION['code_tries'] = $_SESSION['code_tries'] + 1;
                }
            }
            $error      = false;
            $error_code = 0;
        }
        
        $this->template
            		->set('template', 'main')
                    ->set('view', 'pages/auth')
                    ->set('error', $error)
                    ->set('error_code', $error_code)
            		->render();
    }
    
    function checkUserLoggedin() {
        if(isset($this->session->userdata('userData')->password)) {
            $dbPassword = $this->general_model->getTableWhere('users', 'password', $this->session->userdata('userData')->password);
            if(!empty($dbPassword) && $dbPassword[0]->userId == $this->session->userdata('userData')->userId && $dbPassword[0]->userLevel > 0) {
                echo json_encode(array('result' => true));
            } else {
                echo json_encode(array('result' => false));
            }
        } else {
            echo json_encode(array('result' => false));
        }
        die();
    }

    function check_database($password) {
        
        if(!empty($password) && isset($password) && !is_null($password)){
    		$username = $this->input->post('email');
    		$result = $this->login_model->login($username, $password);
    		if($result) {
    			$user = $this->general_model->getRowById('users', 'userId', $result->userId);
                if(!empty($user) && !empty($user->phone)){
                    if( $user->userLevel == 1 || $user->userLevel == 4 || $user->userLevel == 2 ){
                        $user_phone = str_replace("-", "", $user->phone);
                        $code = rand(99999, 999999);
                        //sendSms("Your Login code is: $code", "Cube", $user_phone);
                        $session_hash = $user->userId . $user->adminId . $_SERVER['HTTP_USER_AGENT'] . $_SERVER['REMOTE_ADDR'];
                        $session_data = array(
                            'userId'        => $user->userId,
                            'customerId'    => $user->adminId,
                            'session'       => hash('sha256', $session_hash),
                            'expires'       => date('Y-m-d H:i:s', strtotime('+10 Minutes')),
                            'is_used'       => 0,
                            'ip_address'    => $_SERVER['REMOTE_ADDR'],
                            'code'          => hash('sha256', $code),
                            'browser'       => $_SERVER['HTTP_USER_AGENT'],
                            'dateCreation'  => date('Y-m-d H:i:s'),
                            'lastUpdate'    => date('Y-m-d H:i:s')
                        );
                        $this->general_model->insertRow('customers_session', $session_data);
                        
                        $sessionArray = array(
            				'userLevel' => (string)$result->userLevel,
                            'userData' => $result
            			);
                        $this->session->set_userdata($sessionArray);
                        
                        return true;
                    }else{
                        $sessionArray = array(
            				'userLevel' => (string)$result->userLevel,
                            'userData' => $result
            			);
                        $this->session->set_userdata($sessionArray);
                        //debug($sessionArray);
            			return true;
                    }
                }else{
                    $this->form_validation->set_message('check_database', 'שם משתמש או סיסמה שגויים!');
    			    return false;
                }
    		} else {
    			$this->form_validation->set_message('check_database', 'שם משתמש או סיסמה שגויים!');
    			return false;
    		}
        }else{
            return false;
        }
	}

	function logout() {

        $red = 'login';
        $this->session->unset_userdata('type');
        $this->session->unset_userdata('userData');
        $this->session->unset_userdata('userLevel');
        $this->session->unset_userdata('allowedCampaigns');
        $this->session->unset_userdata('vcCode');
        $this->session->unset_userdata('userDataFull');
        $this->session->unset_userdata('categories');
        $this->session->unset_userdata('customerData');
        $this->session->unset_userdata('vcCodesAll');
        $this->session->unset_userdata('campaignId');
        $this->session->unset_userdata('campaignName');
        redirect($red, 'refresh');
	}

}
