<?php

namespace CarDealerPress\includes\functions;

use CarDealerPress\includes\helpers\helpers;

if ( ! defined( 'ABSPATH' ) ) {
	exit;
}

class Saved_Ajax {
	public function __construct() {
	}

	// legacy theme
	public function saved_ajax_handler() {
		$data_request = array();
		$nonce_check = isset( $_REQUEST['nonce'] ) && wp_verify_nonce( sanitize_key($_REQUEST['nonce']), 'cdp_nonce' );
		if ($nonce_check ){
			$data_request = $_REQUEST;
		}
		$handler      = $data_request['handler'] ?? '';
		$request_data = $data_request['data'] ?? array();
		switch ( $handler ) {
			case 'get_gform':
				$output['id'] = $data_request['params']['key'];
				$this->apply_ajax_gravity_hooks( $data_request['params']['hooks'] );
				$form              = gravity_form( $data_request['params']['form'], $display_title = false, $display_description = false, $display_inactive = false, $field_values = false, $ajax = true, $tabindex = 0, $echo = false );
				$output['content'] = '<div class="list-form-wrapper active">' . $form . '</div>';
				break;
			case 'saveForm':
				$output['handler'] = 'saveForm';
				$output['id']      = $data_request['params']['key'];
				$this->apply_ajax_gravity_hooks( $data_request['params']['hooks'] );
				$form              = gravity_form( $data_request['params']['form'], $display_title = false, $display_description = false, $display_inactive = false, $field_values = false, $ajax = true, $tabindex = 0, $echo = false );
				$output['content'] = '<div class="saved-vehicle-form"><div class="cancel-form">Cancel Form [X]</div>' . $form . '</div>';
				break;
			default:
				$output['id']    = '';
				$output['error'] = 'That is not a valid FN parameter. Please check your string and try again.';
				break;
		}

		echo wp_json_encode( $output );
		wp_die();
	}

	public function apply_ajax_gravity_hooks( $data ) {
		$hooks = $this->set_ajax_gravity_hooks( $data );
		foreach ( $hooks as $key => $result ) {
			add_filter( "gform_field_value_" . $key, function ( $value ) use ( $result ) {
				$value = $result;

				return $value;
			} );
		}
		if ( isset( $_COOKIE['cdp_external_user_id'] ) ) {
			add_filter( "gform_field_value_dt_external_user_id", function () {
				// @codingStandardsIgnoreStart
				return sanitize_text_field(wp_unslash($_COOKIE['cdp_external_user_id']));
				// @codingStandardsIgnoreEnd
			} );
		}
	}

	public function set_ajax_gravity_hooks( $data ) {
		$result = array();
		foreach ( $data as $key => $value ) {
			$result[ 'dt_' . $key ] = $value;
		}

		return $result;
	}

}