<?php

class Brivium_Credits_Payment_PayPal_Model_Payment extends XenForo_Model
{
	/**
	 * Gets any log records that apply to the specified transaction.
	 *
	 * @param string $transactionId
	 *
	 * @return array [log id] => info
	 */
	public function getLogByTransactionId($transactionId)
	{
		if ($transactionId === '')
		{
			return array();
		}
		return $this->_getDb()->fetchRow('
			SELECT *
			FROM xf_credits_paypal_log
			WHERE  transaction_id = ?
		', array( $transactionId));
	}

	/**
	 * Gets any log record that indicates a transaction has been processed.
	 *
	 * @param string $transactionId
	 *
	 * @return array|false
	 */
	public function getProcessedTransactionLog($transactionId)
	{
		if ($transactionId === '')
		{
			return array();
		}

		return $this->fetchAllKeyed('
			SELECT *
			FROM xf_credits_paypal_log
			WHERE transaction_id = ?
				AND transaction_type IN (\'payment\', \'cancel\')
			ORDER BY log_date
		', 'payment_log_id', $transactionId);
	}
	public function logPayment($data)
	{
		$this->_getDb()->insert('xf_credits_paypal_log', $data);
		return $this->_getDb()->lastInsertId();
	}
	
	public function sendEmailPayment($user, $dataCredit, $event, $paypalData)
	{
		$currency = !empty($event['currency_id'])?XenForo_Application::get('brcCurrencies')->$event['currency_id']:array();
		
		if($user && $currency && !empty($currency['active']) && isset($user[$currency['column']]) && $dataCredit)
		{
			$currentCredit = $user[$currency['column']] + $dataCredit['amount'];
			$params = array(
				'user' => $user,
				'dataCredit' => $dataCredit,
				'currentCredit' => $currentCredit,
				'currency' => $currency,
				'paypalData' => $paypalData,
				'transactionTime' => XenForo_Application::$time,
				'boardTitle' => XenForo_Application::get('options')->boardTitle
			);
			$mail = XenForo_Mail::create('BRCP_user_email_payment_info', $params, $user['language_id']);
			return $mail->send($user['email'], $user['username']);
		}
		return false;
	}
	
}