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



use App\Modules\generic\Models\Mdl_generic;

use App\Modules\Articles\Models\Mdl_articles;

use CodeIgniter\Controller;

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

  function index(){
    $template = 'home';
		$data['country'] = $this->Mdl_articles->getAllRecords("country");
    $data['seo'] = $this->Mdl_articles->getByValue("seo","page","home");
    $statement = "SELECT DISTINCT month FROM articles ORDER BY articleDate DESC";
    $data['years'] = $this->Mdl_articles->customQuery($statement);
    //print_r($data['years']);die();
		$data['viewFile'] = 'articles/articles';
		$data['scriptFile'] = 'articles';
		$data['country'] = $this->Mdl_articles->getAllRecords("country");
		$data['module'] = "articles";
		$data['captcha'] = "";
		return view('template/'.$template, $data); 
  }  

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

    $statement = "SELECT * FROM articles WHERE status = '1' AND month = '$year' ORDER BY articleDate DESC";
    $articles = $this->Mdl_articles->customQuery($statement);
    //print_r($articles);die();
    if($articles == "No Data"){
      $html_resp = '<div class="row"></div>';
      return $html_resp;
      echo json_encode(array("status"=>"fail","year"=>$year)); exit;
    }else{
      //$html_resp = '<div class="row">';
      foreach($articles as $val){
        if($val->filepath == 'NA'){
          $imgurl = base_url().'public/custom/images/articles/default.jpg';
        }else{
          $imgurl = base_url().$val->filepath;
        }

        if($val->pdfpath == 'NA'){
          $pdfpath = base_url().'public/custom/images/articles/pdfimage.png';
        }else{
          $pdfpath = base_url().$val->pdfpath;
        }
        $html_resp .= '<div class="rounded mb-4 border">
                        <div class="p-3">
                          <div class="row">
                            <div class="col-sm-4">
                              <a href="'.$pdfpath.'" target="_blank">
                                <img src="'.$imgurl.'" class="img-fluid rounded" >
                              </a>
                            </div>
                            <div class="col-sm-8">
                              <h5>'.$val->name.'</h5>
                              <table>
                                <tbody>
                                  <tr>
                                    <td><p class="text-uppercase">Date</p></td>
                                    <td class="pl-3 pr-3">:</td>
                                    <td><p class="text-uppercase">'.date('d-m-Y', strtotime($val->articleDate)).'</p></td>
                                  </tr>
                                  <tr>
                                    <td><p class="text-uppercase">Description</p></td>
                                    <td class="pl-3 pr-3">:</td>
                                    <td><p>'.$val->description.'</p></td>
                                  </tr>
                                  <tr>
                                    <td colspan="3">
                                      <a href="'.$pdfpath.'" target="_blank" class="rounded btn grayGradientBg whiteColor">
                                        <strong>Read More</strong>
                                      </a>
                                    </td>
                                  </tr>
                                  
                                </tbody>
                              </table>
                            </div>
                          </div>
                        </div>
                      </div>';
        //$html_resp .= 'Te';
      }
     // $html_resp .= '</div>';
    //return $html_resp;
      echo json_encode(array("status"=>"success","response"=>$html_resp,"year"=>$year)); exit;
    }
  }

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

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

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

  /*
  **  LIST OF ARTICLES
  */
  function getArticles(){
    $list = $this->Mdl_articles->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'] = 'Articles';
    $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().'articles/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(\'articles\',\'id\',this.id,\'articles\')">DELETE</button>';
      }else{
        $row[] = '';
      }

      $row[] = date("d M Y",strtotime($val->articleDate));
      $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_articles->count_all_1(),
      "recordsFiltered" => $this->Mdl_articles->count_filtered_1(),
      "data" => $data,
    );

    echo json_encode($output);
  }

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

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

    if(! in_array("21.2",$rights)){
      redirect('admin/dashboard','refresh');
    }
    
    $data['viewFile'] = "articles/add-articles";
    $data['scriptFile'] = "admin-articles_v_1.0";
    $data['module'] = "articles";
    $template = 'admin';
    return view('template/'.$template, $data);
  }

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

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

    $this->form_validation->set_rules("description","Description","trim|required|xss_clean|max_length[255]",
    array(
      'required' => 'Description is required.',
      'max_length' => 'Description is invalid.'
    ));

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

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

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

      #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/articles/pdf/'.$pdfimagename.'.'.$pdfext;
        if($pdf !== 1){
          echo json_encode(array("pdfimage"=>$pdf)); exit;
        }
      }else{
        $pdfpath = "NA";
      }
      
      $admin = $this->session->userdata('admin');

      $data = array(
        'name' => strip_tags($content['name']),
        'description' => strip_tags($content['description']),
        'articleDate' => date("Y-m-d",strtotime($content['article_date'])),
        'month' => date("M Y",strtotime($content['article_date'])),
        'filepath'=> strip_tags($imgpath),
        'pdfpath'=> strip_tags($pdfpath),
        '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_articles->insert("articles", $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'] = 'Articles';
        $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 ARTICLES
  */
  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("21.3",$rights)){
      redirect('admin/dashboard','refresh');
    }

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

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

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

    $this->form_validation->set_rules("description","Description","trim|required|xss_clean|max_length[255]",
    array(
      'required' => 'Description is required.',
      'max_length' => 'Description is invalid.'
    ));

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

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

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

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

      #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/articles/pdf/'.$pdfimagename.'.'.$pdfext;
        if($pdf !== 1){
          echo json_encode(array("pdfimage"=>$pdf)); exit;
        }
      }else{
        $pdfpath = $content['pdfpath'];
      }

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

      $data = array(
        'name' => strip_tags($content['name']),
        'description' => strip_tags($content['description']),
        'articleDate' => date("Y-m-d",strtotime($content['article_date'])),
        'month' => date("M Y",strtotime($content['article_date'])),
        'filepath'=> strip_tags($imgpath),
        'pdfpath'=> strip_tags($pdfpath),
        'status' => strip_tags($content['status']),
        'admin'=> Modules::run('admin/getAdminName',$admin['id']),
        'modifiedDate' =>date('Y-m-d H:i:s')
      );
        
        $update = $this->Mdl_articles->update("articles", "id", $content['id'], $data);
      
      #track log
      $admin_array['userid'] = $admin['id'];
      $admin_array['usertype'] = 'admin';
      $admin_array['action_type'] = 'Update';
      $admin_array['modulename'] = 'Articles';
      $admin_array['userip'] = $this->input->ip_address();
      $admin_array['logID'] = $admin['logID'];

      $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/articles';
    $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 uploadPDF($imageName,$key){
    $config['file_name'] = $imageName;
    $config['upload_path'] = './public/custom/images/articles/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;
    }
  }

}
