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



use App\Modules\generic\Models\Mdl_generic;

use App\Modules\Seminars\Models\Mdl_seminars;

use CodeIgniter\Controller;

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

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

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

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

    $statement = "SELECT * FROM seminars WHERE status = '1' AND year = '$year' ORDER BY createdDate desc";
    $seminars = $this->Mdl_seminars->customQuery($statement);

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

        $html_resp .= '
        <div class="grayBg rounded mb-4">
          <a href="javascript:;" id="'.$val->id.'" onclick="headclick(this.id,event)" class="p-3 d-block head">
            <div class="row justify-content-between listData">
              <div class="col-10 col-md-3">
                <h5 class="redColor">'.$val->name.'</h5>
              </div>
            
              <div class="col-md-3 d-none d-md-block">
                <h5 class="redColor">Date</h5>';
                if($val->from_date == "NA"){
                  $html_resp .=  '<p><strong>Date to Be Announced</strong></p>';
                }else{
                  $html_resp .= '<p>Date - <strong>'.date("d M Y",strtotime($val->from_date)).'</strong></p>';
                }
                
                $html_resp .= '</div>
            
              <div class="col-md-4 d-none d-md-block">
                <h5 class="redColor">Venue</h5>
                <p>'.$val->venue.'</p>
              </div>
            
              <div class="col-2 col-md-1 text-center border-left">
                <span class="minusMark">+</span>
              </div>
            </div>
          </a>
          <div class="p-3 overView border-top">
            <h5 class="redColor mb-3">Overview</h5>
            <p class="date d-md-none"><span class="redColor">Date :</span>';
            if($val->from_date == "NA"){
              $html_resp .=  '<strong>Date to Be Announced</strong>';
            }else{
              $html_resp .= '<strong>'.date("d M Y",strtotime($val->from_date)).'</strong>';
            }
            $html_resp .= '</p>
            <p class="venue d-md-none"><span class="redColor">Venue :</span>'.$val->venue.'</p>
            <div>
              <img src="'.$imgurl.'" class="dynamicImage rounded" >
              <p>'.$val->overview.'</p>';
              if(strtotime("now") < strtotime($val->from_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'){
                $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>';
              }
              
              $html_resp .= '<div class="clearfix"></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("seminar","Seminar","trim|required|xss_clean",
    array(
      'required' => 'Seminar is required.'
    ));
    
    $this->form_validation->set_rules("name","Name","trim|required|xss_clean",
    array(
      'required' => 'Name is required.'
    ));

    $this->form_validation->set_rules("company","Company","trim|required|xss_clean",
    array(
      'required' => 'Company is required.'
    ));

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

    $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",
    array(
      'required' => 'Mobile number is required.'
    ));
    
    $this->form_validation->set_rules("country","Country","trim|required|xss_clean",
    array(
      'required' => 'Country is required.'
    ));

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

      $data = array(
        'seminar_name' => strip_tags($content['seminar']),
        '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']),
        'createdDate' =>date('Y-m-d H:i:s'),
        'modifiedDate' =>date('Y-m-d H:i:s')
      );

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

      $mail_data_plex = array(
        "viewFile"=>'seminars/seminar-enquiry',
        "to"=>"office@plexconcil.org",
        "cc" =>"",
        "bcc" =>"",
        "subject"=>"SEMINAR / WORKSHOPS ENQUIRY",
        'seminar_name' => strip_tags($content['seminar']),
        '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'])
      );
      
      $status_ack_mail = Modules::run('email/mailer', $mail_data_plex);

      $insert = $this->Mdl_seminars->insert("seminars_enquiry", $data);
      echo json_encode(array("status"=>"success")); exit;
    }
  }

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

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

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

  /*
  **  LIST OF SEMINARS
  */
  function getSeminars(){
    $list = $this->Mdl_seminars->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';
    $admin_array['modulename'] = 'Seminar';
    $admin_array['userip'] = $this->input->ip_address();

    $log =  insertTrackLog($admin_array);

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

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

    echo json_encode($output);
  }

  /*
  ** ADD SEMINARS
  */
  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("15.2",$rights)){
      redirect('admin/dashboard','refresh');
    }
    
    $data['years_master'] = $this->Mdl_seminars->getByValue("years_master","status","1");
    $data['viewFile'] = "seminars/add-seminars";
    $data['scriptFile'] = "admin-seminars_v_1.0";
    $data['module'] = "seminars";
    $template = 'admin';
    return view('template/'.$template, $data);
  }

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

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

    $this->form_validation->set_rules("from_date","Seminar 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",
    array(
      'required' => 'Venue is required.'
    ));

    $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); 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/seminars/'.$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');

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

      $data = array(
        'year' => strip_tags($content['year']),
        'name' => strip_tags($content['name']),
        'from_date' => $from_date,
        'to_date' => 'NA',
        'venue' => strip_tags($content['venue']),
        '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_seminars->insert("seminars", $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'] = 'Seminar';
      $admin_array['event_id'] = $insertId;
      $admin_array['userip'] = $this->input->ip_address();

      $log =  insertTrackLog($admin_array);

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

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

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

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

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

    $this->form_validation->set_rules("from_date","Seminar Date","trim|xss_clean");

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

    $this->form_validation->set_rules("overview","Overview","trim|xss_clean",
    array(
      'required' => 'Overview is required.'
    ));

    $this->form_validation->set_rules("status","Status","trim|xss_clean|required",
    array(
      'required' => 'Please select status.'
    ));

    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/tradedelegation/'.$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');

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

      $data = array(
        'year' => strip_tags($content['year']),
        'name' => strip_tags($content['name']),
        'from_date' => $from_date,
        'to_date' => 'NA',
        'venue' => strip_tags($content['venue']),
        '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')
      );

      $update = $this->Mdl_seminars->update("seminars","id",$content['id'],$data);
      #track log
      $admin_array['userid'] = $admin['id'];
      $admin_array['usertype'] = 'admin';
      $admin_array['action_type'] = 'Update';
      $admin_array['modulename'] = 'Seminar';
      $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/seminars';
    $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;
    }
  }

  /*
  ** SEMINAR ENQUIRY LISTING PAGE
  */
  function enquiryList(){
    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("15.4",$rights)){
      redirect('admin/dashboard','refresh');
    }

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

  /*
  **  LIST OF SEMINAR  ENQUIRY
  */
  function getSeminarEnquiry(){
    $list = $this->Mdl_seminars->get_datatables();
    $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 Enquiry';
    $admin_array['modulename'] = 'Seminar';
    $admin_array['userip'] = $this->input->ip_address();

    $log =  insertTrackLog($admin_array);

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

      $row[] = strtoupper($val->seminar_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_seminars->count_all(),
      "recordsFiltered" => $this->Mdl_seminars->count_filtered(),
      "data" => $data,
    );

    echo json_encode($output);
  }

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

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