<?php

class ControllerSpecific4861ModuleMaterial extends Controller
{

  private $error = array();

  public function index()
  {
    $language = $this->language->load('specific/' . PREFIX_NAME . '/module/material');
    $this->data = array_merge($this->data, $language);

    $this->document->addScript(array(
      'view/javascript/page.material.js'
    ));


    $this->document->setTitle($this->language->get('heading_title'));

    $this->getList();
  }


  public function insert()
  {
    $this->language->load('specific/' . PREFIX_NAME . '/module/material');

    $this->document->setTitle($this->language->get('heading_title'));

    if (($this->request->server['REQUEST_METHOD'] == 'POST') && $this->validateForm()) {
      $this->load->dmodel('specific/' . PREFIX_NAME . '/material/apoio');
      $this->{'dmodel_specific_' . PREFIX_NAME . '_material_apoio'}->addMaterial($this->request->post);

      $this->session->data['success'] = $this->language->get('text_success');

      $url = $this->getLinkUrl();

      $this->redirect($this->url->link('specific/' . PREFIX_NAME . '/module/material', 'token=' . $this->session->data['token'] . $url, 'SSL'));
    }

    $this->getForm();
  }

  public function update()
  {
    $this->language->load('specific/' . PREFIX_NAME . '/module/material');

    $this->document->setTitle($this->language->get('heading_title'));


    if (($this->request->server['REQUEST_METHOD'] == 'POST') && $this->validateForm()) {
      $this->load->dmodel('specific/' . PREFIX_NAME . '/material/apoio');
      $this->{'dmodel_specific_' . PREFIX_NAME . '_material_apoio'}->editMaterial($this->request->get['material_id'], $this->request->post);

      $this->session->data['success'] = $this->language->get('text_success');

      $url = $this->getLinkUrl();

      $this->redirect($this->url->link('specific/' . PREFIX_NAME . '/module/material', 'token=' . $this->session->data['token'] . $url, 'SSL'));
    }

    $this->getForm();
  }

  public function delete()
  {
    $this->language->load('specific/' . PREFIX_NAME . '/module/material');

    $this->document->setTitle($this->language->get('heading_title'));

    $this->load->dmodel('specific/' . PREFIX_NAME . '/material/apoio');

    if (isset($this->request->post['selected'])) {
      foreach ($this->request->post['selected'] as $material_id) {
        $this->{'dmodel_specific_' . PREFIX_NAME . '_material_apoio'}->deleteMaterial($material_id);
      }

      $this->session->data['success'] = $this->language->get('text_delete_success');

      $url = $this->getLinkUrl();

      $this->redirect($this->url->link('specific/' . PREFIX_NAME . '/module/material', 'token=' . $this->session->data['token'] . $url, 'SSL'));
    }

    $this->getList();
  }

  public function getLinkUrl($remove = array())
  {
    $url = '';

    foreach ($remove as $key => $value) {
      unset($this->request->get[$value]);
    }

    if (isset($this->request->get['page'])) {
      $url .= '&page=' . $this->request->get['page'];
    }

    return $url;

  }

  public function getList()
  {

    $url = $this->getLinkUrl();

    $this->data['breadcrumbs'] = array();

    $this->data['breadcrumbs'][] = array(
      'text' => $this->language->get('text_home'),
      'href' => $this->url->link('common/home', 'token=' . $this->session->data['token'], 'SSL'),
      'separator' => false
    );

    $this->data['breadcrumbs'][] = array(
      'text' => $this->language->get('heading_title'),
      'href' => $this->url->link('specific/' . PREFIX_NAME . '/module/material', 'token=' . $this->session->data['token'] . $url, 'SSL'),
      'separator' => ' :: '
    );

    $this->data['insert'] = $this->url->link('specific/' . PREFIX_NAME . '/module/material/insert', 'token=' . $this->session->data['token'] . $url, 'SSL');
    $this->data['delete'] = $this->url->link('specific/' . PREFIX_NAME . '/module/material/delete', 'token=' . $this->session->data['token'] . $url, 'SSL');

    if (isset($this->request->get['order'])) {
      $order = $this->request->get['order'];
    } else {
      $order = 'DESC';
    }

    if (isset($this->request->get['page'])) {
      $page = $this->request->get['page'];
    } else {
      $page = 1;
    }

    $data = array(
      'order' => $order,
      'start' => ($page - 1) * $this->config->get('config_admin_limit'),
      'limit' => $this->config->get('config_admin_limit')
    );

    $this->load->dmodel('specific/' . PREFIX_NAME . '/material/apoio');
    $material_total = $this->{'dmodel_specific_' . PREFIX_NAME . '_material_apoio'}->getTotalMaterials($data);
    $results = $this->{'dmodel_specific_' . PREFIX_NAME . '_material_apoio'}->getMaterials($data);

    $materials = array();

    if ($results) {

      $this->load->dmodel('tool/image');
      $this->load->library('image_validate');
      $image_validate = new Image_validate();

      foreach ($results as $result) {

        if ($result['image'] && file_exists(DIR_IMAGE . $result['image']) && $image_validate->isValidate($result, true)) {
          $image = $this->dmodel_tool_image->resize($result['image'], 40, 40);
        } else {
          $image = $this->dmodel_tool_image->resize('no_image.jpg', 40, 40);
        }

        $materials[] = array(
          'material_id' => $result['material_id'],
          'titulo' => $result['titulo'],
          'image' => $image,
          'status' => Type_Status::getNickFromValue($result['status']),
          'href' => $this->url->link('specific/' . PREFIX_NAME . '/module/material/update', 'token=' . $this->session->data['token'] . '&material_id=' . $result['material_id'], 'SSL')
        );
      }

    }

    $this->data['materials'] = $materials;

    $url = $this->getLinkUrl(['page']);

    $pagination = new Pagination();
    $pagination->total = $material_total;
    $pagination->page = $page;
    $pagination->limit = $this->config->get('config_admin_limit');
    $pagination->text = $this->language->get('text_pagination');
    $pagination->url = $this->url->link('specific/' . PREFIX_NAME . '/module/material', 'token=' . $this->session->data['token'] . $url . '&page={page}', 'SSL');

    $this->data['pagination'] = $pagination->render();

    if (isset($this->error['warning'])) {
      $this->data['error_warning'] = $this->error['warning'];
    } else {
      $this->data['error_warning'] = '';
    }

    if (isset($this->session->data['success'])) {
      $this->data['success'] = $this->session->data['success'];

      unset($this->session->data['success']);
    } else {
      $this->data['success'] = '';
    }

    $this->children = array(
      'common/header',
      'common/footer'
    );

    $this->response->setOutput($this->render('module/material_list'));

  }

  public function getForm()
  {

    $this->load->dmodel('specific/' . PREFIX_NAME . '/material/apoio');

    $this->load->dmodel('tool/image');
    $this->load->dmodel('tool/files');
    $this->load->library('image_validate');
    $image_validate = new Image_validate();

    $this->document->addScript(array(
      'view/javascript/page.material.js'
    ));

    $url = $this->getLinkUrl();

    $this->data['breadcrumbs'] = array();

    $this->data['breadcrumbs'][] = array(
      'text' => $this->language->get('text_home'),
      'href' => $this->url->link('common/home', 'token=' . $this->session->data['token'], 'SSL'),
      'separator' => false
    );

    $this->data['breadcrumbs'][] = array(
      'text' => $this->language->get('heading_title'),
      'href' => $this->url->link('specific/' . PREFIX_NAME . '/module/material', 'token=' . $this->session->data['token'] . $url, 'SSL'),
      'separator' => ' :: '
    );

    $language = $this->language->load('specific/' . PREFIX_NAME . '/module/material');
    $this->data = array_merge($this->data, $language);


    if (!isset($this->request->get['material_id'])) {
      $this->data['action'] = $this->url->link('specific/' . PREFIX_NAME . '/module/material/insert', 'token=' . $this->session->data['token'] . $url, 'SSL');
    } else {
      $this->data['action'] = $this->url->link('specific/' . PREFIX_NAME . '/module/material/update', 'token=' . $this->session->data['token'] . '&material_id=' . $this->request->get['material_id'] . $url, 'SSL');
    }

    $this->data['cancel'] = $this->url->link('specific/' . PREFIX_NAME . '/module/material', 'token=' . $this->session->data['token'] . $url, 'SSL');

    if (isset($this->request->get['material_id']) && ($this->request->server['REQUEST_METHOD'] != 'POST')) {
      $material_info = $this->{'dmodel_specific_' . PREFIX_NAME . '_material_apoio'}->getMaterial($this->request->get['material_id']);
    }

    $this->data['token'] = $this->session->data['token'];

    $configs = array(
      'status',
      'titulo',
      'image',
      'arquivo'
    );

    foreach ($configs as $config){
      if(isset($this->request->post[$config])){
        $this->data[$config] = $this->request->post[$config];
      }else if(isset($material_info)){
        $this->data[$config] = $material_info[$config];
      }else{
        $this->data[$config] = false;
      }
    }

    $errors = array(
      'titulo',
      'warning'
    );

    foreach ($errors as $error){
      if (isset($this->error[$error])) {
        $this->data['error_'.$error] = $this->error[$error];
      } else {
        $this->data['error_'.$error] = false;
      }
    }

    if ($this->data['image'] && 
        file_exists(DIR_IMAGE . $this->data['image']) && 
        is_file(DIR_IMAGE . $this->data['image']) && 
        $image_validate->isValidate($this->data, true)) {
      $this->data['imagesrc'] = $this->dmodel_tool_image->resize($this->data['image'], 100, 100);
    } else {
      $this->data['imagesrc'] = $this->dmodel_tool_image->resize('no_image.jpg', 100, 100);
    }


    if ($this->data['arquivo'] && file_exists($this->ftrgeralregistry->getPathRecord() . $this->data['arquivo']) && is_file($this->ftrgeralregistry->getPathRecord() . $this->data['arquivo'])) {

      $arquivo = pathinfo($this->data['arquivo']);

      if(in_array('.'.$arquivo['extension'], array_keys(Type_ImgAllowed::getEnumList()))){
        $this->data['arquivosrc'] = $this->dmodel_tool_files->resize($this->data['arquivo'], 100, 100);
      }else{
        $this->data['arquivosrc'] = $this->dmodel_tool_files->getThumb($this->data['arquivo']);
      }

      $this->data['nome_arquivo'] = substr($this->data['arquivo'], strrpos($this->data['arquivo'], '/') + 1);

    }else{
      $this->data['arquivosrc'] = $this->dmodel_tool_files->resize('no_image.jpg', 100, 100);
    }

    $this->data['upFileRecord'] = Type_UploadFile::Tp_Record;

    $this->children = array(
      'common/header',
      'common/footer'
    );

    $this->response->setOutput($this->render('module/material_form'));
  }

  protected function validateForm() {
    if (!$this->user->hasPermission('modify', 'specific/'.PREFIX_NAME.'/module/material')) {
      $this->error['warning'] = $this->language->get('error_permission');
    }

    if(isset($this->request->post['titulo']) && (trim($this->request->post['titulo'])=='')){
      $this->error['titulo'] = $this->language->get('error_titulo');
    }

    if ($this->error && !isset($this->error['warning'])) {
      $this->error['warning'] = $this->language->get('error_warning');
    }

    if (!$this->error) {
      return true;
    } else {
      return false;
    }
  }

}
