<?php
namespace SabaiApps\Directories\Component\Payment\Controller;

use SabaiApps\Directories\Component\FrontendSubmit;
use SabaiApps\Directories\Context;

class OrderAddon extends FrontendSubmit\Controller\AbstractSubmitEntity {

	protected function _getSteps( Context $context, array &$formStorage ) {
		return array(
			'select_plan' => array( 'order' => 3 ),
			'checkout'    => array( 'order' => 99 ),
		);
	}

	public function _getFormForStepSelectPlan( Context $context, array &$formStorage ) {
		if ( $this->Payment_Util_hasPendingOrder( $context->entity ) ) {
			$context->setError(
				__( 'There are currently one or more pending orders for the item selected.', 'directories-pro' ),
				'/' . $this->getPlatform()->getSlug( 'Dashboard', 'dashboard' )
			);
			return false;
		}
		if ( $this->Payment_Util_isSuspended( $context->entity ) ) {
			$context->setError(
				__( 'The selected item is currently suspended.', 'directories-pro' ),
				'/' . $this->getPlatform()->getSlug( 'Dashboard', 'dashboard' )
			);
			return false;
		}

		$form = $this->Payment_Plans_form(
			$context->entity,
			'addon',
			false,
			false
		);
		if ( empty( $form['plan']['#options'] ) ) {
			$this->_submitable = false;
		} else {
			$this->_ajaxSubmit      = false;
			$this->_submitable      = true;
			$this->_submitButtons[] = array(
				'#btn_color' => 'primary',
				'#btn_label' => $this->Filter(
					'payment_checkout_btn_text',
					__( 'Proceed to checkout', 'directories-pro' ),
					array( $context->entity->getBundleName(), 'order_addon' )
				),
				'#btn_size'  => 'lg',
			);
		}
		return $form;
	}

	public function _getFormForStepCheckout( Context $context, array &$formStorage ) {
		if ( ! $plan = $this->_getSelectedPlan( $context, $formStorage ) ) {
			return array();
		}

		$this->_submitButtons  = false;
		$context->is_dashboard = false;
		return $this->getComponent( 'Payment' )->getPaymentComponent( true )->paymentCheckoutForm( $context, $plan, $context->entity, 'order_addon' );
	}

	protected function _complete( Context $context, array $formStorage ) {
		if ( ! $plan = $this->_getSelectedPlan( $context, $formStorage ) ) {
			return false;
		}

		return $this->getComponent( 'Payment' )->getPaymentComponent( true )->paymentCheckoutComplete( $context, $plan, $context->entity, 'order_addon' );
	}

	protected function _getSelectedPlan( Context $context, array $formStorage ) {
		if ( ! empty( $formStorage['values']['select_plan']['plan'] ) ) {
			return $this->getComponent( 'Payment' )->getPaymentComponent( true )
				->paymentGetPlanById( $context->entity->getBundleName(), $formStorage['values']['select_plan']['plan'] );
		}
	}
}
