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

class Admin_accounts extends CI_Controller {

	/**
	 * Index Page for this controller.
	 *
	 * Maps to the following URL
	 * 		http://example.com/index.php/welcome
	 *	- or -  
	 * 		http://example.com/index.php/welcome/index
	 *	- or -
	 * Since this controller is set as the default controller in 
	 * config/routes.php, it's displayed at http://example.com/
	 *
	 * So any other public methods not prefixed with an underscore will
	 * map to /index.php/welcome/<method_name>
	 * @see http://codeigniter.com/user_guide/general/urls.html
	 */
 
	 public function __construct(){
		parent::__construct();
		$this->load->model(array('admin/admin_model','admin/admin_accounts_model','admin/admin_mail_model'));
		if($this->admin_model->is_login === false){  redirect('admin/login', 'refresh'); exit; } 		  
		 if($this->uri->segment(3) != 'my_account'){
			 $this->admin_model->authenticateAdmin('admin_accounts');
		 }
    }
	 
	public function my_account( )
	{
 		$data = array();  
 		 if($this->input->post('myAccountBtn',TRUE)) {
			$this->form_validation->set_rules('name', ' Name', 'trim|xss_clean|required');
 			$this->form_validation->set_rules('username', 'Username', 'trim|xss_clean|required');
			$this->form_validation->set_rules('email', 'Email', 'trim|xss_clean|required|valid_email');
 			if($this->input->post('changeUserPassword',TRUE)) {
				 $this->form_validation->set_rules('password', 'Password', 'trim|xss_clean|required');
				 $this->form_validation->set_rules('password2', 'Confirm Password', 'trim|xss_clean|required|matches[password]');
			}
 			$emailRow = false;
			if ($this->form_validation->run() == TRUE) {
				$userEmail = $this->input->post('email', TRUE);
				$username = $this->input->post('username', TRUE);
 				$emailRow = $this->admin_model->isExistAdminEmail($userEmail,$this->admin_model->login_id);	
				$accUnameRow = $this->admin_model->isExistAdminUsername($username,$this->admin_model->login_id);	
 				if($emailRow){
					$this->form_validation->set_rules('email', 'Email Address', 'callback__custom_required[emailAlreadyExists]');	
				}
				if($accUnameRow){
					$this->form_validation->set_rules('username', 'User Name', 'callback__custom_required[userNameAlreadyExists]');	
				}
			}
  			 if ($this->form_validation->run() == TRUE) {
  					$result  = $this->admin_model->changeAccountDetails($this->admin_model->login_id);
 					if($result === true){
						 $this->session->set_flashdata('successMsg','Account updated successfully!');
						redirect('admin/admin_accounts/my_account');exit;
					}
  			} 
 		 }
 		$this->load->view('admin/my_account',$data);
	}
	public function sub_admins( )
	{
 		$data = array();  
		 
		if($this->input->post('doAction',true) && $this->input->post('ids',true)){
			$doAction = $this->input->post('doAction',true);
			 $this->admin_model->checkAdminPrivilage($doAction=='delete'?'DELETE':'UPDATE','admin/admin_accounts/sub_admins');
 				$successMsg = $this->admin_accounts_model->doAdminAction($this->input->post('doAction',true),$this->input->post('ids',true));
				$this->session->set_flashdata('successMsg',$successMsg);
				$redirectUrl = 'admin/admin_accounts/sub_admins';
				if($this->input->post('listUrl',true) && $this->input->post('doAction',true) != 'delete')$redirectUrl =$this->input->post('listUrl',true);
				redirect($redirectUrl);exit;
		}
		
  		$this->load->view('admin/sub_admins',$data);
	}
	
	
	public function sub_admin_manager($action='add',$accountId=false ) 
	{
		 
		$this->admin_model->checkAdminPrivilage($action=='add'?'INSERT':'UPDATE','admin/admin_accounts/sub_admins');
		if($action == 'view')$this->admin_model->checkAdminPrivilage('VIEW','admin/admin_accounts/sub_admins');
 		$data = array('action'=>$action,'accountId'=>$accountId);  
		if($accountId){
			$adminRow = $this->admin_model->getAdminRow($accountId); 
			if($adminRow === false){
				$this->session->set_flashdata('errMsg','Invalid URI');
				redirect('admin/admin_accounts/sub_admins');exit;
			}
			$data['adminRow'] = $adminRow;
 		}
   		if($this->input->post('subAdminBtn',TRUE)) {
			$this->form_validation->set_rules('name', ' Name', 'trim|xss_clean|required');
 			$this->form_validation->set_rules('username', 'Username', 'trim|xss_clean|required');
			$this->form_validation->set_rules('email', 'Email', 'trim|xss_clean|required|valid_email');
 			if($this->input->post('changeUserPassword',TRUE) || $action == 'add') {
				 $this->form_validation->set_rules('password', 'Password', 'trim|xss_clean|required');
				 $this->form_validation->set_rules('password2', 'Confirm Password', 'trim|xss_clean|required|matches[password]');
			}
  			$this->form_validation->set_rules('accessPrivilege[]', 'Privileges', 'callback__custom_required[isEmptyPrivileges]');	
 			$this->form_validation->set_rules('accessModule[]', 'Access Modules', 'callback__custom_required[isEmptyModules]');	
  			$emailRow = false;
			if ($this->form_validation->run() == TRUE) {
				$userEmail = $this->input->post('email', TRUE);
				$username = $this->input->post('username', TRUE);
 				$emailRow = $this->admin_model->isExistAdminEmail($userEmail,$accountId);	
				$accUnameRow = $this->admin_model->isExistAdminUsername($username,$accountId);	
 				if($emailRow){
					$this->form_validation->set_rules('email', 'Email Address', 'callback__custom_required[emailAlreadyExists]');	
				}
				if($accUnameRow){
					$this->form_validation->set_rules('username', 'User Name', 'callback__custom_required[userNameAlreadyExists]');	
				}
			}
  			 if ($this->form_validation->run() == TRUE) {
   					$result  = $this->admin_model->addEditAdminAccount($accountId);
 					if($result === true){
						if($accountId){
							$this->session->set_flashdata('successMsg','Admin account  updated successfully!');
						}else{
							$this->session->set_flashdata('successMsg','Admin account created successfully!');
						}
						redirect('admin/admin_accounts/sub_admins');exit;
					}
  			} 
 		 }
 		$this->load->view('admin/sub_admin_manager',$data);
	}
	function _custom_required($str, $func) {
		  // var_dump($str);var_dump($func); exit;
        switch($func) {
            case 'emailAlreadyExists':
                $this->form_validation->set_message('_custom_required', 'Email already being used!');
                return FALSE;
                break;
			case 'userNameAlreadyExists':
                $this->form_validation->set_message('_custom_required', 'Username already being used!');
                return FALSE;
                break;	
			case 'valid_username':
				if(!preg_match('/^[A-Za-z0-9_]+$/', $str)) {  
					  $this->form_validation->set_message('_custom_required', 'Please enter valid admin user name!<p></p>');
                	return FALSE;
				}
               
                break;	
			case 'isEmptyPrivileges': 
				if(empty($str)){
					$this->form_validation->set_message('_custom_required', 'Please select at least one privilege!');
					return FALSE;
				}else {
					return TRUE;	
				}
                break;	
			case 'isEmptyModules':
				if(empty($str)){
					$this->form_validation->set_message('_custom_required', 'Please select at least one access modules!');
					return FALSE;
				}else {
					return TRUE;	
				}
                break;	
 			default: return TRUE;	
         }
    }
	function blockLogin(){
		header('HTTP/1.1 403 Forbidden'); 
		echo '<h1>403 Forbidden</h1>';
		exit;	
	}
}

/* End of file welcome.php */
/* Location: ./application/controllers/welcome.php */