<?php

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

class Users extends MY_Controller {

    function __construct() {

        parent::__construct();
    }

    private function _getUserRoles($id = NULL) {
        $this->load->model('settings/users_model');
        $catarr = $this->users_model->getRoles();
        $data = '';
        for ($i = 0; $i < count($catarr); $i++) {
            if ($id != NULL && $id == $catarr[$i]->ID)
                $data .= "<option id=\"option_custom\" selected=\"yes\" value=\"" . $catarr[$i]->ID . "\">" . $catarr[$i]->NAME . "</option>\n";
            else
                $data .= "<option id=\"option_custom\" value=\"" . $catarr[$i]->ID . "\">" . $catarr[$i]->NAME . "</option>\n";
        }
        return $data;
    }
    function getusersautocomplete() {
        $term = $this->input->post('term', TRUE);
        $this->load->model('settings/users_model');
        $rows = $this->users_model->getusersautocomplete($term);

        $keywords = array();
        foreach ($rows as $row)
            array_push($keywords, $row->NAME);
        echo json_encode($keywords);
    }
    function getcardautocomplete() {
        $term = $this->input->post('term', TRUE);
        $this->load->model('settings/users_model');
        $rows = $this->users_model->getcardautocomplete($term);

        $keywords = array();
        foreach ($rows as $row)
            array_push($keywords, $row->CARD);
        echo json_encode($keywords);
    }
    function _roleName($id) {
        $this->load->model('settings/users_model');
        return $this->users_model->roleName($id);
    }

   

    public function index() {
        $data['roles'] = $this->common->getAll('ROLES');
        $data['template'] = 'settings/users_ovw';
        $this->load->view('template',$data);
      
    }
    
     public function getusers() {
         $sql = "SELECT `PEOPLE`.*, `ROLES`.NAME as rolesname FROM `PEOPLE` INNER JOIN `ROLES`
        ON `PEOPLE`.ROLE=`ROLES`.ID";
        $data['data'] = $this->common->customquery($sql);
        echo json_encode($data);
    }
    

       public function addusers() {
        $id = $this->input->post('id');
        if($this->input->post('VISIBLE')==1){
            $visible    =   1;
        }else{
            $visible    =   0;
        }
       if($id == '') {
            $data = array(   
                'ID' => uniqid(),
                'NAME' => $this->input->post('name'),
                'CARD' => $this->input->post('card'),
                'ROLE' => $this->input->post('role'),
                'VISIBLE'=>$visible
            );
          $existdata = $this->common->existdata('PEOPLE',$data);
            if(!empty($existdata)) {
                $this->session->set_flashdata('error_msg', 'The record is already exist');
            } else if($this->input->post('password')=='') {
                $this->session->set_flashdata('error_msg', 'Invalid password');
            } else {
                $data["APPPASSWORD"] =   'sha1:' . strtoupper(sha1($this->input->post('password')));
                $this->common->insert('PEOPLE',$data);
                $this->session->set_flashdata('success_msg', 'The record is added successfuly.');
            }
        } else {
            $data = array(   
                'NAME' => $this->input->post('name'),
                // 'APPPASSWORD' => 'sha1:' . strtoupper(sha1($this->input->post('password'))),
                'CARD' => $this->input->post('card'),
                'ROLE' => $this->input->post('role'),
                'VISIBLE'=>$visible
            );
            if($this->input->post('password')!='')
                $data["APPPASSWORD"] =   'sha1:' . strtoupper(sha1($this->input->post('password')));
            $where = array('ID' => $id);
            $this->session->set_flashdata('success_msg', 'The record has been updated successfuly.');
            $this->common->update('PEOPLE',$where,$data);
        }
        redirect('settings/users');
 
    }
    
      public function editusers($id) {
        $where = array('ID' => $id,);
        $data = $this->common->getWhere('PEOPLE',$where);

        echo json_encode($data);
 
    }
       public function deleteusers($id) {

        $where = array('ID' => $id);  
        $this->common->delete('PEOPLE',$where);
        $this->session->set_flashdata('success_msg', 'The record has been deleted successfuly.');
        redirect('settings/users');
 
    }


    public function password() {
        $this->load->view('settings/head');
        $this->load->view('settings/users_changepassword_view', null);
        $this->load->view('settings/footer');
    }

     public function changepassword() {
        $this->load->library('form_validation');   
        $this->form_validation->set_rules('password1', 'Old Password', 'trim|required');
        $this->form_validation->set_rules('password2', 'New Password', 'trim|required');
        $this->form_validation->set_rules('password3', 'Password Confirmation', 'trim|required|matches[password2]');
        if ($this->input->post('changepassword')) {
            if ($this->form_validation->run() == TRUE) {
                $this->load->model('settings/users_model');
                $id=$this->getuserid($this->session->userdata('user'));
                $oldpwd=$this->getoldpassword($id);
                //var_dump($oldpwd);
               // var_dump('sha1:' . strtoupper(sha1($this->input->post('password1'))));
               // var_dump('sha1:' . strtoupper(sha1($this->input->post('password2'))));
               // var_dump('sha1:' .  strtoupper(sha1($this->input->post('password3'))));
                if($oldpwd == 'sha1:' . strtoupper(sha1($this->input->post('password1')))) {

                     $this->users_model->changepassword($id, $this->input->post('password2'));
                     $this->session->set_flashdata('success_msg', 'Password changed successfully.');
                   
                    redirect('settings/users/changepassword');
                } else {
                     $this->session->set_flashdata('success_msg', 'Old password does not match.');
                     redirect('settings/users/changepassword');
                }
            } else {
           
            $this->session->set_flashdata('success_msg', 'please enter a valid password.');
            $data['template'] = 'settings/users_changepassword_view';
            $this->load->view('template',$data);
            }
        } else {
            $data['template'] = 'settings/users_changepassword_view';
            $this->load->view('template',$data);
        }
    }


    //GET USER ID
    function getuserid($name) {
        $this->load->model('settings/users_model');
        return $this->users_model->getUserID($name);
    }

    //GET USER ID
    function getoldpassword($id) {
        $this->load->model('settings/users_model');
        return $this->users_model->getoldpassword($id);
    }

   

    //GET USER ROLES
    public function getrols() {
        $this->load->model('settings/users_model');
        echo $this->users_model->getrols();
    }

    function roles() {
       $this->load->model('settings/users_model');
        $data['roles'] = $this->users_model->getRoles();
         $data['template'] = 'settings/roles_ovw';
         $this->load->view('template',$data);
    }

     public function getroles() {
        $data['data'] = $this->common->getAll('ROLES');
        echo json_encode($data);
    }
    

       public function addroles() {
        $id = $this->input->post('id');
        $data = array( 
            'NAME' => $this->input->post('name'),
            'PERMISSIONS' => $this->input->post('permissions')
        );
       if($id == '')
       { 
         $existdata = $this->common->existdata('ROLES',$data);
          // print_r( $existdata);die();
           if(!empty($existdata))
           {
           
             $this->session->set_flashdata('success_msg', 'The record is already exist');
           }
           else
           {
$data['ID'] = uniqid();  

          $this->common->insert('ROLES',$data);
          $this->session->set_flashdata('success_msg', 'The record is added successfuly.');
           }
       
       }
        else
       {
          $where = array('ID' => $id);
          $this->session->set_flashdata('success_msg', 'The record has been updated successfuly.');
          $this->common->update('ROLES',$where,$data);
       }
        redirect('settings/users/roles');
 
    }
    
      public function editroles($id) {
        $where = array('ID' => $id,);
        $data = $this->common->getWhere('ROLES',$where);

        echo json_encode($data);
 
    }
       public function deleteroles($id) {

        $where = array('ID' => $id);  
        $this->common->delete('ROLES',$where);
        $this->session->set_flashdata('success_msg', 'The record has been deleted successfuly.');
        redirect('settings/users/roles');
 
    }

   

    function test()
    {
        var_dump($this->_getmenu());
        $this->session->set_userdata('usermenu',$this->_getmenu());
        var_dump($this->session->userdata('usermenu'));
    }
    
    public function login() {
        if ($this->session->userdata('logged_in') == true)
            die(redirect(site_url()));
        if ($this->input->post('login')) {
            $this->load->model('settings/users_model');
            if ($this->users_model->validateLogin($this->input->post('user'), $this->input->post('password'))) {
                $this->session->sess_destroy();
                $data = array(
                    'user' => $this->input->post('user'),
                    'logged_in' => true
                );
                $this->session->set_userdata($data);
                redirect(site_url());
            } else {
                $this->session->set_flashdata('errormsg', '<font color="red"><p align="center">Incorrect Username or Password.</p></font>');
                $this->session->set_flashdata('username_val', $this->input->post('user'));
                $this->session->set_flashdata('password_val', $this->input->post('password'));
                redirect(site_url() . 'settings/users/login');
            }
        } else {
            $this->load->view('settings/login');
        }
    }

    public function logout() {
        $this->session->sess_destroy();
        redirect(site_url() . 'settings/users/login');
    }
    
    private function getidbyrole($name) {
        $this->load->model('settings/users_model');
        return $this->users_model->getidbyrole($name);
    }
    
    //ROLES AUTOCOMPLETE
    function getrolesautocomplete() {
        $term = $this->input->post('term', TRUE);
        $this->load->model('settings/users_model');
        $rows = $this->users_model->getrolesautocomplete($term);
        $keywords = array();
        foreach ($rows as $row)
            array_push($keywords, $row->NAME);
        echo json_encode($keywords);
    }
    function getroleidautocomplete() {
        $term = $this->input->post('term', TRUE);
        $this->load->model('settings/users_model');
        $rows = $this->users_model->getroleidautocomplete($term);
        $keywords = array();
        foreach ($rows as $row)
            array_push($keywords, $row->ID);
        echo json_encode($keywords);
    }
    
    function user(){
        
        $this->load->model('settings/users_model');
        $oper = $this->input->post('oper');
        $role = $this->getidbyrole($this->input->post('ROLE'));
        $id = uniqid();
     
       /* if($oper=='del')
        {
            $id = $this->input->post('id');
            if($id)
            {
                $this->users_model->delete($id);
                $fdata = array('msgt' => 'S', 'msg' => 'Users deleted successfully.');
                $this->session->set_flashdata($fdata);
                redirect(site_url() . 'settings/users');
            }
            else {
                $fdata = array('msgt' => 'E', 'msg' => 'Cannot delete product.');
                $this->session->set_flashdata($fdata);
                redirect(site_url() . 'settings/users');
            }
        }*/
          $this->load->library('form_validation');

        $this->form_validation->set_rules('NAME', 'NAME', 'trim|required');
        $this->form_validation->set_rules('PASSWORD', 'PASSWORD', 'trim|required');
        $this->form_validation->set_rules('CONFIRMPASSWORD', 'CONFIRMPASSWORD', 'trim|required|matches[PASSWORD]');
        $this->form_validation->set_rules('ROLE', 'ROLE', 'trim|required');

                 if ($this->form_validation->run() == TRUE) {
            $form_data = array(
                            'ID' => $id,
                            'NAME' => $this->input->post('NAME'),
                            'APPPASSWORD' => 'sha1:' . strtoupper(sha1($this->input->post('PASSWORD'))),
                            'ROLE' => $role,
                            'CARD' => ($this->input->post('CARD')) ? $this->input->post('CARD') : NULL,
                            'VISIBLE' => 1                     
            );
            var_dump($form_data);
        
        if($oper=='add')
        {
             if ($this->users_model->add($form_data) == TRUE) {
                        $fdata = array('msgt' => 'S', 'msg' => 'Users added successfully.');
                $this->session->set_flashdata($fdata);
                return true;
         }
        }
        elseif($oper=='edit')
        {
            $id = $this->input->post('ID');
            if($id)
            {
               
                $this->users_model->update($id, $form_data);   
            }
        }
       }
    }
    
     
     function record()
    {      
            $oper = $this->input->post('oper');
            $id = uniqid();
            $this->load->model('settings/users_model');
            /*if($oper=='del')
            {
                $id = $this->input->post('id');
                if($id)
                {
                    $this->users_model->delete1($id);
                    $fdata = array('msgt' => 'S', 'msg' => 'Roles deleted successfully.');
                    $this->session->set_flashdata($fdata);
                    redirect(site_url() . 'settings/users');
                }
                else 
                {
                $fdata = array('msgt' => 'E', 'msg' => 'Cannot Roles Unit.');
                $this->session->set_flashdata($fdata);
                redirect(site_url() . 'settings/users');
                }
            }*/
            $this->load->library('form_validation');
            $this->form_validation->set_rules('NAME', 'NAME', 'trim|required');
            $this->form_validation->set_rules('PERMISSIONS', 'PERMISSIONS', 'trim|required');

            if ($this->form_validation->run() == true) {
                $form_data =  array(
                    
                            'ID' => $this->input->post('ID'),
                            'NAME' => $this->input->post('NAME'),
                            'PERMISSIONS' =>htmlspecialchars_decode($this->input->post('PERMISSIONS'))
                          );
                var_dump($form_data);
                if($oper=='add')
                {
                    if ($this->users_model->add1($form_data) == TRUE) {
                            $fdata = array('msgt' => 'S', 'msg' => 'Roles added successfully.');
                            $this->session->set_flashdata($fdata);
                            return true;
                    }
                }
                elseif($oper=='edit')
                {
                    $id = $this->input->post('id');
                    if($id)
                    {
                            $this->users_model->update1($id,$form_data);   
                    }       
                }
             }
     }
      function deleterole()
    { $this->load->model('settings/users_model');
        if ($this->uri->segment(4)) 
            {
           
           if($this->users_model->delete1($this->uri->segment(4))==true){
            $fdata = array('msgt' => 'S', 'msg' => 'Role deleted successfully.');
            $this->session->set_flashdata($fdata);
            redirect(site_url() . 'settings/users/roles');
        } else{
            $fdata = array('msgt' => 'E', 'msg' => 'Cannot delete Role.');
            $this->session->set_flashdata($fdata);

            redirect(site_url() . 'settings/users/roles');
        }
    }}
    function deluser()
    { $this->load->model('settings/users_model');
        if ($this->uri->segment(4)) 
            {
           
            if($this->users_model->delete($this->uri->segment(4))==true){
            $fdata = array('msgt' => 'S', 'msg' => 'User deleted successfully.');
            $this->session->set_flashdata($fdata);
            redirect(site_url() . 'settings/users');
        } else{
            $fdata = array('msgt' => 'E', 'msg' => 'Cannot delete user.');
            $this->session->set_flashdata($fdata);

            redirect(site_url() . 'settings/users');
        }
    }}
}
