<?php
namespace SabaiApps\Directories\Component\WordPressContent\CaptchaApi;

use SabaiApps\Directories\Application;
use SabaiApps\Directories\Component\Captcha\Api\AbstractApi;
use SabaiApps\Directories\Component\Form\Form;
use SabaiApps\Directories\Exception\RuntimeException;

class ReallySimpleCaptchaApi extends AbstractApi {

	const IMG_WIDTH = 72, IMG_HEIGHT = 24;

	protected function _captchaApiInfo() {
		return array(
			'label'            => 'Really Simple CAPTCHA',
			'default_settings' => array(
				'color'    => null,
				'bg_color' => null,
			),
			'weight'           => 5,
		);
	}

	public function captchaApiIsEnabled() {
		return self::classExists( $this->_application );
	}

	public function captchaApiSettingsForm( array $settings, array $parents ) {
		return array(
			'color'    => array(
				'#title'         => __( 'Text color', 'directories-pro' ),
				'#type'          => 'colorpicker',
				'#default_value' => empty( $settings['color'] ) ? '#000000' : $settings['color'],
				'#horizontal'    => true,
			),
			'bg_color' => array(
				'#title'         => __( 'Background color', 'directories-pro' ),
				'#type'          => 'colorpicker',
				'#default_value' => empty( $settings['bg_color'] ) ? '#FFFFFF' : $settings['bg_color'],
				'#horizontal'    => true,
			),
		);
	}

	public function captchaApiForm( array $settings, $name, $trigger = null ) {
		return array(
			'#group' => true,
			'#title' => __( 'Enter the characters you see', 'directories-pro' ),
			'image'  => array(
				'#type'       => 'markup',
				'#pre_render' => array(
					array( array( $this, 'renderCaptcha' ), array( $settings, $trigger ) ),
				),
			),
			'text'   => array(
				// Just create a placeholder for the Captcha field. Captcha will be generated before render so the previous Captcha is not overwritten.
				'#type'             => 'textfield',
				'#value'            => '',
				'#element_validate' => array(
					function ( Form $form, &$value, $element ) use ( $settings, $trigger ) {
								$captcha = $this->_getReallySimpleCaptcha( $settings );
								$prefix  = $this->_getIp() . $trigger;
						if ( ! $captcha->check( $prefix, $value ) ) {
							$form->setError( __( 'You did not enter the correct characters.', 'directories-pro' ), $element );
						}
								$captcha->remove( $prefix );
								$value = '';
					},
				),
			),
		);
	}

	public function renderCaptcha( $form, &$element, $settings, $trigger ) {
		$captcha            = $this->_getReallySimpleCaptcha( $settings );
		$prefix             = $this->_getIp() . $trigger;
		$image              = $captcha->generate_image( $prefix, $captcha->generate_random_word() );
		$image_src          = rtrim(
			str_replace(
				rtrim( str_replace( '\\', '/', ABSPATH ), '/' ),
				rtrim( $this->_application->getPlatform()->getSiteUrl(), '/' ),
				str_replace( '\\', '/', $captcha->tmp_dir )
			),
			'/'
		) . '/' . $image;
		$element['#markup'] = '<img style="display:block;margin-bottom:0.5em;" src="' . $image_src . '?t=' . time() . '" width="' . self::IMG_WIDTH . '" height="' . self::IMG_HEIGHT . '" />';
	}

	private function _getReallySimpleCaptcha( array $settings ) {
		if ( ! $class = self::classExists( $this->_application ) ) {
			throw new RuntimeException( 'Really Simple CAPTCHA class does not exist.' );
		}
		$captcha          = new $class();
		$captcha->tmp_dir = $this->_application->getComponent( 'System' )->getTmpDir();
		/* Array of CAPTCHA image size. Width and height */
		$captcha->img_size = array( self::IMG_WIDTH, self::IMG_HEIGHT );
		/* Background color of CAPTCHA image. RGB color 0-255 */
		$captcha->bg = empty( $settings['bg_color'] ) ? array( 255, 255, 255 ) : $this->_application->System_Color_hexToRgb( substr( $settings['bg_color'], 1 ), true );
		/* Foreground (character) color of CAPTCHA image. RGB color 0-255 */
		$captcha->fg = empty( $settings['color'] ) ? array( 0, 0, 0 ) : $this->_application->System_Color_hexToRgb( substr( $settings['color'], 1 ), true );
		/* Coordinates for a text in an image. */
		$captcha->base = array( 6, 18 );
		/* Font size */
		$captcha->font_size = 14;
		/* Width of a character */
		$captcha->font_char_width = 15;
		/* Image type. 'png', 'gif' or 'jpeg' */
		$captcha->img_type = 'png';
		/* Mode of temporary image files */
		$captcha->file_mode = 0644;
		/* Mode of temporary answer text files */
		$captcha->answer_file_mode = 0640;

		return $captcha;
	}

	public static function classExists( Application $application ) {
		// Check if the Really Simple CAPTCHA class exists
		// If not, try to include it from the plugin directory
		$class_name = '\ReallySimpleCaptcha';
		if ( ! class_exists( $class_name, false ) ) {
			$class_file = $application->getPlatform()->getPluginsDir() . '/really-simple-captcha/really-simple-captcha.php';
			if ( ! file_exists( $class_file ) ) {
				return false;
			}
			require $class_file;
		}
		return class_exists( $class_name, false ) ? $class_name : false;
	}
}
