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



use App\Modules\generic\Models\Mdl_generic;

use App\Modules\Magazine\Models\Mdl_magazine;

use CodeIgniter\Controller;

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

 function index(){
    $statement = 'SELECT * FROM magazine WHERE status = "1" ORDER BY id desc';
    $result = $this->Mdl_magazine->customQuery($statement);
    $data['magazine'] = $result;
    $data['seo'] = $this->Mdl_magazine->getByValue("seo","page","home");
    $data['country'] = $this->Mdl_magazine->getAllRecords("country");
    $data['viewFile'] = "magazine/magazine";
    $data['scriptFile'] = "magazine";
    $data['module'] = "magazine";
    $data['captcha'] = "";
    $template = 'home';
    return view('template/'.$template, $data);
  }

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

    $template = 'admin';
    $data['scriptFile'] = 'admin-magazine_v_1.0';
    $data['viewFile'] = 'magazine/list-magazine';
    $data['module'] = 'magazine';
    return view('template/'.$template, $data);
  }
	
  function pdfmagazine()
  {
      // ORDER BY id desc
      $statement12 = 'SELECT * FROM magazine WHERE status = "1" ';
      //echo $statement;
    $result = $this->Mdl_magazine->customQuery($statement12);
    $data['magazine'] = $result;
    $data['seo'] = $this->Mdl_magazine->getByValue("seo","page","home");
    //filpmagazine 
    $data['viewFile'] = "magazine/magazine_flipbook_new";
    //$data['viewFile'] = "directdownloadmagazine";
    //$data['scriptFile'] = "magazine"; 
    $data['module'] = "magazine";
    $template = 'hometest';
    return view('template/'.$template, $data);
        //$this->load->view('magazine/magazine_flipbook');
    }

	/*
  **  GET LIST OF magazine
  */
  function getmagazine(){
    $list = $this->Mdl_magazine->get_datatables();
    //print_r($list);
    $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'] = 'Magzine';
    $admin_array['userip'] = $this->input->ip_address();
    $log =  insertTrackLog($admin_array);

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

      $row[] = $val->title;
	   $row[] = $val->url;
	   if($val->coverfilepath!='')
	   {
       $cover_url = base_url().$val->coverfilepath;
      $row[] = '<a class="btn btn-rounded btn-outline-info" target="_blank" href="'.$cover_url.'"><i class="fa fa-file-pdf-o" aria-hidden="true"> VIEW </i></a>';
	   }
	   else{
		
      $row[] = '';		   
	   }
      
     // $pdf_url = base_url().$val->filepath;
     // $row[] = '<a class="btn btn-rounded btn-outline-info" target="_blank" href="'.$pdf_url.'"><i class="fa fa-file-pdf-o" aria-hidden="true"> VIEW </i></a>';

			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_magazine->count_all(),
      "recordsFiltered" => $this->Mdl_magazine->count_filtered(),
      "data" => $data,
    );

    echo json_encode($output);
	}
	
  /*
  ** ADD NEW magazine
  */
  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("11.2",$rights)){
      redirect('admin/dashboard','refresh');
    }
    
    $data['viewFile'] = "magazine/add-magazine";
    $data['scriptFile'] = "admin-magazine_v_1.0";
    $data['module'] = "magazine";
    $template = 'admin';
    return view('template/'.$template, $data);
  }

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

    $this->form_validation->set_rules("title","Title","trim|required|xss_clean|max_length[100]",
    array(
      'required' => 'Title is required.','max_length' => 'Title is invalid.'
    )); 
	
	/*
	$this->form_validation->set_rules("url","Flipbook URL","trim|required|xss_clean|max_length[100]",
    array(
      'required' => 'Flipbook url is required.'
    ));  
  */
    if($this->form_validation->run() == FALSE){
      $errors = $this->form_validation->error_array();
      echo json_encode($errors);
    }else{
		 $imgpathcover='';
      if(!empty($_FILES['cover']['name'])){
        $filenamecover= $_FILES['cover']['name'];
        $extcover = pathinfo($filenamecover, PATHINFO_EXTENSION);
        $imagenamecover = strtotime('now');
        $imgcover = $this->uploadFileCover($imagenamecover,"cover");
        $imgpathcover = 'public/custom/files/magazine/cover/'.$imagenamecover.'.'.$extcover;
        if($imgcover !== 1){
          echo json_encode(array("cover"=>$imgcover)); exit;
        }
      } /*else{
        echo json_encode(array("cover"=>"Please upload file")); exit;
      } */
	  if(!empty($_FILES['pdf']['name'])){
        $filename = $_FILES['pdf']['name'];
        $ext = pathinfo($filename, PATHINFO_EXTENSION);
        $imagename = strtotime('now');
        $img = $this->uploadFile($imagename,"pdf");
        $imgpath = 'public/custom/files/magazine/'.$imagename.'.'.$ext;
        if($img !== 1){
          echo json_encode(array("pdf"=>$img)); exit;
        }
      }
      /*else{
        echo json_encode(array("pdf"=>"Please upload file")); exit;
      } */
      $admin_array['logID'] = $admin['logID'];
      $admin = $this->session->userdata('admin');

      $data = array(
        'title'=> strip_tags($content['title']),
		    //'url'=> strip_tags($content['url']),
        'coverfilepath'=> strip_tags($imgpathcover),
        '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_magazine->insert("magazine", $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'] = 'Magzine';
      $admin_array['event_id'] = $insertId;
      $admin_array['userip'] = $this->input->ip_address();
      $log =  insertTrackLog($admin_array);

      echo json_encode(array("status"=>"success")); exit;
    }
  }
  
  /*
  ** UPDATE magazine
  */
  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("11.3",$rights)){
      redirect('admin/dashboard','refresh');
    }

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

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

    $this->form_validation->set_rules("title","Title","trim|required|xss_clean|max_length[100]",
    array(
      'required' => 'Title is required.','max_length' => 'Title is invalid.'
    ));  
/*	$this->form_validation->set_rules("url","Flipbook URL","trim|required|xss_clean|max_length[100]",
    array(
      'required' => 'Flipbook url is required.'
    ));  */ 

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

    if($this->form_validation->run() == FALSE){
      $errors = $this->form_validation->error_array();
      echo json_encode($errors);
    }else{
		if(!empty($_FILES['cover']['name'])){
        if(file_exists('./'.$content['cover_path'])){
          $this->removeImage($content['cover_path']);
        }
        
        $filenamecover = $_FILES['cover']['name'];
        $extcover = pathinfo($filenamecover, PATHINFO_EXTENSION);
        $imagenamecover = strtotime('now');
        $imgcover = $this->uploadFileCover($imagenamecover,"cover");
        $imgpathcover = 'public/custom/files/magazine/cover/'.$imagenamecover.'.'.$extcover;
        if($imgcover !== 1){
          echo json_encode(array("cover"=>$imgcover)); exit;
        }
      }else{
        $imgpathcover = $content['cover_path'];
      }
		
		
		
      if(!empty($_FILES['pdf']['name'])){
        if(file_exists('./'.$content['pdf_path'])){
          $this->removeImage($content['pdf_path']);
        }
        
        $filename = $_FILES['pdf']['name'];
        $ext = pathinfo($filename, PATHINFO_EXTENSION);
        $imagename = strtotime('now');
        $img = $this->uploadFile($imagename,"pdf");
        $imgpath = 'public/custom/files/magazine/'.$imagename.'.'.$ext;
        if($img !== 1){
          echo json_encode(array("pdf"=>$img)); exit;
        }
      }else{
        $imgpath = $content['pdf_path'];
      }
      $admin_array['logID'] = $admin['logID'];
      $admin = $this->session->userdata('admin');

      $data = array(
        'title'=> strip_tags($content['title']),
		    //'url'=> strip_tags($content['url']),
        'filepath'=> strip_tags($imgpath),
		    'coverfilepath'=> strip_tags($imgpathcover),		
        'status'=> strip_tags($content['status']),
        'admin'=>Modules::run('admin/getAdminName',$admin['id']),
        'modifiedDate'=>date('Y-m-d H:i:s')
      );

      $insert = $this->Mdl_magazine->update("magazine", "id", $content['id'], $data);

      #track log
      $admin_array['userid'] = $admin['id'];
      $admin_array['usertype'] = 'admin';
      $admin_array['action_type'] = 'Update';
      $admin_array['modulename'] = 'Magzine';
      $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/files/magazine';
    $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;
    }
  }
  
  function uploadFileCover($imageNamecover,$keycover){
    $configcover['file_name'] = $imageNamecover;
    $configcover['upload_path'] = './public/custom/files/magazine/cover';
    $configcover['allowed_types'] = "JPEG|jpeg|png|PNG|jpg|JPG";
    $configcover['max_size']  = '5000';
    
    $this->load->library('upload',$configcover);
    $this->upload->initialize($configcover);
    if (!$this->upload->do_upload($keycover)){
      return $this->upload->display_errors();
    }else{
      return 1;
    }
  }
}
