<?php
$loader = $this->registry->get('load');
$loader->controller('common/upload');

class ControllerCommonPdfManager extends ControllerCommonUpload
{
  public function __construct($registry)
  {
    parent::__construct($registry);

    $this->setPathFile(DIR_DOWNLOAD);

    $this->setPathValidate('common/filemanager');

    $this->setAllowed($this->allowedPdf);

    $this->setAllowedExt($this->allowedPdfExt);

    $this->setFolder('download');

    $this->setLinkFile($this->urlloja->link('', '', 'SSL', false) . 'download/pdf/');
  }

  public function upload()
  {
    $this->language->load('common/filemanager');

    $json = array();
    $size = 50000000; // 50MB
    $error_size = $this->language->get('error_file_size_pdf');
    
    if (isset($this->request->post['size'])) {
      $size = $this->request->post['size'];
      $error_size = $this->language->get('error_file_size_bigger_pdf');
    }

    if (isset($this->request->post['directory'])) {
      if (isset($this->request->files['file']) && $this->request->files['file']['tmp_name']) {
        $filename = basename(html_entity_decode(preg_replace(['/[^A-Za-z0-9 _ .-]/', '/ /i'], ['', '_'], $this->request->files['file']['name']), ENT_QUOTES, 'UTF-8'));

        if ((strlen($filename) < 3) || (strlen($filename) > 255)) {
          $json['error'] = $this->language->get('error_filename');
        }

        $directory = rtrim(DIR_DOWNLOAD . 'pdf/' . str_replace('../', '', $this->request->post['directory']));

        if (!is_dir($directory)) {
          $json['error'] = $this->language->get('error_directory');
        }

        if ($this->request->files['file']['size'] > $size) {
          $json['error'] = $error_size;
        }

        if ($this->request->files['file']['type'] !== 'application/pdf') {
          $json['error'] = $this->language->get('error_file_type');
        }

        if (strtolower(strrchr($filename, '.')) !== '.pdf') {
          $json['error'] = $this->language->get('error_file_type');
        }

        if ($this->request->files['file']['error'] != UPLOAD_ERR_OK) {
          $json['error'] = 'error_upload_' . $this->request->files['file']['error'];
        }
      } else {
        $json['error'] = $this->language->get('error_file');
      }
    } else {
      $json['error'] = $this->language->get('error_directory');
    }

    if (!$this->user->hasPermission('modify', $this->getPathValidate())) {
      $json['error'] = $this->language->get('error_permission');
    }

    if (!isset($json['error'])) {
      if (@move_uploaded_file($this->request->files['file']['tmp_name'], $directory . '/' . $filename)) {
        $json['success'] = $this->language->get('text_uploaded');
      } else {
        $json['error'] = $this->language->get('error_uploaded');
      }
    }

    $this->response->setOutput(json_encode($json));
  }
}