<?php
/**
 * CDN Admin Interface
 * Handles all admin UI and AJAX requests
 */

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

class USCDN_Admin {
    
    private static $instance = null;
    
    public static function get_instance() {
        if (null === self::$instance) {
            self::$instance = new self();
        }
        return self::$instance;
    }
    
    private function __construct() {
        add_action('admin_menu', [$this, 'add_admin_menu']);
        add_action('admin_enqueue_scripts', [$this, 'enqueue_admin_assets']);
        add_action('admin_init', [$this, 'handle_form_submissions']);
        add_action('admin_notices', [$this, 'show_admin_notices']);
        add_action('wp_ajax_uscdn_test_cdn', [$this, 'ajax_test_cdn']);
        add_action('wp_ajax_uscdn_clear_cache', [$this, 'ajax_clear_cache']);
        
        // Add settings link to plugins page
        add_filter('plugin_action_links_' . USCDN_PLUGIN_BASENAME, [$this, 'add_settings_link']);
    }
    
    /**
     * Add admin menu
     */
    public function add_admin_menu() {
        add_menu_page(
            __('CDN Manager', 'utility-server-cdn'),
            __('CDN Manager', 'utility-server-cdn'),
            'manage_options',
            'uscdn-settings',
            [$this, 'render_settings_page'],
            'dashicons-cloud',
            80
        );
        
        add_submenu_page(
            'uscdn-settings',
            __('Settings', 'utility-server-cdn'),
            __('Settings', 'utility-server-cdn'),
            'manage_options',
            'uscdn-settings',
            [$this, 'render_settings_page']
        );
        
        add_submenu_page(
            'uscdn-settings',
            __('Analytics', 'utility-server-cdn'),
            __('Analytics', 'utility-server-cdn'),
            'manage_options',
            'uscdn-analytics',
            [$this, 'render_analytics_page']
        );
        
        add_submenu_page(
            'uscdn-settings',
            __('Tools', 'utility-server-cdn'),
            __('Tools', 'utility-server-cdn'),
            'manage_options',
            'uscdn-tools',
            [$this, 'render_tools_page']
        );
        
        add_submenu_page(
            'uscdn-settings',
            __('Content Migration', 'utility-server-cdn'),
            __('Content Migration', 'utility-server-cdn'),
            'manage_options',
            'uscdn-migration',
            [$this, 'render_migration_page']
        );
        
        add_submenu_page(
            'uscdn-settings',
            __('Cloudflare', 'utility-server-cdn'),
            __('Cloudflare', 'utility-server-cdn'),
            'manage_options',
            'uscdn-cloudflare',
            [$this, 'render_cloudflare_page']
        );
    }
    
    /**
     * Enqueue admin assets
     */
    public function enqueue_admin_assets($hook) {
        if (strpos($hook, 'uscdn') === false) {
            return;
        }
        
        wp_enqueue_style(
            'uscdn-admin',
            USCDN_PLUGIN_URL . 'admin/css/admin-style.css',
            [],
            USCDN_VERSION
        );
        
        wp_enqueue_script(
            'uscdn-admin',
            USCDN_PLUGIN_URL . 'admin/js/admin-script.js',
            ['jquery'],
            USCDN_VERSION,
            true
        );
        
        wp_localize_script('uscdn-admin', 'uscdnAdmin', [
            'ajaxUrl' => admin_url('admin-ajax.php'),
            'nonce' => wp_create_nonce('uscdn_admin'),
            'strings' => [
                'testing' => __('Testing...', 'utility-server-cdn'),
                'success' => __('Success!', 'utility-server-cdn'),
                'error' => __('Error!', 'utility-server-cdn'),
                'clearing' => __('Clearing cache...', 'utility-server-cdn'),
            ]
        ]);
    }
    
    /**
     * Add settings link to plugins page
     */
    public function add_settings_link($links) {
        $settings_link = sprintf(
            '<a href="%s">%s</a>',
            admin_url('admin.php?page=uscdn-settings'),
            __('Settings', 'utility-server-cdn')
        );
        array_unshift($links, $settings_link);
        return $links;
    }
    
    /**
     * Handle form submissions
     */
    public function handle_form_submissions() {
        if (!current_user_can('manage_options')) {
            return;
        }
        
        // Handle settings save
        if (isset($_POST['uscdn_save_settings'])) {
            check_admin_referer('uscdn_settings');
            
            // Save each setting
            $settings = [
                'enable_origin_url',
                'origin_url',
                'enable_admin_url',
                'admin_url',
                'enable_image_cdn',
                'cdn_image_base',
                'enable_static_cdn',
                'cdn_static_base',
                'enable_link_cdn',
                'cdn_link_base',
                'analytics_enabled',
                'cache_enabled',
                'custom_source_hosts',
                'enable_dynamic_rewriting',
                'dynamic_rewriting_auto_rules',
                'dynamic_rewriting_aggressive',
                'dynamic_rewrite_rules'
            ];
            
            foreach ($settings as $setting) {
                $value = isset($_POST[$setting]) ? $_POST[$setting] : '';
                
                // Sanitize
                if (strpos($setting, '_base') !== false) {
                    $value = esc_url_raw($value);
                } elseif (strpos($setting, 'enable_') !== false || strpos($setting, '_enabled') !== false) {
                    $value = (int) !!$value;
                } else {
                    $value = sanitize_textarea_field($value);
                }
                
                update_option('uscdn_' . $setting, $value);
            }
            
            // Redirect with success message
            wp_redirect(admin_url('admin.php?page=uscdn-settings&saved=1'));
            exit;
        }
        
        // Handle setup wizard completion
        if (isset($_POST['uscdn_complete_setup'])) {
            check_admin_referer('uscdn_setup');
            update_option('uscdn_setup_completed', 1);
            wp_redirect(admin_url('admin.php?page=uscdn-settings&setup_complete=1'));
            exit;
        }
    }
    
    /**
     * Show admin notices
     */
    public function show_admin_notices() {
        if (isset($_GET['saved']) && $_GET['saved'] == '1') {
            echo '<div class="notice notice-success is-dismissible"><p>' . 
                 __('Settings saved successfully!', 'utility-server-cdn') . '</p></div>';
        }
        
        if (isset($_GET['cache_cleared']) && $_GET['cache_cleared'] == '1') {
            echo '<div class="notice notice-success is-dismissible"><p>' . 
                 __('Cache cleared successfully! Header X-Cache-Flush: TRUE sent.', 'utility-server-cdn') . '</p></div>';
        }
        
        if (isset($_GET['setup_complete']) && $_GET['setup_complete'] == '1') {
            echo '<div class="notice notice-success is-dismissible"><p>' . 
                 __('Setup completed! Your CDN is now configured.', 'utility-server-cdn') . '</p></div>';
        }
        
        // Show setup notice if not completed
        if (!USCDN_Settings::is_setup_completed() && !isset($_GET['page'])) {
            echo '<div class="notice notice-info"><p>' . 
                 sprintf(
                     __('Welcome to Utility Server CDN Manager! <a href="%s">Complete the setup wizard</a> to get started.', 'utility-server-cdn'),
                     admin_url('admin.php?page=uscdn-settings')
                 ) . '</p></div>';
        }
    }
    
    /**
     * AJAX: Test CDN
     */
    public function ajax_test_cdn() {
        check_ajax_referer('uscdn_admin', 'nonce');
        
        if (!current_user_can('manage_options')) {
            wp_send_json_error(['message' => 'Unauthorized']);
        }
        
        $cdn_url = isset($_POST['cdn_url']) ? esc_url_raw($_POST['cdn_url']) : '';
        $cdn_type = isset($_POST['cdn_type']) ? sanitize_text_field($_POST['cdn_type']) : '';
        
        if (empty($cdn_url)) {
            wp_send_json_error(['message' => 'CDN URL is required']);
        }
        
        $result = USCDN_Validator::test_cdn_url($cdn_url);
        
        if ($result['success']) {
            wp_send_json_success($result);
        } else {
            wp_send_json_error($result);
        }
    }
    
    /**
     * AJAX: Clear cache
     */
    public function ajax_clear_cache() {
        check_ajax_referer('uscdn_admin', 'nonce');
        
        if (!current_user_can('manage_options')) {
            wp_send_json_error(['message' => 'Unauthorized']);
        }
        
        USCDN_Cache::clear_all_cache();
        
        wp_send_json_success([
            'message' => __('Cache cleared successfully!', 'utility-server-cdn')
        ]);
    }
    
    /**
     * Render settings page
     */
    public function render_settings_page() {
        include USCDN_PLUGIN_DIR . 'admin/views/settings-page.php';
    }
    
    /**
     * Render analytics page
     */
    public function render_analytics_page() {
        include USCDN_PLUGIN_DIR . 'admin/views/analytics-page.php';
    }
    
    /**
     * Render tools page
     */
    public function render_tools_page() {
        include USCDN_PLUGIN_DIR . 'admin/views/tools-page.php';
    }
    
    /**
     * Render migration page
     */
    public function render_migration_page() {
        include USCDN_PLUGIN_DIR . 'admin/views/migration-page.php';
    }
    
    public function render_cloudflare_page() {
        include USCDN_PLUGIN_DIR . 'admin/views/cloudflare-page.php';
    }
}
