<?php

class ControllerSaleCoupon extends Controller
{
  private $error = array();

  public function index()
  {
    $this->language->load('sale/coupon');

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

    $this->load->model('sale/coupon');

    $this->getList();

  }

  public function insert()
  {
    $this->language->load('sale/coupon');

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

    $this->load->model('sale/coupon');

    if (($this->request->server['REQUEST_METHOD'] == 'POST') && $this->validateForm()) {
      $this->model_sale_coupon->addCoupon($this->request->post);

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

      $url = '';

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

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

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

      $this->redirect($this->url->link('sale/coupon', 'token=' . $this->session->data['token'] . $url, 'SSL'));
    }

    $this->getForm();
  }

  public function update()
  {
    $this->language->load('sale/coupon');

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

    $this->load->model('sale/coupon');

    if (($this->request->server['REQUEST_METHOD'] == 'POST') && $this->validateForm()) {
      $this->model_sale_coupon->editCoupon($this->request->get['coupon_id'], $this->request->post);

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

      $url = '';

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

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

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

      $this->redirect($this->url->link('sale/coupon', 'token=' . $this->session->data['token'] . $url, 'SSL'));
    }

    $this->getForm();
  }

  public function delete()
  {
    $this->language->load('sale/coupon');

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

    $this->load->model('sale/coupon');

    if (isset($this->request->post['selected']) && $this->validateDelete()) {
      foreach ($this->request->post['selected'] as $coupon_id) {
        $this->model_sale_coupon->deleteCoupon($coupon_id);
      }

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

      $url = '';

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

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

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

      $this->redirect($this->url->link('sale/coupon', 'token=' . $this->session->data['token'] . $url, 'SSL'));
    }

    $this->getList();
  }

  protected function getList()
  {
    $this->document->addScript(array(
      'view/javascript/page.coupon.list.js'
    ));

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

    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;
    }

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

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

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

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

    $url = '';

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

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

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

    $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('sale/coupon', 'token=' . $this->session->data['token'] . $url, 'SSL'),
      'separator' => ' :: '
    );

    $this->data['insert'] = $this->url->link('sale/coupon/insert', 'token=' . $this->session->data['token'] . $url, 'SSL');
    $this->data['delete'] = $this->url->link('sale/coupon/delete', 'token=' . $this->session->data['token'] . $url, 'SSL');

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

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

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

    if (isset($this->request->get['filter_status'])) {
      $this->data['filter_status'] = $this->request->get['filter_status'];
    } else {
      $this->data['filter_status'] = null;
    }

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

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

    $coupon_total = $this->model_sale_coupon->getTotalCoupons();

    $results = $this->model_sale_coupon->getCoupons($data);

    foreach ($results as $result) {

      $this->data['coupons'][] = array(
        'coupon_id' => $result['coupon_id'],
        'name' => $result['name'],
        'code' => $result['code'],
        'discount' => $result['discount'],
        'date_start' => date($this->language->get('date_format_short'), strtotime($result['date_start'])),
        'date_end' => date($this->language->get('date_format_short'), strtotime($result['date_end'])),
        'status' => ($result['status'] ? $this->language->get('text_enabled') : $this->language->get('text_disabled')),
        'selected' => isset($this->request->post['selected']) && in_array($result['coupon_id'], $this->request->post['selected']),
        'href' => $this->url->link('sale/coupon/update', 'token=' . $this->session->data['token'] . '&coupon_id=' . $result['coupon_id'] . $url, 'SSL')
      );
    }

    $this->data['heading_title'] = $this->language->get('heading_title');

    $this->data['text_no_results'] = $this->language->get('text_no_results');

    $this->data['column_name'] = $this->language->get('column_name');
    $this->data['column_code'] = $this->language->get('column_code');
    $this->data['column_discount'] = $this->language->get('column_discount');
    $this->data['column_date_start'] = $this->language->get('column_date_start');
    $this->data['column_date_end'] = $this->language->get('column_date_end');
    $this->data['column_status'] = $this->language->get('column_status');
    $this->data['column_action'] = $this->language->get('column_action');
    $this->data['column_validate'] = $this->language->get('column_validate');

    $this->data['button_insert'] = $this->language->get('button_insert');
    $this->data['button_delete'] = $this->language->get('button_delete');
    $this->data['button_filter'] = $this->language->get('button_filter');

    $this->data['text_enabled'] = $this->language->get('text_enabled');
    $this->data['text_disabled'] = $this->language->get('text_disabled');

    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'] = '';
    }

    $url = '';

    if ($order == 'ASC') {
      $url .= '&order=DESC';
    } else {
      $url .= '&order=ASC';
    }

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

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

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

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

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

    $this->data['sort_name'] = $this->url->link('sale/coupon', 'token=' . $this->session->data['token'] . '&sort=name' . $url, 'SSL');
    $this->data['sort_code'] = $this->url->link('sale/coupon', 'token=' . $this->session->data['token'] . '&sort=code' . $url, 'SSL');
    $this->data['sort_discount'] = $this->url->link('sale/coupon', 'token=' . $this->session->data['token'] . '&sort=date_start' . $url, 'SSL');
    $this->data['sort_date_start'] = $this->url->link('sale/coupon', 'token=' . $this->session->data['token'] . '&sort=date_start' . $url, 'SSL');
    $this->data['sort_date_end'] = $this->url->link('sale/coupon', 'token=' . $this->session->data['token'] . '&sort=date_end' . $url, 'SSL');
    $this->data['sort_status'] = $this->url->link('sale/coupon', 'token=' . $this->session->data['token'] . '&sort=status' . $url, 'SSL');

    $url = '';

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

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

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

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

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

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

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

    $pagination = new Pagination();
    $pagination->total = $coupon_total;
    $pagination->page = $page;
    $pagination->limit = $this->config->get('config_admin_limit');
    $pagination->text = $this->language->get('text_pagination');
    $pagination->url = $this->config->get('config_adm_ssl') . 'index.php?route=sale/coupon&token=' . $this->session->data['token'] . $url . '&page={page}';

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

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

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

    $this->data['filter_count'] = count(explode('&', $url)) - 1;

    $this->response->setOutput($this->render('sale/coupon_list'));
  }

  protected function getForm()
  {

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


    $language = $this->language->load('sale/coupon');
    $this->data = array_merge($this->data, $language);

    $this->data['ftr_geral'] = new ftr_geral();

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

    if (isset($this->request->get['coupon_id'])) {
      $this->data['coupon_id'] = $this->request->get['coupon_id'];
    } else {
      $this->data['coupon_id'] = 0;
    }

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

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

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

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

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

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

    $url = '';

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

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

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

    $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('sale/coupon', 'token=' . $this->session->data['token'] . $url, 'SSL'),
      'separator' => ' :: '
    );

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

    $this->data['cancel'] = $this->url->link('sale/coupon', 'token=' . $this->session->data['token'] . $url, 'SSL');

    if (isset($this->request->get['coupon_id']) && (!$this->request->server['REQUEST_METHOD'] != 'POST')) {
      $coupon_info = $this->model_sale_coupon->getCoupon($this->request->get['coupon_id']);
    }

    if (isset($this->request->post['name'])) {
      $this->data['name'] = $this->request->post['name'];
    } elseif (!empty($coupon_info)) {
      $this->data['name'] = $coupon_info['name'];
    } else {
      $this->data['name'] = '';
    }

    if (isset($this->request->post['code'])) {
      $this->data['code'] = $this->request->post['code'];
    } elseif (!empty($coupon_info)) {
      $this->data['code'] = $coupon_info['code'];
    } else {
      $this->data['code'] = '';
    }

    if (isset($this->request->post['type'])) {
      $this->data['type'] = $this->request->post['type'];
    } elseif (!empty($coupon_info)) {
      $this->data['type'] = $coupon_info['type'];
    } else {
      $this->data['type'] = '';
    }

    if (isset($this->request->post['discount'])) {
      $this->data['discount'] = $this->request->post['discount'];
    } elseif (!empty($coupon_info)) {
      $this->data['discount'] = number_format($coupon_info['discount'], 2);
    } else {
      $this->data['discount'] = '';
    }

    if (isset($this->request->post['shipping'])) {
      $this->data['shipping'] = $this->request->post['shipping'];
    } elseif (!empty($coupon_info)) {
      $this->data['shipping'] = $coupon_info['shipping'];
    } else {
      $this->data['shipping'] = '';
    }

    if (isset($this->request->post['total'])) {
      $this->data['total'] = $this->request->post['total'];
    } elseif (!empty($coupon_info)) {
      $this->data['total'] = number_format($coupon_info['total'], 2);
    } else {
      $this->data['total'] = '';
    }

    if (isset($this->request->post['coupon_product'])) {
      $products = $this->request->post['coupon_product'];
    } elseif (isset($this->request->get['coupon_id'])) {
      $products = $this->model_sale_coupon->getCouponProducts($this->request->get['coupon_id']);
    } else {
      $products = array();
    }

    $this->load->model('catalog/product');

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

    foreach ($products as $product_id) {
      $product_info = $this->model_catalog_product->getProduct($product_id);

      if ($product_info) {
        $this->data['coupon_product'][] = array(
          'product_id' => $product_info['product_id'],
          'name' => $product_info['name']
        );
      }
    }

    if (isset($this->request->post['coupon_grid'])) {
      $grids = $this->request->post['coupon_grid'];
    } elseif (isset($this->request->get['coupon_id'])) {
      $grids = $this->model_sale_coupon->getCouponGrids($this->request->get['coupon_id']);
    } else {
      $grids = array();
    }

    $this->load->dmodel('catalog/productgrid');

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

    foreach ($grids as $grid) {
      $grid_info = $this->dmodel_catalog_productgrid->getGrid($grid);

      if ($grid_info) {
        $this->data['coupon_grid'][] = array(
          'product_grid_id' => $grid_info['product_grid_id'],
          'description' => $grid_info['description']
        );
      }
    }


    if (isset($this->request->post['coupon_category'])) {
      $categories = $this->request->post['coupon_category'];
    } elseif (isset($this->request->get['coupon_id'])) {
      $categories = $this->model_sale_coupon->getCouponCategories($this->request->get['coupon_id']);
    } else {
      $categories = array();
    }

    $this->load->model('catalog/category');

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

    foreach ($categories as $category_id) {
      $category_info = $this->model_catalog_category->getCategory($category_id);

      if ($category_info) {
        $this->data['coupon_category'][] = array(
          'category_id' => $category_info['category_id'],
          'name' => ($category_info['path'] ? $category_info['path'] . ' &gt; ' : '') . $category_info['name']
        );
      }
    }

    if (isset($this->request->post['date_start'])) {
      $this->data['date_start'] = $this->request->post['date_start'];
    } elseif (!empty($coupon_info)) {
      $this->data['date_start'] = date('d-m-Y', strtotime($coupon_info['date_start']));
    } else {
      $this->data['date_start'] = date('d-m-Y', time());
    }

    if (isset($this->request->post['date_end'])) {
      $this->data['date_end'] = $this->request->post['date_end'];
    } elseif (!empty($coupon_info)) {
      $this->data['date_end'] = date('d-m-Y', strtotime($coupon_info['date_end']));
    } else {
      $this->data['date_end'] = date('d-m-Y', time());
    }

    if (isset($this->request->post['uses_total'])) {
      $this->data['uses_total'] = $this->request->post['uses_total'];
    } elseif (!empty($coupon_info)) {
      $this->data['uses_total'] = $coupon_info['uses_total'];
    } else {
      $this->data['uses_total'] = 1;
    }

    if (isset($this->request->post['uses_customer'])) {
      $this->data['uses_customer'] = $this->request->post['uses_customer'];
    } elseif (!empty($coupon_info)) {
      $this->data['uses_customer'] = $coupon_info['uses_customer'];
    } else {
      $this->data['uses_customer'] = 1;
    }

    if (isset($this->request->post['status'])) {
      $this->data['status'] = $this->request->post['status'];
    } elseif (!empty($coupon_info)) {
      $this->data['status'] = $coupon_info['status'];
    } else {
      $this->data['status'] = 1;
    }

    if (isset($this->request->post['coupon_display'])) {
      $this->data['coupon_display'] = $this->request->post['coupon_display'];
    } elseif (!empty($coupon_info)) {
      $this->data['coupon_display'] = $coupon_info['coupon_display'];
    } else {
      $this->data['coupon_display'] = Type_DisplayModuleOption::Tp_Todos;
    }

    $this->data['Type_DisplayModuleOption'] = $this->load->typeForTwig('Type_DisplayModuleOption');

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

    $this->response->setOutput($this->render('sale/coupon_form'));

  }

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

    if ((utf8_strlen($this->request->post['name']) < 3) || (utf8_strlen($this->request->post['name']) > 128)) {
      $this->error['name'] = $this->language->get('error_name');
    }

    if ((utf8_strlen($this->request->post['code']) < 3) || (utf8_strlen($this->request->post['code']) > 20)) {
      $this->error['code'] = $this->language->get('error_code');
    }

    if(($this->request->post['discount'] <= 0) && ($this->request->post['shipping'] == Type_DsimDnao::Tp_Nao) ){
        $this->error['warning'] = $this->language->get('error_shipping_and_discount_not_filled');
    }

    $coupon_code = $this->model_sale_coupon->getCouponByCode($this->request->post['code']);
    if ($coupon_code) {
      if (!isset($this->request->get['coupon_id'])|| ($coupon_code['coupon_id'] != $this->request->get['coupon_id'])) {
        $this->error['warning'] = $this->language->get('error_exists');
      }
    }

    $coupon_name = $this->model_sale_coupon->getCouponByName($this->request->post['name']);

    if ($coupon_name) {
      if (!isset($this->request->get['coupon_id']) || ($coupon_name['name'] != $this->request->post['name'])) {
        $this->error['name'] = $this->language->get('error_name_exist');
      }
    }

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

  protected function validateDelete()
  {
    if (!$this->user->hasPermission('modify', 'sale/coupon')) {
      $this->error['warning'] = $this->language->get('error_permission');
    }

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

  public function history()
  {
    $this->language->load('sale/coupon');

    $this->load->model('sale/coupon');

    $this->data['text_no_results'] = $this->language->get('text_no_results');

    $this->data['column_order_id'] = $this->language->get('column_order_id');
    $this->data['column_customer'] = $this->language->get('column_customer');
    $this->data['column_amount'] = $this->language->get('column_amount');
    $this->data['column_date_added'] = $this->language->get('column_date_added');

    $adminLimit = $this->config->get('config_admin_limit');

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

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

    $results = $this->model_sale_coupon->getCouponHistories($this->request->get['coupon_id'], ($pageHistory - 1) * $adminLimit, $adminLimit);

    foreach ($results as $result) {
      $this->data['histories'][] = array(
        'order_id' => $result['order_id'],
        'customer' => $result['customer'],
        'amount' => $result['amount'],
        'date_added' => date($this->language->get('date_format_short'), strtotime($result['date_added'])),
        'href' => $this->url->link('sale/order/info', 'token=' . $this->session->data['token'] . '&order_id=' . $result['order_id'], 'SSL')
      );
    }

    $history_total = $this->model_sale_coupon->getTotalCouponHistories($this->request->get['coupon_id']);

    $pagination = new Pagination();
    $pagination->total = $history_total;
    $pagination->page = $pageHistory;
    $pagination->limit = $adminLimit;
    $pagination->text = $this->language->get('text_pagination');
    $pagination->url = $this->url->link('sale/coupon/update', 'token=' . $this->session->data['token'] . '&coupon_id='
        . $this->request->get['coupon_id'] . '&pageHistory={page}' . '#tab-info=1', 'SSL');

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

    $this->response->setOutput($this->render('sale/coupon_history'));
  }
}

