<?php
if ( ! defined( 'ABSPATH' ) ) exit;

/**
 * WP-Cron based automatic cache refresh for Google Reviews.
 *
 * Schedule: every 7 days (well within the 30-day transient expiry).
 * On each run, calls TMNL_Adapter_Google::fetch(true) if Google is enabled.
 */
class TMNL_Cron {

    const HOOK     = 'tmnl_cache_refresh';
    const SCHEDULE = 'tmnl_weekly';

    /** @var TMNL_Adapter_Google */
    private $google;

    public function __construct( $google_adapter ) {
        $this->google = $google_adapter;
        add_filter( 'cron_schedules', array( $this, 'add_schedule' ) );
        add_action( self::HOOK, array( $this, 'refresh' ) );
    }

    // -------------------------------------------------------------------------
    // Lifecycle hooks — called from register_activation/deactivation_hook
    // -------------------------------------------------------------------------

    public static function activate() {
        if ( ! wp_next_scheduled( self::HOOK ) ) {
            // Stagger the first run by 1 hour so activation itself isn't slow.
            wp_schedule_event( time() + HOUR_IN_SECONDS, self::SCHEDULE, self::HOOK );
        }
    }

    public static function deactivate() {
        wp_clear_scheduled_hook( self::HOOK );
    }

    // -------------------------------------------------------------------------
    // Custom cron interval
    // -------------------------------------------------------------------------

    public function add_schedule( $schedules ) {
        $schedules[ self::SCHEDULE ] = array(
            'interval' => 7 * DAY_IN_SECONDS,
            'display'  => __( 'Once Weekly (Kuchikomi Wall)', 'elplan-kuchikomi-wall' ),
        );
        return $schedules;
    }

    // -------------------------------------------------------------------------
    // Refresh callback — runs on each scheduled event
    // -------------------------------------------------------------------------

    public function refresh() {
        $status = $this->google->get_status();
        if ( empty( $status['is_enabled'] ) ) {
            return; // Google source disabled — nothing to do.
        }

        $result = $this->google->fetch( true ); // force = true bypasses transient

        if ( is_wp_error( $result ) ) {
            // Log to debug.log if WP_DEBUG_LOG is enabled.
            // phpcs:ignore WordPress.PHP.DevelopmentFunctions.error_log_error_log
            error_log( '[Kuchikomi Wall] Cron cache refresh failed: ' . $result->get_error_message() );
        }
    }

    // -------------------------------------------------------------------------
    // Utility — used by admin to show next scheduled time
    // -------------------------------------------------------------------------

    public static function next_run() {
        $ts = wp_next_scheduled( self::HOOK );
        return $ts ? $ts : null;
    }
}
