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



use App\Modules\generic\Models\Mdl_generic;

use App\Modules\Government\Models\Mdl_government;

use CodeIgniter\Controller;

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

    /*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';
		
		//echo Modules::run('template/'.$template, $data); 
		return view('template/'.$template, $data);
	}
	
	*/
	
	function index(){
    $statement = 'SELECT * FROM government WHERE status = "1" ORDER BY createdDate desc';
    $result = $this->Mdl_government->customQuery($statement);

    $data['government'] = $result;
    $data['seo'] = $this->Mdl_government->getByValue("seo","page","home");
    $data['country'] = $this->Mdl_government->getAllRecords("country");
    $data['viewFile'] = "government/government";
    $data['module'] = "government";
    $data['captcha'] = "";
    $template = 'home';
   return view('template/'.$template, $data);
  }

	/*************************************************************************/
	/* 														ADMIN MODULE															 */
	/*************************************************************************/
	
	/*
	**	STATISTICS 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("19.1",$rights)){
      redirect('admin/dashboard','refresh');
    }

    $template = 'admin';
    $data['scriptFile'] = 'admin-government_v_1.0';
    $data['viewFile'] = 'government/list-government';
    $data['module'] = "government";
   return view('template/'.$template, $data);
  }
	
	/*
  **  GET LIST OF government
  */
  function getGovernment(){
    $list = $this->Mdl_government->get_datatables();
    $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';
    $admin_array['modulename'] = 'Goverment';
    $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().'government/update/'.$val->id;
      $row[] = '<a class="btn 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(\'government\',\'id\',this.id,\'government\')">DELETE</button>';
      }else{
        $row[] = '';
      }

      $row[] = $val->title;
      
      $pdf_url = base_url().$val->filepath;
      $row[] = '<a class="btn btn-rounded btn-outline-info" target="_blank" href="'.$pdf_url.'"><i class="fa fa-file-pdf-o" aria-hidden="true"> VIEW </i></a>';

			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;
    }

    $output = array(
      "draw" => $_POST['draw'],
      "recordsTotal" => $this->Mdl_government->count_all(),
      "recordsFiltered" => $this->Mdl_government->count_filtered(),
      "data" => $data,
    );

    echo json_encode($output);
	}
	
  /*
  ** ADD NEW government
  */
  function add(){
    if(!Modules::run('security/isAdmin')){
      redirect('admin','refresh');
    }

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

    if(! in_array("19.2",$rights)){
      redirect('admin/dashboard','refresh');
    }
    
    $data['viewFile'] = "government/add-government";
    $data['scriptFile'] = "admin-government_v_1.0";
    $data['module'] = "government";
    $template = 'admin';
   return view('template/'.$template, $data);
  }

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

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

    $this->form_validation->set_rules("overview","Overview","trim|xss_clean");

    if($this->form_validation->run() == FALSE){
      $errors = $this->form_validation->error_array();
      echo json_encode($errors);
    }else{
      if(!empty($_FILES['pdf']['name'])){
        $filename = $_FILES['pdf']['name'];
        $ext = pathinfo($filename, PATHINFO_EXTENSION);
        $imagename = strtotime('now');
        $img = $this->uploadFile($imagename,"pdf");
        $imgpath = 'public/custom/files/government/'.$imagename.'.'.$ext;
        if($img !== 1){
          echo json_encode(array("pdf"=>$img)); exit;
        }
      }
      //else{
//        echo json_encode(array("pdf"=>"Please upload file")); exit;
 //     }

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

      $data = array(
        'title'=> strip_tags($content['title']),
        'overview'=> strip_tags($content['overview']),
        'filepath'=> 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_government->insert("government", $data);
$insertId = $this->db->insert_id();
      #track log
      $admin_array['userid'] = $admin['id'];
      $admin_array['usertype'] = 'admin';
      $admin_array['action_type'] = 'Insert';
      $admin_array['modulename'] = 'Goverment';
      $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 government
  */
  function update($id){
    if(!Modules::run('security/isAdmin')){
      redirect('admin','refresh');
    }

    $admin = $this->session->userdata('admin');
    $arr = $admin['rights'];
    $rights = explode(',',$arr);
    
    if(! in_array("19.3",$rights)){
      redirect('admin/dashboard','refresh');
    }

    $result = $this->Mdl_government->getByValue("government","id",$id);
    if($result == "No Data"){
      redirect('errors','refresh');
    }else{
      $data['government'] = $result;
      $data['viewFile'] = "government/update-government";
      $data['scriptFile'] = "admin-government_v_1.0";
      $data['module'] = "government";
      $template = 'admin';
     return view('template/'.$template, $data);
    }
  }

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

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

    $this->form_validation->set_rules("overview","Overview","trim|xss_clean");

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

    if($this->form_validation->run() == FALSE){
      $errors = $this->form_validation->error_array();
      echo json_encode($errors);
    }else{
      if(!empty($_FILES['pdf']['name'])){
        if(file_exists('./'.$content['pdf_path'])){
          $this->removeImage($content['pdf_path']);
        }
        
        $filename = $_FILES['pdf']['name'];
        $ext = pathinfo($filename, PATHINFO_EXTENSION);
        $imagename = strtotime('now');
        $img = $this->uploadFile($imagename,"pdf");
        $imgpath = 'public/custom/files/government/'.$imagename.'.'.$ext;
        if($img !== 1){
          echo json_encode(array("pdf"=>$img)); exit;
        }
      }else{
        $imgpath = $content['pdf_path'];
      }

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

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

      $insert = $this->Mdl_government->update("government", "id", $content['id'], $data);

      #track log
      $admin_array['userid'] = $admin['id'];
      $admin_array['usertype'] = 'admin';
      $admin_array['action_type'] = 'Update';
      $admin_array['modulename'] = 'Goverment';
      $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/files/government';
    $config['allowed_types'] = "pdf|PDF";
    $config['max_size']  = '5000';
    
    $this->load->library('upload',$config);
    $this->upload->initialize($config);
    if (!$this->upload->do_upload($key)){
      return $this->upload->display_errors();
    }else{
      return 1;
    }
  }

}
