<?php

$loader = $this->registry->get('load');
$loader->controller('module/filter');

class ControllerModuleFuturaFiltroMarca extends ControllerModuleFilter
{

  protected function index($setting)
  {

    if (!$this->config->get('futurafiltromarca_status')) {
      return false;
    }

    $this->data['futurafiltromarca_status'] = $this->config->get('futurafiltromarca_status');

    if (!isset($this->request->get['route'])) {
      return false;
    }


    $this->language->load('module/futurafiltromarca');

    $this->data['heading_title_manufacturer'] = $this->language->get('heading_title_manufacturer');
    $this->data['futurafiltromarca_heading_title']= $this->config->get('futurafiltromarca_heading_title');
    $this->data['text_clear'] = $this->language->get('text_clear');
    $this->data['text_placeholder'] = $this->language->get('text_placeholder');
    $this->data['text_apply'] = $this->language->get('text_apply');

    $data = parent::getFilters();

    if (isset($this->request->get['filbrand'])) {
      $filtromarca = explode(',', (string)$this->request->get['filbrand']);
    } else {
      $filtromarca = "";
    }

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

    $this->data['listManufacturer'] = false;
    $this->data['clearmanufacturer'] = false;
    $listManufacturer = $this->model_catalog_product->getGradeProdutosList($data, 'PRODUCT_MANUFACTURER');

    if (($listManufacturer) && ($filtromarca)) {
      foreach ($listManufacturer as $manufacturer) {
        $this->data['listManufacturer'][] = array(
          'manufacturer_id' => $manufacturer['manufacturer_id'],
          'name' => $manufacturer['name'],
          'checked' => in_array($manufacturer['manufacturer_id'], $filtromarca) ? "checked" : ""
        );
      }
      $this->data['clearmanufacturer'] = true;
    } else {
      $this->data['listManufacturer'] = $listManufacturer;
    }

    if ($this->config->get('futuragrade_order_filtro') && ($this->data['listManufacturer'])) {
      usort($this->data['listManufacturer'], function ($a, $b) {
        if (isset($b["checked"]) && isset($a["checked"])) {
          return strcmp($b["checked"], $a["checked"]);
        }
      });
    }


    if (file_exists(DIR_TEMPLATE . $this->config->get('config_template') . '/template/module/futurafiltromarca.twig')) {
      $this->template = $this->config->get('config_template') . '/template/module/futurafiltromarca.twig';
    } else {
      $this->template = 'default/template/module/futurafiltromarca.twig';
    }

    $this->render('module/futurafiltromarca');
  }

}
