<?php
/**
 * Widgets module AJAX handlers.
 *
 * @package Noesia_Smart_Waiter
 */

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

if ( ! class_exists( 'Noesia_SWA_Module_Widgets_Ajax' ) ) {
    class Noesia_SWA_Module_Widgets_Ajax {

        /**
         * @var Noesia_SWA_Widgets_Data
         */
        protected $data;

        public function __construct( $data ) {
            if ( ! $data instanceof Noesia_SWA_Widgets_Data ) {
                return;
            }

            $this->data = $data;

            add_action( 'wp_ajax_noesia_swa_widgets_refresh_rates', array( $this, 'handle_refresh_rates' ) );
            add_action( 'wp_ajax_noesia_swa_widgets_speed_ping', array( $this, 'handle_speed_ping' ) );
        }

        protected function verify_request() {
            check_ajax_referer( 'noesia_swa_nonce', 'nonce' );
            if ( ! current_user_can( 'manage_options' ) ) {
                wp_send_json_error(
                    array(
                        'message' => __( 'Unauthorized.', 'noesia-smart-waiter' ),
                    ),
                    403
                );
            }
        }

        public function handle_refresh_rates() {
            $this->verify_request();

            $payload = $this->data->get_context();
            $payload['rates_payload'] = $this->data->get_currency_rates( true );
            $payload['rates_payload']['favorites']    = array( 'EUR', 'USD', 'GBP', 'CHF', 'AED', 'CAD', 'AUD', 'JPY' );
            $payload['rates_payload']['source_label'] = __( 'European Central Bank daily reference feed', 'noesia-smart-waiter' );

            wp_send_json_success( $payload );
        }

        public function handle_speed_ping() {
            $this->verify_request();

            $server_time_unix_ms = (int) round( microtime( true ) * 1000 );

            wp_send_json_success(
                array(
                    'server_time_unix_ms' => $server_time_unix_ms,
                    'server_time_iso_utc' => gmdate( 'c', (int) floor( $server_time_unix_ms / 1000 ) ),
                )
            );
        }
    }
}
