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



use App\Modules\generic\Models\Mdl_generic;

use App\Modules\Exhibitions\Models\Mdl_exhibitions;

use CodeIgniter\Controller;

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

  function index(){
    $template = 'home';
		$data['country'] = $this->Mdl_exhibitions->getAllRecords("country");
    $data['seo'] = $this->Mdl_exhibitions->getByValue("seo","page","home");
    $statement = "SELECT * FROM years_master WHERE status = '1' ORDER BY year desc";
    $data['years'] = $this->Mdl_exhibitions->customQuery($statement);

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

    function getExhibitionData(){
    $content = $this->input->post();
    $year = $content['year'];

    $statement = "SELECT * FROM exhibitions WHERE status = '1' AND year = '$year' ORDER BY from_date desc";
    $exhibitions = $this->Mdl_exhibitions->customQuery($statement);

    if($exhibitions == "No Data"){
      echo json_encode(array("status"=>"fail")); exit;
    }else{
      $html_resp = '';
      foreach($exhibitions as $val){
        if($val->filepath == 'NA'){
          $imgurl = base_url().'public/custom/images/exhibitions/default.jpg';
        }else{
          $imgurl = base_url().$val->filepath;
        }
        
        if($val->filepath_forpdf == 'NA' || $val->filepath_forpdf == ''){
          $imgurl1 = 'NA';
        }else{
          $imgurl1 = base_url().$val->filepath_forpdf;
        }

        if($val->url == ''){
          $redirect = '<img src="'.$imgurl.'" class="img-fluid rounded">';
        }else{
          $redirect = '<a href="'.$val->url.'" target="_blank" ><img src="'.$imgurl.'" class="img-fluid rounded"></a>';
        }

        $html_resp .= '<div class="rounded mb-4 border">
        <div class="p-3">
          <div class="row">
            <div class="col-sm-4">'.$redirect.'</div>
            <div class="col-sm-8">
              <h5 class="redColor mb-3">'.$val->name.'</h5>
              <table class="exhibitionTable">
                <tr>
                  <td><p class="text-uppercase">Date</p></td>
                  <td class="pl-3 pr-3">:</td>';
                  if($val->from_date == "NA" || $val->to_date == "NA"){
                    $html_resp .=  '<td><p><strong>Date to Be Announced</strong></p></td>';
                  }else{
                    $html_resp .= '<td><p><strong>From - '.date("d M Y",strtotime($val->from_date)).' To - '.date("d M Y",strtotime($val->to_date)).'</strong></p></td>';
                  }
                  
                  $html_resp .= '</tr>
                <tr>
                  <td><p class="text-uppercase">Venue</p></td>
                  <td class="pl-3 pr-3">:</td>
                  <td><p><strong>'.$val->venue.'</strong></p></td>
                </tr>
              </table>';
              if(strtotime("now") < strtotime($val->to_date)){
                $html_resp .= '<a href="javascript:;" id="'.$val->name.'" onclick="show(this.id,event)"  data-src="#quickEnquiry" data-fancybox class="btn grayGradientBg whiteColor">Quick Enquiry</a>';
              }else if($val->from_date == 'NA' || $val->to_date == 'NA'){
                $html_resp .= '<a href="javascript:;" id="'.$val->name.'" onclick="show(this.id,event)"  data-src="#quickEnquiry" data-fancybox class="btn grayGradientBg whiteColor">Quick Enquiry</a>';
              }
              
              if($imgurl1 != 'NA'){
                $html_resp .= '&nbsp;&nbsp;&nbsp;<a href="'.$imgurl1.'" id="'.$imgurl1.'" class="btn grayGradientBg whiteColor" target="_blank">Indian Exhibitors Directory</a>';
              }
              
              $html_resp .= '</div>
          </div>
        </div>
      </div>';
      }

      echo json_encode(array("status"=>"success","response"=>$html_resp)); exit;
    }
  }

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

    $this->form_validation->set_rules("exhibition","Exhibition","trim|required|xss_clean|max_length[100]",
    array(
      'required' => 'Exhibition Name is required.',
      'max_length' => 'Exhibition Name 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("company","Company","trim|required|xss_clean|max_length[100]",
    array(
      'required' => 'Company is required.',
      'max_length' => 'Company is invalid.'
    ));

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

    $this->form_validation->set_rules("designation","Designation","trim|xss_clean");
    $this->form_validation->set_rules("address","Address","trim|xss_clean");
    $this->form_validation->set_rules("contact","Landline number","trim|xss_clean");

    $this->form_validation->set_rules("mobile","Mobile","trim|required|xss_clean|max_length[100]",
    array(
      'required' => 'Mobile number is required.',
      'max_length' => 'Mobile Number is invalid.'
    ));
    
    $this->form_validation->set_rules("country","Country","trim|required|xss_clean|max_length[100]",
    array(
      'required' => 'Country is required.',
      'max_length' => 'Country is invalid.'
    ));

    $this->form_validation->set_rules("product","Product","trim|xss_clean");

    $this->form_validation->set_rules("hs","HS code","trim|xss_clean");
    
    $this->form_validation->set_rules("radio","Area","trim|xss_clean");

    if($this->form_validation->run() == FALSE){
      $errors = $this->form_validation->error_array();
      echo json_encode($errors); exit;
    }else{
      if(isset($content['radio']) && !empty($content['radio'])){
        $area = $content['radio'];
      }else{
        $area = '';
      }

      $data = array(
        'exhibition_name' => strip_tags($content['exhibition']),
        'name' => strip_tags($content['name']),
        'company' => strip_tags($content['company']),
        'email' => strip_tags($content['email']),
        'mobile' => strip_tags($content['mobile']),
        'contact' => strip_tags($content['contact']),
        'country' => strip_tags($content['country']),
        'address' => strip_tags($content['address']),
        'product' => strip_tags($content['product']),
        'hs_code' => strip_tags($content['hs']),
        'area' => strip_tags($area),
        'createdDate' =>date('Y-m-d H:i:s'),
        'modifiedDate' =>date('Y-m-d H:i:s')
      );

      $insert = $this->Mdl_exhibitions->insert("exhibition_enquiry", $data);

      $mail_data = array(
        "viewFile"=>'exhibitions/exhibition-ack',
        "to"=>$content['email'],
        "cc" =>"",
        "bcc" =>"",
        "subject"=>"EXHIBITION ENQUIRY ACKNOWLEDGEMENT",
        "name" => $content['name']
      );
      
      $status_ack_mail = Modules::run('email/mailer', $mail_data);

      $mail_data_plex = array(
        "viewFile"=>'exhibitions/exhibition-enquiry',
        "to"=>"k.goda@plexconcil.org",        
	      "cc" =>"",
        "bcc" =>"",
        "subject"=>"EXHIBITION ENQUIRY",
        'exhibition_name' => strip_tags($content['exhibition']),
        'name' => strip_tags($content['name']),
        'company' => strip_tags($content['company']),
        'email' => strip_tags($content['email']),
        'mobile' => strip_tags($content['mobile']),
        'contact' => strip_tags($content['contact']),
        'country' => strip_tags($content['country']),
        'address' => strip_tags($content['address']),
        'product' => strip_tags($content['product']),
        'hs_code' => strip_tags($content['hs']),
        'area' => strip_tags($area)
      );
      
      $status_ack_mail = Modules::run('email/mailer', $mail_data_plex);

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

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

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

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

  /*
  **  LIST OF EXHIBITION
  */
  function getExhibitions(){
    $list = $this->Mdl_exhibitions->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';
    $admin_array['modulename'] = 'Exhibition';
    $admin_array['logID'] = $admin['logID'];
    $admin_array['userip'] = $this->input->ip_address();

    $log =  insertTrackLog($admin_array);

    $i = 1;
    foreach ($list as $val) {
      $row = array();
      $url = base_url().'exhibitions/update/'.$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(\'exhibitions\',\'id\',this.id,\'exhibitions\')">DELETE</button>';
      }else{
        $row[] = '';
      }

      $row[] = $val->year;
      $row[] = strtoupper($val->name);
      if($val->from_date == "NA" || $val->to_date == "NA"){
        $row[] = 'Date to Be Announced';
      }else{
        $row[] = 'From '.date("d M Y",strtotime($val->from_date)).' To '.date("d M Y",strtotime($val->to_date));
      }
     
      $row[] = $val->venue;
      
      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_exhibitions->count_all_1(),
      "recordsFiltered" => $this->Mdl_exhibitions->count_filtered_1(),
      "data" => $data,
    );

    echo json_encode($output);
  }

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

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

    if(! in_array("12.2",$rights)){
      redirect('admin/dashboard','refresh');
    }
    
    $data['years_master'] = $this->Mdl_exhibitions->getByValue("years_master","status","1");
    $data['viewFile'] = "exhibitions/add-exhibitions";
    $data['scriptFile'] = "admin-exhibitions_v_1.0";
    $data['module'] = "exhibitions";
    $template = 'admin';
    return view('template/'.$template, $data);
  }

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

    $this->form_validation->set_rules("year","Year","trim|required|xss_clean|max_length[100]",
    array(
      'required' => 'Year is required.',
      'max_length' => 'Year 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("from_date","Start Date","trim|xss_clean");

    $this->form_validation->set_rules("to_date","End Date","trim|xss_clean");
    
    $this->form_validation->set_rules("venue","Venue","trim|required|xss_clean|max_length[100]",
    array(
      'required' => 'Venue is required.',
      'max_length' => 'Venue is invalid.'
    ));

$this->form_validation->set_rules("url","Link","trim|xss_clean");

if(!empty($_FILES['pdf']['name'])){
        $filename = $_FILES['pdf']['name'];
        $img1 = $this->uploadFiles($filename,"pdf");
        $str_replacefile=str_replace(' ','_',$filename);
        $imgpath1 = 'public/custom/files/exhibitions/'.$str_replacefile;
        if($img1 !== 1){
          echo json_encode(array("pdf"=>$img1)); exit;
        }
}

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

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

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

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

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

      $data = array(
        'year' => strip_tags($content['year']),
        'name' => strip_tags($content['name']),
        'from_date' => $from_date,
        'to_date' => $to_date,
        'venue' => strip_tags($content['venue']),
        'filepath'=> strip_tags($imgpath),
        'filepath_forpdf'=> strip_tags($imgpath1),
 'url' => strip_tags($content['url']),
        '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_exhibitions->insert("exhibitions", $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'] = 'Exhibition';
    $admin_array['event_id'] = $insertId;
    $admin_array['logID'] = $admin['logID'];
    $admin_array['userip'] = $this->input->ip_address();

      $log =  insertTrackLog($admin_array);

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

  /*
  ** UPDATE EXHIBITIONS
  */
  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("12.3",$rights)){
      redirect('admin/dashboard','refresh');
    }

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

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

    $this->form_validation->set_rules("year","Year","trim|required|xss_clean|max_length[100]",
    array(
      'required' => 'Year is required.',
      'max_length' => 'Year 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("from_date","Start Date","trim|xss_clean");

    $this->form_validation->set_rules("to_date","End Date","trim|xss_clean");
    
    $this->form_validation->set_rules("venue","Venue","trim|required|xss_clean|max_length[100]",
    array(
      'required' => 'Venue is required.',
      'max_length' => 'Venue is invalid.'
    ));

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

 $this->form_validation->set_rules("url","Link","trim|xss_clean");

        if(!empty($_FILES['pdf']['name'])){
            
                
                $filename = $_FILES['pdf']['name'];
                $img1 = $this->uploadFiles($filename,"pdf");
               $str_replacefile=str_replace(' ','_',$filename);
        $imgpath1 = 'public/custom/files/exhibitions/'.$str_replacefile;
                if($img1 !== 1){
                  echo json_encode(array("pdf"=>$img1)); exit;
                }
        }     
        
    if($this->form_validation->run() == FALSE){
      $errors = $this->form_validation->error_array();
      echo json_encode($errors); exit;
    }else{
      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/exhibitions/'.$imagename.'.'.$ext;
        if($img !== 1){
          echo json_encode(array("image"=>$img)); exit;
        }
      }else{
        $imgpath = $content['imgpath'];
      }

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

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

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

      $data = array(
        'year' => strip_tags($content['year']),
        'name' => strip_tags($content['name']),
        'from_date' => $from_date,
        'to_date' => $to_date,
        'venue' => strip_tags($content['venue']),
        'filepath'=> strip_tags($imgpath),
        'filepath_forpdf'=> strip_tags($imgpath1),
'url' => strip_tags($content['url']),
        'status' => strip_tags($content['status']),
        'admin'=> Modules::run('admin/getAdminName',$admin['id']),
        'modifiedDate' =>date('Y-m-d H:i:s')
      );

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

      #track log
      $admin_array['userid'] = $admin['id'];
      $admin_array['usertype'] = 'admin';
      $admin_array['action_type'] = 'Update';
      $admin_array['modulename'] = 'Exhibition';
      $admin_array['logID'] = $admin['logID'];
    $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/exhibitions';
    $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;
    }
  }
  
  
  function uploadFiles($imageName,$key){
    $config['file_name'] = $imageName;
    $config['upload_path'] = './public/custom/files/exhibitions';
    $config['allowed_types'] = "pdf|PDF";
    $config['max_size']  = '10000';
    
    $config['overwrite'] = true;
    $this->load->library('upload',$config);
    $this->upload->initialize($config);
    if (!$this->upload->do_upload($key)){
      return $this->upload->display_errors();
    }else{
      return 1;
    }
  }




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

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

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

    $template = 'admin';
    $data['scriptFile'] = 'admin-exhibitions_v_1.0';
    $data['viewFile'] = 'exhibitions/list-exhibition-enquiry';
    $data['module'] = "exhibitions";
    return view('template/'.$template, $data);
  }

  /*
  **  LIST OF EXHIBITION ENQUIRY
  */
  function getExhibitionEnquiry(){
    $list = $this->Mdl_exhibitions->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 Exhibition Enquiry';
    $admin_array['modulename'] = 'Exhibition';
    $admin_array['logID'] = $admin['logID'];
    $admin_array['userip'] = $this->input->ip_address();
    
    $log =  insertTrackLog($admin_array);

    $i = 1;
    foreach ($list as $val) {
      $row = array();
      $url = base_url().'exhibitions/enquiry/'.$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(\'exhibition_enquiry\',\'id\',this.id,\'exhibition_enquiry\')">DELETE</button>';
      }else{
        $row[] = '';
      }

      $row[] = strtoupper($val->exhibition_name);
      $row[] = strtoupper($val->name);
      $row[] = strtoupper($val->company);
      $row[] = strtoupper($val->email);
      $row[] = $val->mobile;
      $row[] = date('d-m-Y',strtotime($val->createdDate));
      $data[] = $row;
      $i++;
    }

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

    echo json_encode($output);
  }

  /*
  **  VIEW EXHIBITION ENQUIRY
  */
  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("12.4",$rights)){
      redirect('admin/dashboard','refresh');
    }

    $result = $this->Mdl_exhibitions->getByValue("exhibition_enquiry","id",$id);
    if($result == "No Data"){
      redirect('errors','refresh');
    }else{
      $data['enquiry'] = $result;
      $data['viewFile'] = "exhibitions/view-enquiry";
      $data['module'] = "exhibitions";
      $template = 'admin';
      return view('template/'.$template, $data);
    }
  }

}
