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



use App\Modules\generic\Models\Mdl_generic;

use App\Modules\Coa\Models\Mdl_coa;

use CodeIgniter\Controller;

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

   /* function index(){	
        //parent::Controller();
		$query_1 = 'SELECT * FROM banner WHERE status = "1" ORDER BY createdDate desc';
		$data['banners'] = $this->Mdl_home->customQuery($query_1);

		// $query_2 = 'SELECT title, slug, SubString(content, 1, 80) AS content FROM announcement WHERE status = "1" ORDER BY createdDate desc LIMIT 3';
		// $data['announcement'] = $this->Mdl_home->customQuery($query_2);

		$query_2 = 'SELECT SubString(name, 1, 80)AS name, post_date  FROM circulars WHERE status = "1" ORDER BY post_date desc LIMIT 3';
		$data['announcement'] = $this->Mdl_home->customQuery($query_2);
		// echo '<pre>';
		// print_r($data['announcement']);exit;
		// $data['announcement'] = "No Data";

		$query_3 = 'SELECT country, SubString(enquiry, 1, 80) AS enquiry FROM business_leads WHERE status = "1" ORDER BY createdDate desc LIMIT 3';
		$data['business'] = $this->Mdl_home->customQuery($query_3);

		$query_3 = 'SELECT * FROM advertise WHERE status = "1" ORDER BY createdDate desc';
		$data['advertise'] = $this->Mdl_home->customQuery($query_3);

        //$data['magazine'] = $this->Mdl_home->getByValue("e_magazine","id",1);
        $data['magazine'] = $this->Mdl_home->getByValue("magazine","id",1);

		$template = 'home';
		$data['country'] = $this->Mdl_home->getAllRecords("country");
		$data['seo'] = $this->Mdl_home->getByValue("seo","page","home");
		$data['view'] = 'home';
		$data['scriptFile'] = 'home';
		$data['module'] = "template";
		$data['viewFile'] = 'home';
		
		$template = 'home';
		
		//return view('template/'.$template, $data); 
		return view('template/'.$template, $data);
	}
	*/
	
	function index(){
		$template = 'home';
		$data['country'] = $this->Mdl_coa->getAllRecords("country");
    $data['seo'] = $this->Mdl_coa->getByValue("seo","page","home");

    $param_1 = array(
      "designation" => "1",
      "status" => "1"
    );
    //$where ="designation = 1 and status=1";
    $where ="designation = 1 ";
    $data['chairman'] = $this->Mdl_coa->getByValues1("coa",$where);
    // $data['chairman'] = "No Data";
   // print_r($data['chairman']);
    $param_2 = array(
      "designation" => "2",
      "status" => "1"
    );
    //$where2 ="designation = 2 and status=1";
    $where2 ="designation = 2";
    $data['vicechairman'] = $this->Mdl_coa->getByValues1("coa",$where2);
    // $data['vicechairman'] = "No Data";

    $param_3 = array(
      "designation" => "3",
      "status" => "1"
    );
    //$where3 ="designation = 3 and status=1";
    $where3 ="designation = 3";
    $data['panel'] = $this->Mdl_coa->getByValues1("coa",$where3);
    // $data['panel'] = "No Data";

    $param_4 = array(
      "designation" => "4",
      "status" => "1"
    );
    //$where4 ="designation = 4 and status=1";
    $where4 ="designation = 4 ";
    $data['coa'] = $this->Mdl_coa->getByValues1("coa",$where4);
    // $data['coa'] = "No Data";

    $param_5 = array(
      "designation" => "5",
      "status" => "1"
    );
    //$where5 ="designation = 5 and status=1";
    $where5 ="designation = 5 ";
    $data['regional'] = $this->Mdl_coa->getByValues1("coa",$where5);
    // $data['regional'] = "No Data";
    //	$data['viewFile'] = 'template/includes/home';
        $data['viewFile'] = 'coa/coa';
		$data['scriptFile'] = 'coa';
		$data['module'] = "coa";
	    $data['country'] = $this->Mdl_coa->getAllRecords("country");
		$data['captcha'] = "";
		return view('template/'.$template, $data); 
  }  

  function viewProfile($slug){
    $param = array(
      "slug" => $slug,
      "status" => "1"
    );
    $where ="slug = $slug and status=1";
    $member = $this->Mdl_coa->getByValues("coa",$where);

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

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

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

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

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

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

    $data['designation'] = $this->Mdl_coa->getByValue("coa_designations", "parent", 0);
    $template = 'admin';
    $data['scriptFile'] = 'admin-coa_v_1.0';
    $data['viewFile'] = 'coa/list-designations';
    $data['module'] = "coa";
    return view('template/'.$template, $data);
  }

  /*
  **  LIST OF DESIGNATION
  */
  function getDesignations(){
    $list = $this->Mdl_coa->get_datatables_1();
    $data = array();
    $no = $_POST['start']; 
    
    $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'] = 'COA';
    $admin_array['userip'] = $this->input->ip_address();
    $admin_array['logID'] = $admin['logID'];

    $log =  insertTrackLog($admin_array);

    foreach ($list as $val) {
      $row = array();
      $url = base_url().'coa/update-designation/'.$val->id;
      // $row[] = '<a class="btn waves-effect waves-light btn-success" href="'.$url.'">UPDATE</a>';
      $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(\'coa_designations\',\'id\',this.id,\'coa_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_coa->count_all_1(),
      "recordsFiltered" => $this->Mdl_coa->count_filtered_1(),
      "data" => $data,
    );

    echo json_encode($output);
  }

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

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

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

    $template = 'admin';
    $data['scriptFile'] = 'admin-coa_v_1.0';
    $data['viewFile'] = 'add-designation';
    $data['module'] = "coa";
    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",
        array(
        'required' => "Designation is required"
      ));

      if($this->form_validation->run() == FALSE){
        $errors = $this->form_validation->error_array();
        echo json_encode($errors);
      }else{
        $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_coa->insert('coa_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'] = 'COA';
        $admin_array['event_id'] = $insertId;
        $admin_array['userip'] = $this->input->ip_address();
        $admin_array['logID'] = $admin['logID'];

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

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

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

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

    $data['designation'] = $this->Mdl_coa->getByValue("coa_designations", "parent", 0);
    $template = 'admin';
    $data['scriptFile'] = 'admin-coa_v_1.0';
    $data['viewFile'] = 'add-division';
    $data['module'] = "coa";
    return view('template/'.$template, $data);
	}
	
  /*
  **  ADD DIVISION ACTION
  */
  function addDivisionAction(){
    $content = $this->input->post();

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

      $this->form_validation->set_rules("name","name","trim|required|xss_clean",
        array(
        'required' => "Division name is required"
      ));

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

        $data = array(
          'name' => strip_tags(strtoupper($content['name'])),
          'parent' => strip_tags($content['designation']),
          '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_coa->insert('coa_designations',$data);  
        $insertId = $this->db->insert_id();
        #track log
        $admin_array['userid'] = $admin['id'];
        $admin_array['usertype'] = 'admin';
        $admin_array['action_type'] = 'Insert Division';
        $admin_array['modulename'] = 'COA';
        $admin_array['event_id'] = $insertId;
        $admin_array['userip'] = $this->input->ip_address();
        $admin_array['logID'] = $admin['logID'];

        $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 = $this->session->userdata('admin');
    $arr = $admin['rights'];
    $rights = explode(',',$arr);

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

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

    $data['designation'] = $designation;
    $data['parent'] = $this->Mdl_coa->getByValue("coa_designations", "parent", 0);

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

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

    $token= $this->session->userdata("token");
    if($content["csrfToken"] == $token){
      if(isset($content["name"])){
        $this->form_validation->set_rules("name","Designation","trim|required|xss_clean",
        array(
          'required' => "Designation is required"
        ));
      
        $name = $content["name"];
      }else if(isset($content["dname"])){
        $this->form_validation->set_rules("dname","Division","trim|required|xss_clean",
        array(
          'required' => "Division is required"
        ));

        $name = $content["dname"];
      }
     
      $this->form_validation->set_rules("parent","Parent Designation","trim|required|xss_clean",
      array(
        'required' => "Designation not selected"
      ));

      $this->form_validation->set_rules("status","Status","trim|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{
        
        $admin = $this->session->userdata('admin');

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

        $update = $this->Mdl_coa->update("coa_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'] = 'COA';
        $admin_array['userip'] = $this->input->ip_address();
        $admin_array['logID'] = $admin['logID'];

        $log =  insertTrackLog($admin_array);

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

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

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

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

    $data['designation'] = $this->Mdl_coa->getByValue("coa_designations", "parent", 0);
    $template = 'admin';
    $data['scriptFile'] = 'admin-coa_v_1.0';
    $data['viewFile'] = 'list-coa';
    $data['module'] = "coa";
    return view('template/'.$template, $data);
  }

  /*
  **  LIST OF COA
  */
  function getCOA(){
    $list = $this->Mdl_coa->get_datatables_2();
    $data = array();
    $no = $_POST['start']; 
    $admin = $this->session->userdata('admin');

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

    $log =  insertTrackLog($admin_array);

    $i = 1;
    foreach ($list as $val) {
      $row = array();
      // $url = base_url().'coa/update/'.$val->id;
      $url = base_url().'coa/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(\'coa\',\'id\',this.id,\'coa\')">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("coa_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_coa->count_all_2(),
      "recordsFiltered" => $this->Mdl_coa->count_filtered_2(),
      "data" => $data,
    );

    echo json_encode($output);
  }

  /*
  **  LIST OF DIVISION
  */
  function getDivisionList(){
    $content = $this->input->post();
    
    if($content['designation'] == ""){
      echo json_encode(array("status"=>"fail")); exit;
    }

    $result = $this->Mdl_coa->getByValue("coa_designations", "parent", $content['designation']);

    if($result == "No Data"){
      echo json_encode(array("status"=>"fail")); exit;
    }else{
      $division = array();
      foreach($result as $val){
        $division[$val->id] = strtoupper($val->name);
      }

      echo json_encode($division); exit;
    }
  }

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

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

    if(! in_array("3.6",$rights)){
      redirect('admin/dashboard','refresh');
    }
    
    $data['designation'] = $this->Mdl_coa->getByValue("coa_designations", "parent", 0);
    $data['viewFile'] = "add-coa";
    $data['scriptFile'] = "admin-coa_v_1.0";
    $data['module'] = "coa";
    $template = 'admin';
    return view('template/'.$template, $data);
  }

  /*
  ** ADD COA ACTION
  */
  function addCOAAction(){
    $content = $this->input->post();
    // print_r($content); exit;

    $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("division","division","trim|xss_clean");
    
    $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("mobile","Mobile","trim|xss_clean");
    
     $this->form_validation->set_rules("fax","Fax","trim|xss_clean");

    $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/coa/'.$imagename.'.'.$ext;
        if($img !== 1){
          echo json_encode(array("image"=>$img)); exit;
        }
      }else{
        $imgpath = "NA";
      }

      $admin = $this->session->userdata('admin');

      $data = array(
        'name' => strip_tags($content['name']),
        'slug' => strip_tags($slug),
        'designation' => strip_tags($content['designation']),
        'division' => strip_tags($content['division']),
        '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_coa->insert("coa", $data);
    $insertId = $this->db->insert_id();
      #track log
      $admin_array['userid'] = $admin['id'];
      $admin_array['usertype'] = 'admin';
      $admin_array['action_type'] = 'Insert COA';
      $admin_array['modulename'] = 'COA';
      $admin_array['event_id'] = $insertId;
      $admin_array['userip'] = $this->input->ip_address();
      $admin_array['logID'] = $admin['logID'];

      $log =  insertTrackLog($admin_array);

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

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

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

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

    $result = $this->Mdl_coa->getByValue("coa","id",$id);
    if($result == "No Data"){
      redirect('errors','refresh');
    }else{
      $data['designation'] = $this->Mdl_coa->getByValue("coa_designations", "parent", 0);
      if($result[0]->division !== '0' || $result[0]->division !== ""){
        $data['division'] = $this->Mdl_coa->getByValue("coa_designations", "parent", $result[0]->designation);
      }
      
      $data['coa'] = $result;
      // $data['viewFile'] = "update-coa";
      $data['viewFile'] = "view-coa";
      $data['scriptFile'] = "admin-coa_v_1.0";
      $data['module'] = "coa";
      $template = 'admin';
      return view('template/'.$template, $data);
    }
  }

  /*
  ** UPDATE COA ACTION
  */
  function updateCOAAction(){
    $content = $this->input->post();
    // print_r($content); exit;

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

    $this->form_validation->set_rules("division","division","trim|xss_clean");
    
    $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[255]",

    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("mobile","Mobile","trim|xss_clean");
    
    $this->form_validation->set_rules("fax","Fax","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($content['imgpath'] !== 'NA' && 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/coa/'.$imagename.'.'.$ext;
        if($img !== 1){
          echo json_encode(array("image"=>$img)); exit;
        }
      }else{
        $imgpath = $content['imgpath'];
      }

      $admin = $this->session->userdata('admin');

      $data = array(
        'name' => strip_tags($content['name']),
        'slug' => strip_tags($slug),
        'designation' => strip_tags($content['designation']),
        'division' => strip_tags($content['division']),
        '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' => strip_tags($content['status']),
        'admin'=> Modules::run('admin/getAdminName',$admin['id']),
        'modifiedDate' =>date('Y-m-d H:i:s')
      );

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

      #track log
      $admin_array['userid'] = $admin['id'];
      $admin_array['usertype'] = 'admin';
      $admin_array['action_type'] = 'Update COA';
      $admin_array['modulename'] = 'COA';
      $admin_array['userip'] = $this->input->ip_address();
      $admin_array['logID'] = $admin['logID'];
      
      $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/coa';
    $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;
    }
  }


}
