<?php
if ( ! defined( 'ABSPATH' ) ) {
    exit;
}

/**
 * Lida com as chamadas AJAX do painel de administração do Hub.
 */
class WPCM_Hub_Ajax_Handler {

    public function __construct() {
        add_action( 'wp_ajax_wpcm_hub_sync_sites', array( $this, 'handle_sync_sites' ) );
        add_action( 'wp_ajax_wpcm_hub_test_connection', array( $this, 'handle_test_connection' ) );
    }

    /**
     * Disparado pelo botão "Sincronizar Todos os Sites".
     * Agenda os trabalhos em vez de executá-los.
     */
    public function handle_sync_sites() {
        check_ajax_referer( 'wpcm_hub_sync_nonce', '_ajax_nonce' );

        if ( ! current_user_can( 'manage_options' ) ) {
            wp_send_json_error( array( 'message' => __( 'Permission denied.', 'wpcm-agency-hub' ) ) );
        }

        $result = WPCM_Hub_Job_Scheduler::schedule_global_sync();
        
        /* translators: 1: Number of sites scheduled, 2: Number of sites already in queue. */
        $msg_string = __( '%1$d site(s) scheduled for sync. %2$d were already in the queue.', 'wpcm-agency-hub' );
        
        $message = sprintf(
            $msg_string,
            $result['success'],
            $result['skipped']
        );

        wp_send_json_success( array( 'message' => $message ) );
    }

    /**
     * Lida com a chamada AJAX do botão "Testar Conexão".
     */
    public function handle_test_connection() {
        check_ajax_referer( 'wpcm_hub_sync_nonce', '_ajax_nonce' );

        if ( ! current_user_can( 'manage_options' ) ) {
            wp_send_json_error( array( 'message' => __( 'Permission denied.', 'wpcm-agency-hub' ) ) );
        }

        $post_id = isset( $_POST['post_id'] ) ? absint( $_POST['post_id'] ) : 0;
        if ( ! $post_id ) {
            wp_send_json_error( array( 'message' => __( 'Invalid Post ID.', 'wpcm-agency-hub' ) ) );
        }

        $site_url    = isset( $_POST['site_url'] ) ? esc_url_raw( wp_unslash( $_POST['site_url'] ) ) : '';
        $api_key     = isset( $_POST['api_key'] ) ? sanitize_text_field( wp_unslash( $_POST['api_key'] ) ) : '';
        $disable_ssl = ( isset( $_POST['disable_ssl'] ) && $_POST['disable_ssl'] === '1' );

        if ( empty( $site_url ) || empty( $api_key ) ) {
            wp_send_json_error( array( 'message' => __( 'Site URL and API Key are required.', 'wpcm-agency-hub' ) ) );
        }

        $api_endpoint = trailingslashit( $site_url ) . 'wp-json/wpcm-client/v1/test-connection';
        $ssl_verify_status = ! $disable_ssl;

        $response = wp_remote_get( $api_endpoint, array(
            'timeout'    => 15,
            'headers'    => array( 'X-Api-Key' => $api_key ),
            'user-agent' => 'WPCM-Hub-Test/' . WPCM_HUB_VERSION,
            'sslverify'  => $ssl_verify_status,
        ) );

        if ( is_wp_error( $response ) ) {
            wp_send_json_error( array( 'message' => $response->get_error_message() ) );
        }

        $response_code = wp_remote_retrieve_response_code( $response );

        if ( $response_code === 200 ) {
            update_post_meta( $post_id, '_status', 'connected' );
            wp_send_json_success( array( 'message' => __( 'Connection successful!', 'wpcm-agency-hub' ) ) );
        } elseif ( $response_code === 401 || $response_code === 403 ) {
            wp_send_json_error( array( 'message' => __( 'Invalid API Key.', 'wpcm-agency-hub' ) ) );
        } else {
            /* translators: %s: HTTP response code. */
            $msg_string = __( 'Client site responded with error code %s.', 'wpcm-agency-hub' );
            
            $error_message = sprintf( $msg_string, $response_code );
            
            wp_send_json_error( array( 'message' => $error_message ) );
        }
    }
}