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



use App\Modules\generic\Models\Mdl_generic;

use App\Modules\Secretariat\Models\Mdl_secretariat;

use CodeIgniter\Controller;

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

   function index(){
		$template = 'home';
		$data['country'] = $this->Mdl_secretariat->getAllRecords("country");
    $data['seo'] = $this->Mdl_secretariat->getByValue("seo","page","home");

    $param_1 = array(
      "designation" => "1",
      "status" => "1"
    );
    $where ="designation = 1 ";
    $data['ed'] = $this->Mdl_secretariat->getByValues("secretariat",$where);
    // $data['ed'] = "No Data";
    
    $param_2 = array(
      "designation" => "2",
      "status" => "1"
    );
    $where2= "designation = 2 ";
    $data['rd'] = $this->Mdl_secretariat->getByValues("secretariat",$where2);
    // $data['rd'] = "No Data";

		$data['viewFile'] = 'secretariat/secretariat';
		$data['scriptFile'] = 'secretariat';
		$data['module'] = "secretariat";
		return view('template/'.$template, $data); 
  }  

  function viewProfile($slug){
    $param = array(
      "slug" => $slug,
      "status" => "1"
    );
     $where3= "slug = $slug ";
    $member = $this->Mdl_secretariat->getByValues("secretariat",$where3);

    if($member == "No Data"){
      redirect('errors',refresh);
    }

    $template = 'home';
		$data['country'] = $this->Mdl_secretariat->getAllRecords("country");
		$data['seo'] = $this->Mdl_secretariat->getByValue("seo","page","home");
		$data['member'] = $member;
		$data['viewFile'] = 'secretariat/view-profile';
		$data['module'] = "secretariat";
		return view('template/'.$template, $data); 
  }

  /**********************************************************************/
  /*                            ADMIN MODULES                           */
  /**********************************************************************/

  /*
  **  DESIGNATION LISTING PAGE
  */
  function designations(){
    if(!Modules::run('security/isAdmin')){
      redirect('admin','refresh');
    }

    $admin_array['logID'] = $admin['logID'];
    $admin = $this->session->userdata('admin');
    $arr = $admin['rights'];
    $rights = explode(',',$arr);

    if(! in_array("4.2",$rights)){
      redirect('admin/dashboard','refresh');
    }

    $template = 'admin';
    $data['scriptFile'] = 'admin-secretariat_v_1.0';
    $data['viewFile'] = 'secretariat/list-designations';
    $data['module'] = "secretariat";
    return view('template/'.$template, $data);
  }

  /*
  **  LIST OF DESIGNATION
  */
  function getDesignations(){
    $list = $this->Mdl_secretariat->get_datatables_1();
    $data = array();
    $no = $_POST['start']; 

    $admin_array['logID'] = $admin['logID'];
    $admin = $this->session->userdata('admin');

    #track log
    $admin_array['userid'] = $admin['id'];
    $admin_array['usertype'] = 'admin';
    $admin_array['action_type'] = 'View Designation';
    $admin_array['modulename'] = 'Secretariat';
    $admin_array['userip'] = $this->input->ip_address();

    $log =  insertTrackLog($admin_array);

    foreach ($list as $val) {
      $row = array();
      $url = base_url().'secretariat/update-designation/'.$val->id;
      $row[] = '<a class="btn btn-block btn-rounded btn-outline-success" href="'.$url.'">UPDATE</a>';
      
      if($admin['isAdmin'] !== '1'){
        $row[] = '<button class="btn btn-block btn-rounded btn-outline-danger" id="'.$val->id.'" onclick="callDeleteFunction(\'secretariat_designations\',\'id\',this.id,\'secretariat_designations\')">DELETE</button>';
      }else{
        $row[] = '';
      }

      $row[] = $val->name;

      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->admin;
      $row[] = date('d-m-Y',strtotime($val->modifiedDate));
      $data[] = $row;
    }

    $output = array(
      "draw" => $_POST['draw'],
      "recordsTotal" => $this->Mdl_secretariat->count_all_1(),
      "recordsFiltered" => $this->Mdl_secretariat->count_filtered_1(),
      "data" => $data,
    );

    echo json_encode($output);
  }

  /*
  **  ADD DESIGNATION PAGE
  */
  function addDesignation(){
		if(!Modules::run('security/isAdmin')){
      redirect('admin','refresh');
    }

    $admin_array['logID'] = $admin['logID'];
    $admin = $this->session->userdata('admin');
    $arr = $admin['rights'];
    $rights = explode(',',$arr);

    if(! in_array("4.3",$rights)){
      redirect('admin/dashboard','refresh');
    }

    $template = 'admin';
    $data['scriptFile'] = 'admin-secretariat_v_1.0';
    $data['viewFile'] = 'secretariat/add-designation';
    $data['module'] = "secretariat";
    return view('template/'.$template, $data);
	}
	
  /*
  **  ADD DESIGNATION ACTION
  */
  function addDesignationAction(){
    $content = $this->input->post();

    $token= $this->session->userdata("token");
    if($content["csrfToken"] == $token){
      $this->form_validation->set_rules("name","name","trim|required|xss_clean|max_length[255]",
    array(
        'required' => "Name is required",'max_length' => "Name is invalid"
      ));

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

        $data = array(
          'name' => strip_tags(strtoupper($content['name'])),
          'parent' => 0,
          'status' => '1',
          'admin' => Modules::run('admin/getAdminName',$admin['id']),
          'createdDate' => date("Y-m-d H:i:s"),
          'modifiedDate' => date("Y-m-d H:i:s")
        );

        $insert = $this->Mdl_secretariat->insert('secretariat_designations',$data);  
$insertId = $this->db->insert_id();
        #track log
        $admin_array['userid'] = $admin['id'];
        $admin_array['usertype'] = 'admin';
        $admin_array['action_type'] = 'Insert Designation';
        $admin_array['modulename'] = 'Secretariat';
        $admin_array['event_id'] = $insertId;
        $admin_array['userip'] = $this->input->ip_address();

        $log =  insertTrackLog($admin_array);

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

  /*
  **  UPDATE DESIGNATION PAGE
  */
  function updateDesignation($id){
    if(!Modules::run('security/isAdmin')){
      redirect('admin','refresh');
    } 

    $admin_array['logID'] = $admin['logID'];
    $admin = $this->session->userdata('admin');
    $arr = $admin['rights'];
    $rights = explode(',',$arr);

    if(! in_array("4.4",$rights)){
      redirect('admin/dashboard','refresh');
    }

    $designation = $this->Mdl_secretariat->getByValue("secretariat_designations","id",$id);
    if($designation == "No Data"){
      redirect('errors','refresh');
    }

    $data['designation'] = $designation;

    $template = 'admin';
    $data['scriptFile'] = 'admin-secretariat_v_1.0';
    $data['viewFile'] = 'secretariat/update-designation';
    $data['module'] = "secretariat";
    return view('template/'.$template, $data);
  }

  /*
  **  UPDATE DESIGNATION ACTION
  */
  function updateDesignationAction(){
    $content = $this->input->post();

    $token= $this->session->userdata("token");
    if($content["csrfToken"] == $token){
      $this->form_validation->set_rules("name","Designation","trim|required|xss_clean|max_length[255]",
      array(
        'required' => "Designation is required",'max_length' => "Designation is invalid"
      ));
  
      $this->form_validation->set_rules("status","Status","trim|required|xss_clean|max_length[100]",
      array(
        'required' => "Status not selected",'max_length' => "Status is invalid"
      ));
      
      if($this->form_validation->run() == FALSE){
        $errors = $this->form_validation->error_array();
        echo json_encode($errors);
      }else{

        $admin_array['logID'] = $admin['logID'];
        $admin = $this->session->userdata('admin');

        $data = array(
          'name' => strip_tags(strtoupper($content['name'])),
          'status' => strip_tags($content['status']),
          'admin' => Modules::run('admin/getAdminName',$admin['id']),
          'modifiedDate' => date("Y-m-d H:i:s")
        );

        $update = $this->Mdl_secretariat->update("secretariat_designations","id",$content['id'],$data);

        #track log
        $admin_array['userid'] = $admin['id'];
        $admin_array['usertype'] = 'admin';
        $admin_array['action_type'] = 'Update Designation';
        $admin_array['modulename'] = 'Secretariat';
        $admin_array['userip'] = $this->input->ip_address();

        $log =  insertTrackLog($admin_array);

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

  /*
  ** SECRETARIAT LISTING PAGE
  */
  function viewall(){
    if(!Modules::run('security/isAdmin')){
      redirect('admin','refresh');
    }

    $admin_array['logID'] = $admin['logID'];
    $admin = $this->session->userdata('admin');
    $arr = $admin['rights'];
    $rights = explode(',',$arr);

    if(! in_array("4.1",$rights)){
      redirect('admin/dashboard','refresh');
    }

    $data['designation'] = $this->Mdl_secretariat->getByValue("secretariat_designations", "parent", 0);
    $template = 'admin';
    $data['scriptFile'] = 'admin-secretariat_v_1.0';
    $data['viewFile'] = 'secretariat/list-secretariat';
    $data['module'] = "secretariat";
    return view('template/'.$template, $data);
  }

  /*
  **  LIST OF SECRETARIAT
  */
  function getSecretariat(){
    $list = $this->Mdl_secretariat->get_datatables_2();
    $data = array();
    $no = $_POST['start']; 
    
    $admin_array['logID'] = $admin['logID'];
    $admin = $this->session->userdata('admin');

    #track log
    $admin_array['userid'] = $admin['id'];
    $admin_array['usertype'] = 'admin';
    $admin_array['action_type'] = 'View Secretariat';
    $admin_array['modulename'] = 'Secretariat';
    $admin_array['userip'] = $this->input->ip_address();

    $log =  insertTrackLog($admin_array);

    $i = 1;
    foreach ($list as $val) {
      $row = array();
      $url = base_url().'secretariat/view/'.$val->id;
      $row[] = '<a class="btn btn-block btn-rounded btn-outline-success" href="'.$url.'">VIEW</a>';
      
      if($admin['isAdmin'] !== '1'){
        $row[] = '<button class="btn btn-block btn-rounded btn-outline-danger" id="'.$val->id.'" onclick="callDeleteFunction(\'secretariat\',\'id\',this.id,\'secretariat\')">DELETE</button>';
      }else{
        $row[] = '';
      }

      if($val->image == 'NA' || $val->image == ""){
        $row[] = '<img src="'.base_url().'public/custom/images/coa/default.jpg" class="img-circle img-fluid">';
      }else{
        $row[] = '<img src="'.base_url().$val->image.'" class="img-circle img-fluid">';
      }
      
      $row[] = strtoupper($val->name);
      $row[] = $this->getName("secretariat_designations",$val->designation,"name");
      
      if($val->status == '1'){
        $status = '<span class="badge badge-success">ACTIVE</span>';
      }else{
        $status = '<span class="badge badge-danger">DEACTIVE</span>';
      }
      $row[] = $status;
      
      $row[] = strtoupper($val->admin);
      $row[] = date('d-m-Y',strtotime($val->modifiedDate));
      $data[] = $row;
      $i++;
    }

    $output = array(
      "draw" => $_POST['draw'],
      "recordsTotal" => $this->Mdl_secretariat->count_all_2(),
      "recordsFiltered" => $this->Mdl_secretariat->count_filtered_2(),
      "data" => $data,
    );

    echo json_encode($output);
  }

  /*
  ** ADD SECRETARIAT
  */
  function add(){
    if(!Modules::run('security/isAdmin')){
      redirect('admin','refresh');
    }

    $admin_array['logID'] = $admin['logID'];
    $admin = $this->session->userdata('admin');
    $arr = $admin['rights'];
    $rights = explode(',',$arr);

    if(! in_array("4.5",$rights)){
      redirect('admin/dashboard','refresh');
    }
    
    $data['designation'] = $this->Mdl_secretariat->getByValue("secretariat_designations", "parent", 0);
    $data['viewFile'] = "secretariat/add-secretariat";
    $data['scriptFile'] = "admin-secretariat_v_1.0";
    $data['module'] = "secretariat";
    $template = 'admin';
    return view('template/'.$template, $data);
  }

  /*
  ** ADD SECRETARIAT ACTION
  */
  function addSecretariatAction(){
    $content = $this->input->post();

    $this->form_validation->set_rules("designation","Designation","trim|required|xss_clean|max_length[100]",
    array(
      'required' => 'Please select designation.','max_length' => 'Designation is invalid.'
    ));
    
    $this->form_validation->set_rules("name","Name","trim|required|xss_clean|max_length[255]",
    array(
      'required' => 'Name is required.','max_length' => 'Name is invalid.'
    ));
    
    $this->form_validation->set_rules("organisation","Organisation","trim|required|xss_clean|max_length[100]",
    array(
      'required' => 'Organisation is required.','max_length' => 'Organisation is invalid.'
    ));

    $this->form_validation->set_rules("address","Address","trim|required|xss_clean|max_length[500]",
    array(
      'required' => 'Address is required.','max_length' => 'Address is invalid.'
    ));

    $this->form_validation->set_rules("office_number","Office Number","trim|required|xss_clean|max_length[100]",
    array(
      'required' => 'Office Number is required.','max_length' => 'Office Number is invalid.'
    ));

    $this->form_validation->set_rules("fax","Fax","trim|xss_clean");

    $this->form_validation->set_rules("mobile","Mobile Number","trim|xss_clean");


    $this->form_validation->set_rules("email_1","Email","trim|required|xss_clean|valid_email|max_length[255]",
    array(
      'required' => 'Email is required.',
      'valid_email' => 'Email is invalid.',
      'max_length' => 'Email is invalid.'
    ));

    $this->form_validation->set_rules("email_2","Email","trim|xss_clean|valid_email|max_length[255]",
    array(
      'valid_email' => 'Email is invalid.','max_length' => 'Email is invalid.'
    ));

    $this->form_validation->set_rules("about","About","trim|xss_clean");

    if($this->form_validation->run() == FALSE){
      $errors = $this->form_validation->error_array();
      echo json_encode($errors); exit;
    }else{
      $find = array("/","|","_","?","(",")","-",":","!","'",".",",","\r","\n","\r\n");
      $replace = array("");
      $new_string = str_replace($find,$replace,strtolower($content['name']));
      $new_string = preg_replace('/^\s+|\s+$|\s+(?=\s)/','',$new_string);
      $slug = str_replace(" ","-",trim($new_string));

      if(!empty($_FILES['image']['name'])){
        $filename = $_FILES['image']['name'];
        $ext = pathinfo($filename, PATHINFO_EXTENSION);
        $imagename = strtotime('now');
        $img = $this->uploadFile($imagename,"image");
        $imgpath = 'public/custom/images/secretariat/'.$imagename.'.'.$ext;
        if($img !== 1){
          echo json_encode(array("image"=>$img)); exit;
        }
      }else{
        $imgpath = "NA";
      }

      $admin_array['logID'] = $admin['logID'];
      $admin = $this->session->userdata('admin');

      $data = array(
        'name' => strip_tags($content['name']),
        'slug' => strip_tags($slug),
        'designation' => strip_tags($content['designation']),
        'organisation' => strip_tags($content['organisation']),
        'address' => strip_tags($content['address']),
        'office_number' => strip_tags($content['office_number']),
        'email_1' => strip_tags($content['email_1']),
        'email_2' => strip_tags($content['email_2']),
        'about' => strip_tags($content['about']),
        'mobile' => strip_tags($content['mobile']),
        'fax' => strip_tags($content['fax']),
        'image'=> strip_tags($imgpath),
        'status' => '1',
        'admin'=> Modules::run('admin/getAdminName',$admin['id']),
        'createdDate' =>date('Y-m-d H:i:s'),
        'modifiedDate' =>date('Y-m-d H:i:s')
      );

      $insert = $this->Mdl_secretariat->insert("secretariat", $data);

      #track log
      $admin_array['userid'] = $admin['id'];
      $admin_array['usertype'] = 'admin';
      $admin_array['action_type'] = 'Insert Secretariat';
      $admin_array['modulename'] = 'Secretariat';
      $admin_array['userip'] = $this->input->ip_address();

      $log =  insertTrackLog($admin_array);

      echo json_encode(array("status"=>"success")); exit;
    }
  }

  /*
  ** UPDATE SECRETARIAT
  */
  function view($id){
    if(!Modules::run('security/isAdmin')){
      redirect('admin','refresh');
    }

    $admin_array['logID'] = $admin['logID'];
    $admin = $this->session->userdata('admin');
    $arr = $admin['rights'];
    $rights = explode(',',$arr);

    if(! in_array("4.6",$rights)){
      redirect('admin/dashboard','refresh');
    }

    $result = $this->Mdl_secretariat->getByValue("secretariat","id",$id);
    if($result == "No Data"){
      redirect('errors','refresh');
    }else{
      $data['designation'] = $this->Mdl_secretariat->getByValue("secretariat_designations", "parent", 0);
      
      $data['secretariat'] = $result;
      $data['viewFile'] = "secretariat/view-secretariat";
      $data['scriptFile'] = "admin-secretariat_v_1.0";
      $data['module'] = "secretariat";
      $template = 'admin';
      return view('template/'.$template, $data);
    }
  }

  /*
  ** UPDATE SECRETARIAT ACTION
  */
  function updateSecretariatAction(){
    $content = $this->input->post();

    $this->form_validation->set_rules("designation","Designation","trim|required|xss_clean|max_length[100]",
    array(
      'required' => 'Please select designation.','max_length' => 'Designation is invalid.'
    ));
    
    $this->form_validation->set_rules("name","Name","trim|required|xss_clean|max_length[255]",
    array(
      'required' => 'Name is required.','max_length' => 'Name is invalid.'
    ));
    
    $this->form_validation->set_rules("organisation","Organisation","trim|required|xss_clean|max_length[100]",
    array(
      'required' => 'Organisation is required.','max_length' => 'Organisation is invalid.'
    ));

    $this->form_validation->set_rules("address","Address","trim|required|xss_clean|max_length[500]",
    array(
      'required' => 'Address is required.','max_length' => 'Address is invalid.'
    ));

    $this->form_validation->set_rules("office_number","Office Number","trim|required|xss_clean|max_length[100]",
    array(
      'required' => 'Office Number is required.','max_length' => 'Office Number is invalid.'
    ));

    $this->form_validation->set_rules("email_1","Email","trim|required|xss_clean|valid_email|max_length[255]",
    array(
      'required' => 'Email is required.',
      'valid_email' => 'Email is invalid.',
      'max_length' => 'Email is invalid.'
    ));

    $this->form_validation->set_rules("email_2","Email","trim|xss_clean|valid_email|max_length[255]",
    array(
      'valid_email' => 'Email is invalid.','max_length' => 'Email is invalid.'
    ));

    $this->form_validation->set_rules("fax","Fax","trim|xss_clean");

    $this->form_validation->set_rules("mobile","Mobile Number","trim|xss_clean");

    $this->form_validation->set_rules("about","About","trim|xss_clean");

    $this->form_validation->set_rules("status","Status","trim|xss_clean|required|max_length[100]",
    array(
      'required' => 'Please select status.','max_length' => 'Status is invalid.'
    ));

    if($this->form_validation->run() == FALSE){
      $errors = $this->form_validation->error_array();
      echo json_encode($errors); exit;
    }else{
      $find = array("/","|","_","?","(",")","-",":","!","'",".",",","\r","\n","\r\n");
      $replace = array("");
      $new_string = str_replace($find,$replace,strtolower($content['name']));
      $new_string = preg_replace('/^\s+|\s+$|\s+(?=\s)/','',$new_string);
      $slug = str_replace(" ","-",trim($new_string));

      if(!empty($_FILES['image']['name'])){
        if(file_exists('./'.$content['imgpath'])){
          $this->removeImage($content['imgpath']);
        }
        
        $filename = $_FILES['image']['name'];
        $ext = pathinfo($filename, PATHINFO_EXTENSION);
        $imagename = strtotime('now');
        $img = $this->uploadFile($imagename,"image");
        $imgpath = 'public/custom/images/secretariat/'.$imagename.'.'.$ext;
        if($img !== 1){
          echo json_encode(array("image"=>$img)); exit;
        }
      }else{
        $imgpath = $content['imgpath'];
      }

      $admin_array['logID'] = $admin['logID'];
      $admin = $this->session->userdata('admin');

      $data = array(
        'name' => strip_tags($content['name']),
        'slug' => strip_tags($slug),
        'designation' => strip_tags($content['designation']),
        'organisation' => strip_tags($content['organisation']),
        'address' => strip_tags($content['address']),
        'office_number' => strip_tags($content['office_number']),
        'email_1' => strip_tags($content['email_1']),
        'email_2' => strip_tags($content['email_2']),
        'about' => strip_tags($content['about']),
        'fax' => strip_tags($content['fax']),
        'mobile' => strip_tags($content['mobile']),
        'image'=> strip_tags($imgpath),
        'status' => strip_tags($content['status']),
        'admin'=> Modules::run('admin/getAdminName',$admin['id']),
        'modifiedDate' =>date('Y-m-d H:i:s')
      );

      $update = $this->Mdl_secretariat->update("secretariat","id",$content['id'],$data);

      #track log
      $admin_array['userid'] = $admin['id'];
      $admin_array['usertype'] = 'admin';
      $admin_array['action_type'] = 'Update Secretariat';
      $admin_array['modulename'] = 'Secretariat';
      $admin_array['userip'] = $this->input->ip_address(); 

      $log =  insertTrackLog($admin_array);

      echo json_encode(array("status"=>"success")); exit;
    }
  }

  /*
  **  FILE UPLOAD
  */
  function uploadFile($imageName,$key){
    $config['file_name'] = $imageName;
    $config['upload_path'] = './public/custom/images/secretariat';
    $config['allowed_types'] = "jpg|png|jpeg|svg";
    $config['max_size']  = '2048';
    $config['max_width']  = '3000';
    $config['max_height']  = '3000';
    
    $this->load->library('upload',$config);
    $this->upload->initialize($config);
    if (!$this->upload->do_upload($key)){
      return $this->upload->display_errors();
    }else{
      return 1;
    }
  }

}
