<?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 DiscountFieldWidget extends AbstractWidget {

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

	public function fieldWidgetForm( IField $field, array $settings, $value = null, ?IEntity $entity = null, array $parents = array(), $language = null ) {
		$discount_type = $code_value = $code_random = $max_redemptions = $date_range = $applicable_plans = null;
		if ( isset( $value ) ) {
			$data           = $value['data'] ?? array();
			$discount_type  = $value['discount_type'] ?? null;
			$discount_value = $value['discount_value'] ?? null;
			if ( isset( $value['discount_code'] )
				&& strlen( $value['discount_code'] )
			) {
				if ( strpos( $value['discount_code'], '-' ) !== false ) {
					list($code_value, $code_random) = explode( '-', $value['discount_code'], 2 );
				} else {
					$code_value  = $value['discount_code'];
					$code_random = '';
				}
			}
			$max_redemptions = $value['max_redemptions'] ?? 0;
			$date_range      = ! empty( $value['starts_at'] ) && ! empty( $value['expires_at'] ) ? array( $value['starts_at'], $value['expires_at'] ) : null;
		}
		$discount_types = $this->_application->PaymentGateway_Util_discountTypes();
		$form           = array(
			'#admin_only_main'  => true,
			'#element_validate' => array(
				function ( Form $form, &$value, $element ) use ( $discount_types ) {
					if ( empty( $value['discount_type'] )
					|| ! isset( $discount_types[ $value['discount_type'] ] )
						) {
						$form->setError( $element, __( 'Invalid discount type selected.', 'directories-pro' ) );
						return;
					}
					if ( $value['discount_type'] === 'fixed' ) {
						if ( ! isset( $value['value_fixed'] ) || ! is_numeric( $value['value_fixed'] ) ) {
							$form->setError( $element, __( 'Please enter a valid fixed discount amount.', 'directories-pro' ) );
							return;
						}
						$value['discount_value'] = $value['value_fixed'];
						unset( $value['value_fixed'] );
					} elseif ( $value['discount_type'] === 'percentage' ) {
						if ( ! isset( $value['value_percent'] )
							|| ! is_numeric( $value['value_percent'] )
							|| $value['value_percent'] < 1
							|| $value['value_percent'] > 100
						) {
							$form->setError( $element, __( 'Please enter a valid percentage discount amount.', 'directories-pro' ) );
							return;
						}
						$value['discount_value'] = $value['value_percent'];
						unset( $value['value_percent'] );
					}
					if ( isset( $value['discount_code']['value'] ) ) {
						$code = strtoupper( $value['discount_code']['value'] );
						if ( ! empty( $value['discount_code']['append_random'] )
							&& isset( $value['discount_code']['random'] )
							&& strlen( $value['discount_code']['random'] )
						) {
							$code .= '-' . strtoupper( $value['discount_code']['random'] );
						}
						$value['discount_code'] = $code;
					} else {
						$value['discount_code'] = '';
					}
					if ( ! empty( $value['date_range'][0] ) ) {
						$value['starts_at'] = $value['date_range'][0];
					}
					if ( ! empty( $value['date_range'][1] ) ) {
						$value['expires_at'] = $value['date_range'][1];
					}
					unset( $value['date_range'] );

					// Update usage count by counting the number of usage history entries
					$value['usage_count'] = empty( $value['usage_history'] ) || ! is_array( $value['usage_history'] )
					? 0
					: count( array_filter( $value['usage_history'] ) ); // usage_history may contain empty entries

					// foreach ([] as $key) {
					// if (isset($value[$key])) {
					// $value['data'][$key] = $value[$key];
					// unset($value[$key]);
					// }
					// }
				},
			),
			'discount_type'     => array(
				'#type'          => 'select',
				'#title'         => __( 'Discount type', 'directories-pro' ),
				'#options'       => $discount_types,
				'#default_value' => $discount_type,
				'#horizontal'    => true,
				'#required'      => true,
				'#weight'        => 1,
			),
			'value_fixed'       => array(
				'#title'            => __( 'Discount amount', 'directories-pro' ),
				'#type'             => 'number',
				'#default_value'    => $discount_type === 'fixed' && isset( $discount_value ) ? $discount_value : null,
				'#field_prefix'     => $this->_application->Payment_Components_impl( 'default' )->paymentGetCurrency(),
				'#numeric'          => true,
				'#step'             => 0.01,
				'#horizontal'       => true,
				'#states'           => array(
					'visible' => array(
						$type_selector = sprintf( '[name="%s"]', $this->_application->Form_Form_fieldName( array( $parents, 'discount_type' ) ) ) => array(
							'type'  => 'value',
							'value' => 'fixed',
						),
					),
				),
				'#weight'           => 2,
				'#display_required' => true,
			),
			'value_percent'     => array(
				'#title'            => __( 'Discount percentage', 'directories-pro' ),
				'#type'             => 'slider',
				'#default_value'    => $discount_type === 'percentage' && isset( $discount_value ) ? $discount_value : null,
				'#field_suffix'     => '%',
				'#min_value'        => 1,
				'#max_value'        => 100,
				'#horizontal'       => true,
				'#states'           => array(
					'visible' => array(
						$type_selector => array(
							'type'  => 'value',
							'value' => 'percentage',
						),
					),
				),
				'#weight'           => 2,
				'#display_required' => true,
			),
			'description'       => array(
				'#type'          => 'textarea',
				'#title'         => __( 'Description', 'directories-pro' ),
				'#rows'          => 3,
				'#default_value' => isset( $entity ) ? $entity->getContent() : null,
				'#horizontal'    => true,
				'#weight'        => 5,
			),
			'discount_code'     => array(
				'#title'            => __( 'Discount code', 'directories-pro' ),
				'#horizontal'       => true,
				'#display_required' => true,
				'#weight'           => 10,
				'#row'              => true,
				'#group'            => true,
				'#row_gutter'       => 'none',
				'value'             => array(
					'#type'          => 'textfield',
					'#placeholder'   => 'SALE2025',
					'#default_value' => $code_value,
					'#col'           => 6,
					'#col_grow'      => true,
					'#class'         => 'drts-grow',
					'#attributes'    => array( 'style' => 'text-transform:uppercase;' ),
					'#max_length'    => 40,
					'#alnum'         => true,
					'#required'      => true,
				),
				'separator'         => array(
					'#type'       => 'item',
					'#markup'     => '<span class="' . DRTS_BS_PREFIX . 'text-center ' . DRTS_BS_PREFIX . 'my-0" style="font-weight:bold;font-size:1.5rem">-</span>',
					'#col'        => 1,
					'#states'     => array(
						'visible' => array(
							$append_random_selector = sprintf( '[name="%s[]"]', $this->_application->Form_Form_fieldName( array( $parents, 'discount_code', 'append_random' ) ) ) => array(
								'type'  => 'checked',
								'value' => true,
							),
						),
					),
					'#attributes' => array( 'style' => 'text-align:center;' ),
					'#class'      => DRTS_BS_PREFIX . 'text-center',
				),
				'random'            => array(
					'#type'             => 'textfield',
					'#default_value'    => isset( $code_random ) && strlen( $code_random ) ? $code_random : substr( str_shuffle( 'ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789' ), 0, 8 ),
					'#col'              => 5,
					'#class'            => 'drts-paymentgateway-discount-code-random',
					'#attributes'       => array( 'style' => 'text-transform:uppercase;' ),
					'#states'           => array(
						'visible' => array(
							$append_random_selector => array(
								'type'  => 'checked',
								'value' => true,
							),
						),
					),
					'#max_length'       => 10,
					'#alnum'            => true,
					'#field_suffix'     => '<i class="fas fa-rotate-right"></i>',
					'#field_suffix_btn' => true,
					'#js_ready'         => '$("#__FORM_ID__").find(".drts-paymentgateway-discount-code-random button").click(function(e) {
    e.preventDefault();
    $(this).closest(".drts-paymentgateway-discount-code-random").find("input[type=text]").val(Math.random().toString(36).substring(2, 10).toUpperCase());
});',
				),
				'append_random'     => array(
					'#type'          => 'checkbox',
					'#title'         => __( 'Append random characters', 'directories-pro' ),
					'#default_value' => ! isset( $code_random ) || strlen( $code_random ),
					'#switch'        => false,
				),
			),
			'max_redemptions'   => array(
				'#type'          => 'slider',
				'#integer'       => true,
				'#title'         => __( 'Max. redemptions', 'directories-pro' ),
				'#default_value' => $max_redemptions,
				'#min_value'     => 0,
				'#max_value'     => 100,
				'#min_text'      => __( 'Unlimited', 'directories-pro' ),
				'#horizontal'    => true,
				'#weight'        => 15,
			),
			'date_range'        => array(
				'#type'          => 'daterangepicker',
				'#title'         => __( 'Date range', 'directories-pro' ),
				'#description'   => __( 'Enter the period during which this discount is valid. Leave empty if there is no restriction.', 'directories-pro' ),
				'#default_value' => $date_range,
				'#horizontal'    => true,
				'#weight'        => 25,
			),
			'usage_history'     => array( '#weight' => 35 ) + $this->_application->PaymentGateway_Util_notesForm(
				__( 'Discount usage history', 'directories-pro' ),
				$value['usage_history'] ?? null,
				isset( $entity ) ? (array) $entity->getSingleFieldValue( 'paymentgateway_discount', 'usage_history' ) : array(),
				false,
				true,
				array( 'added_by' => __( 'Used by: %s', 'directories-pro' ) )
			),
		);

		return $form;
	}
}
