<?php

if (! defined('ABSPATH')) {

    exit;

}

class CacheMeBaby_Cron {

    public function __construct() {

        // Cron hook (called by WP on schedule)

        add_action('cache_me_baby_cron_hook',       [$this, 'crawl_site']);

        // AJAX: warm cache immediately

        add_action('wp_ajax_warm_cache_ajax',       [$this, 'handle_ajax_cache_warming']);

        // When a post is updated (auto warm)

        add_action('save_post',                     [$this, 'trigger_cache_on_update'], 10, 3);

        // When admin saves plugin settings, we do a “custom” action to update cron

        add_action('cache_me_baby_update_cron',     [$this, 'update_cron_schedule']);

    }

    /**

     * Update the WP Cron schedule (daily, weekly, etc.)

     */

    public function update_cron_schedule() {

        wp_clear_scheduled_hook('cache_me_baby_cron_hook');

        $schedule = get_option('cache_me_baby_cron_schedule', 'none');

        if ('none' === $schedule) {

            return;

        }

        if (! in_array($schedule, ['daily', 'weekly', 'monthly'], true)) {

            $schedule = 'daily';

        }

        if (! wp_next_scheduled('cache_me_baby_cron_hook')) {

            wp_schedule_event(time() + 60, $schedule, 'cache_me_baby_cron_hook');

        }

    }

    /**

     * AJAX: Kick off a manual crawl

     */

    public function handle_ajax_cache_warming() {

        check_ajax_referer('cache_me_baby_nonce', 'nonce');

        $this->crawl_site();

    }

    /**

     * The function that visits all selected post type URLs

     */

    public function crawl_site() {

        $selected_post_types = get_option('cache_me_baby_post_types', []);

        if (! is_array($selected_post_types)) {

            $selected_post_types = [];

        }

        $excluded_urls = explode("\n", get_option('cache_me_baby_excluded_urls', ''));

        $offset = isset($_POST['offset']) ? intval($_POST['offset']) : 0;

        $limit  = isset($_POST['limit']) ? intval($_POST['limit']) : -1;

        $args = [

            'post_type'      => $selected_post_types,

            'post_status'    => 'publish',

            'posts_per_page' => $limit,

            'offset'         => $offset,

        ];

        $query = new WP_Query($args);

        $urls  = [];

        while ($query->have_posts()) {

            $query->the_post();

            $urls[] = get_permalink();

        }

        wp_reset_postdata();

        // Remove excluded URLs

        $urls = array_diff($urls, array_map('trim', $excluded_urls));

        // Visit each URL to "warm" the cache

        foreach ($urls as $url) {

            wp_remote_get($url, [

                'timeout'    => 10,

                'blocking'   => true,

                'user-agent' => 'WP Fix It Cache Me Baby',

            ]);

        }

        // After warming, purge Cloudflare if configured

        $main_instance = CacheMeBaby::get_instance();

        if ($main_instance->is_cloudflare_nameservers() &&

            get_option('cache_me_baby_cloudflare_zone_id') &&

            get_option('cache_me_baby_cloudflare_api_token')) {

            // Use the Cloudflare class to purge

            if (class_exists('CacheMeBaby_Cloudflare')) {

                $cloudflare = new CacheMeBaby_Cloudflare();

                $cloudflare->purge_cloudflare_cache();

            }

        }

        wp_send_json_success([

            'urls'  => $urls,

            'total' => $query->found_posts,

        ]);

    }

    /**

     * Auto-warm cache when a post/page is updated

     */

    public function trigger_cache_on_update($post_id, $post, $update) {

        if (wp_is_post_autosave($post_id) || wp_is_post_revision($post_id)) {

            return;

        }

        if (get_option('cache_me_baby_auto_cache_update', '0') !== '1') {

            return;

        }

        $selected_post_types = get_option('cache_me_baby_post_types', []);

        if (! in_array($post->post_type, $selected_post_types, true)) {

            return;

        }

        $post_url = get_permalink($post_id);

        if ('publish' === $post->post_status && ! empty($post_url)) {

            // Warm just that updated post

            wp_remote_get($post_url, [

                'timeout'    => 10,

                'blocking'   => false,

                'user-agent' => 'WP Fix It Cache Me Baby',

            ]);

            // If Cloudflare is in use, purge there too

            $main_instance = CacheMeBaby::get_instance();

            if ($main_instance->is_cloudflare_nameservers() &&

                get_option('cache_me_baby_cloudflare_zone_id') &&

                get_option('cache_me_baby_cloudflare_api_token')) {

                if (class_exists('CacheMeBaby_Cloudflare')) {

                    $cloudflare = new CacheMeBaby_Cloudflare();

                    $cloudflare->purge_cloudflare_cache();

                }

            }

        }

    }

}