<?php
/**
 * Global Data Hub AJAX controller.
 *
 * @package Noesia_Smart_Waiter
 */

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

if ( ! class_exists( 'Noesia_SWA_Global_Data_Hub_Ajax' ) ) {
    /**
     * AJAX owner.
     */
    class Noesia_SWA_Global_Data_Hub_Ajax {

        /**
         * Service.
         *
         * @var Noesia_SWA_Global_Data_Hub_Service
         */
        private $service;

        /**
         * Constructor.
         *
         * @param Noesia_SWA_Global_Data_Hub_Service $service Service.
         */
        public function __construct( Noesia_SWA_Global_Data_Hub_Service $service ) {
            $this->service = $service;
        }

        /**
         * Register hooks.
         *
         * @return void
         */
        public function register_hooks() {
            add_action( 'wp_ajax_noesia_swa_global_data_hub_bootstrap', array( $this, 'handle_bootstrap' ) );
            add_action( 'wp_ajax_noesia_swa_global_data_hub_save_settings', array( $this, 'handle_save_settings' ) );
            add_action( 'wp_ajax_noesia_swa_global_data_hub_fetch_tourism', array( $this, 'handle_fetch_tourism' ) );
            add_action( 'wp_ajax_noesia_swa_global_data_hub_fetch_development', array( $this, 'handle_fetch_development' ) );
            add_action( 'wp_ajax_noesia_swa_global_data_hub_fetch_digital', array( $this, 'handle_fetch_digital' ) );
            add_action( 'wp_ajax_noesia_swa_global_data_hub_fetch_population', array( $this, 'handle_fetch_population' ) );
            add_action( 'wp_ajax_noesia_swa_global_data_hub_fetch_imf_macro', array( $this, 'handle_fetch_imf_macro' ) );
            add_action( 'wp_ajax_noesia_swa_global_data_hub_fetch_oecd', array( $this, 'handle_fetch_oecd' ) );
            add_action( 'wp_ajax_noesia_swa_global_data_hub_fetch_health', array( $this, 'handle_fetch_health' ) );
            add_action( 'wp_ajax_noesia_swa_global_data_hub_fetch_medical_evidence', array( $this, 'handle_fetch_medical_evidence' ) );
            add_action( 'wp_ajax_noesia_swa_global_data_hub_fetch_compare', array( $this, 'handle_fetch_compare' ) );
        }

        /**
         * Verify request.
         *
         * @return void
         */
        private function verify_request() {
            check_ajax_referer( 'noesia_swa_nonce', 'nonce' );

            if ( ! current_user_can( 'manage_options' ) ) {
                wp_send_json_error(
                    array(
                        'message' => __( 'Unauthorized request.', 'noesia-smart-waiter' ),
                    ),
                    403
                );
            }
        }

        /**
         * Read posted settings payload.
         *
         * @return array<string,mixed>
         */
        private function get_posted_settings() {
            $raw = $this->get_unslashed_post_array( 'settings' );

            if ( ! is_array( $raw ) ) {
                return array();
            }

            return map_deep( $raw, 'sanitize_text_field' );
        }

        /**
         * Read posted compare countries.
         *
         * @return array<int,string>
         */
        private function get_posted_compare_countries() {
            $raw = $this->get_unslashed_post_array( 'countries' );

            if ( ! is_array( $raw ) ) {
                return array();
            }

            return array_values( array_filter( array_map( 'sanitize_text_field', $raw ), 'is_string' ) );
        }

        /**
         * Read an unslashed POST array after request verification.
         *
         * @param string $key POST field name.
         * @return array<mixed>
         */
    private function get_unslashed_post_array( $key ) {
	$request_key = sanitize_key( $key );

	if ( '' === $request_key ) {
		return array();
	}

	// phpcs:ignore WordPress.Security.NonceVerification.Missing -- AJAX nonce and capability are verified before this helper is used.
	if ( ! isset( $_POST[ $request_key ] ) ) {
		return array();
	}

	// phpcs:ignore WordPress.Security.NonceVerification.Missing,WordPress.Security.ValidatedSanitizedInput.InputNotSanitized -- AJAX nonce and capability are verified before this helper is used; returned arrays are validated and sanitized by the owning request handlers/service layer.
$value = wp_unslash( $_POST[ $request_key ] );

	return is_array( $value ) ? $value : array();
}

/**
 * Read a posted boolean flag after request verification.
 *
 * @param string $key POST field name.
 * @return bool
 */
private function get_posted_boolean( $key ) {
	$request_key = sanitize_key( $key );

	if ( '' === $request_key ) {
		return false;
	}

	// phpcs:ignore WordPress.Security.NonceVerification.Missing -- AJAX nonce and capability are verified before this helper is used.
	if ( ! isset( $_POST[ $request_key ] ) ) {
		return false;
	}

	// phpcs:ignore WordPress.Security.NonceVerification.Missing -- AJAX nonce and capability are verified before this helper is used.
	$value = sanitize_text_field( wp_unslash( (string) $_POST[ $request_key ] ) );

	return in_array( $value, array( '1', 'true', 'yes', 'on' ), true );
}

        /**
         * Handle bootstrap.
         *
         * @return void
         */
        public function handle_bootstrap() {
            $this->verify_request();
            wp_send_json_success( $this->service->get_shell_payload() );
        }

        /**
         * Handle save settings.
         *
         * @return void
         */
        public function handle_save_settings() {
            $this->verify_request();

            $settings = $this->service->save_settings( $this->get_posted_settings() );

            wp_send_json_success(
                array(
                    'settings' => $settings,
                    'message'  => __( 'Global Data Hub settings saved.', 'noesia-smart-waiter' ),
                )
            );
        }

        /**
         * Handle tourism fetch.
         *
         * @return void
         */
        public function handle_fetch_tourism() {
            $this->verify_request();

            $force = $this->get_posted_boolean( 'force' );
            wp_send_json_success( $this->service->get_tourism_payload( $force ) );
        }

        /**
         * Handle development fetch.
         *
         * @return void
         */
        public function handle_fetch_development() {
            $this->verify_request();

            $force = $this->get_posted_boolean( 'force' );
            wp_send_json_success( $this->service->get_development_payload( $force ) );
        }

        /**
         * Handle digital and connectivity fetch.
         *
         * @return void
         */
        public function handle_fetch_digital() {
            $this->verify_request();

            $force = $this->get_posted_boolean( 'force' );
            wp_send_json_success( $this->service->get_digital_payload( $force ) );
        }


        /**
         * Handle population and society fetch.
         *
         * @return void
         */
        public function handle_fetch_population() {
            $this->verify_request();

            $force = $this->get_posted_boolean( 'force' );
            wp_send_json_success( $this->service->get_population_payload( $force ) );
        }

        /**
         * Handle IMF macro fetch.
         *
         * @return void
         */
        public function handle_fetch_imf_macro() {
            $this->verify_request();

            $force = $this->get_posted_boolean( 'force' );
            wp_send_json_success( $this->service->get_imf_macro_payload( $force ) );
        }

        /**
         * Handle OECD fetch.
         *
         * @return void
         */
        public function handle_fetch_oecd() {
            $this->verify_request();

            $force = $this->get_posted_boolean( 'force' );
            wp_send_json_success( $this->service->get_oecd_payload( $force ) );
        }

        /**
         * Handle Health fetch.
         *
         * @return void
         */
        public function handle_fetch_health() {
            $this->verify_request();

            $force = $this->get_posted_boolean( 'force' );
            wp_send_json_success( $this->service->get_health_payload( $force ) );
        }

        /**
         * Handle medical evidence fetch.
         *
         * @return void
         */
        public function handle_fetch_medical_evidence() {
            $this->verify_request();

            $force = $this->get_posted_boolean( 'force' );
            // phpcs:ignore WordPress.Security.NonceVerification.Missing -- Nonce verified in verify_request().
            $query = isset( $_POST['query'] ) ? sanitize_text_field( wp_unslash( $_POST['query'] ) ) : '';
            // phpcs:ignore WordPress.Security.NonceVerification.Missing -- Nonce verified in verify_request().
            $language = isset( $_POST['language'] ) ? sanitize_text_field( wp_unslash( $_POST['language'] ) ) : 'any';
            wp_send_json_success( $this->service->get_medical_evidence_payload( $query, $force, $language ) );
        }


        /**
         * Handle compare countries fetch.
         *
         * @return void
         */
        public function handle_fetch_compare() {
            $this->verify_request();

            $force = $this->get_posted_boolean( 'force' );
            wp_send_json_success( $this->service->get_compare_payload( $this->get_posted_compare_countries(), $force ) );
        }

    }
}
