<?php
namespace SabaiApps\Directories\Component\Field\Renderer;

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

class WhatsAppRenderer extends AbstractRenderer {

	protected function _fieldRendererInfo() {
		return array(
			'label'            => __( 'WhatsApp link', 'directories-pro' ),
			'field_types'      => array( 'phone' ),
			'default_settings' => array(
				'type'                => 'default',
				'label'               => null,
				'button'              => false,
				'target'              => '_self',
				'prefix_country_code' => false,
				'country_code'        => null,
				'message'             => null,
			),
		);
	}

	protected function _fieldRendererSettingsForm( IField $field, array $settings, array $parents = array() ) {
		return array(
			'type'                => array(
				'#title'         => __( 'Display format', 'directories-pro' ),
				'#type'          => 'select',
				'#options'       => $this->_getWhatsAppDisplayFormatOptions(),
				'#default_value' => $settings['type'],
			),
			'label'               => array(
				'#placeholder'   => __( 'Custom label', 'directories-pro' ),
				'#type'          => 'textfield',
				'#default_value' => $settings['label'],
				'#states'        => array(
					'visible' => array(
						sprintf( 'select[name="%s"]', $this->_application->Form_Form_fieldName( array_merge( $parents, array( 'type' ) ) ) ) => array( 'value' => 'label' ),
					),
				),
			),
			'button'              => array(
				'#title'         => __( 'Show as button', 'directories-pro' ),
				'#type'          => 'checkbox',
				'#default_value' => ! empty( $settings['button'] ),
			),
			'target'              => array(
				'#title'         => __( 'Open link in', 'directories-pro' ),
				'#type'          => 'select',
				'#options'       => $this->_getLinkTargetOptions(),
				'#default_value' => $settings['target'],
			),
			'prefix_country_code' => array(
				'#type'          => 'checkbox',
				'#title'         => __( 'Prefix with country code', 'directories-pro' ),
				'#default_value' => ! empty( $settings['prefix_country_code'] ),
			),
			'country_code'        => array(
				'#type'          => 'select',
				'#select2'       => true,
				'#default_value' => $settings['country_code'],
				'#options'       => $this->_getCountryCodeOptions(),
				'#states'        => array(
					'visible' => array(
						sprintf( 'input[name="%s"]', $this->_application->Form_Form_fieldName( array_merge( $parents, array( 'prefix_country_code' ) ) ) ) => array(
							'type'  => 'checked',
							'value' => true,
						),
					),
				),
			),
			'message'             => array(
				'#title'                 => __( 'Pre-filled message', 'directories-pro' ),
				'#type'                  => 'textfield',
				'#default_value'         => $settings['message'],
				'#description'           => $this->_application->System_Util_availableTags(
					$this->_application->Entity_Tokens(
						$field->Bundle,
						false,
						array(
							'site'           => true,
							'current_user'   => true,
							'auto_increment' => true,
						)
					)
				),
				'#description_no_escape' => true,
			),
		);
	}

	protected function _getWhatsAppDisplayFormatOptions() {
		return array(
			'default' => __( 'WhatsApp number', 'directories-pro' ),
			'label'   => __( 'Custom label', 'directories-pro' ),
		);
	}

	protected function _getCountryCodeOptions() {
		$ret       = array();
		$countries = $this->_application->System_Countries();
		foreach ( $this->_application->System_Countries_phone() as $country => $phone ) {
			if ( ! isset( $countries[ $country ] ) ) {
				continue;
			}

			$ret[ $phone ] = $countries[ $country ] . ' ' . $phone;
		}
		asort( $ret, SORT_LOCALE_STRING );
		return $ret;
	}

	protected function _fieldRendererRenderField( IField $field, array &$settings, Entity\Type\IEntity $entity, array $values, ?array $context = null, $more = 0 ) {
		$ret          = array();
		$country_code = empty( $settings['prefix_country_code'] ) || ( ! $country_code = preg_replace( '/\D/', '', $settings['country_code'] ) ) ? '' : $country_code;
		$label        = $settings['type'] === 'label' ? $this->_application->H( $settings['label'] ) : null;
		$text         = strlen( $settings['message'] ) ? $this->_application->H( '&text=' . rawurlencode( $this->_application->Entity_Tokens_replace( $settings['message'], $entity, false, array( 'escape' => false ) ) ) ) : '';
		$attr         = $icon = '';
		if ( $settings['target'] === '_blank' ) {
			$attr .= ' target="_blank" rel="noopener noreferrer"';
		}
		if ( ! empty( $settings['button'] ) ) {
			$classes = DRTS_BS_PREFIX . 'btn ' . DRTS_BS_PREFIX . 'btn-sm';
			$attr   .= ' class="' . $classes . '" style="background-color:#25D366;color:#fff;"';
			$icon    = '<i class="fab fa-whatsapp"></i> ';
		}
		foreach ( $values as $value ) {
			$ret[] = sprintf(
				'<a href="https://api.whatsapp.com/send?phone=%s%s%s"%s>%s%s</a>',
				$country_code,
				preg_replace( '/\D/', '', $value ),
				$text,
				$attr,
				$icon,
				isset( $label ) ? $label : $this->_application->H( $value )
			);
		}

		return implode( $settings['_separator'], $ret );
	}

	protected function _fieldRendererReadableSettings( IField $field, array $settings ) {
		$formats = $this->_getWhatsAppDisplayFormatOptions();
		$ret     = array(
			'type' => array(
				'label' => __( 'Display format', 'directories-pro' ),
				'value' => $formats[ $settings['type'] ],
			),
		);
		if ( $settings['type'] === 'label' ) {
			$ret['label'] = array(
				'label' => __( 'Custom label', 'directories-pro' ),
				'value' => $settings['label'],
			);
		}
		$ret['show_as_button'] = array(
			'label'   => __( 'Show as button', 'directories-pro' ),
			'value'   => ! empty( $settings['button'] ),
			'is_bool' => true,
		);
		$targets               = $this->_getLinkTargetOptions( true );
		$ret['target']         = array(
			'label' => __( 'Open link in', 'directories-pro' ),
			'value' => $targets[ $settings['target'] ],
		);
		if ( ! empty( $settings['prefix_country_code'] ) ) {
			$ret['country_code'] = array(
				'label' => __( 'Country code', 'directories-pro' ),
				'value' => $settings['country_code'],
			);
		}
		if ( strlen( $settings['message'] ) ) {
			$ret['message'] = array(
				'label' => __( 'Pre-filled message', 'directories-pro' ),
				'value' => $settings['message'],
			);
		}
		return $ret;
	}
}
