<?php
class ModelTotalDesconto extends Model {
	public function getTotal(&$total_data, &$total, &$taxes) {
		if (!$this->config->get('desconto_status')) {
			return;
		}

		if (!isset($this->session->data['payment_method']['code'])){
			return;
		}

		$descontos = $this->config->get('desconto_module');

		if (!is_array($descontos)) {
			return;
		}

		$descontos_ativos = array();

		foreach ($descontos as $desc) {
			if ($desc['forma_pgto'] == $this->session->data['payment_method']['code']) {
				$minimo = floatval($desc['minimo']);
				$desconto = floatval($desc['desconto']);

				if ($desconto < 1 || $desconto > 99) {
					continue;
				}

				$descontos_ativos[] = array(
					'forma_pgto' => $desc['forma_pgto'],
					'minimo'     => $minimo,
					'desconto'   => $desconto
				);
			}
		}

		$sort_order = array();

		foreach ($descontos_ativos as $key => $value) {
			$sort_order[$key] = $value['minimo'];
		}

		array_multisort($sort_order, SORT_DESC, $descontos_ativos);

		$total_desconto = 0;
		$sub_total = $this->cart->getSubTotal();

		foreach ($descontos_ativos as $desc) {
			extract($desc);

			if ($sub_total >= $minimo) {
				$desconto_calc = $desconto / 100;
				$total_desconto = $sub_total * $desconto_calc;

				$this->load->language('payment/' . $desc['forma_pgto']);
				$name = strip_tags($this->language->get('text_title'));

				break;
			}
		}

		if ($total_desconto > 0) {
			$this->load->language('total/desconto');

			$total_data[] = array(
				'code'       => 'desconto',
				'title'      => sprintf($this->language->get('text_desconto'), $desconto, $name),
				'text'       => $this->currency->format(-$total_desconto),
				'value'      => -$total_desconto,
				'sort_order' => $this->config->get('desconto_sort_order')
			);

			$total -= $total_desconto;
		}
	}
}