<?php

/*
 * This class should be used to include ajax actions.
 */

class Dahm_Ajax
{

	protected static $instance = null;
	private $shared = null;

	private function __construct()
	{

		//assign an instance of the plugin info
		$this->shared = Dahm_Shared::get_instance();

		//AJAX requests for logged-in users
		add_action('wp_ajax_dahm_wizard_generate_connections', array($this, 'dahm_wizard_generate_connections'));

	}

	/*
	 * Return an istance of this class.
	 */
	public static function get_instance()
	{

		if (null == self::$instance) {
			self::$instance = new self;
		}

		return self::$instance;

	}

	/*
	 * Ajax handler used to generate the connections based on the data available in the table of the Wizard menu.
	 *
	 * This method is called when the "Generate Connections" button available in the Wizard menu is clicked.
	 */
	public function dahm_wizard_generate_connections()
	{

		//check the referer
		if ( ! check_ajax_referer('dahm', 'security', false)) {
			echo "Invalid AJAX Request";
			die();
		}

		//check the capability
		if ( ! current_user_can(get_option($this->shared->get('slug') . "_wizard_menu_capability"))) {
			echo 'Invalid Capability';
			die();
		}

		//Set the PHP "Max Execution Time" and "Memory Limit" based on the values defined in the options
		$this->shared->set_met_and_ml();

		//init vars
		$query_result = false;
		$query_result_alternate = false;
		$query_result_counter = 0;
		$query_result_alternate_counter = 0;

		//get the data of the table
		$table_data_a = json_decode(stripslashes($_POST['table_data']));

		//Save the data ------------------------------------------------------------------------------------------------

		global $wpdb;
		$table_name = $wpdb->prefix . $this->shared->get('slug') . "_connect";

		foreach ($table_data_a as $row_index => $row_data) {

			$url_to_connect = sanitize_text_field($row_data[0]);

			if(!empty($url_to_connect)){

                $url = [];
                $language = [];
                $script = [];
                $locale = [];

				for($i=1;$i<=100;$i++){

					$url[$i] = esc_url_raw($row_data[1+(4*($i-1))]);
					$language[$i] = sanitize_text_field($row_data[2+(4*($i-1))]);
                    $script[$i] = sanitize_text_field($row_data[3+(4*($i-1))]);
					$locale[$i] = sanitize_text_field($row_data[4+(4*($i-1))]);

                    if(!$this->shared->is_valid_language($language[$i])){
                        $language[$i] = 'x-default';
                    }

                    if(!$this->shared->is_valid_script($script[$i])){
                        $script[$i] = '';
                    }
					
					if(!$this->shared->is_valid_locale($locale[$i])){
						$locale[$i] = '';
					}

				}

                //Create the serialized fields for the database
                $url_json = json_encode($url);
                $language_json = json_encode($language);
                $script_json = json_encode($script);
                $locale_json = json_encode($locale);

				//add a new connection into the database
				$safe_sql = $wpdb->prepare("INSERT INTO $table_name SET url_to_connect = %s,
                 url = %s,
                 language = %s,
                 script = %s,
                 locale = %s",
                    $url_to_connect,
                    $url_json,
                    $language_json,
                    $script_json,
                    $locale_json
                );

				$query_result = $wpdb->query($safe_sql);

				if ($query_result !== false) {
					$query_result_counter++;
				}

				$auto_alternate_pages = intval(get_option("da_hm_auto_alternate_pages"), 10);
				if($auto_alternate_pages === 1){

					for($i=1;$i<=100;$i++){

						if ( strlen( trim( $url[$i] ) ) > 0 and $url[$i] !== $url_to_connect ) {

							$safe_sql = $wpdb->prepare( "INSERT INTO $table_name SET url_to_connect = %s ,
                         url = %s,
                         language = %s,
                         script = %s,
                         locale = %s",
								$url[$i],
								$url_json,
								$language_json,
								$script_json,
								$locale_json );

							$query_result_alternate = $wpdb->query( $safe_sql );

							if ($query_result_alternate !== false) {
								$query_result_alternate_counter++;
							}

						}

					}

				}

			}

		}

		//send output
		echo json_encode([
			'connections_added' => $query_result_counter,
			'connections_added_alternate' => $query_result_alternate_counter,
			]);
		die();

	}

}