<?php

namespace HvnlyNab\Admin;

defined('ABSPATH') || exit;

class CacheAdmin
{
    public function __construct()
    {
        add_action('admin_menu', [$this, 'add_admin_menu']);
        add_action('admin_init', [$this, 'register_settings']);
        add_action('admin_enqueue_scripts', [$this, 'enqueue_scripts']);
        add_action('wp_ajax_hvnly_clear_cache', [$this, 'ajax_clear_cache']);
        add_action('wp_ajax_hvnly_get_cache_stats', [$this, 'ajax_get_cache_stats']);
        add_action('wp_ajax_hvnly_update_cache_settings', [$this, 'ajax_update_cache_settings']);
        add_action('wp_ajax_hvnly_clear_shortcode_cache', [$this, 'ajax_clear_shortcode_cache']);
        add_action('wp_ajax_hvnly_clear_dynamic_css', [$this, 'ajax_clear_dynamic_css']);
    }

    public function add_admin_menu()
    {
        add_submenu_page(
            'edit.php?post_type=hvnly_property',
            __('Cache Management', 'havenlytics'),
            __('Cache', 'havenlytics'),
            'manage_options',
            'hvnly_property_cache',
            [$this, 'cache_admin_page']
        );
    }

    public function register_settings()
    {
        register_setting('hvnly_cache_settings', 'hvnly_cache_enabled', [
            'type' => 'boolean',
            'default' => 1,
            'sanitize_callback' => 'absint'
        ]);

        register_setting('hvnly_cache_settings', 'hvnly_cache_ttl', [
            'type' => 'integer',
            'default' => HOUR_IN_SECONDS * 6,
            'sanitize_callback' => 'absint'
        ]);

        register_setting('hvnly_cache_settings', 'hvnly_cache_compression', [
            'type' => 'boolean',
            'default' => 0,
            'sanitize_callback' => 'absint'
        ]);

        register_setting('hvnly_cache_settings', 'hvnly_cache_debug', [
            'type' => 'boolean',
            'default' => 0,
            'sanitize_callback' => 'absint'
        ]);
    }

    public function enqueue_scripts($hook)
    {
        if ('hvnly_property_page_hvnly_property_cache' !== $hook) {
            return;
        }

        wp_enqueue_script(
            'hvnly-admin-cache',
            HVNLYNAB_ASSETS_URL . '/admin/js/hvnly-admin-cache.js',
            ['jquery'],
            HVNLYNAB_VERSION,
            true
        );

        wp_localize_script('hvnly-admin-cache', 'hvnlyCacheAdmin', [
            'ajaxurl' => admin_url('admin-ajax.php'),
            'nonce' => wp_create_nonce('hvnly_cache_nonce'),
            'clearingText' => __('Clearing cache...', 'havenlytics'),
            'clearedText' => __('Cache cleared successfully!', 'havenlytics'),
            'errorText' => __('Error clearing cache', 'havenlytics'),
        ]);

        wp_enqueue_style(
            'hvnly-admin-cache',
            HVNLYNAB_ASSETS_URL . '/admin/css/hvnly-admin-cache.css',
            [],
            HVNLYNAB_VERSION
        );
    }

    public function cache_admin_page()
    {
        if (!current_user_can('manage_options')) {
            wp_die(esc_html__('You do not have sufficient permissions to access this page.', 'havenlytics'));
        }

        $cache_stats = HVNLY_NAB()->engine()->get_cache_stats();
        $performance_metrics = HVNLY_NAB()->engine()->get_performance_metrics();

        $cache_enabled = (bool) get_option('hvnly_cache_enabled', 1);
        $cache_ttl = (int) get_option('hvnly_cache_ttl', HOUR_IN_SECONDS * 6);
        $cache_compression = (bool) get_option('hvnly_cache_compression', 0);
        $cache_debug = (bool) get_option('hvnly_cache_debug', 0);

?>
        <div class="wrap hvnly-cache-admin">
            <h1><?php esc_html_e('Havenlytics Cache Management', 'havenlytics'); ?></h1>

            <!-- Cache Statistics -->
            <div class="hvnly-cache-stats">
                <div class="stats-grid">
                    <?php
                    $stat_items = [
                        'Total Cache Size' => $cache_stats['cache_size_human'],
                        'Main Search Cache' => number_format($cache_stats['search_cache_count']),
                        'Term Cache' => number_format($cache_stats['term_cache_count']),
                        'Cache Hit Rate' => esc_html($cache_stats['cache_hit_rate']) . '%',
                        'Sidebar Cache' => number_format($cache_stats['sidebar_cache_count']),
                        'Total Cached Items' => number_format($cache_stats['total_cached_items']),
                    ];

                    foreach ($stat_items as $label => $value) : ?>
                        <div class="stat-card">
                            <h3><?php echo esc_html($label); ?></h3>
                            <div class="stat-value"><?php echo esc_html($value); ?></div>
                        </div>
                    <?php endforeach; ?>
                </div>
            </div>

            <!-- Quick Actions -->
            <div class="hvnly-cache-actions">
                <div class="action-buttons">
                    <button type="button" id="hvnly-clear-cache" class="button button-primary">
                        <?php esc_html_e('Clear All Cache', 'havenlytics'); ?>
                    </button>
                    <button type="button" id="hvnly-clear-search-cache" class="button">
                        <?php esc_html_e('Clear Main Search Cache', 'havenlytics'); ?>
                    </button>
                    <button type="button" id="hvnly-clear-sidebar-cache" class="button">
                        <?php esc_html_e('Clear Sidebar Cache', 'havenlytics'); ?>
                    </button>
                    <button type="button" id="hvnly-clear-terms-cache" class="button">
                        <?php esc_html_e('Clear Terms Cache', 'havenlytics'); ?>
                    </button>
                    
                    <hr style="margin: 15px 0; border-color: #ccc;">
                    <h3 style="margin: 0 0 10px 0; font-size: 14px;"><?php esc_html_e('Shortcode Cache', 'havenlytics'); ?></h3>
                    
                    <button type="button" id="hvnly-clear-shortcode-cache" class="button button-secondary">
                        <?php esc_html_e('Clear All Shortcode Cache', 'havenlytics'); ?>
                    </button>
                    <button type="button" id="hvnly-clear-grid-shortcode" class="button">
                        <?php esc_html_e('Clear Grid Shortcode', 'havenlytics'); ?>
                    </button>
                    <button type="button" id="hvnly-clear-list-shortcode" class="button">
                        <?php esc_html_e('Clear List Shortcode', 'havenlytics'); ?>
                    </button>
                    <button type="button" id="hvnly-clear-search-shortcode" class="button">
                        <?php esc_html_e('Clear Search Shortcode', 'havenlytics'); ?>
                    </button>
                    
                    <hr style="margin: 15px 0; border-color: #ccc;">
                    <h3 style="margin: 0 0 10px 0; font-size: 14px;"><?php esc_html_e('Dynamic CSS Cache', 'havenlytics'); ?></h3>
                    
                    <button type="button" id="hvnly-clear-dynamic-css" class="button button-secondary">
                        <?php esc_html_e('Clear Dynamic CSS Cache', 'havenlytics'); ?>
                    </button>
                    
                    <button type="button" id="hvnly-refresh-stats" class="button">
                        <?php esc_html_e('Refresh Stats', 'havenlytics'); ?>
                    </button>
                </div>
            </div>

            <!-- Cache Settings -->
            <div class="hvnly-cache-settings">
                <form method="post" action="options.php" id="hvnly-cache-settings-form">
                    <?php settings_fields('hvnly_cache_settings'); ?>
                    <table class="form-table">
                        <tr>
                            <th scope="row"><?php esc_html_e('Enable Caching', 'havenlytics'); ?></th>
                            <td>
                                <label>
                                    <input type="checkbox" name="hvnly_cache_enabled" value="1" <?php echo checked($cache_enabled, 1, false); ?> />
                                    <?php esc_html_e('Enable property search and term caching', 'havenlytics'); ?>
                                </label>
                            </td>
                        </tr>
                        <tr>
                            <th scope="row"><?php esc_html_e('Cache Duration', 'havenlytics'); ?></th>
                            <td>
                                <select name="hvnly_cache_ttl">
                                    <?php
                                    $ttl_options = [
                                        3600 => __('1 Hour', 'havenlytics'),
                                        7200 => __('2 Hours', 'havenlytics'),
                                        21600 => __('6 Hours', 'havenlytics'),
                                        43200 => __('12 Hours', 'havenlytics'),
                                        86400 => __('24 Hours', 'havenlytics')
                                    ];

                                    foreach ($ttl_options as $value => $label) : ?>
                                        <option value="<?php echo esc_attr($value); ?>" <?php echo selected($cache_ttl, $value, false); ?>>
                                            <?php echo esc_html($label); ?>
                                        </option>
                                    <?php endforeach; ?>
                                </select>
                                <p class="description"><?php esc_html_e('How long should cached data be stored?', 'havenlytics'); ?></p>
                            </td>
                        </tr>
                        <tr>
                            <th scope="row"><?php esc_html_e('Cache Compression', 'havenlytics'); ?></th>
                            <td>
                                <label>
                                    <input type="checkbox" name="hvnly_cache_compression" value="1" <?php echo checked($cache_compression, 1, false); ?> />
                                    <?php esc_html_e('Compress cached data to save database space', 'havenlytics'); ?>
                                </label>
                            </td>
                        </tr>
                        <tr>
                            <th scope="row"><?php esc_html_e('Debug Mode', 'havenlytics'); ?></th>
                            <td>
                                <label>
                                    <input type="checkbox" name="hvnly_cache_debug" value="1" <?php echo checked($cache_debug, 1, false); ?> />
                                    <?php esc_html_e('Enable debug logging for cache operations', 'havenlytics'); ?>
                                </label>
                            </td>
                        </tr>
                    </table>
                    <?php submit_button(__('Save Settings', 'havenlytics')); ?>
                </form>
            </div>

            <!-- Performance Metrics -->
            <div class="hvnly-cache-performance">
                <table class="widefat">
                    <thead>
                        <tr>
                            <th><?php esc_html_e('Metric', 'havenlytics'); ?></th>
                            <th><?php esc_html_e('Value', 'havenlytics'); ?></th>
                        </tr>
                    </thead>
                    <tbody>
                        <?php
                        $performance_items = [
                            'Cache Hits' => number_format($performance_metrics['cache_hits']),
                            'Cache Misses' => number_format($performance_metrics['cache_misses']),
                            'Queries Executed' => number_format($performance_metrics['queries_executed']),
                            'Average Query Time' => round($performance_metrics['average_query_time'], 4) . 's',
                            'Cache Efficiency' => esc_html($performance_metrics['cache_efficiency']) . '%',
                            'Memory Usage' => size_format($performance_metrics['memory_usage']),
                            'Total Queries Saved' => number_format($performance_metrics['total_queries_saved']),
                        ];

                        foreach ($performance_items as $label => $value) : ?>
                            <tr>
                                <td><?php echo esc_html($label); ?></td>
                                <td><?php echo esc_html($value); ?></td>
                            </tr>
                        <?php endforeach; ?>
                    </tbody>
                </table>
            </div>
        </div>
<?php
    }

    public function ajax_clear_cache()
    {
        check_ajax_referer('hvnly_cache_nonce', 'nonce');

        if (!current_user_can('manage_options')) {
            wp_send_json_error('Insufficient permissions');
        }

        $cache_type = sanitize_key($_POST['cache_type'] ?? 'all');

        switch ($cache_type) {
            case 'search':
                HVNLY_NAB()->engine()->clear_transients_by_pattern('search_');
                break;
            case 'sidebar':
                HVNLY_NAB()->engine()->clear_transients_by_pattern('sidebar_');
                break;
            case 'terms':
                HVNLY_NAB()->engine()->clear_transients_by_pattern('terms_');
                break;
            case 'all':
            default:
                HVNLY_NAB()->engine()->clear_all_cache();
                break;
        }

        wp_send_json_success(esc_html__('Cache cleared successfully', 'havenlytics'));
    }

    public function ajax_get_cache_stats()
    {
        check_ajax_referer('hvnly_cache_nonce', 'nonce');

        if (!current_user_can('manage_options')) {
            wp_send_json_error('Insufficient permissions');
        }

        $stats = HVNLY_NAB()->engine()->get_cache_stats();
        $performance = HVNLY_NAB()->engine()->get_performance_metrics();

        wp_send_json_success([
            'stats' => $stats,
            'performance' => $performance
        ]);
    }

    public function ajax_update_cache_settings() {
        check_ajax_referer('hvnly_cache_nonce', 'nonce');

        if (! current_user_can('manage_options')) {
            wp_send_json_error('Insufficient permissions');
        }

        $settings_raw = filter_input(INPUT_POST, 'settings', FILTER_DEFAULT, FILTER_REQUIRE_ARRAY) ?: [];

        $settings = [];
        foreach ($settings_raw as $key => $value) {
            $safe_key = sanitize_key($key);
            $safe_value = $this->sanitize_setting($safe_key, $value);
            $settings[$safe_key] = $safe_value;
            update_option('hvnly_' . $safe_key, $safe_value);
        }

        $new_config = [
            'cache_ttl' => absint($settings['cache_ttl'] ?? HOUR_IN_SECONDS * 6),
            'cache_compression' => !empty($settings['cache_compression']),
            'enable_performance' => !empty($settings['cache_debug']),
        ];

        HVNLY_NAB()->engine()->update_config($new_config);

        wp_send_json_success(esc_html__('Settings updated successfully', 'havenlytics'));
    }

    public function ajax_clear_shortcode_cache() {
        check_ajax_referer('hvnly_cache_nonce', 'nonce');

        if (!current_user_can('manage_options')) {
            wp_send_json_error('Insufficient permissions');
        }

        $shortcode_type = sanitize_key($_POST['shortcode_type'] ?? 'all');

        if (class_exists('HvnlyNab\Frontend\Shortcodes\Registry')) {
            if ($shortcode_type === 'all') {
                \HvnlyNab\Frontend\Shortcodes\Registry::clear_all_caches();
                wp_send_json_success(esc_html__('All shortcode caches cleared successfully', 'havenlytics'));
            } else {
                \HvnlyNab\Frontend\Shortcodes\Registry::clear_cache($shortcode_type);
                $message = sprintf(
                    /* translators: %s: shortcode type name */
                    esc_html__('%s shortcode cache cleared successfully', 'havenlytics'),
                    esc_html($shortcode_type)
                );
                wp_send_json_success($message);
            }
        } else {
            HVNLY_NAB()->engine()->clear_transients_by_pattern('hvnly_property_grid_%');
            HVNLY_NAB()->engine()->clear_transients_by_pattern('hvnly_property_list_%');
            HVNLY_NAB()->engine()->clear_transients_by_pattern('hvnly_featured_properties_%');
            HVNLY_NAB()->engine()->clear_transients_by_pattern('hvnly_property_search_%');
            wp_send_json_success(esc_html__('Shortcode caches cleared via pattern', 'havenlytics'));
        }
    }

    /**
     * AJAX handler for clearing dynamic CSS cache
     */
    public function ajax_clear_dynamic_css()
    {
        check_ajax_referer('hvnly_cache_nonce', 'nonce');
        
        if (!current_user_can('manage_options')) {
            wp_send_json_error('Insufficient permissions');
        }
        
        // Clear the dynamic CSS cache
        delete_transient('hvnly_dynamic_css');
        
        // Clear using CacheManager if available
        if (class_exists('HvnlyNab\Core\CacheManager')) {
            \HvnlyNab\Core\CacheManager::delete_transient('hvnly_dynamic_css');
        }
        
        // Clear style generator cache
        if (class_exists('HvnlyNab\Core\DynamicStyleGenerator')) {
            $generator = \HvnlyNab\Core\DynamicStyleGenerator::get_instance();
            $generator->clear_css_cache();
        }
        
        // Clear via engine if available
        if (function_exists('HVN') && HVNLY_NAB()->engine()) {
            HVNLY_NAB()->engine()->clear_transients_by_pattern('hvnly_dynamic_css');
        }
        
        wp_send_json_success(esc_html__('Dynamic CSS cache cleared successfully', 'havenlytics'));
    }

    private function sanitize_setting($key, $value)
    {
        switch ($key) {
            case 'cache_ttl':
                return absint($value);
            case 'cache_enabled':
            case 'cache_compression':
            case 'cache_debug':
                return !empty($value) ? 1 : 0;
            default:
                return sanitize_text_field($value);
        }
    }
}