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

class Users extends Admin_Controller {

    function __construct() {
        parent::__construct();
        $this->load->model('users_model');
	}
	
	public function index() {
	    $ownerId = $this->session->userdata('userData');
        $users = $this->general_model->getTableWhere('users', 'adminId', '1');
        $users2 = $this->general_model->getTableWhere('users', 'userId', '885');
        $this->template
            ->set('view', 'admin/users/index')
    		->set('users', $users)
    		->set('users2', $users2)
            ->render();
	}
    
    public function userForm() {
        
        $this->session->unset_userdata('flashMsg');
    	$payment_boxes  = reindex_by_key($this->db->query("SELECT * FROM `customer_invoices_boxes`")->result(), 'box_id');
    	$permessions_array = $campaigns = $suppliers = $operators = $agents = $texts = $sub_permessions_array = $sub_texts = array();

        if($this->uri->segment(4) === FALSE) {
    		$userId = '';
            $user[0] = $this->general_model->getTableEmptyArray('users');
            $mode = 'הוספת';
    	} else {
    	    $userId = $this->uri->segment(4);
    		$cUser = $this->general_model->getRowById('users', 'userId', $userId);
            $user = $this->users_model->getUserById($userId);
            $mode = 'עריכת';
            
            if( $user[0]->userLevel == 1 || $user[0]->userLevel == 2 ){
                $main_permessions = $this->db->query("SELECT * FROM `users_permissions_admins_main` WHERE `parentType` = '' ")->result();
                $permessions_array = $texts = array();
                foreach( $main_permessions as $mPer ){
                    $user_permessions = $this->db->query("SELECT * FROM `users_permissions_admins` WHERE `userId` = '$userId' AND `type` = '$mPer->type' AND `text` = '$mPer->text' ")->row();
                    if(!empty($user_permessions)){
                        $per = $user_permessions->permission;
                    }else{
                        $per = 0;
                    }
                    $permessions_array[$mPer->type][$mPer->text] = $per;
                    $texts[$mPer->type][$mPer->text] = $mPer->desc;
                }
                
                $sub_permessions = $this->db->query("SELECT * FROM `users_permissions_admins_main` WHERE `parentType` != '' ")->result();
                
                $sub_permessions_array = $sub_texts = array();
                foreach( $sub_permessions as $sPer ){
                    $user_sub_permessions = $this->db->query("SELECT * FROM `users_permissions_admins` WHERE `userId` = '$userId' AND `type` = '$sPer->type' AND `text` = '$sPer->text' ")->row();
                    if(!empty($user_sub_permessions)){
                        $s_per = $user_sub_permessions->permission;
                    }else{
                        $s_per = 0;
                    }
                    $sub_permessions_array[$sPer->type][$sPer->parentType][$sPer->text] = $s_per;
                    $sub_texts[$sPer->type][$sPer->parentType][$sPer->text] = $sPer->desc;
                }
            }
    	}
        
        $userTypes = $this->general_model->getUserTypes();
        $this->template
    		->set('view', 'admin/users/userForm')
    		->set('metaDescription', 'description')
            ->set('user', $user[0])
            // ->set('cUser', $cUser)
            ->set('userId', $userId)
            ->set('userTypes', $userTypes)
            ->set('mode', $mode)
            ->set('payment_boxes', $payment_boxes)
            ->set('permessions_array', $permessions_array)
            ->set('sub_permessions_array', $sub_permessions_array)
            ->set('sub_texts', $sub_texts)
            ->set('texts', $texts)
    		->render();
    }

    function userAction() {
	    $username           = $this->input->post('username');
		$userId             = $this->input->post('userId');
        $firstName          = $this->input->post('firstname');
		$lastName           = $this->input->post('lastname');
		$email              = strtolower($this->input->post('email'));
        $phone              = $this->input->post('phone');
		$password           = $this->input->post('password');
        $typeId             = $this->input->post('userType');
        $isActive           = $this->input->post('isActive') ? 1 : 0;
        $payment_box        = $this->input->post('payment_box');
        $view_permissions   = $this->input->post('view_permissions') ? 1 : 0;
        
		if(!isset($userId) || $userId == '' || $userId == null) {
            if(checkEmailExists($email, 'users')) {
                $this->session->set_flashdata('flashMsgType', 'Error');
                $this->session->set_flashdata('flashMsg', 'כתובת המייל '.$email.' קיימת במערכת!');
    			redirect('admin/users/userForm/', 'location');
            }     
            $password   = $password != '' ? $password : generateRandomString(8);
            $salt       = $this->encrypt->encode(generateRandomString(32));
		    $saltedPW   =  $password . $salt;
		    $hashedPW   = hash('sha256', $saltedPW);
               
            $sqlData = array(
                'username'          => $username,
                'firstname'         => $firstName,
                'lastname'          => $lastName,
                'email'             => $email,
                'phone'             => $phone,
                'password'          => $hashedPW,
                'isActive'          => 1,
                'salt'              => $salt,
                'typeId'            => 1,
                'userLevel'         => $typeId,   
                'adminId'           => getAdminId(),
                'allowedCampaigns'  => $allowedCampaigns,
                'allowedSuppliers'  => $allowedSuppliers,
                'creationDate'      => date('Y-m-d H:i:s'),
                'lastUpdate'        => date('Y-m-d H:i:s')
            );
			$result = $this->users_model->insertUser($sqlData);
			if (!$result == false) {
			    $this->changeUserPassword($result);
                $this->session->set_flashdata('flashMsgType', 'Success');
				$this->session->set_flashdata('flashMsg', $firstName.' '.$lastName.' נשמר בהצלחה.');
				redirect('admin/users', 'refresh');
			} else {
			    $this->session->set_flashdata('flashMsgType', 'Error'); 
				$this->session->set_flashdata('flashMsg', 'Sorry! We have an error, please try again.');
				redirect('admin/users/', 'refresh');
			}
		} else {
            $sqlData = array(
                'username'          => $username,
                'firstname'         => $firstName,
                'lastname'          => $lastName,
                'isActive'          => $isActive,
                'typeId'            => 1,
                'userLevel'         => $typeId,
                'view_permissions'  => $view_permissions,
                'lastUpdate'        => date('Y-m-d H:i:s'),
                'payment_box'       => $payment_box,
                'email'       => $email,
                'phone'       => $phone,
            );

            if($password != '') {
                $this->changeUserPassword($userId, $password);
            }
			$result = $this->users_model->updateUserById($sqlData, $userId);
			if ($result) {
			    $this->session->set_flashdata('flashMsgType', 'Success'); 
				$this->session->set_flashdata('flashMsg','השינויים נשמרו בהצלחה!');
			}
			else {
			    $this->session->set_flashdata('flashMsgType', 'Error');  
				$this->session->set_flashdata('flashMsg','Sorry! We have an error, please try again.');
			}
			redirect('admin/users', 'location');
		}
	}
    
    public function changeUserPassword($userId, $newPassword = '') {
        
        $user = $this->general_model->getRowById('users', 'userId', intval($userId));
        if($newPassword == '') $newPassword = generateRandomString(8);
        $saltedPW = $newPassword . $user->salt;
   		$hashedPW = hash('sha256', $saltedPW);
        $updateSuccess = $this->general_model->updateRowById('users', 'userId', $userId, array( 'password' => $hashedPW ));
        if($updateSuccess) {
            $this->session->set_flashdata('flashMsgType', 'Success'); 
			$this->session->set_flashdata('flashMsg', 'סיסמה חדשה נשלחה לכתובת המייל.');            
        }
        return;           
    }    

    function updateUserPermession(){
        $data = (object)$_POST;
        $user_permession = $this->db->query("SELECT * FROM `users_permissions` WHERE `userId` = '$data->userId' AND `type` = '$data->type' AND `text` = '$data->text' ")->row();
        if(!empty($user_permession)){
            $addPerm = $this->general_model->updateRowById('users_permissions', 'perId', $user_permession->perId, array( 'permission' => $data->per, 'lastUpdate' => date('Y-m-d H:i:s') ));
            $history_data = array(
                    'type'              => $data->type,
                    'userId'            => getUserId(),
                    'editedUser'        => $data->userId,
                    'text'              => $data->text,
                    'old_permission'    => $user_permession->permission,
                    'new_permission'    => $data->per,
                    'dateCreation'      => date('Y-m-d H:i:s')
                );
            
            $addhistory = $result = $this->general_model->insertRow('users_permissions_history', $history_data);
        }else{
            $per_data = array(
                    'type'          => $data->type,
                    'userId'        => $data->userId,
                    'text'          => $data->text,
                    'permission'    => $data->per,
                    'createdBy'     => getUserId(),
                    'dateCreation'  => date('Y-m-d H:i:s'),
                    'lastUpdate'    => date('Y-m-d H:i:s')
                );
            
            $addPerm = $result = $this->general_model->insertRow('users_permissions', $per_data);
        }
        if(!empty($addPerm)){
            echo json_encode(array("result" => true ));
        }else{
            echo json_encode(array("result" => false ));
        }
    }
    
    function updateAdminsPermession(){
        $data = (object)$_POST;
        $admin_permession = $this->db->query("SELECT * FROM `users_permissions_admins` WHERE `userId` = '$data->userId' AND `type` = '$data->type' AND `text` = '$data->text' ")->row();
        if(!empty($admin_permession)){
            $addPerm = $this->general_model->updateRowById('users_permissions_admins', 'perId', $admin_permession->perId, array( 'permission' => $data->per, 'lastUpdate' => date('Y-m-d H:i:s') ));
            $history_data = array(
                    'type'              => $data->type,
                    'userId'            => getUserId(),
                    'editedUser'        => $data->userId,
                    'text'              => $data->text,
                    'old_permission'    => $admin_permession->permission,
                    'new_permission'    => $data->per,
                    'dateCreation'      => date('Y-m-d H:i:s')
                );
            
            $addhistory = $result = $this->general_model->insertRow('users_permissions_admins_history', $history_data);
        }else{
            $per_data = array(
                    'type'          => $data->type,
                    'userId'        => $data->userId,
                    'text'          => $data->text,
                    'permission'    => $data->per,
                    'createdBy'     => getUserId(),
                    'dateCreation'  => date('Y-m-d H:i:s'),
                    'lastUpdate'    => date('Y-m-d H:i:s')
                );
            
            $addPerm = $result = $this->general_model->insertRow('users_permissions_admins', $per_data);
        }
        if(!empty($addPerm)){
            echo json_encode(array("result" => true ));
        }else{
            echo json_encode(array("result" => false ));
        }
    }
    
    function updateAdminsPermessionMain(){
        $data = (object)$_POST;
        $admin_permessions = $this->db->query("SELECT * FROM `users_permissions_admins` WHERE `type` = '$data->type' ")->result();
        foreach( $admin_permessions as $admin_permession){
            $current_permession = $this->db->query("SELECT * FROM `users_permissions_admins` WHERE `userId` = '$data->userId' AND `type` = '$admin_permession->type' AND `text` = '$admin_permession->text' ")->row();
            if(!empty($current_permession)){
                $addPerm = $this->general_model->updateRowById('users_permissions_admins', 'perId', $current_permession->perId, array( 'permission' => $data->per, 'lastUpdate' => date('Y-m-d H:i:s') ));
                $history_data = array(
                        'type'              => $admin_permession->type,
                        'userId'            => getUserId(),
                        'editedUser'        => $data->userId,
                        'text'              => $admin_permession->text,
                        'old_permission'    => $data->per ? 1 : 0,
                        'new_permission'    => $data->per,
                        'dateCreation'      => date('Y-m-d H:i:s')
                    );
                
                $addhistory = $result = $this->general_model->insertRow('users_permissions_admins_history', $history_data);
            }else{
                $per_data = array(
                        'type'          => $admin_permession->type,
                        'userId'        => $data->userId,
                        'text'          => $admin_permession->text,
                        'permission'    => $data->per,
                        'createdBy'     => getUserId(),
                        'dateCreation'  => date('Y-m-d H:i:s'),
                        'lastUpdate'    => date('Y-m-d H:i:s')
                    );
                
                $addPerm = $result = $this->general_model->insertRow('users_permissions_admins', $per_data);
            }
        }
        if(!empty($addPerm)){
            echo json_encode(array("result" => true ));
        }else{
            echo json_encode(array("result" => false ));
        }
    }
    
    function updateAdminsSubPermessionMain(){
        $data = (object)$_POST;
        $admin_sub_permessions = $this->db->query("SELECT * FROM `users_permissions_admins_main` WHERE `type` = '$data->type' AND `parentType` LIKE '$data->sub' ")->result();
        foreach( $admin_sub_permessions as $admin_permession){
            $current_permession = $this->db->query("SELECT * FROM `users_permissions_admins` WHERE `userId` = '$data->userId' AND `type` = '$admin_permession->type' AND `text` = '$admin_permession->text' ")->row();
            if(!empty($current_permession)){
                $addPerm = $this->general_model->updateRowById('users_permissions_admins', 'perId', $current_permession->perId, array( 'permission' => $data->per, 'lastUpdate' => date('Y-m-d H:i:s') ));
                $history_data = array(
                        'type'              => $admin_permession->type,
                        'userId'            => getUserId(),
                        'editedUser'        => $data->userId,
                        'text'              => $admin_permession->text,
                        'old_permission'    => $data->per ? 1 : 0,
                        'new_permission'    => $data->per,
                        'dateCreation'      => date('Y-m-d H:i:s')
                    );
                
                $addhistory = $result = $this->general_model->insertRow('users_permissions_admins_history', $history_data);
            }else{
                $per_data = array(
                        'type'          => $admin_permession->type,
                        'userId'        => $data->userId,
                        'text'          => $admin_permession->text,
                        'permission'    => $data->per,
                        'createdBy'     => getUserId(),
                        'dateCreation'  => date('Y-m-d H:i:s'),
                        'lastUpdate'    => date('Y-m-d H:i:s')
                    );
                
                $addPerm = $result = $this->general_model->insertRow('users_permissions_admins', $per_data);
            }
        }
        if(!empty($addPerm)){
            echo json_encode(array("result" => true ));
        }else{
            echo json_encode(array("result" => false ));
        }
    }
}
