<?php

class ModelExtensionTotalTrackingDiscount extends Model {
	public function getTotal($total) {
		if($this->config->get('total_tracking_discount_no_coupon')) {
			foreach($total['totals'] as $_v) {
				if($_v['code'] == 'coupon' && $_v['value'] < 0) return;
			}
		}
	
		$this->load->model('account/customer');
		$sub_total = $this->cart->getSubTotal();
		if (!$this->config->get('total_tracking_discount_status') || !isset($this->request->cookie['tracking']) || !$sub_total) return;
		
		$cart_products = $this->cart->getProducts();
		
		$apply_to = $this->config->get('total_tracking_discount_apply_to');
		if (!$apply_to) $apply_to = 'a';
		$aff = $mark = false;
		if (strpos($apply_to, 'a') !== false) $aff = $this->model_account_customer->getAffiliateByTracking($this->request->cookie['tracking']);
		if (!$aff || !$aff['status']) {
			if (strpos($apply_to, 'm') === false) return;
			$this->load->model('checkout/marketing');
			$mark = $this->model_checkout_marketing->getMarketingByCode($this->request->cookie['tracking']);
			if (!$mark) return;
		} else  {
			$_res = $this->db->query("SELECT `amount`, `type` FROM " . DB_PREFIX . "affiliate_tracking_discount WHERE customer_id = '" . (int)$aff['customer_id'] . "'");
			if($_res->num_rows > 0) {
				$AMOUNT = floatval($_res->row['amount']);				
				$this->config->set('total_tracking_discount_type', ($_res->row['type'] === 'fixed' ? 'fixed' : 'percent'));			
			}
		}
		
		if(!isset($AMOUNT)) $AMOUNT = floatval($this->config->get('total_tracking_discount_amount'));
		if($AMOUNT < 0.01) return;
		
		if(in_array($this->config->get('total_tracking_discount_when'), array('first', 'period'))) {
			if(!$this->customer->isLogged()) return;
			$_oss = is_array($this->config->get('config_complete_status')) ? $this->config->get('config_complete_status') : array();
			if(is_array($this->config->get('config_processing_status'))) $_oss = array_merge($_oss, $this->config->get('config_processing_status'));
			$_q = "SELECT o.order_id FROM `" . DB_PREFIX . "order` o, " . DB_PREFIX . "order_total ot WHERE ot.order_id = o.order_id AND ot.code = 'tracking_discount' AND o.customer_id = '" . (int)$this->customer->getId() . "' AND o.order_status_id > '0' ";			
			if(sizeof($_oss) > 0) $_q .= " AND o.order_status_id IN (" . implode(',', $_oss) . ") ";
			if($this->config->get('total_tracking_discount_when') == 'period') $_q .= " AND o.date_added > SUBDATE(NOW(), INTERVAL " . $this->config->get('total_tracking_discount_period') . " DAY) ";
			$_q .= " LIMIT 1";
			$_res = $this->db->query($_q);			
			if($_res->num_rows > 0) return;
		}				
		
		$this->load->language('extension/total/tracking_discount');
		
		if($this->config->get('total_tracking_discount_type') != 'fixed' && $this->config->get('total_tracking_discount_what') != 'total') {
			$what = explode('_', $this->config->get('total_tracking_discount_what'));
			$field = $what[1] == 'one' ? 'price' : 'total';
			
			$products = array();
			foreach($cart_products as $_p) {
				$products[] = $_p[$field];
			}
			if($what[0] == 'all') {
				$st = array_sum($products);
			} else {
				sort($products);
				$_index = $what[0] == 'min' ? 0 : (sizeof($products) - 1);
				$st = $products[$_index];
			}		
		} else {		
			$st = $total['total'];
		}

		if($this->config->get('total_tracking_discount_type') == 'fixed') {
			if($this->config->get('total_tracking_discount_fixed_per_item')) {
				$q = 0;
				foreach($cart_products as $_p) {
					$q += $_p['quantity'];
				}
				$AMOUNT *= $q;
			}
			$_fixed_max = $st * ((float) $this->config->get('total_tracking_discount_fixed_max')) * 0.01;
			$dsc =  $AMOUNT < $_fixed_max ?  $AMOUNT : $_fixed_max;
		} else {
			$_perc = $AMOUNT * 0.01;
			$dsc = $st - ($st * (1 - $_perc));
		}
		
		foreach ($cart_products as $product) {
			$discount = $dsc * ($product['total'] / $sub_total);
			if ($product['tax_class_id']) {
				$tax_rates = $this->tax->getRates($product['total'] - ($product['total'] - $discount), $product['tax_class_id']);
							
				foreach ($tax_rates as $tax_rate) {
					if ($tax_rate['type'] == 'P') {
						$total['taxes'][$tax_rate['tax_rate_id']] -= $tax_rate['amount'];
					}
				}
			}
		}			
		
		$total['totals'][] = array(
                            'code'       => 'tracking_discount',
                            'title'      => $this->language->get('text_tracking_discount'),
                            'value'      => -$dsc,
                            'sort_order' => $this->config->get('total_tracking_discount_sort_order')
		);
        $total['total'] -= $dsc;		
	}
}

