<?php
namespace SabaiApps\Directories\Component\Captcha\DisplayElement;

use SabaiApps\Directories\Component\Display\Element\AbstractElement;
use SabaiApps\Directories\Component\Entity\Model\Bundle;
use SabaiApps\Directories\Component\Display\Model\Display;
use SabaiApps\Directories\Context;

class CaptchaDisplayElement extends AbstractElement {

	protected function _displayElementInfo( Bundle $bundle ) {
		return array(
			'type'             => 'utility',
			'label'            => 'Captcha',
			'description'      => __( 'Show a captcha field', 'directories-pro' ),
			'default_settings' => array(),
			'icon'             => 'fas fa-shield-alt',
			'designable'       => array( 'margin' ),
		);
	}

	protected function _displayElementSupports( Bundle $bundle, Display $display ) {
		return in_array( $display->type, array( 'form' ) )
			&& ! empty( $bundle->info['public'] )
			&& $bundle->entitytype_name === 'post';
	}

	public function displayElementRender( Bundle $bundle, array $element, $var, ?array $context = null ) {
		if ( $this->_application->getPlatform()->isAdmin()
			|| isset( $var['#entity'] ) // do not show if editing entity
			|| ( ! $html = $var->render()->getHtml( 'captcha', $var->settings['#wrap'] ) )
		) {
			return;
		}

		return array( 'raw' => $html );
	}

	public function displayElementIsPreRenderable( Bundle $bundle, array &$element ) {
		return true;
	}

	public function displayElementPreRender( Bundle $bundle, array $element, &$var ) {
		if ( isset( $var['#entity'] ) // do not show if editing entity
			|| ( ! $form = $this->_application->Captcha_Apis_form( $bundle->name . '-' . $element['id'] ) )
		) {
			return;
		}

		// Inject form into a variable so that it can be obtained on render
		$var['captcha'] = $form;
	}
}
