<?php
class Calendarista_StripeHelper{
	private $name = 'Stripe';
	public function __construct(){}
	
    public function charge()
    {
        if (!(array_key_exists('action', $_POST) 
			&& $_POST['action'] == 'calendarista_stripe_charge')){
				return;
		}
		if(!isset($_POST['stagingId'])){
			return false;
		}
		if(!class_exists('Stripe')){
			require_once CALENDARISTA_STRIPE_SDK . 'init.php';
		}
		$settings = self::getSettings();
		\Stripe\Stripe::setApiKey($settings->secretKey);
		$intent = null;
		 $upfrontPayment = isset($_POST['upfrontPayment']) ? (int)$_POST['upfrontPayment'] : 0;
		 $checkoutHelper = new Calendarista_CheckoutHelper(array('stagingId'=>sanitize_text_field($_POST['stagingId']), 'upfrontPayment'=>$upfrontPayment));
		   if($checkoutHelper->stockValid()){
				try{
				   if (isset($_POST['payment_method_id'])) {
						$customers = \Stripe\Customer::all(array('email'=>$_POST['customer_email'], 'limit'=>1));
						$customer = null;
						if($customers && count($customers->data) > 0){
							$customer = $customers->data[0];
						}else{
							$customer = \Stripe\Customer::create(array(
								'email'=>$_POST['customer_email'],
								'name'=>$_POST['full_name'],
								'source'=>$_POST['payment_intent_id']
							));
						}
						$intent = \Stripe\PaymentIntent::create(array(
							'payment_method'=>$_POST['payment_method_id']
							, 'amount'=>$_POST['total']
							, 'currency'=>$_POST['currency']
							, 'confirm'=>true
							, 'automatic_payment_methods'=>array('enabled'=>true, 'allow_redirects'=>'never')
							, 'description'=>$_POST['itemName']
							, 'customer'=>$customer
						));
					}
					if (isset($_POST['payment_intent_id'])) {
						$intent = \Stripe\PaymentIntent::retrieve($_POST['payment_intent_id']);
						//already confirmed on the client
						//$intent->confirm();
					}
					$this->generatePaymentResponse($intent);
				} catch (\Stripe\Exception\ApiErrorException $e) {
					# Display error on client
					echo json_encode(['error'=>$e->getMessage()]);
				}
		   }else{
				$checkoutHelper->notifyOutOfStock();
				echo json_encode(['error'=>$checkoutHelper->getOutOfStockErrorMessage()]);
			}
    }
	protected function generatePaymentResponse($intent) {
		$stagingId = $_POST['stagingId'];
		$upfrontPayment = isset($_POST['upfrontPayment']) ? (int)$_POST['upfrontPayment'] : 0;
		if (in_array($intent->status, array('requires_source_action', 'requires_action')) &&
			$intent->next_action->type == 'use_stripe_sdk') {
			# Tell the client to handle the action
			echo json_encode([
				'requires_action' => true,
				'payment_intent_client_secret' => $intent->client_secret
			]);
		} else if ($intent->status == 'succeeded') {
			# The payment didn’t need any additional actions and completed!
			# Handle post-payment fulfillment
			$invoiceId = $this->log($stagingId, $intent->id, $upfrontPayment);
			echo json_encode(['success' => true, 'invoiceId'=>$invoiceId]);
		} else {
			# Invalid status
			http_response_code(500);
			echo json_encode(['error' => 'Invalid PaymentIntent status']);
		}
	}
	protected function log($stagingId, $chargeId, $upfrontPayment){
		if($stagingId){
			//log booking
			$checkoutHelper = new Calendarista_CheckoutHelper(array(
				'stagingId'=>$stagingId
				, 'paymentOperator'=>$this->name
				, 'paymentDate'=>new Calendarista_DateTime()
				, 'transactionId'=>$chargeId
				, 'upfrontPayment'=>$upfrontPayment
			));
			$order = $checkoutHelper->log();
			Calendarista_CheckoutHelper::confirmAndNotify($order->id, false);
			do_action('calendarista_after_payment', $order->id, Calendarista_PaymentOperator::STRIPE);
			return $order->invoiceId;
		}
		return null;
	}
	public static function getSettings(){
		$repo = new Calendarista_PaymentSettingRepository();
		$result = $repo->read(Calendarista_PaymentOperator::STRIPE);
		if($result){
			return new Calendarista_StripeSetting($result);
		}
		return false;
	}
}
?>