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



use App\Modules\generic\Models\Mdl_generic;

use App\Modules\Circulars\Models\Mdl_circulars;

use CodeIgniter\Controller;

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

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

  function dgft(){
    $statement = "SELECT * FROM circulars WHERE type='dgft' AND status='1' ORDER BY post_date desc";
    $result = $this->Mdl_circulars->customQuery($statement);

		$template = 'home';
		$data['country'] = $this->Mdl_circulars->getAllRecords("country");
		$data['seo'] = $this->Mdl_circulars->getByValue("seo","page","home");
		$data['circulars'] = $result;
		$data['name'] = "DGFT";
		$data['viewFile'] = 'circulars/circulars-details';
    $data['scriptFile'] = 'circulars';
		$data['module'] = "circulars";
		return view('template/'.$template, $data); 
  }

  function rbi(){
    $statement = "SELECT * FROM circulars WHERE type='rbi' AND status='1' ORDER BY post_date desc";
    $result = $this->Mdl_circulars->customQuery($statement);

		$template = 'home';
		$data['country'] = $this->Mdl_circulars->getAllRecords("country");
		$data['seo'] = $this->Mdl_circulars->getByValue("seo","page","home");
    $data['circulars'] = $result;
    $data['name'] = "RBI";  
    $data['viewFile'] = 'circulars/circulars-details';
    $data['scriptFile'] = 'circulars';
		$data['module'] = "circulars";
		return view('template/'.$template, $data); 
  }

  function fta(){
    $statement = "SELECT * FROM circulars WHERE type='fta' AND status='1' ORDER BY post_date desc";
    $result = $this->Mdl_circulars->customQuery($statement);

		$template = 'home';
		$data['country'] = $this->Mdl_circulars->getAllRecords("country");
		$data['seo'] = $this->Mdl_circulars->getByValue("seo","page","home");
    $data['circulars'] = $result;
    $data['name'] = "FTA";
    $data['viewFile'] = 'circulars/circulars-details';
    $data['scriptFile'] = 'circulars';
		$data['module'] = "circulars";
		return view('template/'.$template, $data); 
  }

  function customs(){
    $statement = "SELECT * FROM circulars WHERE type='customs' AND status='1' ORDER BY post_date desc";
    $result = $this->Mdl_circulars->customQuery($statement);

		$template = 'home';
		$data['country'] = $this->Mdl_circulars->getAllRecords("country");
		$data['seo'] = $this->Mdl_circulars->getByValue("seo","page","home");
    $data['circulars'] = $result;
    $data['name'] = "CUSTOMS";
    $data['viewFile'] = 'circulars/circulars-details';
    $data['scriptFile'] = 'circulars';
		$data['module'] = "circulars";
		return view('template/'.$template, $data); 
  }

  function gst(){
    $statement = "SELECT * FROM circulars WHERE type='gst' AND status='1' ORDER BY post_date desc";
    $result = $this->Mdl_circulars->customQuery($statement);

		$template = 'home';
		$data['country'] = $this->Mdl_circulars->getAllRecords("country");
		$data['seo'] = $this->Mdl_circulars->getByValue("seo","page","home");
    $data['circulars'] = $result;
    $data['name'] = "GST";
    $data['viewFile'] = 'circulars/circulars-details';
    $data['scriptFile'] = 'circulars';
		$data['module'] = "circulars";
		return view('template/'.$template, $data); 
  }

  function all(){
    $statement = "SELECT * FROM circulars WHERE status='1' ORDER BY post_date desc";
    $result = $this->Mdl_circulars->customQuery($statement);

		$template = 'home';
		$data['country'] = $this->Mdl_circulars->getAllRecords("country");
		$data['seo'] = $this->Mdl_circulars->getByValue("seo","page","home");
    $data['name'] = "";
    $data['circulars'] = $result;
    $data['viewFile'] = 'circulars/circulars-details';
    $data['scriptFile'] = 'circulars';
		$data['module'] = "circulars";
		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("20.1",$rights)){
      redirect('admin/dashboard','refresh');
    }

    $template = 'admin';
    $data['scriptFile'] = 'admin-circulars_v_1.0';
    $data['viewFile'] = 'circulars/list-circulars';
    $data['module'] = "circulars";
    return view('template/'.$template, $data);
  }
	
	/*
  **  GET LIST OF CIRCULAR
  */
  function getCirculars(){
    $list = $this->Mdl_circulars->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'] = 'Circulars';
    $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().'circulars/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(\'circulars\',\'id\',this.id,\'circulars\')">DELETE</button>';
      }else{
        $row[] = '';
      }

      $row[] = $val->name;
      
      $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_circulars->count_all(),
      "recordsFiltered" => $this->Mdl_circulars->count_filtered(),
      "data" => $data,
    );

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

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

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

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

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

    $this->form_validation->set_rules("post_date","Last Date","trim|xss_clean");
    $this->form_validation->set_rules("last_date","Last Date","trim|xss_clean");

    $this->form_validation->set_rules("title","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); exit;
    }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/circulars/'.$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');

      if($content['last_date'] == ""){
        $last_date = '';
      }else{
        $last_date = date('Y-m-d',strtotime($content['last_date']));
      }

      if($content['post_date'] == ""){
        $post_date = date('Y-m-d');
      }else{
        $post_date = date('Y-m-d',strtotime($content['post_date']));
      }

      $data = array(
        'type'=> strip_tags($content['type']),
        'name'=> strip_tags($content['title']),
        'filepath'=> strip_tags($imgpath),
        'post_date'=> $post_date,
        'last_date'=> $last_date,
        '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_circulars->insert("circulars", $data);
        $insertId = $this->db->insert_id();

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

      $log =  insertTrackLog($admin_array);

      echo json_encode(array("status"=>"success")); exit;
    }
  }
  
  /*
  ** UPDATE CIRCULARS
  */
  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("20.3",$rights)){
      redirect('admin/dashboard','refresh');
    }

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

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

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

    $this->form_validation->set_rules("post_date","Last Date","trim|xss_clean");
    $this->form_validation->set_rules("last_date","Last Date","trim|xss_clean");

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

    $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); exit;
    }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/circulars/'.$imagename.'.'.$ext;
        if($img !== 1){
          echo json_encode(array("pdf"=>$img)); exit;
        }
      }else{
        $imgpath = $content['pdf_path'];
      }

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

      if($content['last_date'] == ""){
        $last_date = '';
      }else{
        $last_date = date('Y-m-d',strtotime($content['last_date']));
      }

      if($content['post_date'] == ""){
        $post_date = "";
      }else{
        $post_date = date('Y-m-d',strtotime($content['post_date']));
      }

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

      $insert = $this->Mdl_circulars->update("circulars", "id", $content['id'], $data);
      
      #track log
      $admin_array['userid'] = $admin['id'];
      $admin_array['usertype'] = 'admin';
      $admin_array['action_type'] = 'Update';
      $admin_array['modulename'] = 'Circulars';
      $admin_array['userip'] = $this->input->ip_address();
      $admin_array['logID'] = $admin['logID'];
      
      $log =  insertTrackLog($admin_array);

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

  function updateCircularData(){
    $circulars = $this->Mdl_circulars->getAllRecords("circulars");
    foreach($circulars as $val){
      $post_date = date('Y-m-d',strtotime($val->createdDate));

      $data = array(
        'post_date'=> $post_date
      );

      $insert = $this->Mdl_circulars->update("circulars", "id", $val->id, $data);
    }
  }

	/*
  **  FILE UPLOAD
  */
  function uploadFile($imageName,$key){
    $config['file_name'] = $imageName;
    $config['upload_path'] = './public/custom/files/circulars';
    $config['allowed_types'] = "pdf|PDF";
    $config['max_size']  = '20000';
    
    $this->load->library('upload',$config);
    $this->upload->initialize($config);
    if (!$this->upload->do_upload($key)){
      return $this->upload->display_errors();
    }else{
      return 1;
    }
  }

}
