<?php
/**
 * Cloudflare Integration Handler
 * 
 * Handles all Cloudflare API interactions including cache purging,
 * developer mode, and cache settings management.
 * 
 * @package Utility_Server_CDN
 * @since 1.0.5
 */

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

class CDN_Cloudflare {
    
    /**
     * Cloudflare API base URL
     */
    private $api_base = 'https://api.cloudflare.com/client/v4';
    
    /**
     * Initialize the Cloudflare handler
     */
    public function __construct() {
        // Register AJAX handlers
        add_action('wp_ajax_uscdn_cf_purge_all', array($this, 'ajax_purge_all'));
        add_action('wp_ajax_uscdn_cf_purge_urls', array($this, 'ajax_purge_urls'));
        add_action('wp_ajax_uscdn_cf_toggle_dev_mode', array($this, 'ajax_toggle_dev_mode'));
        add_action('wp_ajax_uscdn_cf_toggle_always_online', array($this, 'ajax_toggle_always_online'));
        add_action('wp_ajax_uscdn_cf_set_cache_ttl', array($this, 'ajax_set_cache_ttl'));
        add_action('wp_ajax_uscdn_cf_test_connection', array($this, 'ajax_test_connection'));
        add_action('wp_ajax_uscdn_cf_get_settings', array($this, 'ajax_get_settings'));
    }
    
    /**
     * Get Cloudflare credentials from settings
     */
    private function get_credentials() {
        return array(
            'zone_id' => get_option('uscdn_cf_zone_id', ''),
            'api_token' => get_option('uscdn_cf_api_token', '')
        );
    }
    
    /**
     * Check if Cloudflare is configured
     */
    public function is_configured() {
        $creds = $this->get_credentials();
        return !empty($creds['zone_id']) && !empty($creds['api_token']);
    }
    
    /**
     * Make API request to Cloudflare
     */
    private function make_request($endpoint, $method = 'GET', $data = null) {
        $creds = $this->get_credentials();
        
        if (!$this->is_configured()) {
            return array(
                'success' => false,
                'message' => 'Cloudflare credentials not configured'
            );
        }
        
        $url = $this->api_base . $endpoint;
        
        $args = array(
            'method' => $method,
            'headers' => array(
                'Content-Type' => 'application/json',
                'Authorization' => 'Bearer ' . $creds['api_token']
            ),
            'timeout' => 30
        );
        
        if ($data !== null) {
            $args['body'] = json_encode($data);
        }
        
        $response = wp_remote_request($url, $args);
        
        if (is_wp_error($response)) {
            return array(
                'success' => false,
                'message' => $response->get_error_message()
            );
        }
        
        $body = json_decode(wp_remote_retrieve_body($response), true);
        
        if (!isset($body['success'])) {
            return array(
                'success' => false,
                'message' => 'Invalid API response'
            );
        }
        
        return array(
            'success' => $body['success'],
            'message' => $body['success'] ? 'Success' : (isset($body['errors'][0]['message']) ? $body['errors'][0]['message'] : 'API request failed'),
            'data' => isset($body['result']) ? $body['result'] : null,
            'errors' => isset($body['errors']) ? $body['errors'] : array()
        );
    }
    
    /**
     * Purge all cache
     */
    public function purge_all_cache() {
        $creds = $this->get_credentials();
        $endpoint = "/zones/{$creds['zone_id']}/purge_cache";
        
        return $this->make_request($endpoint, 'POST', array('purge_everything' => true));
    }
    
    /**
     * Purge specific URLs
     */
    public function purge_urls($urls) {
        if (empty($urls)) {
            return array(
                'success' => false,
                'message' => 'No URLs provided'
            );
        }
        
        // Ensure URLs is an array
        if (!is_array($urls)) {
            $urls = array($urls);
        }
        
        $creds = $this->get_credentials();
        $endpoint = "/zones/{$creds['zone_id']}/purge_cache";
        
        return $this->make_request($endpoint, 'POST', array('files' => $urls));
    }
    
    /**
     * Purge by prefix (wildcard)
     */
    public function purge_prefix($prefixes) {
        if (empty($prefixes)) {
            return array(
                'success' => false,
                'message' => 'No prefixes provided'
            );
        }
        
        // Ensure prefixes is an array
        if (!is_array($prefixes)) {
            $prefixes = array($prefixes);
        }
        
        $creds = $this->get_credentials();
        $endpoint = "/zones/{$creds['zone_id']}/purge_cache";
        
        return $this->make_request($endpoint, 'POST', array('prefixes' => $prefixes));
    }
    
    /**
     * Toggle developer mode
     */
    public function toggle_dev_mode($enabled) {
        $creds = $this->get_credentials();
        $endpoint = "/zones/{$creds['zone_id']}/settings/development_mode";
        $value = $enabled ? 'on' : 'off';
        
        return $this->make_request($endpoint, 'PATCH', array('value' => $value));
    }
    
    /**
     * Toggle always online
     */
    public function toggle_always_online($enabled) {
        $creds = $this->get_credentials();
        $endpoint = "/zones/{$creds['zone_id']}/settings/always_online";
        $value = $enabled ? 'on' : 'off';
        
        return $this->make_request($endpoint, 'PATCH', array('value' => $value));
    }
    
    /**
     * Set browser cache TTL
     */
    public function set_cache_ttl($ttl) {
        $creds = $this->get_credentials();
        $endpoint = "/zones/{$creds['zone_id']}/settings/browser_cache_ttl";
        
        // Validate TTL value
        $valid_ttls = array(0, 30, 60, 120, 300, 1200, 1800, 3600, 7200, 10800, 14400, 18000, 28800, 43200, 57600, 72000, 86400, 172800, 259200, 345600, 432000, 691200, 1382400, 2073600, 2678400, 5356800, 16070400, 31536000);
        
        if (!in_array($ttl, $valid_ttls)) {
            return array(
                'success' => false,
                'message' => 'Invalid TTL value'
            );
        }
        
        return $this->make_request($endpoint, 'PATCH', array('value' => intval($ttl)));
    }
    
    /**
     * Get current settings
     */
    public function get_settings() {
        $creds = $this->get_credentials();
        
        // Get development mode status
        $dev_mode = $this->make_request("/zones/{$creds['zone_id']}/settings/development_mode", 'GET');
        
        // Get always online status
        $always_online = $this->make_request("/zones/{$creds['zone_id']}/settings/always_online", 'GET');
        
        // Get cache TTL
        $cache_ttl = $this->make_request("/zones/{$creds['zone_id']}/settings/browser_cache_ttl", 'GET');
        
        return array(
            'dev_mode' => $dev_mode,
            'always_online' => $always_online,
            'cache_ttl' => $cache_ttl
        );
    }
    
    /**
     * Test API connection
     */
    public function test_connection() {
        $creds = $this->get_credentials();
        $endpoint = "/zones/{$creds['zone_id']}";
        
        $result = $this->make_request($endpoint, 'GET');
        
        if ($result['success']) {
            $zone_name = isset($result['data']['name']) ? $result['data']['name'] : 'Unknown';
            $result['message'] = "Connected successfully to zone: {$zone_name}";
        }
        
        return $result;
    }
    
    /**
     * AJAX: Purge all cache
     */
    public function ajax_purge_all() {
        check_ajax_referer('uscdn-cloudflare-nonce', 'nonce');
        
        if (!current_user_can('manage_options')) {
            wp_send_json_error('Insufficient permissions');
        }
        
        $result = $this->purge_all_cache();
        
        if ($result['success']) {
            wp_send_json_success($result['message']);
        } else {
            wp_send_json_error($result['message']);
        }
    }
    
    /**
     * AJAX: Purge specific URLs
     */
    public function ajax_purge_urls() {
        check_ajax_referer('uscdn-cloudflare-nonce', 'nonce');
        
        if (!current_user_can('manage_options')) {
            wp_send_json_error('Insufficient permissions');
        }
        
        $urls = isset($_POST['urls']) ? $_POST['urls'] : '';
        $type = isset($_POST['type']) ? $_POST['type'] : 'urls';
        
        // Parse URLs (one per line)
        $url_array = array_filter(array_map('trim', explode("\n", $urls)));
        
        if (empty($url_array)) {
            wp_send_json_error('No URLs provided');
        }
        
        if ($type === 'wildcard') {
            $result = $this->purge_prefix($url_array);
        } else {
            $result = $this->purge_urls($url_array);
        }
        
        if ($result['success']) {
            wp_send_json_success($result['message']);
        } else {
            wp_send_json_error($result['message']);
        }
    }
    
    /**
     * AJAX: Toggle developer mode
     */
    public function ajax_toggle_dev_mode() {
        check_ajax_referer('uscdn-cloudflare-nonce', 'nonce');
        
        if (!current_user_can('manage_options')) {
            wp_send_json_error('Insufficient permissions');
        }
        
        $enabled = isset($_POST['enabled']) && $_POST['enabled'] === 'true';
        $result = $this->toggle_dev_mode($enabled);
        
        if ($result['success']) {
            wp_send_json_success($result['message']);
        } else {
            wp_send_json_error($result['message']);
        }
    }
    
    /**
     * AJAX: Toggle always online
     */
    public function ajax_toggle_always_online() {
        check_ajax_referer('uscdn-cloudflare-nonce', 'nonce');
        
        if (!current_user_can('manage_options')) {
            wp_send_json_error('Insufficient permissions');
        }
        
        $enabled = isset($_POST['enabled']) && $_POST['enabled'] === 'true';
        $result = $this->toggle_always_online($enabled);
        
        if ($result['success']) {
            wp_send_json_success($result['message']);
        } else {
            wp_send_json_error($result['message']);
        }
    }
    
    /**
     * AJAX: Set cache TTL
     */
    public function ajax_set_cache_ttl() {
        check_ajax_referer('uscdn-cloudflare-nonce', 'nonce');
        
        if (!current_user_can('manage_options')) {
            wp_send_json_error('Insufficient permissions');
        }
        
        $ttl = isset($_POST['ttl']) ? intval($_POST['ttl']) : 0;
        $result = $this->set_cache_ttl($ttl);
        
        if ($result['success']) {
            wp_send_json_success($result['message']);
        } else {
            wp_send_json_error($result['message']);
        }
    }
    
    /**
     * AJAX: Test connection
     */
    public function ajax_test_connection() {
        check_ajax_referer('uscdn-cloudflare-nonce', 'nonce');
        
        if (!current_user_can('manage_options')) {
            wp_send_json_error('Insufficient permissions');
        }
        
        $result = $this->test_connection();
        
        if ($result['success']) {
            wp_send_json_success($result['message']);
        } else {
            wp_send_json_error($result['message']);
        }
    }
    
    /**
     * AJAX: Get current settings
     */
    public function ajax_get_settings() {
        check_ajax_referer('uscdn-cloudflare-nonce', 'nonce');
        
        if (!current_user_can('manage_options')) {
            wp_send_json_error('Insufficient permissions');
        }
        
        $settings = $this->get_settings();
        
        // Parse the results
        $response = array(
            'dev_mode' => array(
                'enabled' => false,
                'time_remaining' => 0
            ),
            'always_online' => array(
                'enabled' => false
            ),
            'cache_ttl' => array(
                'value' => 14400 // default
            )
        );
        
        // Developer mode
        if ($settings['dev_mode']['success'] && isset($settings['dev_mode']['data'])) {
            $response['dev_mode']['enabled'] = ($settings['dev_mode']['data']['value'] === 'on');
            if (isset($settings['dev_mode']['data']['time_remaining'])) {
                $response['dev_mode']['time_remaining'] = $settings['dev_mode']['data']['time_remaining'];
            }
        }
        
        // Always online
        if ($settings['always_online']['success'] && isset($settings['always_online']['data'])) {
            $response['always_online']['enabled'] = ($settings['always_online']['data']['value'] === 'on');
        }
        
        // Cache TTL
        if ($settings['cache_ttl']['success'] && isset($settings['cache_ttl']['data'])) {
            $response['cache_ttl']['value'] = intval($settings['cache_ttl']['data']['value']);
        }
        
        wp_send_json_success($response);
    }
}
