<?php
require_once (PATH_TABLES . "corporate_gift/CorporateGiftRecipientTable.php") ;
require_once (PATH_MODELS . "base/MasterBase.php") ;

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

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

	function getRecipientByGiftID($gift_id){
		$sql = "SELECT * FROM " . CorporateGiftRecipientTable::C_TABLE . " rec " .
				" LEFT JOIN " . CustomerTable::C_TABLE . " cus ON rec." . CorporateGiftRecipientTable::C_CUSTOMER_ID . " = cus." . CustomerTable::C_ID .
				" LEFT JOIN " . CustomerContactTable::C_TABLE . " con ON rec." . CorporateGiftRecipientTable::C_CONTACT_ID . " = con." . CustomerContactTable::C_CONTACT_ID .
				" WHERE " . CorporateGiftRecipientTable::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 " . CorporateGiftRecipientTable::C_TABLE . 
					" WHERE " . CorporateGiftRecipientTable::C_CUSTOMER_ID . " = " . $customer_id .
					" AND " . CorporateGiftRecipientTable::C_CONTACT_ID . " = " . $contact_id . 
					" AND " . CorporateGiftRecipientTable::C_ID . " = " . $gift_id;
			$this->db->executeSql($sql);
		}
	}

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

	}
}
