<?php

class ControllerCommonNotification extends Controller
{
  protected function index()
  {

    if (!$this->user->isLogged()) {
      return false;
    }

    $this->load->type('tipocomum');
    $this->load->helper('ftr_geral');

    $language = $this->language->load('common/header');
    $this->data = array_merge($this->data, $language);

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

    $this->data['mlnotifications'] = array(
      $this->getMlnotifications(),
      $this->getMlquestion(),
      $this->getMlNoticies()
    );

    $this->data['store_rating_module_status'] = $this->config->get('store_rating_module_status');
    $this->data['store_ratings'] = ($this->data['store_rating_module_status']) ? $this->getStoreRating() : false;

    $this->data['reviews_status'] = ($this->config->get('config_rating_status') == Type_Status::Tp_Habilitado) ? true : false;
    $this->data['reviews'] = ($this->data['reviews_status']) ? $this->getReview() : false;

    $this->data['system_notifications'] = ($this->getsystemNotifications());

    $notifications = array(
      'mlquestion' => $this->getMlquestion(),
      'mlnotifications' => $this->getMlnotifications(),
      'mlnoticies' => $this->getMlNoticies(),
      'store_ratings' => $this->data['store_ratings'],
      'reviews' => $this->data['reviews'],
      'system_notifications' =>  $this->data['system_notifications']
    );

    if (count(array_filter($notifications)) > 0) {
      $this->session->data['active_notifications'] = true;

      if ($notifications['store_ratings'])
        $this->session->data['quantity_notifications'] = count(array_filter($notifications['store_ratings']));
      else
        $this->session->data['quantity_notifications'] = 0;

      if ($notifications['reviews'])
        $this->session->data['quantity_notifications'] += count(array_filter($notifications['reviews']));
      else
        $this->session->data['quantity_notifications'] += 0;

        if ($notifications['system_notifications'])
            $this->session->data['quantity_notifications'] += count(array_filter($notifications['system_notifications']));
        else
            $this->session->data['quantity_notifications'] += 0;
    }
    $this->data['active_notifications'] = isset($this->session->data['active_notifications']) ? true : false;

    $this->data['review'] = $this->url->link('catalog/review', 'token=' . $this->session->data['token'], 'SSL');
    $this->data['store_rating'] = $this->url->link('catalog/store_rating', 'token=' . $this->session->data['token'], 'SSL');

    $this->response->setOutput($this->render('common/notification'));

  }

  public function getMlnotifications()
  {

    $this->load->type('tipocomum');
    $this->load->helper('ftr_geral');

    $this->language->load('common/header');

    $notifications = false;

    if ($this->config->get('mercadolivre_status')) {
      $this->load->model('mercadolivre/error');
      $result = $this->model_mercadolivre_error->getErrorsTotal();
      if ($result > 0) {
        $notifications['mercadolivre'] = array(
          'link' => $this->url->link('module/mercadolivre/error', 'token=' . $this->session->data['token'] . '&type=' . Type_TitleModules::Tp_Marketplace, 'SSL'),
          'title' => $this->language->get('text_notification_error_mercadolivre_title'),
          'text' => $this->language->get('text_notification_error_mercadolivre')
        );
      }
    }
    return $notifications;
  }

  public function getReview()
  {

    $reviews = false;

    $data = array(
      'order' => 'DESC',
      'start' => 0,
      'limit' => 9,
      'status' => Type_Status::Tp_Desabilitado,
      'notification_status' => Type_Status::Tp_Habilitado
    );

    $this->load->model('catalog/review');
    $results = $this->model_catalog_review->getReviews($data);

    foreach ($results as $key => $result) {
      $reviews[] = array(
        'review_id' => $result['review_id'],
        'rating' => $result['rating'],
        'date_added' => $result['date_added'],
        'name' => $result['name'],
        'text' => $result['text'],
        'author' => $result['author'],
        'href' => $this->url->link('catalog/review', 'token=' . $this->session->data['token'] . '&review_id=' . $result['review_id'], 'SSL'),
        'type' => TypeNotification_Status::Tp_Review
      );
    }

    return $reviews;
  }

  public function getStoreRating()
  {

    $storeRatings = array();

    $data = array(
      'order' => 'DESC',
      'start' => 0,
      'limit' => 9,
      'allow' => 1,
      'status' => Type_Status::Tp_Desabilitado,
      'notification_status' => Type_Status::Tp_Habilitado
    );

    $this->load->model('catalog/store_rating');
    $results = $this->model_catalog_store_rating->getRatings($data);

    foreach ($results as $key => $result) {
      $storeRatings[] = array(
        'store_rating_id' => $result['store_rating_id'],
        'rating' => $result['rating'],
        'date_added' => $result['date_added'],
        'text' => $result['text'],
        'author' => $result['author'],
        'href' => $this->url->link('catalog/store_rating', 'token=' . $this->session->data['token'] . '&store_rating_id=' . $result['store_rating_id'], 'SSL'),
        'type' => TypeNotification_Status::Tp_Storerating
      );
    }

    return $storeRatings;

  }

  public function getsystemNotifications(){
      $notifications = array();

      $data = array(
          'order' => 'DESC',
          'start' => 0,
          'limit' => 9,
          'allow' => 1,
          'status' => Type_Status::Tp_Desabilitado,
          'notification_status' => Type_Status::Tp_Habilitado
      );

      $this->load->model('catalog/system_notification');
      $results = $this->model_catalog_system_notification->getSystemNotifications($data);

      foreach ($results as $key => $result) {
          $notifications[] = array(
              'notification_id' => $result['notification_id'],
              'title'           => $result['title'],
              'message'         => $result['message'],
              'priority'        => $result['priority'],
              'date_added'      => $result['date_added'],
              'type' => TypeNotification_Status::Tp_SystemNotification
          );
      }

      return $notifications;
  }


  public function getMlquestion()
  {

    $questions = false;

    if ($this->config->get('mercadolivre_status')) {


      $this->load->helper('ftr_geral');
      $this->load->model('mercadolivre/questions');

      $data = array(
        'filter_data_start' => date('Y-m-d'),
        'filter_data_end' => date('Y-m-d'),
        'filter_question_status' => Type_MercadoLivreQuestionStatus::Tp_Unanswered
      );

      $result = $this->model_mercadolivre_questions->getQuestionsList($data);

      if (count($result) > 0) {
        $questions['mercadolivre'] = array(
          'link' => $this->url->link('module/mercadolivre/question', 'token=' . $this->session->data['token'] . '&type=' . Type_TitleModules::Tp_Marketplace, 'SSL'),
          'title' => $this->language->get('text_notification_question_mercadolivre_title'),
          'text' => $this->language->get('text_notification_question_mercadolivre')
        );
      }
    }

    return $questions;
  }

  public function getMlNoticies()
  {

    $noticies = false;

    if ($this->config->get('mercadolivre_status')) {

      $this->load->helper('ftr_geral');
      $this->load->dmodel('mercadolivre/melinoticies');

      $data = array(
        'data_atual' => true
      );

      $result = $this->dmodel_mercadolivre_melinoticies->getNoticies($data);

      if ($result && count($result) > 0) {
        $noticies['mercadolivre'] = array(
          'link' => $this->url->link('module/mercadolivre/noticies', 'token=' . $this->session->data['token'] . '&type=' . Type_TitleModules::Tp_Marketplace, 'SSL'),
          'title' => $this->language->get('text_notification_noticies_mercadolivre_title'),
          'text' => $this->language->get('text_notification_noticies_mercadolivre')
        );
      }
    }

    return $noticies;
  }

  public function clear()
  {

    $json = array();

    $this->load->type('tipocomum');
    $this->load->helper('ftr_geral');

    if ($this->request->post['dados']) {
      $dados = $this->request->post['dados'];
    } else {
      $json['error']['dados'] = 'Nenhuma notificação encontrada!';
    }

    if (!$json) {

      foreach ($dados as $key => $value) {
        if ($value['type'] == TypeNotification_Status::Tp_Review) {
          $sql = "UPDATE " . DB_PREFIX . "review SET notification_status=" . Type_Status::Tp_Desabilitado . " WHERE review_id=" . $value['id'];
        } else {
          $sql = "UPDATE " . DB_PREFIX . "store_rating SET notification_status=" . Type_Status::Tp_Desabilitado . " WHERE store_rating_id=" . $value['id'];
        }

        $this->db->query($sql);
      }

    }

    $this->response->setOutputJson($json);

  }

    public function updateNotificationRead()
    { //Alterar status da notificação.
        $data = $this->request->get;
        $language = $this->language->load('common/header');
        $this->data = array_merge($this->data, $language);

        $this->load->model('catalog/system_notification');
        $results = $this->model_catalog_system_notification->updateNotificationRead($data);

        $this->response->setOutputjson(['success' => $results,
                                        'message' => $this->language->get('text_update_read')]);
    }

    public function getQuantityNotification(){
      $quantidade = 0;

      $this->load->model('catalog/review');
      $quantidade += $this->model_catalog_review->getTotalReviewsNotApproval();

      $this->load->model('catalog/store_rating');
      $quantidade += $this->model_catalog_store_rating->getTotalRatingsNotApproval();

      $this->load->model('catalog/system_notification');
      $quantidade += $this->model_catalog_system_notification->getTotalNotify();

      $this->response->setOutputjson(['value' => $quantidade]);

    }

}