<?php

/*
 * this class should be used to work with the public side of wordpress
 */
class Dahm_Public{
    
    //general class properties
    protected static $instance = null;
    private $shared = null;
    
    private function __construct() {
        
        //assign an instance of the plugin info
        $this->shared = Dahm_Shared::get_instance();
        
        //write in front-end head
        add_action('wp_head', array($this, 'set_hreflang'));

        //write in the get_footer hook
        add_action( 'get_footer', array($this, 'generate_log'));

        //enqueue styles
        add_action( 'wp_enqueue_scripts', array( $this, 'enqueue_styles' ) );

	    /*
	     * Add custom routes to the Rest API
	     */
	    add_action( 'rest_api_init', array($this, 'rest_api_register_route'));

    }
    
    /*
     * create an instance of this class
     */
    public static function get_instance() {

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

        return self::$instance;
        
    }

    /*
     * Write the connections in the 'head' section of the page
     */
    public function set_hreflang(){

        //retrive a numeric array with the connections
        $hreflang_output = $this->shared->generate_hreflang_output();

        //echo the connections in the head of the document
        if( $hreflang_output != false ){
            foreach ($hreflang_output as $single_connection) {
                echo $single_connection;
            }
        }

    }

    /*
     * Write the log with the connections
     */
    public function generate_log(){

        //don't show the log if the current user has no edit_posts capabilities or if the log in not enabled
        if( !current_user_can(get_option($this->shared->get('slug') . "_connections_menu_capability")) or ( intval(get_option("da_hm_show_log"), 10) != 1 ) ){ return; }

        //retrive a numeric array with the connections
        $hreflang_output = $this->shared->generate_hreflang_output();

        //echo the connections in the head of the document
        if( $hreflang_output !== false ){ ?>

            <div id="da-hm-log-container">
                <p id="da-hm-log-heading" ><?php esc_html_e('The following lines have been added in the HEAD section of this page', 'dahm'); ?>:</p>
                <?php
                foreach ($hreflang_output as $key => $single_connection) {
                    echo "<p>" . esc_html( $single_connection ) . "</p>";
                }
                ?>
            </div>

            <?php
        }

    }

    //enqueue styles
    public function enqueue_styles(){

        //enqueue the style used to show the log if the current user has the edit_posts capability and if the log is enabled
        if( current_user_can(get_option($this->shared->get('slug') . "_connections_menu_capability")) and ( intval(get_option("da_hm_show_log"), 10) == 1 ) ){
            wp_enqueue_style($this->shared->get('slug') . '-general', $this->shared->get('url') . 'public/assets/css/general.css', array(), $this->shared->get('ver'));
        }

    }

	/*
	 * Add custom routes to the Rest API
	 */
	function rest_api_register_route(){

		//Add the GET 'daext-hreflang-manager/v1/options' endpoint to the Rest API
		register_rest_route(
			'daext-hreflang-manager/v1', '/post/(?P<id>\d+)', array(
				'methods'  => 'GET',
				'callback' => array($this, 'rest_api_daext_hreflang_manager_read_connections_callback'),
				'permission_callback' => '__return_true'
			)
		);

		//Add the POST 'daext-hreflang-manager/v1/post' endpoint to the Rest API
		register_rest_route(
			'daext-hreflang-manager/v1', '/post/', array(
				'methods'  => 'POST',
				'callback' => array($this, 'rest_api_daext_hreflang_manager_post_connection_callback'),
				'permission_callback' => '__return_true'
			)
		);

		//Add the GET 'daext-hreflang-manager/v1/options' endpoint to the Rest API
		register_rest_route(
			'daext-hreflang-manager/v1', '/options/', array(
				'methods'  => 'GET',
				'callback' => array($this, 'rest_api_daext_hreflang_manager_read_options_callback'),
				'permission_callback' => '__return_true'
			)
		);

		//Create this endpoint only if Sync -> Status is equal to "Enabled" and Sync -> Role is equal to "Master"
		$sync_status = intval(get_option($this->shared->get('slug') . "_sync_status"), 10);
		$sync_role = intval(get_option($this->shared->get('slug') . "_sync_role"), 10);
		if($sync_status === 1 and $sync_role === 0){

			//Add the GET 'daext-hreflang-manager/v1/sync' endpoint to the Rest API
			register_rest_route(
				'daext-hreflang-manager/v1', '/sync/', array(
					'methods'  => 'GET',
					'callback' => array($this, 'rest_api_daext_hreflang_manager_read_all_connections_callback'),
					'permission_callback' => '__return_true'
				)
			);

		}

	}

	/*
	 * Callback for the GET 'daext-hreflang-manager/v1/options' endpoint of the Rest API
	 */
	function rest_api_daext_hreflang_manager_read_connections_callback( $data ) {

		//Check the capability
		if (!current_user_can(get_option($this->shared->get('slug') . "_editor_sidebar_capability"))) {
			return new WP_Error(
				'rest_read_error',
				'Sorry, you are not allowed to view the Hreflang Manager options.',
				array('status' => 403)
			);
		}

		//Generate the response

		$url_to_connect = $this->shared->get_permalink($data['id'], true);

		global $wpdb;
		$table_name = $wpdb->prefix . "da_hm_connect";
		$safe_sql = $wpdb->prepare("SELECT * FROM $table_name WHERE url_to_connect = %s", $url_to_connect);
		$row = $wpdb->get_row($safe_sql, ARRAY_A);

		if($wpdb->num_rows > 0){

            //Decode the connection data
            $row['url'] = json_decode($row['url']);
            $row['language'] = json_decode($row['language']);
            $row['script'] = json_decode($row['script']);
            $row['locale'] = json_decode($row['locale']);

            //Convert the $row in the format used in the JavaScript part of the sidebar
            for($i=1;$i<=100;$i++){
                $row['url' . $i] = $row['url']->{$i};
                $row['language' . $i] = $row['language']->{$i};
                $row['script' . $i] = $row['script']->{$i};
                $row['locale' . $i] = $row['locale']->{$i};
            }

            //Unset the properties not used in the JavaScript part of the sidebar
            unset($row->url);
            unset($row->language);
            unset($row->script);
            unset($row->locale);

			//Prepare the response
			$response = new WP_REST_Response($row);

		}else{

			return false;
		}

		return $response;

	}

	/*
     * Callback for the POST 'daext-hreflang-manager/v1/post/' endpoint of the Rest API.
	 *
	 * This method is used to save the connection when the "Update" button of the Gutenberg editor is clicked.
     */
	function rest_api_daext_hreflang_manager_post_connection_callback( $data ) {

		//Check the capability
		if (!current_user_can(get_option($this->shared->get('slug') . "_editor_sidebar_capability"))) {
			return new WP_Error(
				'rest_read_error',
				'Sorry, you are not allowed to view to add a connection.',
				array('status' => 403)
			);
		}

		$data = json_decode($data->get_body());
		$post_id = $data->postId;
		$data = $data->connectionData;

        //Init vars
		$url = [];
		$language = [];
		$script = [];
		$locale = [];

		//initialize the variables that include the URLs, the languages, the script and the locale
		for($i=1;$i<=100;$i++){

			if( isset($data->{'url' . $i}) and strlen(trim($data->{'url' . $i})) > 0 ) {
				$url[$i] = esc_url_raw($data->{'url' . $i});
				$at_least_one_url = true;
			}else {
				$url[$i] = '';
			}

			if( isset($data->{'language' . $i}) ){
				$language[$i] = sanitize_text_field($data->{'language' . $i});
			}else{
				$language[$i] = get_option($this->shared->get('slug') . '_default_language_' . $i);
			}

            if( isset($data->{'script' . $i}) ){
                $script[$i] = sanitize_text_field($data->{'script' . $i});
            }else{
                $script[$i] = get_option($this->shared->get('slug') . '_default_script_' . $i);
            }
			
			if( isset($data->{'locale' . $i}) ){
				$locale[$i] = sanitize_text_field($data->{'locale' . $i});
			}else{
				$locale[$i] = get_option($this->shared->get('slug') . '_default_locale_' . $i);
			}

		}

		//json encode for the serialized field of the database
		$url_json = json_encode($url);
		$language_json = json_encode($language);
		$script_json = json_encode($script);
		$locale_json = json_encode($locale);

		/*
         * save the fields in the da_hm_connect database table:
         *
         * - if a row with the da_hm_connect equal to the current permalink already exists update the row
         *
         * - if a row with the da_hm_connect equal to the current permalink doesn't exists create a new row
         */
		$permalink = $this->shared->get_permalink($post_id, true);

		//look for $permalink in the url_to_connect field of the da_hm_connect database table
		global $wpdb;
		$table_name = $wpdb->prefix . "da_hm_connect";
		$safe_sql = $wpdb->prepare("SELECT * FROM $table_name WHERE url_to_connect = %s", $permalink);
		$permalink_connections = $wpdb->get_row($safe_sql);

		if($permalink_connections !== null){

			//update an existing connection
			$safe_sql = $wpdb->prepare("UPDATE $table_name SET
                 url = %s,
                 language = %s,
                 script = %s,
                 locale = %s
                WHERE url_to_connect = %s ",
				$url_json,
				$language_json,
				$script_json,
				$locale_json,
				$permalink);

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

		}else{

			//Return ( do not create a new connection ) if there are not a single url defined
			if(!isset($at_least_one_url)){return;}

			//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",
				$permalink,
				$url_json,
				$language_json,
				$script_json,
				$locale_json);

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

		}

		//Generate the response
		$response = new WP_REST_Response($data);

		return $response;

	}

	/*
     * Callback for the GET 'daext-hreflang-manager/v1/options' endpoint of the Rest API
     */
	function rest_api_daext_hreflang_manager_read_options_callback( $data ) {

		//Check the capability
		if (!current_user_can(get_option($this->shared->get('slug') . "_editor_sidebar_capability"))) {
			return new WP_Error(
				'rest_read_error',
				'Sorry, you are not allowed to view the Hreflang Manager options.',
				array('status' => 403)
			);
		}

		//Generate the response
		$response = [];
		foreach($this->shared->get('options') as $key => $value){
			$response[$key] = get_option($key);
		}

		//Prepare the response
		$response = new WP_REST_Response($response);

		return $response;

	}

	/*
     * Callback for the GET 'daext-hreflang-manager/v1/sync' endpoint of the Rest API
     */
	function rest_api_daext_hreflang_manager_read_all_connections_callback( $data ) {

		$prepared_connection_a = [];

		global $wpdb;
		$table_name = $wpdb->prefix . "da_hm_connect";
		$safe_sql = "SELECT * FROM $table_name";
		$connection_a = $wpdb->get_results($safe_sql, ARRAY_A);

		if(count($connection_a) > 0){

//            foreach($connection_a as $connection){
//
//	            //Decode the connection data
//	            $connection['url'] = json_decode($connection['url']);
//	            $connection['language'] = json_decode($connection['language']);
//	            $connection['script'] = json_decode($connection['script']);
//	            $connection['locale'] = json_decode($connection['locale']);
//
//	            //Convert the $connection in the format used in the JavaScript part of the sidebar
//	            for($i=1;$i<=100;$i++){
//		            $connection['url' . $i] = $connection['url']->{$i};
//		            $connection['language' . $i] = $connection['language']->{$i};
//		            $connection['script' . $i] = $connection['script']->{$i};
//		            $connection['locale' . $i] = $connection['locale']->{$i};
//	            }
//
//	            //Unset the properties not used in the JavaScript part of the sidebar
//	            unset($connection->url);
//	            unset($connection->language);
//	            unset($connection->script);
//	            unset($connection->locale);
//
//                $prepared_connection_a[] = $connection;
//
//            }

			//Prepare the response
			$response = new WP_REST_Response($connection_a);

		}else{

			$response = false;
            
		}

		return $response;

	}
    
}