<?php
namespace SabaiApps\Directories\Component\Membership\DisplayButton;

use SabaiApps\Directories\Application;
use SabaiApps\Directories\Component\Entity\Type\IEntity;
use SabaiApps\Directories\Component\Entity\Model\Bundle;
use SabaiApps\Directories\Component\Dashboard\DisplayButton\AbstractDisplayButton;
use SabaiApps\Directories\Component\Payment\DisplayButton\DashboardDisplayButtonTrait;

class MembershipDashboardDisplayButton extends AbstractDisplayButton {

	use DashboardDisplayButtonTrait {
		DashboardDisplayButtonTrait::_getLabel as _traitGetLabel;
	}

	protected $_isApplyMembership;

	public function __construct( Application $application, $name ) {
		parent::__construct( $application, $name, substr( $name, strlen( 'membership_' ) ) );
	}

	protected function _getUrl( Bundle $bundle, IEntity $entity, array $settings, $displayName, $isGuest = false ) {
		if ( $this->_isApplyMembership( $entity ) ) {
			if ( ! $apply_slug = $this->_application->getComponent( 'Membership' )->hasSlug( 'apply_membership' ) ) {
				return;
			}

			return $this->_application->Url( '/' . $apply_slug );
		}

		return $this->_application->Dashboard_Panels_panelUrl(
			'account',
			'membership',
			'/membership/' . $this->_route,
			array(),
			(bool) $this->_isModal( $bundle, $entity, $settings )
		);
	}

	protected function _isApplyMembership( IEntity $entity ) {
		if ( ! isset( $this->_isApplyMembership ) ) {
			$this->_isApplyMembership = $this->_route === 'upgrade' && ! $this->_application->Payment_Plan( $entity );
		}
		return $this->_isApplyMembership;
	}

	protected function _isModal( Bundle $bundle, IEntity $entity, array $settings ) {
		if ( $this->_isApplyMembership( $entity )
			&& $this->_application->getComponent( 'Membership' )->hasSlug( 'apply_membership' )
		) {
			return false;
		}

		return array( 'size' => 'lg' );
	}

	protected function _getModalTitle( Bundle $bundle, IEntity $entity, $label ) {
		return __( 'Membership', 'directories-pro' ) . ' - ' . $label;
	}

	protected function _getLabel( Bundle $bundle, IEntity $entity, array $settings ) {
		if ( $this->_isApplyMembership( $entity ) ) {
			if ( $this->_application->getComponent( 'Membership' )->hasSlug( 'apply_membership' ) ) {
				return $this->_application->getComponent( 'Membership' )->getTitle( 'apply_membership' );
			}
			return __( 'Apply Membership', 'directories-pro' );
		}
		return $this->_traitGetLabel( $bundle, $entity, $settings );
	}
}
