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

use SabaiApps\Directories\Component\Field;
use SabaiApps\Directories\Component\Entity;

class SubscriptionsFieldWidget extends Field\Widget\AbstractWidget {

	protected function _fieldWidgetInfo() {
		return array(
			'label'       => __( 'Subscriptions', 'directories-pro' ),
			'field_types' => array( $this->_name ),
		);
	}

	public function fieldWidgetForm( Field\IField $field, array $settings, $value = null, ?Entity\Type\IEntity $entity = null, array $parents = array(), $language = null ) {
		if ( ! isset( $entity )
			|| ( ! $payment_component = $this->_application->getComponent( 'Payment' )->getPaymentComponent( false ) )
			|| empty( $field->Bundle->info['payment_enable'] )
		) {
			return;
		}

		$subscriptions = array();
		foreach ( $payment_component->paymentGetSubscriptions( $entity ) as $subscription ) {
			$status = $subscription->paymentSubscriptionStatus();
			if ( is_array( $status ) ) {
				$status_color = $status[1];
				$status       = $status[0];
			} else {
				$status_color = 'secondary';
			}
			$subscription_label                                      = $this->_application->H( $subscription->paymentSubscriptionNumber() );
			$subscription_admin_url                                  = $subscription->paymentSubscriptionAdminUrl();
			$subscriptions[ $subscription->paymentSubscriptionId() ] = array(
				'number' => $subscription_admin_url ? '<a href="' . $subscription_admin_url . '">' . $subscription_label . '</a>' : $subscription_label,
				'date'   => $subscription->paymentSubscriptionNextPaymentHtml(),
				'name'   => $this->_application->H( $subscription->paymentSubscriptionName() ),
				'status' => '<span class="' . DRTS_BS_PREFIX . 'badge ' . DRTS_BS_PREFIX . 'bg-' . $status_color . '">' . $this->_application->H( $status ) . '</span>',
			);
		}
		if ( empty( $subscriptions ) ) {
			return;
		}

		return array(
			'#type'     => 'tableselect',
			'#header'   => array(
				'number' => '#',
				'name'   => __( 'Plan name', 'directories-pro' ),
				'status' => __( 'Status', 'directories-pro' ),
				'date'   => __( 'Next Payment', 'directories-pro' ),
			),
			'#options'  => $subscriptions,
			'#disabled' => true,
			'#class'    => 'drts-data-table',
			'#size'     => 'sm',
		);
	}
}
