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

		$weight_hdw_zones = $this->config->get('weight_hdw_zone');
		$weight_hdw_zones = is_array($weight_hdw_zones) ? $weight_hdw_zones : array();

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

		$weight = $this->cart->getWeight();

		$quote_data = array();

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

			$cost = 0;

			$rates = trim($zone['rate']);
			$rates = preg_replace('/[^0-9:.\n]/', "\n", $rates);
			$rates = preg_replace('/\n+/', "\n", trim($rates));
			$rates = explode("\n", $rates);

			foreach ($rates as $rate) {
				$data = explode(':', $rate);

				if (floatval($data[0]) >= $weight) {
					if (isset($data[1])) {
						$cost = floatval($data[1]);
					}

					break;
				}
			}

			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');

			if ($cost > 0.01) {
				$titulo .= '  (' . $this->language->get('text_weight') . ' ' . $this->weight->format($weight, $this->config->get('config_weight_class_id')) . ')';
			}

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

		$method_data = array();

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

		return $method_data;
	}
}