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



use App\Modules\generic\Models\Mdl_generic;

use App\Modules\Bsm\Models\Mdl_bsm;

use CodeIgniter\Controller;

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

  function index(){

    $template = 'home';

		$data['country'] = $this->Mdl_bsm->getAllRecords("country");

    $data['seo'] = $this->Mdl_bsm->getByValue("seo","page","home");

    $query_1 = "SELECT DISTINCT year FROM bsm WHERE type = 'bsm' ORDER BY year DESC";

    $data['bsm_year'] = $this->Mdl_bsm->customQuery($query_1);



    $query_2 = "SELECT DISTINCT year FROM bsm WHERE type = 'rbsm' ORDER BY year DESC";

    $data['rbsm_year'] = $this->Mdl_bsm->customQuery($query_2);



		$data['viewFile'] = 'bsm/bsm';

		$data['scriptFile'] = 'bsm';

		$data['module'] = "bsm";

		return view('template/'.$template, $data); 

  }  



  function getBsmData($year){
      

    $statement = "SELECT * FROM bsm WHERE status = '1' AND type = 'bsm' AND year = '$year'  ORDER BY createdDate desc";

    $rbsm = $this->Mdl_bsm->customQuery($statement);



    if($rbsm == "No Data"){

      return '';

    }else{

      $html_resp = '';

      foreach($rbsm as $val){

        if($val->filepath == 'NA'  || $val->filepath == ''){
          $imgurl = base_url().'public/custom/images/bsm/default.jpg';
        }else{
          $imgurl = base_url().$val->filepath;
        }
        
        /*
        if($val->filepath_forpdf == 'NA'  || $val->filepath_forpdf == ''){
          $readmorepdf = '';
        }else{
          $readmorepdf = base_url().$val->filepath_forpdf;
        }
        */
        //$html_resp .= '<p>'.$val->name.'</p>';
        
        
         $html_resp .= '<div class="rounded mb-4 border">
        <div class="p-3">
          <div class="row">
            <div class="col-sm-4"><img src="'.$imgurl.'" width=200px;></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") || ($val->from_date == "0000-00-00" || $val->to_date == "0000-00-00"))
                  {
                    $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>';
                  }
                  if($val->filepath_forpdf != '')
                  { 
                      $html_resp .=  '</tr><tr><td><p><a href="'.$val->filepath_forpdf.'" class="btn grayGradientBg whiteColor" target="_blank"><strong>Read More >> </strong></a></p></td>';
                  }
                      // $html_resp .=  '</tr><tr><td><p><a href="'.$readmorepdf.'" class="btn grayGradientBg whiteColor" target="_blank"><strong>Read More >> </strong></a></p></td>';
                
                  $html_resp .= '</tr>
              </table>
             </div>
          </div>
        </div>
      </div>';
    
      }



      return $html_resp;

    }

  }



  function getRbsmData($year){

    $statement = "SELECT * FROM bsm WHERE status = '1' AND type = 'rbsm' AND year = '$year' ORDER BY createdDate desc";

    $rbsm = $this->Mdl_bsm->customQuery($statement);



    if($rbsm == "No Data"){

      return '';

    }else{

      $html_resp = '';

      foreach($rbsm as $val){

        if($val->filepath == 'NA'  || $val->filepath == ''){
          $imgurl = base_url().'public/custom/images/bsm/default.jpg';
        }else{
          $imgurl = base_url().$val->filepath;
        }
        /* 
        if($val->filepath_forpdf == 'NA'  || $val->filepath_forpdf == ''){
          $readmorepdf = '';
        }else{
          $readmorepdf = base_url().$val->filepath_forpdf;
        }
       */
       
        //$html_resp .= '<p>'.$val->name.'</p>';
        
          $html_resp .= '<div class="rounded mb-4 border">
        <div class="p-3">
          <div class="row">
            <div class="col-sm-4"><img src="'.$imgurl.'" width=200px></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") || ($val->from_date == "0000-00-00" || $val->to_date == "0000-00-00"))
                  {
                    $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>';
                  }
                  if($val->filepath_forpdf != '')
                  {
                      $html_resp .=  '</tr><tr><td><p><a href="'.$val->filepath_forpdf.'" class="btn grayGradientBg whiteColor" target="_blank"><strong>Read More >> </strong></a></p></td>';
                  }
                  //  $html_resp .=  '</tr><tr><td><p><a href="'.$readmorepdf.'" class="btn grayGradientBg whiteColor" target="_blank"><strong>Read More >> </strong></a></p></td>';
                  $html_resp .= '</tr>
              </table>
             </div>
          </div>
        </div>
      </div>';

      }



      return $html_resp;

    }

  }



  /**********************************************************************/

  /*                            ADMIN MODULES                           */

  /**********************************************************************/



  /*

  ** BSM 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("22.1",$rights)){

      redirect('admin/dashboard','refresh');

    }



    $template = 'admin';

    $data['scriptFile'] = 'admin-bsm_v_1.0';

    $data['viewFile'] = 'bsm/list-bsm';

    $data['module'] = "bsm";

    return view('template/'.$template, $data);

  }



  /*

  **  LIST OF BSM

  */

  function getBsm(){

    $list = $this->Mdl_bsm->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'] = 'BSM';
    $admin_array['userip'] = $this->input->ip_address();
    $admin_array['logID'] = $admin['logID'];

    $log =  insertTrackLog($admin_array);

    $i = 1;

    foreach ($list as $val) {

      $row = array();

      $url = base_url().'bsm/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(\'bsm\',\'id\',this.id,\'bsm\')">DELETE</button>';

      }else{

        $row[] = '';

      }



      $row[] = strtoupper($val->type);

      $row[] = $val->year;

      $row[] = strtoupper($val->name);
      
   //   $row[] = ($val->filepath_forpdf);
      

      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_bsm->count_all_1(),

      "recordsFiltered" => $this->Mdl_bsm->count_filtered_1(),

      "data" => $data,

    );



    echo json_encode($output);

  }



  /*

  ** ADD BSM

  */

  function add(){

    if(!Modules::run('security/isAdmin')){

      redirect('admin','refresh');

    }



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

    $arr = $admin['rights'];

    $rights = explode(',',$arr);



    if(! in_array("22.2",$rights)){

      redirect('admin/dashboard','refresh');

    }

    

    $data['years_master'] = $this->Mdl_bsm->getByValue("years_master","status","1");

    $data['viewFile'] = "add-bsm";

    $data['scriptFile'] = "admin-bsm_v_1.0";

    $data['module'] = "bsm";

    $template = 'admin';

    return view('template/'.$template, $data);

  }



  /*

  ** ADD BSM ACTION

  */

  function addBsmAction(){

    $content = $this->input->post();



    $this->form_validation->set_rules("type","Type","trim|required|xss_clean|max_length[100]",

    array(

      'required' => 'Type is required.',
      'max_length' => 'Type is invalid.'

    ));



    $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("from_date","Start Date","trim|xss_clean|max_length[100]");

    $this->form_validation->set_rules("to_date","End Date","trim|xss_clean|max_length[100]");

    $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("filepath_forpdf","Link","trim|required|xss_clean|max_length[100]");

    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/bsm/'.$imagename.'.'.$ext;
        if($img !== 1){
          echo json_encode(array("image"=>$img)); exit;
        }
      }else{
        $imgpath = "NA";
      }
    
    /*          
      if(!empty($_FILES['file']['name'])){
        $filename = $_FILES['file']['name'];
        $ext = pathinfo($filename, PATHINFO_EXTENSION);
        $imagename = strtotime('now');
        $img = $this->uploadFileForPDF($imagename,"file");
        $readmorepath = 'public/custom/files/bsm/'.$imagename.'.'.$ext;
        if($img !== 1){
          echo json_encode(array("file"=>$img)); exit;
        }
      }
    */


      $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(

        'type' => strip_tags($content['type']),

        'year' => strip_tags($content['year']),

        'name' => strip_tags($content['name']),

        'from_date' => $from_date,
        
        'to_date' => $to_date,
        
        'filepath'=> strip_tags($imgpath),
        
        'filepath_forpdf' => strip_tags($content['filepath_forpdf']),
        
        '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_bsm->insert("bsm", $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'] = 'BSM';
    $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 BSM

  */

  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("22.3",$rights)){

      redirect('admin/dashboard','refresh');

    }



    $result = $this->Mdl_bsm->getByValue("bsm","id",$id);

    if($result == "No Data"){

      redirect('errors','refresh');

    }else{

      $data['years_master'] = $this->Mdl_bsm->getByValue("years_master","status","1");

      $data['bsm'] = $result;

      $data['viewFile'] = "bsm/update-bsm";

      $data['scriptFile'] = "admin-bsm_v_1.0";

      $data['module'] = "bsm";

      $template = 'admin';

      return view('template/'.$template, $data);

    }

  }



  /*

  ** UPDATE BSM ACTION

  */

  function updateBsmAction(){

    $content = $this->input->post();



    $this->form_validation->set_rules("type","Type","trim|required|xss_clean|max_length[100]",

    array(

      'required' => 'Type is required.',
      'max_length' => 'Type is invalid.'

    ));



    $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|max_length[100]");

    $this->form_validation->set_rules("to_date","End Date","trim|xss_clean|max_length[100]");


    $this->form_validation->set_rules("status","Status","trim|xss_clean|max_length[100]|required",

    array(

      'required' => 'Please select status.',
      'max_length' => 'status is invalid.'

    ));

    //$this->form_validation->set_rules("filepath_forpdf","Link","trim|required|xss_clean|max_length[100]");

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

        
        /*
         if(!empty($_FILES['file']['name'])){
        if(file_exists('./'.$content['pdf_path'])){
          $this->removeImage($content['pdf_path']);
        }
        
        $filename = $_FILES['file']['name'];
        $ext = pathinfo($filename, PATHINFO_EXTENSION);
        $imagename = strtotime('now');
        $img = $this->uploadFileForPDF($imagename,"file");
        $readmorepath = 'public/custom/files/bsm/'.$imagename.'.'.$ext;
        if($img !== 1){
          echo json_encode(array("pdf"=>$img)); exit;
        }
      }else{
        $readmorepath = $content['pdf_path'];
      }
      */

      $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(

        'type' => strip_tags($content['type']),

        'year' => strip_tags($content['year']),

        'name' => strip_tags($content['name']),

        'from_date' => $from_date,
        
        'to_date' => $to_date,
        
        'filepath'=> strip_tags($imgpath),
        
        'filepath_forpdf' => strip_tags($content['filepath_forpdf']),
        
        'status' => strip_tags($content['status']),

        'admin'=> Modules::run('admin/getAdminName',$admin['id']),

        'modifiedDate' =>date('Y-m-d H:i:s')

      );



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

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

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

    }

  }
  
   function uploadFile($imageName,$key){
    $config['file_name'] = $imageName;
    $config['upload_path'] = './public/custom/images/bsm';
    $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 file_check($str){
    $allowed_mime_type_arr = array('pdf');
    if(isset($_FILES['file']['name']) && $_FILES['file']['name']!=""){
      $filename = $_FILES['file']['name'];
      $ext = pathinfo($filename, PATHINFO_EXTENSION);
      if(in_array($ext, $allowed_mime_type_arr)){
        return true;
      }else{
        $this->form_validation->set_message('file_check', 'Please select only pdf file.');
        return false;
      }
    }else{
      $this->form_validation->set_message('file_check', 'Please choose a file to upload.');
      return false;
    }
  }
  
  function uploadFileForPDF($imageName,$key){
    $config['file_name'] = $imageName;
    $config['upload_path'] = './public/custom/files/bsm';
    $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;
    }
  }
	

}
