<?php 
namespace App\Modules\Admin\Controllers;
ini_set("memory_limit","512M");
error_reporting(E_ALL ^ E_NOTICE);



use App\Modules\generic\Models\Mdl_generic;

use App\Modules\Admin\Models\Mdl_admin;

use CodeIgniter\Controller;

class Admin extends Controller
{
   private $db;
 protected  $viewFile;
 protected  $email;
 protected  $captcha; 
 protected  $isLogin;
 
    /**
     * Constructor.
     */
    public function __construct()
    {
        //$db = \Config\Database::connect();
        $this->Mdl_admin = new Mdl_admin();
    }

	function index(){
		if(!Modules::run('security/isAdmin')){

      //$captcha = Modules::run('captcha/Captcha');
      $captcha='';
      $data['captcha'] = $captcha;
      
      $this->session->set_userdata('salt', random_string('alpha', 10));
      
      $data['salt'] = $this->session->userdata('salt');
     	view('login', $data);
		}else{
			redirect('admin/dashboard');
		}
  }
  
  /*function admin_test_login(){
		if(!Modules::run('security/isAdmin')){

      $captcha = Modules::run('captcha/Captcha');
      $data['captcha'] = $captcha;
      
      $this->session->set_userdata('salt', random_string('alpha', 10));
      
      $data['salt'] = $this->session->userdata('salt');
     	$this->load->view('login-admin-test', $data);
		}else{
			redirect('admin/dashboard');
		}
	}*/
	
	/*
	**	Admin Login Submit
  */
  /*function loginAction_admin_test(){

    date_default_timezone_set("Asia/kolkata");
		$content = $this->input->post();
		
		$token = $this->session->userdata("token");
		if($content["csrfToken"] == $token){
			
			$this->form_validation->set_rules("uname","Username","required|xss_clean",array(
				'required' => "Username is required"
			));
			
			$this->form_validation->set_rules("pword","Password","required|xss_clean",array(
				'required' => "Password is required."
      ));
      
      $this->form_validation->set_rules("captcha","Captcha","required|xss_clean",array(
				'required' => "Captcha is required."
			));
		
			if($this->form_validation->run() == FALSE){
				$errors = $this->form_validation->error_array();
				echo json_encode($errors);
			}else{

        $captcha_insert = $content['captcha'];
        $contain_sess_captcha = $this->session->userdata('valuecaptchaCode');
        if($captcha_insert != $contain_sess_captcha) {

          echo json_encode(array("captcha" => "Captcha is Incorrect !")); 
          exit;

        }else{
          $uname = $content['uname'];
          $pass = $content['pword'];
          $hashpass = $content['hash'];
          $param = array(
            'username' => $uname
          );

          $admin = $this->Mdl_admin->getByValues("admin_master",$param);

          if($admin !== "No Data"){

            foreach($admin as $row){
              $id = $row->id;
              $status = $row->status;
              $nextLoginTime = $row->nextLoginTime;
            }
            $startTime = date("Y-m-d H:i:s");

            if($startTime < $nextLoginTime){
              echo json_encode(array("status" => "fail", "message"=>"PLEASE TRY AGAIN LATER !")); exit;
            }

            $login_data = array(
              'loginTryCount' => '0',
              'status' => '1'
            );

            $update_admin_login = $this->Mdl_admin->update("admin_master", "id", $id, $login_data);
            $admin = $this->Mdl_admin->getByValues("admin_master",$param);

            if($admin[0]->status == '1'){
              $salt = $this->session->userdata('salt');
              $pass_hash = md5($pass);
              $database_pass_hash = md5($salt.$pass_hash);

              echo $hashpass.' = '.$database_pass_hash;

              if($hashpass == $database_pass_hash){
                echo "Match";
              }else{
                echo "Not Match";
              }
              // $check = Modules::run('security/verifyPassoword',$pass,$admin[0]->password);
              $check = Modules::run('security/verifyPassoword',$hashpass,$database_pass_hash);

              var_dump($check);
              die();
              if($check){
                foreach($admin as $row){
                  $id = $row->id;
                  $name = $row->name;
                  $isAdmin = $row->isAdmin;
                  $username = $row->username;
                  $status = $row->status;
                  $rights = $row->rights;
                  $nextLoginTime = $row->nextLoginTime;
                }
                
                $data = array(
                  'userid'=> $id,
                  'userip'=> $this->input->ip_address(),
                  'loginDateTime'=> date('Y-m-d H:i:s'),
                  'loginStatus'=> 1,
                  'logoutDateTime'=> '',
                  'action'=> 'Login',
                  'modulename'=> 'Admin Login',
                  'EventDateTime'=> date('Y-m-d H:i:s')
                );
          
                $insert = $this->Mdl_admin->insert("admin_login_activity", $data);

                $login_rec = 'SELECT logID FROM admin_login_activity ORDER BY logID desc LIMIT 1';
					      $record = $this->Mdl_admin->customQuery($login_rec);
                $logid = $record[0]->logID;

                $sessionData = array(
                  'id'=>$id,
                  'name'=>$name,
                  'isAdmin'=>$isAdmin,
                  'username'=>$username,
                  'status'=>$status,
                  'rights'=>$rights,
                  'logid' => $logid,
                  'type'=>'admin'
                );

                $this->session->set_userdata('admin', $sessionData);
                echo json_encode(array("status"=>"success")); exit;
              }else{

                foreach($admin as $row){
                  $id = $row->id;
                  $loginTryCount = $row->loginTryCount;
                }

                $incr_login_count = $loginTryCount + 1;
                
                if($incr_login_count == 3){

                  $login_data = array(
                    'loginTryCount' => $incr_login_count,
                    'status' => '0',
                    'nextLoginTime' => date('Y-m-d H:i:s', strtotime('+15 minutes', strtotime(date("Y-m-d H:i:s"))))
                  );
                  $msg = 'YOU HAVE ATTEMPTS MANY TIME ! PLEASE TRY AGAIN LATER !';
                }else{

                  $login_data = array(
                    'loginTryCount' => $incr_login_count
                  );
                  $msg = 'WRONG USERNAME OR PASSWORD.';
                }
                
                $update_admin_login_count = $this->Mdl_admin->update("admin_master", "id", $id, $login_data);
                
                $data = array(
                  'userid'=> $id,
                  'userip'=> $this->input->ip_address(),
                  'loginDateTime'=> date('Y-m-d H:i:s'),
                  'loginStatus'=> 0,
                  'logoutDateTime'=> '',
                  'action'=> 'Login',
                  'modulename'=> 'Admin Login',
                  'EventDateTime'=> date('Y-m-d H:i:s')
                );
          
                $insert = $this->Mdl_admin->insert("admin_login_activity", $data);

                echo json_encode(array("status"=>"fail","title"=>"Error","message"=>$msg)); exit;
              }
            }else{
              echo json_encode(array("status"=>"fail","title"=>"Error" ,"message"=>"ACCOUNT IS NOT ACTIVE.")); exit;
            }
          }else{
            echo json_encode(array("status"=>"fail","title"=>"Error","message"=>"USER DOES NOT EXIST.")); exit;
          }
        }

        
			}
		}else{
			echo json_encode(array("status"=>"invalid")); exit;
		}
  }*/

  function refresh_captcha(){
    if(!Modules::run('security/isAdmin')){
      $content = $this->input->post();
      
      if($content['req'] == 1){
        $captcha = Modules::run('captcha/Captcha');
        echo json_encode(array("status"=>"success", "message" => '', 'res' => $captcha)); exit;
      }else{
        echo json_encode(array("status"=>"fail", "message" => 'Something went wrong !', "res" => $captcha)); exit;
      }
      
    }
  }
  
	function loginAction(){

    date_default_timezone_set("Asia/kolkata");
		$content = $this->input->post();
		//print_r($content);
		$token = $this->session->userdata("token");
		if($content["csrfToken"] == $token){
			
			$this->form_validation->set_rules("uname","Username","required|xss_clean|max_length[255]",array(
				'required' => "Username is required"
			));
			
			$this->form_validation->set_rules("pword","Password","required|xss_clean|max_length[100]",array(
				'required' => "Password is required."
      ));
      
      $this->form_validation->set_rules("captcha","Captcha","required|xss_clean|max_length[100]",array(
				'required' => "Captcha is required."
			));
		
			if($this->form_validation->run() == FALSE){
				$errors = $this->form_validation->error_array();
				echo json_encode($errors);
			}else{

        $captcha_insert = $content['captcha'];
        $contain_sess_captcha = $this->session->userdata('valuecaptchaCode');
        if($captcha_insert != $contain_sess_captcha) {

          echo json_encode(array("captcha" => "Captcha is Incorrect !")); 
          exit;

        }else{
            $salt = $this->session->userdata('salt');
          $uname = $content['uname'];
          $pass = $content['pword'];
          //$hashpass = $content['hash'];
          $param = array(
            'username' => $uname
          );

          $admin = $this->Mdl_admin->getByValues("admin_master",$param);

          if($admin !== "No Data"){

            foreach($admin as $row){
              $id = $row->id;
              $status = $row->status;
              $nextLoginTime = $row->nextLoginTime;
            }
            $startTime = date("Y-m-d H:i:s");

            if($startTime < $nextLoginTime){
              echo json_encode(array("status" => "fail", "message"=>"PLEASE TRY AGAIN LATER !")); exit;
            }

            $login_data = array(
              'loginTryCount' => '0',
              'status' => '1'
            );

            $update_admin_login = $this->Mdl_admin->update("admin_master", "id", $id, $login_data);
            $admin = $this->Mdl_admin->getByValues("admin_master",$param);
            //print_r($admin);
            if($admin[0]->status == '1'){

               $salt = $this->session->userdata('salt');
              //$pass_hash = md5($admin[0]->pword);
              //$database_pass_hash = md5($salt.$admin[0]->password);
              $database_pass_hash = $admin[0]->password;
              //echo $hashpass;
              if($pass == $database_pass_hash){
                $check = 1;
              }else{
                $check = 0;
              }
              //echo "<br>logincheck".$check;
                    //die();
              //$check = Modules::run('security/verifyPassoword',$pass,$admin[0]->password);
              

              // var_dump($check);
              // die();
              
              
              if($check){
               $login_rec = 'SELECT logID FROM admin_login_activity where userid ='.$id.' ORDER BY logID desc LIMIT 1';
			  $record1 = $this->Mdl_admin->customQuery($login_rec);
                $logoutDateTime = $record1[0]->logoutDateTime;
                if($logoutDateTime =='0000-00-00 00:00:00')
                {
                      $logout_data = array(
                                              'loginStatus'=> 0,
                                              'logoutDateTime'=> date('Y-m-d H:i:s')
                                            );
                     $update_admin_logout = $this->Mdl_admin->update("admin_login_activity", "userid", $id, $logout_data);
    
                }
                
   
                foreach($admin as $row){
                  $id = $row->id;
                  $name = $row->name;
                  $isAdmin = $row->isAdmin;
                  $username = $row->username;
                  $status = $row->status;
                  $rights = $row->rights;
                  $nextLoginTime = $row->nextLoginTime;
                }
                
                $data = array(
                'username'=> $username,
                  'userid'=> $id,
                  'userip'=> $this->input->ip_address(),
                  'loginDateTime'=> date('Y-m-d H:i:s'),
                  'loginStatus'=> 1,
                  'logoutDateTime'=> '',
                  'action'=> 'Login',
                  'modulename'=> 'Admin Login',
                  'usertype'=> 1,
                  'EventDateTime'=> date('Y-m-d H:i:s')
                );
          
                $insert = $this->Mdl_admin->insert("admin_login_activity", $data);

                $login_rec = 'SELECT logID FROM admin_login_activity ORDER BY logID desc LIMIT 1';
					      $record = $this->Mdl_admin->customQuery($login_rec);
                $logid = $record[0]->logID;

                $sessionData = array(
                  'id'=>$id,
                  'name'=>$name,
                  'isAdmin'=>$isAdmin,
                  'username'=>$username,
                  'status'=>$status,
                  'rights'=>$rights,
                  'logID' => $logid,
                  'type'=>'admin'
                );
                session_regenerate_id(true);
                $this->session->set_userdata('admin', $sessionData);
                // $admin = $this->session->userdata('admin');
                
                // echo "<pre>";
                // print_r($admin);
                // die;
                
                $this->session->unset_userdata('valuecaptchaCode');
                $this->session->unset_userdata('salt');
                
                echo json_encode(array("status"=>"success")); exit;
              }else{

                foreach($admin as $row){
                  $id = $row->id;
                  $loginTryCount = $row->loginTryCount;
                }

                $incr_login_count = $loginTryCount + 1;
                
                if($incr_login_count == 3){

                  $login_data = array(
                    'loginTryCount' => $incr_login_count,
                    'status' => '0',
                    'nextLoginTime' => date('Y-m-d H:i:s', strtotime('+15 minutes', strtotime(date("Y-m-d H:i:s"))))
                  );
                  $msg = 'YOU HAVE ATTEMPTS MANY TIME ! PLEASE TRY AGAIN LATER !';
                }else{

                  $login_data = array(
                    'loginTryCount' => $incr_login_count
                  );
                  $msg = 'WRONG USERNAME OR PASSWORD.';
                }
                
                $update_admin_login_count = $this->Mdl_admin->update("admin_master", "id", $id, $login_data);
                
                $data = array(
                  'userid'=> $id,
                  'username'=> $username,
                  'userip'=> $this->input->ip_address(),
                  'loginDateTime'=> date('Y-m-d H:i:s'),
                  'loginStatus'=> 0,
                  'logoutDateTime'=> '',
                  'action'=> 'Login',
                  'modulename'=> 'Admin Login',
                  'usertype'=> 1,
                  'EventDateTime'=> date('Y-m-d H:i:s')
                );
          
                $insert = $this->Mdl_admin->insert("admin_login_activity", $data);

                echo json_encode(array("status"=>"fail","title"=>"Error","message"=>$msg)); exit;
              }
            }else{
              echo json_encode(array("status"=>"fail","title"=>"Error" ,"message"=>"ACCOUNT IS NOT ACTIVE.")); exit;
            }
          }else{
            echo json_encode(array("status"=>"fail","title"=>"Error","message"=>"USER DOES NOT EXIST.")); exit;
          }
        }

        
			}
		}else{
			echo json_encode(array("status"=>"invalid")); exit;
		}
	}
	
	/* 
	**	Admin Logout 
	*/
	function logout(){
    date_default_timezone_set("Asia/kolkata");
    
    $admin = $this->session->userdata('admin');
    $logid = $admin['logID'];

    $logout_data = array(
      'loginStatus'=> 0,
      'logoutDateTime'=> date('Y-m-d H:i:s')
    );

    $update_admin_logout = $this->Mdl_admin->update("admin_login_activity", "logID", $logid, $logout_data);
    
    delete_cookie('ci_session');
		$this->session->unset_userdata('admin');
		// $this->session->sess_destroy();
		redirect('admin','refresh');
	}
	
  /* 
  **  Admin Dashboard 
  */
  function dashboard(){
    if(!Modules::run('security/isAdmin')){
      redirect('admin','refresh');
    }

    $magazine = $this->Mdl_admin->getByValue("e_magazine","id",1);

    $template = 'admin';
    $data['magazine'] = $magazine;
    $data['module'] = "admin";
    $data['scriptFile'] = "admin_v_1.1";
    $data['viewFile'] = "admin/dashboard";
    echo Modules::run('template/'.$template, $data);
  }
  
  /*
  **  UPDATE MAGAZINE LINK
  */
  function updateMagazine(){
    $content = $this->input->post();
    
    $this->form_validation->set_rules("url","Magazine Link","trim|required|xss_clean",
    array(
      'required' => "Magazine Link is required"
    ));

    if($this->form_validation->run() == FALSE){
      $errors = $this->form_validation->error_array();
      echo json_encode($errors); exit;
    }else{
      $admin = $this->session->userdata('admin');

      $data = array(
        'url' => strip_tags($content['url']),
        'modifiedBy'=>$admin['id'],
        'modifiedDate' => date("Y-m-d")
      );

      $update = $this->Mdl_admin->update("e_magazine","id",1,$data);
      echo json_encode(array("status"=>"success")); exit;  
    }
  }

  /* 
  **  Get Admin Name 
  */
  function getAdminName($id){
    $admin = $this->Mdl_admin->getByValues("admin_master",array('id' => $id));
    if($admin !== "No Data"){
      return $admin[0]->name;
    }else{
      return "No Record Found.";
    }
  }

  /*
  ** DELETE ACTION 
  */
  function deleteAction(){
    $content = $this->input->post();
    
    if(!Modules::run('security/isAdmin')){
      echo json_encode(array('status'=>'deny'));
    }

    $admin = $this->session->userdata('admin');
    if($admin['isAdmin'] == '1'){
      echo json_encode(array('status'=>'deny'));
    }

    if($content['table'] == 'coa_designations'){
      $result = $this->Mdl_admin->deleteById($content['table'],'parent',$content['val']);
    }else if($content['table'] == 'secretariat_designations'){
      $result = $this->Mdl_admin->deleteById($content['table'],'parent',$content['val']);
    }

    $result = $this->Mdl_admin->deleteById($content['table'],$content['col'],$content['val']);
    echo json_encode(array('status'=>'success'));
  }

	/* ============================================================== */
  /*                          ADMIN MODULES                         */
  /* ============================================================== */
	
  /*
  **  Admin Listing Page
  */
  function viewall(){
    if(!Modules::run('security/isAdmin')){
      redirect('admin','refresh');
    }

    $admin = $this->session->userdata('admin');
    $isAdmin = $admin['isAdmin'];
    
    if($isAdmin !== '0'){
      redirect('admin/dashboard','refresh');
    }

    $template = 'admin';
    $data['scriptFile'] = 'admin_v_1.1';
    $data['viewFile'] = 'admin/list-admin';
    $data['module'] = "admin";
    echo Modules::run('template/'.$template, $data);
  }

  /*
  **  Get List Of Admins
  */
  function getAdminList(){
    $list = $this->Mdl_admin->get_datatables();
    $data = array();
    $no = $_POST['start'];

    $sess = $this->session->userdata('admin');
    $adm_id = $sess['id'];  
    
    foreach ($list as $val) {
      if($val->isAdmin == '1' && $val->id !== $adm_id){
        $row = array();
        $url = base_url().'admin/update/'.$val->id;
        $row[] = '<a class="btn btn-rounded btn-outline-success" href="'.$url.'">UPDATE</a>';

        if($sess['isAdmin'] !== '1'){
          $row[] = '<button class="btn btn-block btn-rounded btn-outline-danger" id="'.$val->id.'" onclick="callDeleteFunction(\'admin_master\',\'id\',this.id,\'admin\')">DELETE</button>';
        }else{
          $row[] = '';
        }

        if($val->status == '1'){
          $status = '<span class="badge badge-success">ACTIVE</span>';
        }else{
          $status = '<span class="badge badge-danger">DEACTIVE</span>';
        }

        $row[] = $status;

        $row[] = $val->name;
        $row[] = $val->username;
        $row[] = $val->pword;
        
        // $rights = explode(",",$val->rights);
        // $str = '';
        // foreach ($rights as $value) {
        //   switch ($value) {
        //     // MANAGE BANNER
        //     case '1.1':
        //       $str .= 'BANNERS LISTING PAGE <br>';
        //       break;
            
        //     case '1.2':
        //       $str .= 'ADD NEW BANNER <br>';
        //       break;

        //     case '1.3':
        //       $str .= "UPDATE EXISTING BANNER <br>";
        //       break;

        //     // MANAGE ADVERTISE 
        //     case '18.1':
        //       $str .= 'ADVERTISE LISTING PAGE <br>';
        //       break;
            
        //     case '18.2':
        //       $str .= 'ADD NEW ADVERTISE <br>';
        //       break;

        //     case '18.3':
        //       $str .= "UPDATE EXISTING ADVERTISE <br>";
        //       break;

        //     case '18.4':
        //       $str .= 'ADVERTISE ENQUIRY LISTING PAGE<br>';
        //       break;

        //     // MANAGE TENDERS
        //     case '9.1':
        //       $str .= 'TENDER LISTING PAGE <br>';
        //       break;
            
        //     case '9.2':
        //       $str .= 'ADD NEW TENDER <br>';
        //       break;

        //     case '9.3':
        //       $str .= "UPDATE EXISTING TENDER <br>";
        //       break;

        //     // MANAGE BUSINESS / TRADE LEADS
        //     case '10.1':
        //       $str .= 'BUSINESS / TRADE LEADS LISTING PAGE <br>';
        //       break;
            
        //     case '10.2':
        //       $str .= 'ADD NEW BUSINESS / TRADE LEADS <br>';
        //       break;

        //     case '10.3':
        //       $str .= "UPDATE EXISTING BUSINESS / TRADE LEADS <br>";
        //       break;

        //     // MANAGE COA
        //     case '3.4':
        //       $str .= "MANAGE COA DESIGNATION MASTER <br>";
        //       break;

        //     case '3.1':
        //       $str .= 'COA LISTING PAGE <br>';
        //       break;
            
        //     case '3.2':
        //       $str .= 'ADD NEW COA <br>';
        //       break;

        //     case '3.3':
        //       $str .= "UPDATE EXISTING COA <br>";
        //       break;

        //     // MANAGE SECRETARIAT
        //     case '4.4':
        //       $str .= "MANAGE SECRETARIAT DESIGNATION MASTER <br>";
        //       break;

        //     case '4.1':
        //       $str .= 'SECRETARIAT LISTING PAGE <br>';
        //       break;
            
        //     case '4.2':
        //       $str .= 'ADD NEW SECRETARIAT <br>';
        //       break;

        //     case '4.3':
        //       $str .= "UPDATE EXISTING SECRETARIAT <br>";
        //       break;

        //     // MANAGE MEMORANDUM
        //     case '5.1':
        //       $str .= 'MEMORANDUM LISTING PAGE <br>';
        //       break;
            
        //     case '5.2':
        //       $str .= 'ADD NEW MEMORANDUM <br>';
        //       break;

        //     case '5.3':
        //       $str .= "UPDATE EXISTING MEMORANDUM <br>";
        //       break;

        //     // MANAGE ANNUAL REPORT
        //     case '6.1':
        //       $str .= 'ANNUAL REPORT LISTING PAGE <br>';
        //       break;
            
        //     case '6.2':
        //       $str .= 'ADD NEW ANNUAL REPORT <br>';
        //       break;

        //     case '6.3':
        //       $str .= "UPDATE EXISTING ANNUAL REPORT <br>";
        //       break;

        //     // MANAGE YEAR MASTER
        //     case '13.1':
        //       $str .= 'YEAR MASTER LISTING PAGE <br>';
        //       break;
            
        //     case '13.2':
        //       $str .= 'ADD NEW YEAR MASTER <br>';
        //       break;

        //     case '13.3':
        //       $str .= "UPDATE EXISTING YEAR MASTER <br>";
        //       break;

        //     // MANAGE EXHIBITIONS 
        //     case '12.1':
        //       $str .= 'EXHIBITIONS LISTING PAGE <br>';
        //       break;
            
        //     case '12.2':
        //       $str .= 'ADD NEW EXHIBITION <br>';
        //       break;

        //     case '12.3':
        //       $str .= "UPDATE EXISTING EXHIBITION <br>";
        //       break;

        //     case '12.4':
        //       $str .= 'EXHIBITION ENQUIRY LISTING PAGE<br>';
        //       break;
              
        //     // MANAGE SEMINARS
        //     case '15.1':
        //       $str .= 'SEMINARS LISTING PAGE <br>';
        //       break;
            
        //     case '15.2':
        //       $str .= 'ADD NEW SEMINAR <br>';
        //       break;

        //     case '15.3':
        //       $str .= "UPDATE EXISTING SEMINAR <br>";
        //       break;

        //     case '15.4':
        //       $str .= 'SEMINAR ENQUIRY LISTING PAGE<br>';
        //       break;

        //     // MANAGE TRADE DELEGATION
        //     case '14.1':
        //       $str .= 'TRADE DELEGATION LISTING PAGE <br>';
        //       break;
            
        //     case '14.2':
        //       $str .= 'ADD NEW TRADE DELEGATION <br>';
        //       break;

        //     case '14.3':
        //       $str .= "UPDATE EXISTING TRADE DELEGATION <br>";
        //       break;

        //     case '14.4':
        //       $str .= 'TRADE DELEGATION ENQUIRY LISTING PAGE<br>';
        //       break;

        //     // MANAGE BSM / RBSM
        //     case '22.1':
        //       $str .= 'BSM / RBSM LISTING PAGE <br>';
        //       break;
            
        //     case '22.2':
        //       $str .= 'ADD NEW BSM / RBSM <br>';
        //       break;

        //     case '22.3':
        //       $str .= "UPDATE EXISTING BSM / RBSM <br>";
        //       break;

        //     // MANAGE AWARDS
        //     case '11.1':
        //       $str .= 'AWARDS LISTING PAGE <br>';
        //       break;
            
        //     case '11.2':
        //       $str .= 'ADD NEW AWARD <br>';
        //       break;

        //     case '11.3':
        //       $str .= "UPDATE EXISTING AWARD <br>";
        //       break;

        //     // MANAGE FAQ
        //     case '7.1':
        //       $str .= 'FAQ LISTING PAGE <br>';
        //       break;
            
        //     case '7.2':
        //       $str .= 'ADD NEW FAQ <br>';
        //       break;

        //     case '7.3':
        //       $str .= "UPDATE EXISTING FAQ <br>";
        //       break;

        //     // MANAGE CIRCULARS
        //     case '20.1':
        //       $str .= 'CIRCULARS LISTING PAGE <br>';
        //       break;
            
        //     case '20.2':
        //       $str .= 'ADD NEW CIRCULAR <br>';
        //       break;

        //     case '20.3':
        //       $str .= "UPDATE EXISTING CIRCULAR <br>";
        //       break;

        //     // MANAGE STATISTICS
        //     case '8.1':
        //       $str .= 'STATISTICS LISTING PAGE <br>';
        //       break;
            
        //     case '8.2':
        //       $str .= 'ADD NEW STATISTICS <br>';
        //       break;

        //     case '8.3':
        //       $str .= "UPDATE EXISTING STATISTICS <br>";
        //       break;

        //     // MANAGE GOVERNMENT
        //     case '19.1':
        //       $str .= 'GOVT. REPRESENTATIONS LISTING PAGE <br>';
        //       break;
            
        //     case '19.2':
        //       $str .= 'ADD NEW GOVT. REPRESENTATION <br>';
        //       break;

        //     case '19.3':
        //       $str .= "UPDATE EXISTING GOVT. REPRESENTATION <br>";
        //       break;

        //     // MANAGE ARTICLES
        //     case '21.1':
        //       $str .= 'ARTICLES LISTING PAGE <br>';
        //       break;
            
        //     case '21.2':
        //       $str .= 'ADD NEW ARTICLE <br>';
        //       break;

        //     case '21.3':
        //       $str .= "UPDATE EXISTING ARTICLE <br>";
        //       break;

        //     // MANAGE MESSAGE 
        //     case '16.1':
        //       $str .= 'MESSAGE LISTING PAGE <br>';
        //       break;

        //     // MANAGE TRADE ENQUIRY
        //     case '17.1':
        //       $str .= 'TRADE ENQUIRY LISTING PAGE <br>';
        //       break;

        //     // MANAGE CAREERS
        //     case '23.1':
        //       $str .= 'CAREERS LISTING PAGE <br>';
        //       break;
            
        //     case '23.2':
        //       $str .= 'POST NEW JOB <br>';
        //       break;

        //     case '23.3':
        //       $str .= "UPDATE EXISTING JOB <br>";
        //       break;

        //     case '23.4':
        //       $str .= 'JOB ENQUIRY LISTING PAGE<br>';
        //       break;

        //     // MANAGE NEWSLETTERS
        //     case '2.1':
        //       $str .= 'NEWSLETTER SUBSCRIBERS LISTING <br>';
        //       break;
        //   }
        // }
        // $row[] = $str;

        $data[] = $row;
      }
    }

    $output = array(
      "draw" => $_POST['draw'],
      "recordsTotal" => $this->Mdl_admin->count_all(),
      "recordsFiltered" => $this->Mdl_admin->count_filtered(),
      "data" => $data,
    );
    //output to json format
    echo json_encode($output);
  }
	
	/*
  **  Add Admin Page
  */
  function add(){
		if(!Modules::run('security/isAdmin')){
      redirect('admin','refresh');
    }

    $admin = $this->session->userdata('admin');
    $isAdmin = $admin['isAdmin'];
    
    if($isAdmin !== '0'){
      redirect('admin/dashboard','refresh');
    }

    $template = 'admin';
    $data['scriptFile'] = 'admin_v_1.1';
    $data['viewFile'] = 'admin/add-admin';
    $data['module'] = "admin";
    echo Modules::run('template/'.$template, $data);
	}
	
  /*
  **  Add Admin Action
  */
  function addAdminAction(){
    $content = $this->input->post();

    $token= $this->session->userdata("token");
    if($content["csrfToken"] == $token){
      $this->form_validation->set_rules("name","Name","trim|required|xss_clean|regex_match[/^[A-Z a-z]+$/]",
        array(
        'required' => "Please enter Name",
        'regex_match' => "%s should not contain numbers or other special characters."
      ));

      $this->form_validation->set_rules("username","Username","trim|required|xss_clean",
        array(
        'required' => "Please enter Username"
      ));

      $this->form_validation->set_rules("pword","Password","trim|required|xss_clean",
        array(
        'required' => "Please enter Password"
      ));

      $this->form_validation->set_rules("rights[]","Rights","required|xss_clean",array(
        'required' => "Rights not selected"
      ));
      
      if($this->form_validation->run() == FALSE){
        $errors = $this->form_validation->error_array();
        echo json_encode($errors);
      }else{
        $password = Modules::run('security/makeHash',$content['pword']);

        $data = array(
          'name' => strip_tags(strtoupper($content['name'])),
          'username' => strip_tags($content['username']),
          'password' => $password,
          'pword' => strip_tags($content['pword']),
          'status' => '1',
          'rights' => implode(",", $content['rights']),
          'isAdmin' => '1',
          'createdDate' => date("Y-m-d H:i:s"),
          'modifiedDate' => date("Y-m-d H:i:s")
        );

        $insert = $this->Mdl_admin->insert('admin_master',$data);  
        echo json_encode(array("status"=>"success")); exit;  
      }
    }else{
      echo json_encode(array("status"=>"invalid")); exit;
    }
  }

  /*
  **  Edit Admin Page
  */
  function update($id){
    if(!Modules::run('security/isAdmin')){
      redirect('admin','refresh');
    }

    $admin = $this->session->userdata('admin');
    $isAdmin = $admin['isAdmin'];
    
    if($isAdmin !== '0'){
      redirect('admin/dashboard','refresh');
    }

    $admin = $this->Mdl_admin->getByValue("admin_master","id",$id);
    if($admin !== "No Data"){
      $data['admin'] = $admin;
    }else{
      $data['admin'] = "No Data";
    }

    $template = 'admin';
    $data['scriptFile'] = 'admin_v_1.1';
    $data['viewFile'] = 'admin/edit-admin';
    $data['module'] = "admin";
    echo Modules::run('template/'.$template, $data);
  }

  /*
  **  Edit Admin Action
  */
  function editAdminAction(){
    $content = $this->input->post();

    $token= $this->session->userdata("token");
    if($content["csrfToken"] == $token){
      $this->form_validation->set_rules("name","Name","trim|required|xss_clean|regex_match[/^[A-Z a-z]+$/]",
        array(
        'required' => "Please enter Name",
        'regex_match' => "%s should not contain numbers or other special characters."
      ));

      $this->form_validation->set_rules("username","Username","trim|required|xss_clean",
        array(
        'required' => "Please enter Username"
      ));

      $this->form_validation->set_rules("pword","Password","trim|required|xss_clean",
        array(
        'required' => "Please enter Password"
      ));

      $this->form_validation->set_rules("rights[]","Rights","required|xss_clean",array(
        'required' => "Rights not selected"
      ));

      $this->form_validation->set_rules("status[]","Status","required|xss_clean",array(
        'required' => "Status not selected"
      ));
      
      if($this->form_validation->run() == FALSE){
        $errors = $this->form_validation->error_array();
        echo json_encode($errors);
      }else{
        $password = Modules::run('security/makeHash',$content['pword']);

        $data = array(
          'name' => strip_tags(strtoupper($content['name'])),
          'username' => strip_tags($content['username']),
          'password' => $password,
          'pword' => strip_tags($content['pword']),
          'status' => strip_tags($content['status']),
          'rights' => implode(",", $content['rights']),
          'modifiedDate' => date("Y-m-d H:i:s")
        );

        $update = $this->Mdl_admin->update("admin_master","id",$content['id'],$data);
        echo json_encode(array("status"=>"success")); exit;  
      }
    }else{
      echo json_encode(array("status"=>"invalid")); exit;
    }
  }

	/*
  **  Change Password
  */
	function changepassword(){
		if(!Modules::run('security/isAdmin')){
      redirect('admin','refresh');
    }
    $this->session->set_userdata('salt', random_string('alpha', 10));
      
    $data['salt'] = $this->session->userdata('salt'); 

    $template = 'admin';
    $data['scriptFile'] = 'admin_v_1.1';
    $data['viewFile'] = 'admin/change-password';
    $data['module'] = "admin";
    echo Modules::run('template/'.$template, $data);
	}

  /*
  **  Change Password Action
  */
  function changePasswordAction(){
    $content = $this->input->post();

    $token= $this->session->userdata("token");
    if($content["csrfToken"] == $token){
      
      $sess = $this->session->userdata('admin');
      $adm_id = $sess['id'];
      $admin = $this->Mdl_admin->getByValue("admin_master","id",$adm_id);

      //$hashpass = $content['hash'];
      $npwordhash = $content['npword'];
      $opwordhash = $content['opword'];

      $database_pass_hash = $admin[0]->password;
      $salt = $this->session->userdata('salt');
     // $pass_hash = md5($salt.$database_pass_hash);
      //  $pass_hash = hash('sha256',$database_pass_hash);
      if($opwordhash == $database_pass_hash){
        $check = 1;
      }else{
        $check = 0;
      }

      if($check == 0){
        echo json_encode(array("status"=>"fail","title"=>"Error" ,"message"=>"INVALID OLD PASSWORD.")); exit;
      }

      // echo "<pre>";
      // print_r($content);
      // die;
      $this->form_validation->set_rules("opword","Old Password","trim|required|xss_clean|max_length[100]",
        array(
        'required' => "Please enter Old Password"
      ));

      $this->form_validation->set_rules("npword","New Password","trim|required|xss_clean|max_length[100]",
        array(
        'required' => "Please enter New Password"
      ));

      // $this->form_validation->set_rules("npword","New Password","trim|required|xss_clean|min_length[8]|max_length[15]|regex_match[/^[A-Za-z]{5}[0-9]{4}[!@#$%^&]$/]",
      //   array(
      //   'required' => "Please enter New Password",
      //   'regex_match' => 'The {field} field must have  at least five Letters, four Number & one special character.' . ' ' . htmlentities('!@#$%^&').' <br> Ex. TestP1234@'
      // ));

      $this->form_validation->set_rules("cnpword","Confirm New Password","trim|required|xss_clean|matches[npword]|max_length[100]",
        array(
        'required' => "Please enter Confirm New Password"
      ));

      if($this->form_validation->run() == FALSE){
        $errors = $this->form_validation->error_array();
        echo json_encode($errors);
      }else{
        $adminchangepass = $this->Mdl_admin->getByValue("adminpass","adminid",$adm_id);

        if(count($adminchangepass) > 0){
          $password_match = false;
          for($i=0;$i<count($adminchangepass);$i++){
            if($content['npword'] == $adminchangepass[$i]->oldpassword){
              $password_match = true;
            }
          }
        }

        if($password_match == true){
          echo json_encode(array("status"=>"error")); exit;
        }

        if($admin[0]->password == $content['opword']){

          $this->session->set_userdata('salt', random_string('alpha', 10));

          //$password = Modules::run('security/makeHash',$content['npword']);  

          $data = array(
            'password' => $npwordhash,
            'pword' => $npwordhash,
            'modifiedDate' => date("Y-m-d H:i:s")
          );

          $update = $this->Mdl_admin->update("admin_master","id",$adm_id,$data);

          if($update){
            $change_pass_data = array(
              'adminid'=> $adm_id,
              'userip'=> $this->input->ip_address(),
              'oldpassword'=> $opwordhash,
              'newpassword'=> $npwordhash,
              'status'=> 1,
              'EventDateTime'=> date('Y-m-d H:i:s')
            );
      
            $insert = $this->Mdl_admin->insert("adminpass", $change_pass_data);
          }
          echo json_encode(array("status"=>"success")); exit; 
        }else{
          echo json_encode(array("opword"=>"Password does not match with the current password.")); exit;
        }
      }
    }else{
      echo json_encode(array("status"=>"invalid")); exit;
    }
  }


  /*
  **  Forgot Password
  */
	function forgotpassword(){
		$captcha = Modules::run('captcha/Captcha');
    $data['captcha'] = $captcha;

    $this->load->view('forgot-password', $data);
  }
  
  function forgotpasswordAction(){

    date_default_timezone_set("Asia/kolkata");
		$content = $this->input->post();
    
    // echo "<pre>";
    // print_r($_SESSION);

    // print_r($content);

		// echo $token = $this->session->userdata("token");
    
    //die;
    // if($content["csrfToken"] == $token){
			
			$this->form_validation->set_rules("uname","Username","required|xss_clean",array(
				'required' => "Username is required"
			));
    
      $this->form_validation->set_rules("captcha","Captcha","required|xss_clean",array(
				'required' => "Captcha is required."
      ));
      
			if($this->form_validation->run() == FALSE){
				$errors = $this->form_validation->error_array();
				echo json_encode($errors);
			}else{
        
        $captcha_insert = $content['captcha'];
        $contain_sess_captcha = $this->session->userdata('valuecaptchaCode');
        if($captcha_insert != $contain_sess_captcha) {

          echo json_encode(array("captcha" => "Captcha is Incorrect !")); 
          exit;

        }

        $uname = $content['uname'];
        $param = array(
          'email' => $uname
        );

        $admin = $this->Mdl_admin->getByValues("admin_master",$param);

        if($admin !== "No Data"){

          if($admin[0]->status == '1'){

            
            foreach($admin as $row){
              $id = $row->id;
              $name = $row->name;
              $isAdmin = $row->isAdmin;
              $username = $row->username;
              $email = $row->email;
            }
              
            /*
                Mail sent to admin for reset password
            */

            $mail_data = array(
              "viewFile" => 'admin/forgot-password',
              "to"=> $email,
              "cc" => "",
              "bcc" => "",
              "subject" => "FORGOT PASSWORD - PLEXCONCIL ADMIN",
              'name' => strip_tags($name),
              'id' => hash('sha256', $id)
            );
            
            $status_ack_mail = Modules::run('email/mailer', $mail_data);

            $data = array(
              'userid'=> $id,
              'userip'=> $this->input->ip_address(),
              'loginDateTime'=> date('Y-m-d H:i:s'),
              'loginStatus'=> 1,
              'logoutDateTime'=> '',
              'action'=> 'Forgot Password',
              'modulename'=> 'Admin Forgot Password',
              'EventDateTime'=> date('Y-m-d H:i:s')
            );
        
            $insert = $this->Mdl_admin->insert("admin_login_activity", $data);
            
            echo json_encode(array("status"=>"success")); exit;
          
          }else{
            echo json_encode(array("status"=>"fail","title"=>"Error" ,"message"=>"ACCOUNT IS NOT ACTIVE.")); exit;
          }
        }else{
          echo json_encode(array("status"=>"fail","title"=>"Error","message"=>"USER DOES NOT EXIST.")); exit;
        }
        
      }
		// }else{
		// 	echo json_encode(array("status"=>"invalid")); exit;
		// }
  }
  
  /*
  **  Reset Password
  */
	function resetpassword($id){
    //$displaykey="SHA2(id,'256')";
    $param = array(
      "SHA2(id,'256')" => $id
    );

    $admin = $this->Mdl_admin->getByValues("admin_master",$param);

    if($admin[0]->status == '1'){
      
      foreach($admin as $row){
        $id = $row->id;
        $name = $row->name;
        $isAdmin = $row->isAdmin;
        $username = $row->username;
        $email = $row->email;
      }
      $data['email'] = $email;
      $data['id'] = hash('sha256', $id);
      $this->load->view('reset-password', $data);
    }else{
      redirect('admin/login');
    }
  }

  function resetpasswordAction(){
    $content = $this->input->post();

    $token= $this->session->userdata("token");
    //if($content["csrfToken"] == $token){
      
      /*$this->form_validation->set_rules("npword","New Password","trim|required|xss_clean|min_length[8]|max_length[100]|regex_match[/^[A-Za-z]{5}[0-9]{4}[!@#$%^&]$/]",
        array(
        'required' => "Please enter New Password",
        'regex_match' => 'The {field} field must have  at least five Letters, four Number & one special character.' . ' ' . htmlentities('!@#$%^&').' <br> Ex. TestP1234@'
      ));*/
      
       $this->form_validation->set_rules("npword","New Password","trim|required|xss_clean|min_length[8]|max_length[100]",
        array(
        'required' => "Please enter New Password",
        //'regex_match' => 'The {field} field must have  at least five Letters, four Number & one special character.' . ' ' . htmlentities('!@#$%^&').' <br> Ex. TestP1234@'
      ));

      $this->form_validation->set_rules("cnpword","Confirm New Password","trim|required|xss_clean|matches[npword]",
        array(
        'required' => "Please enter Confirm New Password"
      ));

      if($this->form_validation->run() == FALSE){
        $errors = $this->form_validation->error_array();
        echo json_encode($errors);
      }else{
        $adm_id = $content["aid"];

        $admin = $this->Mdl_admin->getByValue("admin_master","SHA2(id,'256')",$adm_id);

        $adminchangepass = $this->Mdl_admin->getByValue("adminpass","SHA2(adminid,'256')",$adm_id);

        if(count($adminchangepass) > 0){
          $password_match = false;
          for($i=0;$i<count($adminchangepass);$i++){
            if($content['npword'] == $adminchangepass[$i]->oldpassword){
              $password_match = true;
            }
          }
        }

        if($password_match == true){
          echo json_encode(array("status"=>"error")); exit;
        }

        $this->session->set_userdata('salt', random_string('alpha', 10));

        //$password = md5($content['npword']);
        $password = $content['npword'];
        $data = array(
          'password' => $password,
          'pword' => $password,
          'modifiedDate' => date("Y-m-d H:i:s")
        );

        $update = $this->Mdl_admin->update("admin_master","SHA2(id,'256')",$adm_id,$data);

        if($update){
          $change_pass_data = array(
            'adminid'=> $admin[0]->id,
            'userip'=> $this->input->ip_address(),
            'oldpassword'=> $admin[0]->pword,
            'newpassword'=> $content['npword'],
            'status'=> 1,
            'EventDateTime'=> date('Y-m-d H:i:s')
          );
    
          $insert = $this->Mdl_admin->insert("adminpass", $change_pass_data);
        }
        echo json_encode(array("status"=>"success")); exit; 

      }
    // }else{
    //   echo json_encode(array("status"=>"invalid")); exit;
    // }
  }
}
