<?php

if (! defined('ABSPATH')) {

    exit;

}

class CacheMeBaby_Cloudflare {

    public function __construct() {

        // Cloudflare-specific AJAX calls

        add_action('wp_ajax_test_cloudflare_connection',   [$this, 'test_cloudflare_connection']);

        add_action('wp_ajax_purge_cloudflare_cache',       [$this, 'purge_cloudflare_cache_callback']);

        add_action('wp_ajax_warm_cloudflare_cache_ajax',   [$this, 'handle_ajax_cloudflare_cache_warming']);

    }

    /**

     * AJAX: Test Cloudflare Connection

     */

    public function test_cloudflare_connection() {

        check_ajax_referer('cache_me_baby_nonce', 'nonce');

        $zone_id = isset($_POST['zone_id']) ? sanitize_text_field($_POST['zone_id']) : '';

        $api_key = isset($_POST['api_token']) ? sanitize_text_field($_POST['api_token']) : '';

        $email   = isset($_POST['email'])     ? sanitize_email($_POST['email']) : '';

        if (empty($zone_id) || empty($api_key) || empty($email)) {

            wp_send_json_error('Cloudflare credentials are missing.');

        }

        $url = "https://api.cloudflare.com/client/v4/zones/$zone_id";

        $args = [

            'headers' => [

                'X-Auth-Email' => $email,

                'X-Auth-Key'   => $api_key,

                'Content-Type' => 'application/json',

            ],

            'timeout' => 15,

        ];

        $response = wp_remote_get($url, $args);

        if (is_wp_error($response)) {

            wp_send_json_error('Connection failed: ' . $response->get_error_message());

        }

        $data = json_decode(wp_remote_retrieve_body($response), true);

        if (! empty($data['success'])) {

            wp_send_json_success('Connection successful!');

        } else {

            $errors = ! empty($data['errors']) ? wp_list_pluck($data['errors'], 'message') : ['Unknown error'];

            wp_send_json_error(implode(', ', $errors));

        }

    }

    /**

     * AJAX: Purge Cloudflare Cache

     */

    public function purge_cloudflare_cache_callback() {

        check_ajax_referer('cache_me_baby_nonce', 'nonce');

        $main_instance = CacheMeBaby::get_instance();

        if (! $main_instance->is_cloudflare_nameservers()) {

            wp_send_json_success('Site is not on Cloudflare.');

        }

        $result = $this->purge_cloudflare_cache();

        if (is_wp_error($result)) {

            wp_send_json_error($result->get_error_message());

        }

        wp_send_json_success('Cloudflare cache purged.');

    }

    /**

     * Actually do the purge of Cloudflare

     */

    public function purge_cloudflare_cache() {

        $zone_id         = get_option('cache_me_baby_cloudflare_zone_id');

        $global_api_key  = get_option('cache_me_baby_cloudflare_api_token');

        $email           = get_option('cache_me_baby_cloudflare_email', 'support@wpfixit.com');

        if (empty($zone_id) || empty($global_api_key)) {

            return new WP_Error('missing_credentials', 'Cloudflare credentials are missing.');

        }

        $url = "https://api.cloudflare.com/client/v4/zones/$zone_id/purge_cache";

        $args = [

            'body'    => json_encode(['purge_everything' => true]),

            'headers' => [

                'X-Auth-Email' => $email,

                'X-Auth-Key'   => $global_api_key,

                'Content-Type' => 'application/json',

            ],

            'timeout' => 15,

        ];

        return wp_remote_post($url, $args);

    }

    /**

     * If you have a separate AJAX for “warm_cloudflare_cache_ajax”

     * (the user’s original code references it), handle it here.

     */

    public function handle_ajax_cloudflare_cache_warming() {

        check_ajax_referer('cache_me_baby_nonce', 'nonce');

        // Possibly do advanced logic or just call purge:

        $this->purge_cloudflare_cache();

        wp_send_json_success('Cloudflare cache purged via warm_cloudflare_cache_ajax!');

    }

}