<?php
/**
 * Math Captcha
 */

class SG_Math_Captcha extends GA_Integration {
	/**
	 * Setting initial params
	 */
	public function __construct() {

		$this->title = __( 'Math Captcha', 'giveasap' );
		$this->settings_id = 'sg_math_captcha';
		$this->image = untrailingslashit( GASAP_URI ) . '/includes/integrations/assets/math.jpg';
		$this->desc = __( 'Enable Math Captcha. This will work if PHP Sessions are enabled on your server.', 'giveasap' );

		parent::__construct();

		add_action( 'init', array( $this, 'start_captcha' ) );
		add_action( 'sg_process_registration', array( $this, 'sg_process_math_captcha' ) );
		add_action( 'sg_form_before_button', array( $this, 'sg_show_math_captcha' ), 20, 3 );
	}

	/**
	 * Show math captcha
	 *
	 * @since 2.13.0
	 *
	 * @param GiveASAP_Front $front
	 * @param array          $settings
	 * @param WP_User        $user
	 */
	function sg_show_math_captcha( $front, $settings, $user ) {
		if ( $user->ID ) {
			return;
		}

		$operator = $_SESSION['sg_operator'];
		if ( ! $operator ) {
			$operator = '-';
		} else {
			$operator = '+';
		}
		?>
		<p class="sg_math_captcha">
			<strong><?php echo esc_html( $_SESSION['sg_int1'] ) . ' ' . $operator . ' ' . $_SESSION['sg_int2']; ?></strong>
			<input name="sg_math_captcha" class="giveasap_input" type="number" />
		</p>
		<?php
	}

	/**
	 * Process the captcha and add error if wrong.
	 *
	 * @param GiveASAP_Front $front
	 */
	public function sg_process_math_captcha( $front ) {
		if ( isset( $_POST['sg_math_captcha'] ) ) {
			$operator = $_SESSION['sg_operator'];
			$result   = 0;
			if ( ! $operator ) {
				$result = absint( $_SESSION['sg_int1'] ) - absint( $_SESSION['sg_int2'] );
			} else {
				$result = absint( $_SESSION['sg_int1'] ) + absint( $_SESSION['sg_int2'] );
			}

			if ( floatval( $result ) !== floatval( $_POST['sg_math_captcha'] ) ) {
				$front->add_error( 'captcha', __( 'The result is wrong. Try again', 'giveasap' ) );
				$this->create_session_vars();
			}
		}
	}

	/**
	 * Captcha
	 */
	public function start_captcha() {
		if ( ! session_id() ) {
			session_start();
		}

		if ( ! isset( $_SESSION['sg_operator'] ) ) {
			$this->create_session_vars();
		}
	}

	/**
	 * Create the session variables.
	 */
	private function create_session_vars() {
		$_SESSION['sg_int1']     = rand(0, 20);
		$_SESSION['sg_int2']     = rand(0, $_SESSION['sg_int1'] - 1);
		$_SESSION['sg_operator'] = rand(0, 1);
	}
}

add_filter( 'giveasap_integrations', 'sg_math_captcha_register' );

/**
 * Registering Math Captcha
 *
 * @return array
 */
function sg_math_captcha_register( $integrations ) {

	$integrations['sg_math_captcha'] = 'SG_Math_Captcha';

	return $integrations;
}