<?php

class ModelExtensionAffClassic extends Model {
	
	public function transferToCredits($customer_id, $amount, $order_id = 0) {
		if(!$amount || !preg_match("/^\-?\d+(?:\.\d+)?$/", $amount)) return false;
		$this->load->model('account/customer');
		$this->load->language('affiliate/aff_classic');			
		$this->config->set('_sc_transaction', true);
		$multiplier = $this->config->get('module_aff_classic_transfer_multiplier');
		if(!$multiplier || !preg_match("/^\d+(?:\.\d+)$/", $multiplier)) $multiplier = 1;
		$multiplier = (float)$multiplier;
		$this->model_account_customer->addTransaction($customer_id, $this->language->get('text_transaction_to_credits'), ($amount * $multiplier), $order_id);
		$this->config->set('_no_affiliate_transaction_mail', true);
			
		$q = "SELECT customer_transaction_id FROM " . DB_PREFIX . "customer_transaction WHERE customer_id = '" . (int)$customer_id . "' AND order_id = '" . (int)$order_id . "' AND amount = '" . (float)$amount . "' ORDER BY customer_transaction_id DESC LIMIT 1";
		$res = $this->db->query($q);
		if($res->num_rows) {
			$c_tr_id = (int)$res->row['customer_transaction_id'];
		} else {
			$c_tr_id = 0;
		}
		$this->db->query("INSERT INTO " . DB_PREFIX . "customer_affiliate_transaction SET customer_transaction_id = '" . $c_tr_id . "', customer_id = '" . (int)$customer_id . "', order_id = '" . (int)$order_id . "', description = '" . $this->db->escape($this->language->get('text_transaction_from_affiliate')) . "', amount = '" . (-((float)$amount)) . "', date_added = NOW()");
		return true;
	}

	public function addTransaction($customer_id, $description, $amount = '', $order_id = 0) {
		if(!$this->config->get('module_aff_classic_commission_table')) {
			$this->load->model('account/customer');
			$this->model_account_customer->addTransaction($customer_id, $description, $amount, $order_id);
			return;
		}
		
		$this->db->query("INSERT INTO " . DB_PREFIX . "customer_affiliate_transaction SET customer_id = '" . (int)$customer_id . "', order_id = '" . (int)$order_id . "', description = '" . $this->db->escape($description) . "', amount = '" . (float)$amount . "', date_added = NOW()");
		$ret = $this->db->getLastId();
		if($amount > 0 && $this->config->get('module_aff_classic_commission_to_credits') && $this->config->get('module_aff_classic_commission_to_credits') > 0) $this->transferToCredits($customer_id, $amount, $order_id);
		return $ret;
	}

	public function deleteTransactionByOrderId($order_id) {
		if(!$this->config->get('module_aff_classic_commission_table')) {
			$this->load->model('account/customer');
			$this->model_account_customer->deleteTransactionByOrderId($order_id);
		} else {
			$this->deleteCreditsByField('order_id', $order_id);			
			$this->db->query("DELETE FROM " . DB_PREFIX . "customer_affiliate_transaction WHERE order_id = '" . (int)$order_id . "'");
		}
	}
	
	public function getTransactions($data = array()) {
		$table = $this->config->get('module_aff_classic_commission_table') ? 'customer_affiliate_transaction' : 'customer_transaction';
		
		$sql = "SELECT * FROM `" . DB_PREFIX . $table . "` ";
		$where = array();
		if(isset($data['customer_id']) && $data['customer_id']) $where[] = 
		 " customer_id = '" . (int)$data['customer_id'] . "' ";
		 
		if(sizeof($where)) $sql .= " WHERE " . implode(' AND ', $where);

		$sort_data = array(
			'amount',
			'description',
			'date_added'
		);

		if (isset($data['sort']) && in_array($data['sort'], $sort_data)) {
			$sql .= " ORDER BY " . $data['sort'];
		} else {
			$sql .= " ORDER BY date_added";
		}

		if (isset($data['order']) && ($data['order'] == 'DESC')) {
			$sql .= " DESC";
		} else {
			$sql .= " ASC";
		}

		if (isset($data['start']) || isset($data['limit'])) {
			if ($data['start'] < 0) {
				$data['start'] = 0;
			}

			if ($data['limit'] < 1) {
				$data['limit'] = 20;
			}

			$sql .= " LIMIT " . (int)$data['start'] . "," . (int)$data['limit'];
		}

		$query = $this->db->query($sql);

		return $query->rows;
	}

	public function getTransactionTotal($customer_id) {
		if(!$this->config->get('module_aff_classic_commission_table')) {
			$this->load->model('account/customer');
			return $this->model_account_customer->getTransactionTotal($customer_id);
		}		
		$query = $this->db->query("SELECT SUM(amount) AS total  FROM " . DB_PREFIX . "customer_affiliate_transaction WHERE customer_id = '" . (int)$customer_id . "'");

		return $query->row['total'];
	}
	
	public function getTotalTransactionsByOrderId($order_id) {
		if(!$this->config->get('module_aff_classic_commission_table')) {
			$this->load->model('account/customer');
			return $this->model_account_customer->getTotalTransactionsByOrderId($customer_id);
		}		
		$query = $this->db->query("SELECT COUNT(*) AS total FROM " . DB_PREFIX . "customer_affiliate_transaction WHERE order_id = '" . (int)$order_id . "'");

		return $query->row['total'];
	}
	
	public function getTotalTransactions($customer_id) {
		$table = $this->config->get('module_aff_classic_commission_table') ? 'customer_affiliate_transaction' : 'customer_transaction';
		$query = $this->db->query("SELECT COUNT(*) AS total FROM " . DB_PREFIX . $table . " WHERE customer_id = '" . (int)$customer_id . "'");

		return $query->row['total'];
	}	

	private function deleteCreditsByField($field, $value) {
		$res = $this->db->query("SELECT DISTINCT(customer_transaction_id) AS c_tr_id FROM " . DB_PREFIX . "customer_affiliate_transaction WHERE `" . $field . "` = '" . (int)$value . "' AND customer_transaction_id != '0'");
		if($res->num_rows) {
			$c_tr_ids = array();
			foreach($res->rows as $r) {
				$c_tr_ids[] = (int)$c_tr_id;
			}
			$this->db->query("DELETE FROM " . DB_PREFIX . "customer_transaction WHERE customer_transaction_id IN (" . implode(',', $c_tr_ids) . ")");
		}		
	}	
	
}