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



use App\Modules\generic\Models\Mdl_generic;

use App\Modules\Advertise\Models\Mdl_advertise;

use CodeIgniter\Controller;

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

 function index(){
    $template = 'home';
		$data['country'] = $this->Mdl_advertise->getAllRecords("country");
    $data['seo'] = $this->Mdl_advertise->getByValue("seo","page","home");

		$data['viewFile'] = 'advertise/advertise';
		$data['country'] = $this->Mdl_advertise->getAllRecords("country");
		$data['module'] = "advertise";
		$data['captcha'] = "";
		return view('template/'.$template, $data); 
  }  

  /*
  **  OTP ACTION 
  */
  function generateOtp(){
    $content = $this->input->post();

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

    if($content['ad_isd'] == "91"){
      $this->form_validation->set_rules("ad_mobile","Mobile Number","trim|required|xss_clean|exact_length[10]|integer",
      array(
        'required' => "mobile",
        'integer' => "mobile_invalid",
        'exact_length' => "mobile_length"
      ));
    }else{
      $this->form_validation->set_rules("ad_mobile","Mobile Number","trim|required|xss_clean|min_length[7]|max_length[15]|integer",
      array(
        'required' => "mobile",
        'integer' => "mobile_invalid",
        'min_length' => "mobile_length",
        'max_length' => "mobile_length"
      ));
    }

    if($this->form_validation->run() == FALSE){
      $errors = $this->form_validation->error_array();
      echo json_encode($errors); exit;
    }else{
      $query = 'SELECT * FROM adv_otp WHERE mobile = "'.$content['ad_mobile'].'" ORDER BY createdDate desc LIMIT 1';
      $otp_rec = $this->Mdl_advertise->customQuery($query);

      $new = false;

      if($otp_rec == "No Data"){
        $new = true;  
      }else if($otp_rec[0]->is_blocked == '1'){
        if(strtotime(now) < strtotime($otp_rec[0]->block_till)){
          echo json_encode(array("status"=>"blocked")); exit;
        }else{
          $otp_data = array(
            "count" => 0,
            "is_blocked" => '0',
            "block_till" => date("Y-m-d H:i:s"),
            "modifiedDate" => date("Y-m-d H:i:s")
          );

          $update = $this->Mdl_advertise->update("adv_otp", "id", $otp_rec[0]->id, $otp_data);
        } 
      }

      $otp = rand(1000,9999);

      $response = $this->sendSMS($content['ad_isd'],$content['ad_mobile'],$otp);

      if($response == '1'){
        echo json_encode(array("status"=>"error","msg"=>"Something went wrong. Please try again.")); exit;
      }else{
        $result = json_decode($response, true);

        if($result['type'] == "error"){
          echo json_encode(array("status"=>"error","msg"=>$result['message'])); exit;
        }else if($result['type'] == "success"){
          
          if($new){
            $otp_data = array(
              'mobile' => $content['ad_mobile'],
              'otp' => $otp,
              "count" => 0,
              "is_blocked" => '0',
              "block_till" => date("Y-m-d H:i:s"),
              "createdDate" => date("Y-m-d H:i:s"),
              "modifiedDate" => date("Y-m-d H:i:s")
            );

            $insert = $this->Mdl_advertise->insert('adv_otp',$otp_data);
          }else{
            $otp_data = array(
              'otp' => $otp,
              "modifiedDate" => date("Y-m-d H:i:s")
            );

            $update = $this->Mdl_advertise->update("adv_otp", "id", $otp_rec[0]->id, $otp_data);
          }
          echo json_encode(array("status"=>"success")); exit;
        }
      }
    }
  }

  /*
  **  ADVERTISE ACTION 
  */
  function advertiseAction(){
    $content = $this->input->post();

    $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("name","Name","trim|required|xss_clean|max_length[255]",
    array(
      'required' => "Name is required",
      'max_length' => "Name is invalid"
    ));
      
    $this->form_validation->set_rules("email","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("ad_country","country","trim|xss_clean|required|integer|max_length[100]",
    array(
      'required' => "Select Country",
      "integer" => "Invalid Option",
      'max_length' => "Invalid Option"
    ));

    if($content['ad_country'] == "91"){
      $this->form_validation->set_rules("ad_mobile","Mobile Number","trim|required|xss_clean|exact_length[10]|integer",
      array(
        'required' => "Mobile number is required",
        'integer' => "Mobile number is invalid",
        'exact_length' => "Mobile number is invalid",
        "is_unique" => "Mobile number already exist"
      ));
    }else{
      $this->form_validation->set_rules("ad_mobile","Mobile Number","trim|required|xss_clean|min_length[7]|max_length[15]|integer",
      array(
        'required' => "Mobile number is required",
        'integer' => "Mobile number is invalid",
        'min_length' => "Mobile number is invalid",
        'max_length' => "Mobile number is invalid",
        "is_unique" => "Mobile number already exist"
      ));
    }

    if($content['ad_otp'] !== ''){
      $this->form_validation->set_rules("ad_otp","OTP","trim|required|xss_clean|exact_length[4]|integer",
      array(
        'required' => "OTP is required",
        'integer' => "OTP is invalid",
        'exact_length' => "OTP is invalid"
      ));
    }

    if($this->form_validation->run() == FALSE){
      $errors = $this->form_validation->error_array();
      echo json_encode($errors); exit;
    }else{
      if($content['ad_otp'] == ''){
        echo json_encode(array("status"=>"otp_missing")); exit;
      }else{
        $query = 'SELECT * FROM adv_otp WHERE mobile = "'.$content['ad_mobile'].'" ORDER BY createdDate desc LIMIT 1';
        $otp_rec = $this->Mdl_advertise->customQuery($query);
        if($otp_rec == "No Data"){
          echo json_encode(array("status"=>"otp_missing")); exit;
        }else if($otp_rec[0]->is_blocked == "1"){
          echo json_encode(array("status"=>"blocked")); exit;
        }else if($otp_rec[0]->otp !== $content['ad_otp']){
          $fail_count = $otp_rec[0]->count;
          $fail_count = $fail_count + 1;
          $block = '0';
          $block_time = date("Y-m-d H:i:s");

          if($fail_count > 3){
            $block = '1';
            $block_time = date("Y-m-d H:i:s",strtotime("+3 hours"));
          }

          $otp_data = array(
            "count" => $fail_count,
            "is_blocked" => $block,
            "block_till" => $block_time,
            "modifiedDate" => date("Y-m-d H:i:s")
          );

          $update = $this->Mdl_advertise->update("adv_otp", "id", $otp_rec[0]->id, $otp_data);

          if($block == '1'){
            echo json_encode(array("status"=>"blocked")); exit;
          }else{
            echo json_encode(array("ad_otp"=>"OTP does not match. Try again.")); exit;
          }
        }else if($otp_rec[0]->otp == $content['ad_otp']){
          $countryRec = $this->Mdl_advertise->getByValue("country", "phonecode", $content['ad_country']);
          if($countryRec !== "No Data"){
            $country = $countryRec[0]->countryName;
          }else{
            $country = "No Record";
          }

          $message_data = array(
            'company' => $content['company'],
            'name' => $content['name'],
            'email' => $content['email'],
            'country' => $country,
            "mobile" => $content['ad_mobile'],
            "createdDate" => date("Y-m-d H:i:s")
          );

          $insert = $this->Mdl_advertise->insert('advertise_enquiry',$message_data);

          $mail_data = array(
            "viewFile"=>'advertise/general-ack',
            "to"=>$content['email'],
            "cc" =>"",
            "bcc" =>"",
            "subject"=>"ADVERTISE ENQUIRY ACKNOWLEDGEMENT",
            "name" => $content['name']
          );
          
          $status_ack_mail = Modules::run('email/mailer', $mail_data);
    
          $mail_data_plex = array(
            "viewFile"=>'advertise/advertise-enquiry',
            "to"=>"office@plexconcil.org",
            "cc" =>"",
            "bcc" =>"",
            "subject"=>"ADVERTISE ENQUIRY",
            'name' => strip_tags($content['name']),
            'company' => strip_tags($content['company']),
            'email' => strip_tags($content['email']),
            'mobile' => strip_tags($content['ad_mobile']),
            'country' => $country
          );
          
          $status_ack_mail = Modules::run('email/mailer', $mail_data_plex);

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

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

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

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

  /*
  **  LIST OF ADVERTISE
  */
  function getAdvertise(){
    $list = $this->Mdl_advertise->get_datatables();
    $data = array();
    $no = $_POST['start']; 
    $admin = $this->session->userdata('admin');
    $arr = $admin['rights'];
    $rights = explode(',',$arr);

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

    $log =  insertTrackLog($admin_array);


    foreach ($list as $val) {
      $row = array();
      $url = base_url().'advertise/update/'.$val->id;
      if(in_array("18.3",$rights)){
        $row[] = '<a class="btn btn-block btn-rounded btn-outline-success" href="'.$url.'">UPDATE</a>';
      }else{
        $row[] = '';
      }
      
      if($admin['isAdmin'] !== '1'){
        $row[] = '<button class="btn btn-block btn-rounded btn-outline-danger" id="'.$val->id.'" onclick="callDeleteFunction(\'advertise\',\'id\',this.id,\'advertise\')">DELETE</button>';
      }else{
        $row[] = '';
      }

      $row[] = '<img src="'.base_url().$val->image.'" width="300" height="250">';
      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_advertise->count_all(),
      "recordsFiltered" => $this->Mdl_advertise->count_filtered(),
      "data" => $data,
    );

    echo json_encode($output);
  }

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

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

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

    $data['viewFile'] = "advertise/add-advertise";
    $data['scriptFile'] = "admin-advertise_v_1.0";
    $data['module'] = "advertise";
    $template = 'admin';
    return view('template/'.$template, $data);
  }

  /*
  ** ADD ADVERTISE ACTION
  */
  function addAdvertiseAction(){
     $content = $this->input->post();
     
    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/advertise/'.$imagename.'.'.$ext;
      if($img !== 1){
        echo json_encode(array("image"=>$img)); exit;
      }
    }else{
      echo json_encode(array("image"=>"Image is required")); exit;
    }

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

    $data = array(
      'image'=> strip_tags($imgpath),
      '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_advertise->insert("advertise", $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'] = 'Advertise';
    $admin_array['event_id'] = $insertId;
    $admin_array['userip'] = $this->input->ip_address();

    $log =  insertTrackLog($admin_array);

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

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

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

  /*
  ** UPDATE ADVERTISE ACTION
  */
  function updateAdvertiseAction(){
    $content = $this->input->post();
    
     $this->form_validation->set_rules("url","url","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 invalid.'
    ));

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

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

      $data = array(
        'url'=> strip_tags($content['url']),
        '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_advertise->update("advertise","id",$content['id'],$data);

      #track log
      $admin_array['userid'] = $admin['id'];
      $admin_array['usertype'] = 'admin';
      $admin_array['action_type'] = 'Update';
      $admin_array['modulename'] = 'Advertise';
      $admin_array['event_id'] = $content['id'];
      $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/advertise';
    $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;
    }
  }

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

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

  /*
  ** GET LIST
  */
  function getAdvertiseEnquiry(){
    $list = $this->Mdl_advertise->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'] = 'Enquiry';
    $admin_array['userip'] = $this->input->ip_address();
    $admin_array['logID'] = $admin['logID'];
    
    $log =  insertTrackLog($admin_array);

    $i = 1; 
    foreach ($list as $val) {
      $row = array();
      
      if($admin['isAdmin'] !== '1'){
        $row[] = '<button class="btn btn-block btn-rounded btn-outline-danger" id="'.$val->id.'" onclick="callDeleteFunction(\'advertise_enquiry\',\'id\',this.id,\'advertise-enquiry\')">DELETE</button>';
      }else{
        $row[] = '';
      }

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

    $output = array(
      "draw" => $_POST['draw'],
      "recordsTotal" => $this->Mdl_advertise->count_all_1(),
      "recordsFiltered" => $this->Mdl_advertise->count_filtered_1(),
      "data" => $data,
    );
    
    echo json_encode($output);
  }

  /* ============================================================== */
  /*                          SMS FUNCTION                          */
  /* ============================================================== */

  function sendSMS($isd,$mobile,$otp){
    $msg = 'Your OTP for mobile verification is '.$otp;
    $curl = curl_init();

    curl_setopt_array($curl, array(
      CURLOPT_URL => "http://api.msg91.com/api/v2/sendsms?country=$isd",
      CURLOPT_RETURNTRANSFER => true,
      CURLOPT_ENCODING => "",
      CURLOPT_MAXREDIRS => 10,
      CURLOPT_TIMEOUT => 30,
      CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
      CURLOPT_CUSTOMREQUEST => "POST",
      CURLOPT_POSTFIELDS => "{ \"sender\": \"TMPLEX\", \"route\": \"4\", \"country\": \"$isd\", \"sms\": [ { \"message\": \"$msg\", \"to\": [ \"$mobile\" ] } ] }",
      CURLOPT_SSL_VERIFYHOST => 0,
      CURLOPT_SSL_VERIFYPEER => 0,
      CURLOPT_HTTPHEADER => array(
        "authkey: 275881AvZ3IIFhKSE5cd4038f",
        "content-type: application/json"
      ),
    ));

    $response = curl_exec($curl);
    $err = curl_error($curl);

    curl_close($curl);

    if($err){
      return '1';
    }else{
      return $response;
    }
  }
}
