<?php
class ModelShippingFlatHdw extends Model {
	function getQuote($address) {
		$this->load->language('shipping/flat_hdw');

		$flat_hdw_zones = $this->config->get('flat_hdw_zone');
		$flat_hdw_zones = is_array($flat_hdw_zones) ? $flat_hdw_zones : array();

		$cart_subtotal = floatval($this->cart->getSubTotal());

		$language_id = $this->config->get('config_language_id');

		$quote_data = array();

		foreach ($flat_hdw_zones as $key => $zone) {
			if ($zone['status'] == 0) {
				continue;
			}

			$total_min = floatval($zone['total_min']);
			$total_max = floatval($zone['total_max']);

			if ($cart_subtotal < $total_min || ($total_max > 0 && $cart_subtotal > $total_max)) {
				continue;
			}

			$cost = isset($zone['cost']) ? floatval($zone['cost']) : 0;

			if ($cost <= 0) {
				continue;
			}

			$cep_inicial = intval( preg_replace('/[^0-9]/i', '', $zone['cep_inicial']) );
			$cep_final = intval( preg_replace('/[^0-9]/i', '', $zone['cep_final']) );
			$postcode = intval( preg_replace('/[^0-9]/i', '', $address['postcode']) );

			if ($cep_inicial != '' && $cep_final != '') {
				if ($postcode < $cep_inicial || $postcode > $cep_final) {
					continue;
				}
			}

			if ($zone['geo_zone_id'] > 0) {
				$query = $this->db->query("SELECT *
					FROM
						" . DB_PREFIX . "zone_to_geo_zone
					WHERE
						geo_zone_id = '" . (int)$zone['geo_zone_id'] . "' AND
						country_id = '" . (int)$address['country_id'] . "' AND
						(zone_id = '" . (int)$address['zone_id'] . "' OR zone_id = '0')
				");

				if (!$query->num_rows) {
					continue;
				}
			}

			$titulo = isset($zone['titulo'][$language_id]) ? trim($zone['titulo'][$language_id]) : '';
			$titulo = ($titulo != '') ? $titulo : $this->language->get('text_description');

			$quote_data['flat_hdw_' . $key] = array(
				'code'         => 'flat_hdw.flat_hdw_' . $key,
				'title'        => $titulo,
				'cost'         => $cost,
				'tax_class_id' => $this->config->get('flat_hdw_tax_class_id'),
				'text'         => $this->currency->format($this->tax->calculate($cost, $this->config->get('flat_hdw_tax_class_id'), $this->config->get('config_tax')))
			);

		} // foreach

		$method_data = array();

		if ($quote_data) {
			$method_data = array(
				'code'       => 'flat_hdw',
				'title'      => $this->language->get('text_title'),
				'quote'      => $quote_data,
				'sort_order' => $this->config->get('flat_hdw_sort_order'),
				'error'      => false
			);
		}

		return $method_data;
	}
}