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

use SabaiApps\Directories\Component\Field\Widget\AbstractWidget;
use SabaiApps\Directories\Component\Field\IField;
use SabaiApps\Directories\Component\Entity\Type\IEntity;
use SabaiApps\Directories\Component\Form\Form;

class OrderFieldWidget extends AbstractWidget {

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

	protected function _getPossibleStatuses( $status ) {
		switch ( $status ) {
			case 'pending_payment':
				return array( 'cancelled', 'completed' );
			default:
				return array();
		}
	}

	public function fieldWidgetForm( IField $field, array $settings, $value = null, ?IEntity $entity = null, array $parents = array(), $language = null ) {
		if ( ! isset( $entity ) ) {
			return;
		}

		$status = isset( $value['status'] ) ? $value['status'] : null;
		$form   = array(
			'#admin_only_main'  => true,
			'#element_validate' => array(
				function ( Form $form, &$value ) use ( $entity, $status ) {
					if ( $value['status'] === $status ) {
						return;
					}

					if ( ! $new_values = $this->_application->PaymentGateway_Order_updateStatus(
						$entity,
						$value['status'],
						array(
							'user_id' => $this->_application->getUser()->id,
							'save'    => false,
							'notes'   => $value['notes'],
						)
					) ) {
						return;
					}

					$value = $new_values + $value;
				},
			),
			'number'            => array(
				'#type'          => 'textfield',
				'#title'         => $field->Bundle->getLabel( 'singular' ),
				'#default_value' => isset( $value['number'] ) ? $value['number'] : null,
				'#horizontal'    => true,
			),
		);
		if ( ( $content_entity = $this->_application->Entity_Entity( $value['parent_entity_type'], $value['parent_entity_id'] ) )
			&& ( $content_bundle = $this->_application->Entity_Bundle( $content_entity ) ) ) {
			$form['content'] = array(
				'#type'       => 'item',
				'#title'      => $content_bundle->getLabel( 'singular' ),
				'#markup'     => '<a href="' . $this->_application->Entity_AdminUrl( $content_entity ) . ' ">' . $this->_application->H( $this->_application->Entity_Title( $content_entity ) ) . '</a>',
				'#horizontal' => true,
			);
		}
		if ( ( $possible_statuses = $this->_getPossibleStatuses( $status ) ) ) {
			$statuses            = $this->_application->PaymentGateway_Order_statuses();
			$possible_statuses[] = $status;
			$options             = array();
			foreach ( $statuses as $status_name => $_status ) {
				if ( in_array( $status_name, $possible_statuses ) ) {
					$options[ $status_name ] = $_status['label'];
				}
			}
			$form['status'] = array(
				'#type'          => 'select',
				'#title'         => __( 'Status', 'directories-pro' ),
				'#options'       => $options,
				'#default_value' => $status,
				'#horizontal'    => true,
			);
		} else {
			$status_markup = $this->_application->PaymentGateway_Order_statusLabel( $status, true, true );
			$settings      = $this->_application->Payment_Components_impl( 'default' )->getSettings();
			$gateway_label = isset( $settings['gateways']['options'][ $value['gateway'] ] ) ? $settings['gateways']['options'][ $value['gateway'] ] : 'N/A';
			switch ( $status ) {
				case 'completed':
					if ( $gateway_item_id = $entity->getSingleFieldValue( 'paymentgateway_order', 'gateway_item_id' ) ) {
						if ( ( $gateway = $this->_application->PaymentGateway_Util_gateway( $value['gateway'], true ) )
							&& ( $gateway_order_url = $gateway->paymentGatewayOrderUrl( $entity ) )
						) {
							$gateway_item_id = '<a target="_blank" rel="external nofollow noopener noreferrer" href="' . $this->_application->H( $gateway_order_url ) . '">' . $this->_application->H( $gateway_item_id ) . '</a>';
						} else {
							$gateway_item_id = $this->_application->H( $gateway_item_id );
						}
						$status_markup .= ' ' . sprintf(
							$this->_application->H( __( 'Paid via %1$s (ID: %2$s) on %3$s', 'directories-pro' ) ),
							$this->_application->H( $gateway_label ),
							$gateway_item_id,
							isset( $value['data']['status_updated'] ) ? $this->_application->System_Date_datetime( $value['data']['status_updated'] ) : 'N/A'
						);
					} elseif ( isset( $value['data']['status_updated'] ) ) {
							$status_markup .= ' ' . $this->_application->System_Date_datetime( $value['data']['status_updated'] );
					}
					break;
				case 'pending_payment':
					$status_markup .= ' ' . $this->_application->H( sprintf( __( 'To be paid via %s', 'directories-pro' ), $gateway_label ) );
					break;
				default:
					break;
			}
			$form['status'] = array(
				'#type'       => 'item',
				'#title'      => __( 'Status', 'directories-pro' ),
				'#markup'     => $status_markup,
				'#horizontal' => true,
			);
		}
		$form['summary'] = array(
			'#title'      => __( 'Order summary', 'directories-pro' ),
			'#type'       => 'item',
			'#markup'     => $this->_application->PaymentGateway_Order_renderSummary( $entity ),
			'#horizontal' => true,
		);
		$form['notes']   = $this->_application->PaymentGateway_Util_notesForm(
			__( 'Order notes', 'directories-pro' ),
			$value['notes'] ?? null,
			(array) $entity->getSingleFieldValue( 'paymentgateway_order', 'notes' ),
			true
		);

		return $form;
	}
}
