<?php
if (! defined('ABSPATH')) {
    exit;
}
class CacheMeBaby_Admin {
    public function __construct() {
        // Admin hooks
        add_action('admin_menu', [$this, 'add_admin_menu']);
        add_action('admin_init', [$this, 'register_plugin_settings']);
        add_action('admin_enqueue_scripts', [$this, 'enqueue_admin_styles']);
        add_action('admin_bar_menu', [$this, 'add_admin_bar_menu'], 100);
        // If admin bar is hidden, remove that menu
        if (get_option('cache_me_baby_hide_admin_bar', '0') === '1') {
            remove_action('admin_bar_menu', [$this, 'add_admin_bar_menu'], 100);
        }
    }
    /**
     * Create our submenu under Tools
     */
    public function add_admin_menu() {
        add_submenu_page(
            'tools.php',
            'Cache Me Baby',
            'Cache Me Baby',
            'manage_options',
            'cache-me-baby',
            [$this, 'main_admin_page_html'],
            1
        );
    }
    /**
     * Add “Cache Me Baby” to the Admin Bar
     */
    public function add_admin_bar_menu($admin_bar) {
        if (! is_admin_bar_showing() || ! current_user_can('manage_options')) {
            return;
        }
        $admin_bar->add_node([
            'id'    => 'cache-me-baby',
            'title' => 'Cache Me Baby',
            'href'  => admin_url('tools.php?page=cache-me-baby'),
            'meta'  => ['title' => 'Cache Me Baby - Warm Up Cache'],
        ]);
    }
    /**
     * Register our plugin’s settings in WP
     */
    public function register_plugin_settings() {
        register_setting('cache_me_baby_options', 'cache_me_baby_post_types');
        register_setting('cache_me_baby_options', 'cache_me_baby_excluded_urls');
        register_setting('cache_me_baby_options', 'cache_me_baby_cron_schedule');
        register_setting('cache_me_baby_options', 'cache_me_baby_auto_cache_update');
        register_setting('cache_me_baby_options', 'cache_me_baby_cloudflare_zone_id');
        register_setting('cache_me_baby_options', 'cache_me_baby_cloudflare_api_token');
        register_setting('cache_me_baby_options', 'cache_me_baby_cloudflare_email');
        add_settings_section('cache_me_baby_main_section', 'Cache Warm-up Settings', null, 'cache-me-baby-settings');
        add_settings_field(
            'cache_me_baby_post_types',
            'Post Types to Include',
            [$this, 'post_types_field_html'],
            'cache-me-baby-settings',
            'cache_me_baby_main_section'
        );
        add_settings_field(
            'cache_me_baby_excluded_urls',
            'Exclude URLs',
            [$this, 'excluded_urls_field_html'],
            'cache-me-baby-settings',
            'cache_me_baby_main_section'
        );
    }
    /**
     * Render the post types checkbox field
     */
    public function post_types_field_html() {
        $post_types = get_post_types(['public' => true], 'objects');
        $selected   = get_option('cache_me_baby_post_types', []);
        foreach ($post_types as $post_type) {
            if ('attachment' === $post_type->name) {
                continue;
            }
            $count = wp_count_posts($post_type->name)->publish;
            if (0 === $count) {
                continue;
            }
            echo '<label style="cursor: pointer; display: block; margin-bottom: 5px;">';
            echo '<input type="checkbox" name="cache_me_baby_post_types[]" value="' . esc_attr($post_type->name) . '" style="display: none;" ' . (in_array($post_type->name, $selected) ? 'checked' : '') . '>';
            echo '<span class="cache-me-baby-count">' . absint($count) . '</span> ';
            echo esc_html($post_type->label);
            echo '</label>';
        }
    }
    /**
     * Render the excluded URLs textarea field
     */
    public function excluded_urls_field_html() {
        $excluded_urls = get_option('cache_me_baby_excluded_urls', '');
        echo '<textarea name="cache_me_baby_excluded_urls" rows="5" cols="50">' . esc_textarea($excluded_urls) . '</textarea>';
        echo '<p>Enter one URL per line to exclude from cache warming.</p>';
    }
    /**
     * Render the cron schedule dropdown
     */
    public function cron_schedule_field_html() {
        $selected_schedule = get_option('cache_me_baby_cron_schedule', 'none');
        echo '<select name="cache_me_baby_cron_schedule">
                <option value="none" ' . selected($selected_schedule, 'none', false) . '>No Scheduled Cache Warm Up</option>
                <option value="daily" ' . selected($selected_schedule, 'daily', false) . '>Daily Cache Warm Up</option>
                <option value="weekly" ' . selected($selected_schedule, 'weekly', false) . '>Weekly Cache Warm Up</option>
                <option value="monthly" ' . selected($selected_schedule, 'monthly', false) . '>Monthly Cache Warm Up</option>
              </select>';
        echo '<p>Choose how often the cache warming should run automatically.</p>';
    }
    /**
     * Enqueue CSS in WP Admin
     */
    public function enqueue_admin_styles() {
        wp_enqueue_style(
            'cache-me-baby-styles',
            plugin_dir_url(__FILE__) . 'assets/css/cache-me-baby.css',
            [],
            filemtime(plugin_dir_path(__FILE__) . 'assets/css/cache-me-baby.css')
        );
    }
    /**
     * Output the main admin page (the plugin’s settings & interface)
     */
    public function main_admin_page_html() {
        // We'll need the main plugin instance to check Cloudflare
        $main_instance = CacheMeBaby::get_instance();
        echo '<div class="wrap">';
        if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['cache_me_baby_save_settings'])) {
            update_option('cache_me_baby_post_types',        $_POST['cache_me_baby_post_types']         ?? []);
            update_option('cache_me_baby_cron_schedule',     $_POST['cache_me_baby_cron_schedule']      ?? 'daily');
            update_option('cache_me_baby_auto_cache_update', isset($_POST['cache_me_baby_auto_cache_update']) ? '1' : '0');
            update_option('cache_me_baby_hide_admin_bar',    isset($_POST['cache_me_baby_hide_admin_bar']) ? '1' : '0');
            update_option('cache_me_baby_cloudflare_zone_id',  $_POST['cache_me_baby_cloudflare_zone_id']  ?? '');
            update_option('cache_me_baby_cloudflare_api_token', $_POST['cache_me_baby_cloudflare_api_token'] ?? '');
            update_option('cache_me_baby_cloudflare_email',     $_POST['cache_me_baby_cloudflare_email']     ?? '');
            echo '<div class="updated"><p>Settings saved!</p></div>';
            // Trigger Cron class to update the schedule:
            do_action('cache_me_baby_update_cron');
        }
        echo '<div class="cache-me-baby-container">
                <div class="cache-me-baby-main-content">
                <div id="hide-during_clear">
                    <h2 style="font-size:23px;">Let\'s Warm Up Your Cache</h2>
                    <p>This will visit all published pages, posts, and selected custom post types to pre-load the cache.</p>
                    <p>This helps improve website speed by ensuring pages are already cached before visitors arrive.</p>
                    <p>Click the button below and the system will automatically visit each page and store them in the cache.</p>
                    <div class="cache_me_baby_main_buttons" style="display:flex;gap:7%;align-items:flex-start;">
                    <div id="customConfirmModal" style="display:none; position: fixed; top:0; left:0; width: 100%; height:100%; background: rgba(0,0,0,0.5); z-index:10000;">
  <div style="position: relative; width:380px; margin: 20% auto; background: white; padding:33px; border-radius: 5px; text-align: center;">
    <p id="customConfirmMessage"></p>
    <button id="customConfirmYes" class="button button-primary">Yes... LETS GO!</button>
    <button id="customConfirmNo" class="button">Not Now</button>
  </div>
</div>
                        <div style="flex:0;">
        <button type="button" id="warm_cache_ajax" class="button button-primary">
            <span class="dashicons dashicons-performance"></span> LETS GO CACHING
        </button>
      </div>
      <div style="flex:0;">
      </div>
                    </div>
                    </div>
                    <div id="cache_warming_status"></div>
                    <div id="hide-during_clear">
                    <hr style="max-width:95%;margin-top:33px;">
                    <h2 style="font-size:23px;">Cache Warming Settings</h2>
                    <p>For more control over cache warming, visit the settings area below to customize what and when you wish to cache on your site.</p>
                    <form method="post">
                        <div class="cache_me_baby_settings_area" style="display:flex;gap:20px;align-items:flex-start;">
                            <div style="flex:1;">
                                <h3>What Content to Warm&nbsp;&nbsp;<span style="font-size:16px">(click to add/remove)</h3>';
        // Post types
        $this->post_types_field_html();
        echo '                  <h3>Exclude URLs From Warmer</h3>';
        // Excluded URLs
        $this->excluded_urls_field_html();
        echo '                  <input style="margin:23px 0;" type="submit" name="cache_me_baby_save_settings" id="save_warm_cache_settings" class="button button-primary" value="Save Settings">
                            </div>
                            <div style="flex:1;max-width: 48%;">
                                <h3>Auto Warm Cache on Update</h3>
                                <label><input type="checkbox" name="cache_me_baby_auto_cache_update" value="1" ' . checked(get_option('cache_me_baby_auto_cache_update', '0'), '1', false) . '> Automatically warm cache when a post/page is updated</label>
                                <hr class="nice-divider">
                                <h3>Schedule Cache Warming</h3>';
        if (defined('DISABLE_WP_CRON') && DISABLE_WP_CRON) {
            echo '<p style="color:red;font-weight:bold;">WP Cron is disabled on this site.<br>The scheduled cache warming feature cannot be used.</p>';
        } else {
            $this->cron_schedule_field_html();
        }
        echo '              <hr class="nice-divider">
                                <h3>Admin Menu Bar</h3>
                                <label><input type="checkbox" name="cache_me_baby_hide_admin_bar" value="1" ' . checked(get_option('cache_me_baby_hide_admin_bar', '0'), '1', false) . '> Hide admin bar <b>"Cache Me Baby"</b> link</label>';
        // Check if site is on Cloudflare
        if ($main_instance->is_cloudflare_nameservers()) {
            echo '<hr class="nice-divider">
            
            <h3>Cloudflare Connection Settings&nbsp;&nbsp;<span style="font-size:16px">(to clear cache)</span></h3>
                  <p>Enter your Cloudflare Zone ID and API Token below. This information is required to allow the cache warmer to work. To see how <a href="https://developers.cloudflare.com/fundamentals/setup/find-account-and-zone-ids/" target="_blank" rel="noopener noreferrer"><b>view this</b></a>.</p>
                  <p><button type="button" 
                        id="test_cloudflare_connection" 
                        class="button test-connection-button">
                        <span class="dashicons dashicons-image-rotate"></span>Test Connection
                </button></p>
                  ';
            $zone_id       = get_option('cache_me_baby_cloudflare_zone_id', '');
            $display_zone  = get_option('cache_me_baby_cloudflare_zone_id', '');
            $api_token     = get_option('cache_me_baby_cloudflare_api_token', '');
            $display_token = get_option('cache_me_baby_cloudflare_api_token', '');
            $email         = get_option('cache_me_baby_cloudflare_email', '');
            echo '<div style="display: flex; flex-direction: column; gap: 20px;">
        <!-- FIRST ROW -->
        <div style="display: flex; gap: 20px;">
            <!-- API Token Column -->
            <div style="display: flex; flex-direction: column;">
                <label for="cache_me_baby_cloudflare_api_token"><b>Global API Token:</b></label>
                <input type="text" 
                       name="cache_me_baby_cloudflare_api_token" 
                       id="cache_me_baby_cloudflare_api_token" 
                       value="' . esc_attr($display_token) . '"
                       style="max-width: 250px;" />
            </div>
            <!-- Zone ID Column -->
            <div style="display: flex; flex-direction: column;">
                <label for="cache_me_baby_cloudflare_zone_id"><b>Zone ID:</b></label>
                <input type="text" 
                       name="cache_me_baby_cloudflare_zone_id" 
                       id="cache_me_baby_cloudflare_zone_id" 
                       value="' . esc_attr($display_zone) . '"
                       style="max-width: 250px;" />
            </div>
        </div>
        <!-- SECOND ROW -->
        <div style="display: flex; gap: 20px;">
            <!-- Email Column -->
            <div style="display: flex; flex-direction: column;">
                <label for="cache_me_baby_cloudflare_email"><b>Email:</b></label>
                <input type="email" 
                       name="cache_me_baby_cloudflare_email" 
                       id="cache_me_baby_cloudflare_email" 
                       value="' . esc_attr($email) . '"
                       style="max-width: 250px;" />
            </div>
            <!-- Clear Cache Button -->
            <div style="display: flex; flex-direction: column;">
                <label>&nbsp;</label>
                <button type="button" id="warm_cache_cloudflare" class="button button-primary">
                    <span class="dashicons dashicons-trash"></span> Clear CloudflareCache
                </button>
            </div>
        </div>
      </div>';
        }
        echo '          </div>
                        </div>
                        </div>
                    </form>
                    </div>
                <div class="cache-me-baby-sidebar">
                    <div class="speed-worker-container">
                        <div class="speed-worker">
                            <a href="https://www.wpfixit.com/" target="_blank">
                                <img src="' . esc_url(plugins_url('images/round-logo.webp', __FILE__)) . '" alt="Speed Optimization">
                            </a>
                        </div>
                        <h3 class="speed-text">Need More Speed?</h3>
                    </div>
                    <p>Transform your existing WordPress site into a <strong>high-performance, speed-optimized powerhouse</strong> for faster load times and better user experience.</p>
                    <ul>
                        <li>✅ Expert WordPress Speed Optimization</li>
                        <li>✅ Personalized Speed Specialist Assigned</li>
                        <li>✅ Optimize All URLs on Desktop and Mobile</li>
                        <li>✅ Lifetime WP Rocket Plugin ($59/year value)</li>
                        <li>✅ Lifetime Perfmatters Plugin ($25/year value)</li>
                        <li>✅ Website Image Optimization (lossless)</li>
                        <li>✅ Full Website Database Optimization</li>
                        <li>✅ Before & After Speed Benchmark Tests</li>
                        <li>✅ Detailed Optimization Report of All Tasks</li>
                    </ul>
                    <p>
                        <a id="speed_service_button" href="https://www.wpfixit.com/improve-wordpress-speed-and-performance"
                           target="_blank" class="button button-primary">Learn More</a>
                    </p>
                </div>
              </div>';
        echo '</div>';
        // Enqueue the right JS based on Cloudflare check
        if ($main_instance->is_cloudflare_nameservers()) {
            wp_enqueue_script(
                'cache-me-baby-js',
                plugin_dir_url(__FILE__) . 'assets/js/cache-me-baby-cf.js',
                ['jquery'],
                filemtime(plugin_dir_path(__FILE__) . 'assets/js/cache-me-baby-cf.js'),
                true
            );
        } else {
            wp_enqueue_script(
                'cache-me-baby-js',
                plugin_dir_url(__FILE__) . 'assets/js/cache-me-baby.js',
                ['jquery'],
                filemtime(plugin_dir_path(__FILE__) . 'assets/js/cache-me-baby.js'),
                true
            );
        }
        wp_localize_script('cache-me-baby-js', 'cacheMeBabyAjax', [
            'ajaxurl'    => admin_url('admin-ajax.php'),
            'nonce'      => wp_create_nonce('cache_me_baby_nonce'),
            'loadingGif' => plugin_dir_url(__FILE__) . 'images/magic.gif',
        ]);
    }
}