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

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

class OrdersFieldWidget extends Field\Widget\AbstractWidget {

	protected function _fieldWidgetInfo() {
		return array(
			'label'       => __( 'Orders', '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;
		}

		$orders = array();
		foreach ( $payment_component->paymentGetOrders( $entity ) as $order ) {
			$status = $order->paymentOrderStatus();
			if ( is_array( $status ) ) {
				$status_color = $status[1];
				$status       = $status[0];
			} else {
				$status_color = 'secondary';
			}
			$order_label                        = $this->_application->H( $order->paymentOrderNumber() );
			$order_admin_url                    = $order->paymentOrderAdminUrl();
			$orders[ $order->paymentOrderId() ] = array(
				'number' => $order_admin_url ? '<a href="' . $order_admin_url . '">' . $order_label . '</a>' : $order_label,
				'date'   => $this->_application->System_Date( $order->paymentOrderTimestamp() ),
				'name'   => $this->_application->H( $order->paymentOrderName() ),
				'action' => $this->_application->H( $this->_application->Payment_Util_actionLabel( $order->paymentOrderAction(), $order->paymentOrderWasItemDeactivated() ) ),
				'status' => '<span class="' . DRTS_BS_PREFIX . 'badge ' . DRTS_BS_PREFIX . 'bg-' . $status_color . '">' . $this->_application->H( $status ) . '</span>',
				'total'  => $order->paymentOrderTotalHtml(),
			);
		}
		if ( empty( $orders ) ) {
			return;
		}

		return array(
			'#type'     => 'tableselect',
			'#header'   => array(
				'number' => '#',
				'date'   => __( 'Date', 'directories-pro' ),
				'action' => __( 'Action', 'directories-pro' ),
				'name'   => __( 'Name', 'directories-pro' ),
				'total'  => __( 'Total', 'directories-pro' ),
				'status' => __( 'Status', 'directories-pro' ),
			),
			'#options'  => $orders,
			'#disabled' => true,
			'#class'    => 'drts-data-table',
			'#size'     => 'sm',
		);
	}
}
