<?php
namespace SabaiApps\Directories\Component\PaymentGateway;

use SabaiApps\Directories\Component\Payment\IPlan;
use SabaiApps\Directories\Component\Entity\Type\IEntity;

class PaymentPlan implements IPlan {

	protected $_plan;

	public function __construct( IEntity $plan ) {
		$this->_plan = $plan;
	}

	/**
	 * @return IEntity
	 */
	public function getPlan() {
		return $this->_plan;
	}

	protected function _getData( $key = null ) {
		$data = $this->_plan->getSingleFieldValue( 'paymentgateway_plan', 'data' );
		return isset( $key ) ? ( $data[ $key ] ?? null ) : $data;
	}

	public function paymentPlanId() {
		return $this->_plan->getId();
	}

	public function paymentPlanName() {
		return $this->_plan->getSlug();
	}

	public function paymentPlanComponent() {
		return 'default';
	}

	public function paymentPlanType() {
		return $this->_plan->getSingleFieldValue( 'paymentgateway_plan', 'plan_type' );
	}

	public function paymentPlanTitle() {
		return $this->_plan->getTitle();
	}

	public function paymentPlanDescription() {
		return $this->_plan->getContent();
	}

	public function paymentPlanFeatureList() {
		$list         = array();
		$feature_list = $this->_getData( 'feature_list' );
		if ( ! empty( $feature_list['default'] ) ) {
			foreach ( $feature_list['default'] as $value ) {
				if ( isset( $feature_list['options'][ $value ] ) ) {
					$list[] = array(
						'text' => $feature_list['options'][ $value ],
						'icon' => empty( $feature_list['icons'][ $value ] ) ? null : $feature_list['icons'][ $value ],
					);
				}
			}
		}
		return $list;
	}

	public function paymentPlanEntityLevel() {
		$level = $this->_getData( 'level' );
		return $level ?? '';
	}

	public function paymentPlanFeatures() {
		return ( $features = $this->_getData( 'features' ) ) ? $features['enabled'] : array();
	}

	public function paymentPlanIsFeatured() {
		return $this->_plan->getSingleFieldValue( 'paymentgateway_plan', 'featured' ) == 1;
	}

	public function paymentPlanPrice() {
		return $this->_getData( 'price' );
	}

	public function paymentPlanIsPurchasable() {
		return $this->_plan->isPublished()
			&& $this->_plan->getSingleFieldValue( 'paymentgateway_plan', 'active' ) == 1;
	}

	public function paymentPlanInterval() {
		return $this->_getData( 'interval' );
	}

	public function paymentPlanIntervalCount() {
		return $this->_getData( 'interval_count' );
	}
}
