<?php

class ModelExtensionCouponForTracking extends Model {
	
	function getAffiliate($coupon_id) {
		if(!preg_match("/^\d+$/", $coupon_id)) return false;
		$q = "SELECT ca.ctype, a.customer_id, m.marketing_id, m.code FROM " . DB_PREFIX . "coupon_for_tracking ca LEFT JOIN " . DB_PREFIX . "customer_affiliate a ON a.customer_id = ca.customer_id LEFT JOIN " . DB_PREFIX . "marketing m ON m.marketing_id = ca.marketing_id WHERE ca.coupon_id = '" . (int)$coupon_id . "'";
		$res = $this->db->query($q);		

		if($res->num_rows < 1) return false;
		if($res->row['ctype'] == 'a') {
			$this->load->model('account/customer');
			$affiliate = $this->model_account_customer->getAffiliate($res->row['customer_id']);
			if(!$affiliate || !$affiliate['status']) return false;
			$affiliate['coupon_for_tracking_ctype'] = 'a';
			return $affiliate;
		}

		if(!$res->row['marketing_id'] || !$res->row['code']) return false;
		return array(
			'coupon_for_tracking_ctype' => 'm',
			'marketing_id' => $res->row['marketing_id'],
			'code' => $res->row['code']
		);
	}	

}
	
