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



use App\Modules\generic\Models\Mdl_generic;

use App\Modules\Pressreleases\Models\Mdl_Pressreleases;

use CodeIgniter\Controller;

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

  function index(){
    $template = 'home';
	  $statement = "SELECT DISTINCT month FROM pressreleases ORDER BY pressreleaseDate DESC";
    $data['years'] = $this->Mdl_Pressreleases->customQuery($statement);
    
    $data['viewFile'] = 'pressreleases/pressreleases';
		$data['scriptFile'] = 'pressreleases';
		$data['country'] = $this->Mdl_Pressreleases->getAllRecords("country");
		$data['module'] = "pressreleases";
		$data['captcha'] = "";
		return view('template/'.$template, $data); 
  }  

  function getPressReleaseData($year = ''){
    $content = $this->input->post();
    $year = $content['year'];
    $statement = "SELECT * FROM pressreleases where status = '1' AND month = '$year' ORDER BY pressreleaseDate DESC";
    $pressreleases = $this->Mdl_Pressreleases->customQuery($statement);

    if($pressreleases == "No Data"){
      $html_resp = '<div class="col-12 statistics"></div>';
      return $html_resp;
      echo json_encode(array("status"=>"fail","year"=>$year)); exit;
    }else{
      $html_resp = '<div class="col-12 statistics">';
      foreach($pressreleases as $val){
        if($val->pdfpath == 'NA'){
          $pdfpath = base_url().'public/custom/images/pressreleases/pdfimage.png';
        }else{
          $pdfpath = base_url().$val->pdfpath;
        }

        $html_resp .= '<ul class="row">
                        <li class="col-lg-12" style="padding:0">
                        <a href="'.$pdfpath.'" target="_blank" class="rounded">
                          '.$val->name.' <br>
                        <strong>'.date('d M Y', strtotime($val->pressreleaseDate)).'</strong>
                        </a>
                        </li>
                      </ul>';
      }

      $html_resp .= '</div>';
      //echo  $html_resp;
      echo json_encode(array("status"=>"success","response"=>$html_resp,"year"=>$year)); exit;
    }
  }

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

  /*
  ** ARTICLES LISTING PAGE
  */
  function viewall(){
    //var_dump(Modules::run('security/isAdmin'));
    //echo "<pre>". print_r((array)$this->session, true) ."</pre>";
    //die();
    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("25.1",$rights)){
      redirect('admin/dashboard','refresh');
    }
    
    $template = 'admin';
    $data['scriptFile'] = 'admin-pressreleases_v_1.0';
    $data['viewFile'] = 'pressreleases/list-pressreleases';
    $data['module'] = "pressreleases";
    return view('template/'.$template, $data);
  }

  /*
  **  LIST OF ARTICLES
  */
  function getPressRelease(){
    $list = $this->Mdl_Pressreleases->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'] = 'Press Release';
    $admin_array['userip'] = $this->input->ip_address();

    $log =  insertTrackLog($admin_array);


    $i = 1;
    foreach ($list as $val) {
      $row = array();
      $url = base_url().'press-releases/update/'.$val->pressreleasesid;
      $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->pressreleasesid.'" onclick="callDeleteFunction(\'press-releases\',\'id\',this.id,\'press-releases\')">DELETE</button>';
      }else{
        $row[] = '';
      }
      $row[] = date("d M Y",strtotime($val->pressreleaseDate));
      $row[] = strtoupper($val->name);
      
      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_Pressreleases->count_all_1(),
      "recordsFiltered" => $this->Mdl_Pressreleases->count_filtered_1(),
      "data" => $data,
    );

    echo json_encode($output);
  }

  /*
  ** ADD ARTICLES
  */
  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("25.2",$rights)){
      redirect('admin/dashboard','refresh');
    }
    
    $data['scriptFile'] = 'admin-pressreleases_v_1.0';
    $data['viewFile'] = 'pressreleases/add-pressreleases';
    $data['module'] = "pressreleases";
    $template = 'admin';
    return view('template/'.$template, $data);
  }

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

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

    $this->form_validation->set_rules("pressrelease_date","Press Releases Date","trim|required|xss_clean|max_length[100]",
    array(
      'required' => 'Press Releases Date is required.','max_length' => 'Press Release Date is invalid.'
    ));

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

      #upload pdf
      if(!empty($_FILES['pdfimage']['name'])){
        $pdffilename = $_FILES['pdfimage']['name'];
        $pdfext = pathinfo($pdffilename, PATHINFO_EXTENSION);
        $pdfimagename = strtotime('now');
        $pdf = $this->uploadPDF($pdfimagename,"pdfimage");
        $pdfpath = 'public/custom/images/pressreleases/pdf/'.$pdfimagename.'.'.$pdfext;
        if($pdf !== 1){
          echo json_encode(array("pdfimage"=>$pdf)); exit;
        }
      }else{
        $pdfpath = "NA";
      }

      $admin_array['logID'] = $admin['logID'];
      $admin = $this->session->userdata('admin');

      $data = array(
        'name' => strip_tags($content['name']),
        'pdfpath'=> strip_tags($pdfpath),
        'status' => '1',
        'pressreleaseDate' => date("Y-m-d",strtotime($content['pressrelease_date'])),
        'month' => date("M Y",strtotime($content['pressrelease_date'])),
        '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_Pressreleases->insert("pressreleases", $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'] = 'Press Release';
      $admin_array['event_id'] = $insertId;
      $admin_array['userip'] = $this->input->ip_address();

      $log =  insertTrackLog($admin_array);

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

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

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

  /*
  ** UPDATE ARTICLES ACTION
  */
  function updatePressReleaseAction(){
    $content = $this->input->post();
    
    $this->form_validation->set_rules("name","Name","trim|required|xss_clean|max_length[255]",
    array(
      'required' => 'Press Release Title is required.','max_length' => 'Press Release Title is invalid.'
    ));

    $this->form_validation->set_rules("pressrelease_date","Press Releases Date","trim|required|xss_clean|max_length[100]",
    array(
      'required' => 'Press Releases Date is required.','max_length' => 'Press Release Date is invalid.'
    ));
    
    if($this->form_validation->run() == FALSE){
      $errors = $this->form_validation->error_array();
      echo json_encode($errors); exit;
    }else{

      #upload pdf
      if(!empty($_FILES['pdfimage']['name'])){

        if($content['pdfpath'] !== 'NA' && file_exists('./'.$content['pdfpath'])){
          $this->removeImage($content['pdfpath']);
        }
        $pdffilename = $_FILES['pdfimage']['name'];
        $pdfext = pathinfo($pdffilename, PATHINFO_EXTENSION);
        $pdfimagename = strtotime('now');
        $pdf = $this->uploadPDF($pdfimagename,"pdfimage");
        $pdfpath = 'public/custom/images/pressreleases/pdf/'.$pdfimagename.'.'.$pdfext;
        if($pdf !== 1){
          echo json_encode(array("pdfimage"=>$pdf)); exit;
        }
      }else{
        $pdfpath = $content['pdfpath'];
      }

      $admin_array['logID'] = $admin['logID'];
      $admin = $this->session->userdata('admin');

      $data = array(
        'name' => strip_tags($content['name']),
        'pdfpath'=> strip_tags($pdfpath),
        'pressreleaseDate' => date("Y-m-d",strtotime($content['pressrelease_date'])),
        'month' => date("M Y",strtotime($content['pressrelease_date'])),
        'admin'=> Modules::run('admin/getAdminName',$admin['id']),
        'modifiedDate' => date('Y-m-d H:i:s')
      );
      
      $update = $this->Mdl_Pressreleases->update("pressreleases", "pressreleasesid", $content['id'],$data);

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

      $log =  insertTrackLog($admin_array);


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

  /*
  **  FILE UPLOAD
  */
  function uploadPDF($imageName,$key){
    $config['file_name'] = $imageName;
    $config['upload_path'] = './public/custom/images/pressreleases/pdf';
    $config['allowed_types'] = "pdf";
    $config['max_size']  = '5048';
    //$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;
    }
  }

}
