<?php
require_once (PATH_TABLES . "campaign/CampaignRecipientTable.php") ;
require_once (PATH_MODELS . "base/MasterBase.php") ;

class CampaignRecipientClass extends MasterBase {
	function __construct($db) {
		$this->db 		= $db ;
		$this->tbl 		= CampaignRecipientTable::C_TABLE;
	}
	function __destruct() {
	}

	function updateRecipient($cus_id, $con_id, $gift_amt, $gift_id){
		$sql = "UPDATE " . CampaignRecipientTable::C_TABLE . 
					" SET " . CampaignRecipientTable::C_GIFT_AMOUNT . " = " . $gift_amt .
				" WHERE " . CampaignRecipientTable::C_CUSTOMER_ID . " = " . $cus_id . 
				" AND " . CampaignRecipientTable::C_CONTACT_ID . " = " . $con_id .
				" AND " . CampaignRecipientTable::C_ID . " = " . $gift_id;
		$this->db->executeSql($sql);
	}

	function getRecipientByGiftID($gift_id){
		$sql = "SELECT * FROM " . CampaignRecipientTable::C_TABLE . " rec " .
				" LEFT JOIN " . CustomerTable::C_TABLE . " cus ON rec." . CampaignRecipientTable::C_CUSTOMER_ID . " = cus." . CustomerTable::C_ID .
				" LEFT JOIN " . CustomerContactTable::C_TABLE . " con ON rec." . CampaignRecipientTable::C_CONTACT_ID . " = con." . CustomerContactTable::C_CONTACT_ID .
				" WHERE " . CampaignRecipientTable::C_ID . " = " . $gift_id;

		$rows = $this->db->getTable($sql);

		if(!is_null($rows) && count($rows) > 0){
			return $rows;
		}else{
			return [];
		}
	}

	function deleteRecipient($ids, $gift_id){
		foreach($ids as $id){
			$pieces 	 = explode("_", strval($id));

			$customer_id = $pieces[0];
			$contact_id  = $pieces[1];
			$sql = "DELETE FROM " . CampaignRecipientTable::C_TABLE . 
					" WHERE " . CampaignRecipientTable::C_CUSTOMER_ID . " = " . $customer_id .
					" AND " . CampaignRecipientTable::C_CONTACT_ID . " = " . $contact_id . 
					" AND " . CampaignRecipientTable::C_ID . " = " . $gift_id;
			$this->db->executeSql($sql);
		}
	}

	function getGiftRecipientByRefID($gift_id, $ref_id){
		$sql = "SELECT * FROM " . CustomerContactTable::C_TABLE . " con " . 
					" LEFT JOIN " . CampaignRecipientTable::C_TABLE . " rec ON con." . CustomerContactTable::C_CONTACT_ID . " = rec." . CampaignRecipientTable::C_CONTACT_ID .
				" WHERE con." . CustomerContactTable::C_REF_ID . " = '" . $ref_id . "' AND rec." . CampaignTable::C_ID . " = " . $gift_id;
		$row = $this->db->getTable($sql);
		if(!is_null($row) && count($row) > 0){
			return $row[0];
		}else{
			return null;
		}

	}
}
