<?php


/**
 * Class Pay
 */
class Pay {


	/** Initial step in Paypal Express Purchase
	 * @param $f3 \Base
	 * @param $sale \Models\Sale
	 * @param $qty int Quantity to purchase
	 */
	public function paypalPurchase($f3, $sale, $qty){

		ini_set('arg_separator.output', '&');
		require_once(dirname(__FILE__).DIRECTORY_SEPARATOR.'../pay/vendor/autoload.php');

		$gatewayFactory = new \Omnipay\Common\GatewayFactory();

		/**
		 * @var \Omnipay\PayPal\ExpressGateway $gateway The class instance.
		 */
		$gateway = $gatewayFactory->create('PayPal_Express');

		$gateway->setBrandName($sale->site_name);

		$config = new \Models\Config();
		$config->load(array('_id=?',1),null, 3600);
		if ($config->paypal_api_username == null) return ($f3->get('lang_there_was_a_problem_setting_up_the_payment__please_contact_us_using_the_link_at_the_bottom_of_the_page__thanks_'));

		$gateway->setUsername($config->paypal_api_username);
		$gateway->setPassword($config->paypal_api_password);
		$gateway->setSignature($config->paypal_api_signature);
		$gateway->setTestMode($config->sales_test == 1 ? true : false);

		$port = $f3->get('PORT');
		$currPort = ((empty($port)) || ($port == 80) || ($port == 443)) ? '' : ':'.$port;
		$baseUrl = $f3->get('SCHEME').'://'.$f3->get('HOST').$currPort.$f3->get('BASE');
		$returnUrl = $baseUrl .'/index.php?spots&return&buy&'.$sale->_id.'&'.$qty;
		$cancelUrl = $baseUrl .'/index.php?spots&'.$sale->site_key;
		$amount = $sale->pricing_cost * $qty;

		try {
			/**
			 * @var \Omnipay\PayPal\Message\Response $response The class instance.
			 */
		$response = $gateway->purchase(
				array(
						'cancelUrl' => $cancelUrl,
						'returnUrl' => $returnUrl,
						'amount' =>  number_format($amount, 2, '.', ''),
						'currency' => $sale->pricing_currency,
						'description' => $sale->title
				)

		)->send();

			if ($response->isSuccessful()) {
				// payment was successful: update database
			} elseif ($response->isRedirect()) {

				// Enter initial sale record
				$saleRecord = new \Models\Salerecord();
				$saleRecord->date = date('Ymd');
				$saleRecord->sale_id = $sale->_id;
				$saleRecord->transaction_reference = $response->getTransactionReference();
				$saleRecord->payment_status = 'initial';
				$saleRecord->payment_amount = $amount;
				$saleRecord->payment_currency = $sale->pricing_currency;
				$saleRecord->quantity = $qty;
				$saleRecord->save();

				// redirect to offsite payment gateway
				return ($response->getRedirectUrl());
			} else {
				// payment failed: display message to customer
				Utils::Logger('[paypalPurchase]$response->getMessage()='.$response->getMessage());
			}

		} catch (Exception $e){
			Utils::Logger('[paypalPurchase]Error talking to Paypal - '.$e);
		}

		return ($f3->get('lang_there_was_a_problem_setting_up_the_payment__please_contact_us_using_the_link_at_the_bottom_of_the_page__thanks_'));
	}


	/** Second step in Paypal Express Purchase
	 * @param $f3 \Base
	 */
	public function paypalCompletePurchase($f3){

		$token = $f3->get('GET.token');

		if (empty($token)) return ($f3->get('lang_there_was_a_problem_accepting_your_payment__please_contact_us_using_the_link_at_the_bottom_of_the_page__thanks_'));

		$saleRecord = new \Models\Salerecord();
		$saleRecord->load(array('transaction_reference = ?', $token));
		if ($saleRecord->dry()) return ($f3->get('lang_there_was_a_problem_accepting_your_payment__please_contact_us_using_the_link_at_the_bottom_of_the_page__thanks_'));

		ini_set('arg_separator.output', '&');
		require_once(dirname(__FILE__).DIRECTORY_SEPARATOR.'../pay/vendor/autoload.php');

		$gatewayFactory = new \Omnipay\Common\GatewayFactory();

		/**
		 * @var \Omnipay\PayPal\ExpressGateway $gateway The class instance.
		 * @var \Omnipay\PayPal\Message\ExpressAuthorizeResponse $response
		 */
		$gateway = $gatewayFactory->create('PayPal_Express');
		$config = new \Models\Config();
		$config->load(array('_id=?',1),null, 3600);
		if ($config->paypal_api_username == null) return ($f3->get('lang_there_was_a_problem_setting_up_the_payment__please_contact_us_using_the_link_at_the_bottom_of_the_page__thanks_'));

		$gateway->setUsername($config->paypal_api_username);
		$gateway->setPassword($config->paypal_api_password);
		$gateway->setSignature($config->paypal_api_signature);
		$gateway->setTestMode($config->sales_test == 1 ? true : false);

		try {
		$response = $gateway->completePurchase(array(
				'transactionReference' => $token,
				'amount' => number_format($saleRecord->payment_amount, 2, '.', ''),
				'currency' => $saleRecord->payment_currency,
				'description' => $saleRecord->sale_id->title
		))->send();

		if ( $response->isSuccessful()){
			$saleRecord->payment_status = 'complete';
			$saleRecord->error = null;
			$saleRecord->save();
			return ('');
		} else {
			$saleRecord->payment_status = 'error';
			$saleRecord->error = $response->getMessage();
			$saleRecord->save();
			return ($f3->get('lang_there_was_a_problem_accepting_your_payment__please_contact_us_using_the_link_at_the_bottom_of_the_page__thanks_'));
		}

		} catch (Exception $e){
			Utils::Logger('[paypalCompletePurchase]Error talking to Paypal - '.$e);
			return ($f3->get('lang_there_was_a_problem_accepting_your_payment__please_contact_us_using_the_link_at_the_bottom_of_the_page__thanks_'));
		}

	}


	/** Initial step in Stripe Purchase
	 * @param $f3 \Base
	 * @param $sale \Models\Sale
	 * @param $qty int Quantity to purchase
	 */
	public function stripePurchase($f3, $sale, $qty){

		$response = array();
		$response['publishable_key'] = '';
		$response['image'] = '';
		$response['sitename'] = '';
		$response['description'] = '';
		$response['currency'] = '';
		$response['amount'] = '';
		$response['error'] = '';

		$config = new \Models\Config();
		$config->load();
		if ($config->stripe_publishable_key == null) {
			$response['error'] = $f3->get('lang_there_was_a_problem_setting_up_the_payment__please_contact_us_using_the_link_at_the_bottom_of_the_page__thanks_');
			return (json_encode($response));
		}

		$amount = $sale->pricing_cost * $qty;

		$response['publishable_key'] = $config->stripe_publishable_key;
		$response['sitename'] = $sale->site_name;
		$response['description'] = $sale->title;
		$response['amount'] = $amount * 100;
		$response['currency'] = $sale->pricing_currency;

		return (json_encode($response));
	}


	/** Second step in Stripe Purchase
	 * @param $f3 \Base
	 * @param $sale \Models\Sale
	 */
	public function stripeCompletePurchase($f3, $sale){

		$token = $f3->get('PARAMS.token');
		$qty = $f3->get('PARAMS.qty');
		$amount = $sale->pricing_cost * $qty;

		if (empty($token)) return ($f3->get('lang_there_was_a_problem_accepting_your_payment__please_contact_us_using_the_link_at_the_bottom_of_the_page__thanks_'));

		ini_set('arg_separator.output', '&');
		require_once(dirname(__FILE__).DIRECTORY_SEPARATOR.'../pay/vendor/autoload.php');


		$config = new \Models\Config();
		$config->load();
		if ($config->stripe_secret_key == null) return ($f3->get('lang_there_was_a_problem_setting_up_the_payment__please_contact_us_using_the_link_at_the_bottom_of_the_page__thanks_'));


		$gateway = \Omnipay\Omnipay::create('Stripe');
		$gateway->setApiKey($config->stripe_secret_key);

		// Enter initial sale record
		$saleRecord = new \Models\Salerecord();
		$saleRecord->date = date('Ymd');
		$saleRecord->sale_id = $sale->_id;
		$saleRecord->payment_status = 'initial';
		$saleRecord->payment_amount = $amount;
		$saleRecord->payment_currency = $sale->pricing_currency;
		$saleRecord->quantity = $qty;
		$saleRecord->transaction_reference = $token;

		try {
			/**
			 * @var \Omnipay\Stripe\Message\Response $response The class instance.
			 */
			$response = $gateway->purchase(
					array(
							'amount' =>  $amount,
							'currency' => $sale->pricing_currency,
							'token' => $token
					)

			)->send();

			if ( $response->isSuccessful()){
				$saleRecord->payment_status = 'complete';
				$saleRecord->error = null;
				$saleRecord->save();
				return ('');
			} else {
				$saleRecord->payment_status = 'error';
				$saleRecord->error = $response->getMessage();
				Utils::Logger('[stripeCompletePurchase]Error making Stripe payment - '.$response->getMessage());
				$saleRecord->save();
				return ($f3->get('lang_there_was_a_problem_accepting_your_payment__please_contact_us_using_the_link_at_the_bottom_of_the_page__thanks_'));
			}

		} catch (Exception $e){
			Utils::Logger('[stripeCompletePurchase]Error talking to Stripe - '.$e);
			return ($f3->get('lang_there_was_a_problem_accepting_your_payment__please_contact_us_using_the_link_at_the_bottom_of_the_page__thanks_'));
		}

	}

	/** No payment purchases
	 * @param $f3 \Base
	 * @param $sale \Models\Sale
	 */
	public function noPaymentCompletePurchase($f3, $sale){

		$qty = $f3->get('PARAMS.qty');
		$amount = $sale->pricing_cost * $qty;
		$token = $f3->get('PARAMS.token');
		
		ini_set('arg_separator.output', '&');

		// Enter initial sale record
		$saleRecord = new \Models\Salerecord();
		$saleRecord->date = date('Ymd');
		$saleRecord->sale_id = $sale->_id;
		$saleRecord->payment_status = 'initial';
		$saleRecord->payment_amount = $amount;
		$saleRecord->payment_currency = $sale->pricing_currency;
		$saleRecord->quantity = $qty;
		$saleRecord->transaction_reference = $token;

		$saleRecord->payment_status = 'complete';
		$saleRecord->error = null;
		$saleRecord->save();
		return ('');
	}
	
}