<?php

namespace FleekDash\Services\SiteGrowthMeter;

use FleekDash\Services\SiteGrowthMeter\GrowthCalculator;

/**
 * Snapshot Scheduler
 *
 * Handles automatic monthly snapshot creation via WordPress cron
 *
 * @package FleekDash\Services\SiteGrowthMeter
 */
class SnapshotScheduler
{
    const CRON_HOOK = 'fleekdash_growth_meter_monthly_snapshot';
    const CRON_INTERVAL = 'monthly';

    /**
     * Initialize scheduler
     */
    public static function init()
    {
        $instance = new self();
        $instance->registerHooks();
    }

    /**
     * Register WordPress hooks
     */
    private function registerHooks()
    {
        // Register cron hook
        \add_action(self::CRON_HOOK, [$this, 'createMonthlySnapshot']);

        // Register custom cron interval (monthly)
        // Must be registered early (before scheduling)
        \add_filter('cron_schedules', [$this, 'addMonthlyInterval'], 10, 1);
    }

    /**
     * Add monthly interval to WordPress cron schedules
     *
     * @param array $schedules Existing schedules
     * @return array Modified schedules
     */
    public function addMonthlyInterval($schedules)
    {
        if (!isset($schedules['monthly'])) {
            $schedules['monthly'] = [
                'interval' => MONTH_IN_SECONDS, // 30 days
                'display' => __('Once Monthly', 'fleekdash')
            ];
        }

        return $schedules;
    }

    /**
     * Schedule monthly snapshot creation
     *
     * @return bool Success status
     */
    public static function schedule()
    {
        // Clear any existing schedule first
        self::unschedule();

        // Calculate next run: First day of next month at 2:00 AM
        $next_month = date('Y-m-01', strtotime('+1 month'));
        $next_run = strtotime($next_month . ' 02:00:00');

        // If next month is in the past (shouldn't happen), schedule for tomorrow
        if ($next_run < time()) {
            $next_run = strtotime('+1 day 02:00:00');
        }

        $scheduled = \wp_schedule_event($next_run, self::CRON_INTERVAL, self::CRON_HOOK);

        if ($scheduled === false) {
            if (function_exists('fleekdash_log_error')) {
                fleekdash_log_error('Growth Score: Failed to schedule monthly snapshot cron job');
            }
            return false;
        }

        if (function_exists('fleekdash_log_info')) {
            fleekdash_log_info('Growth Score: Monthly snapshot cron job scheduled for ' . date('Y-m-d H:i:s', $next_run));
        }

        return true;
    }

    /**
     * Unschedule monthly snapshot creation
     *
     * @return bool Success status
     */
    public static function unschedule()
    {
        $timestamp = wp_next_scheduled(self::CRON_HOOK);
        if ($timestamp) {
            \wp_unschedule_event($timestamp, self::CRON_HOOK);
        }

        // Also clear any orphaned schedules
        wp_clear_scheduled_hook(self::CRON_HOOK);

        return true;
    }

    /**
     * Check if snapshot is scheduled
     *
     * @return bool|int Timestamp of next run, or false if not scheduled
     */
    public static function isScheduled()
    {
        return wp_next_scheduled(self::CRON_HOOK);
    }

    /**
     * Create monthly snapshot (cron callback)
     *
     * This method is called by WordPress cron
     */
    public function createMonthlySnapshot()
    {
        try {
            if (function_exists('fleekdash_log_info')) {
                fleekdash_log_info('Growth Score: Monthly snapshot cron job started');
            }

            $calculator = new GrowthCalculator();
            $current_month = date('Y-m');

            // Create snapshot for previous month (since we're at the start of new month)
            $previous_month = date('Y-m', strtotime('-1 month'));
            $result = $calculator->createMonthlySnapshot($previous_month);

            if ($result) {
                if (function_exists('fleekdash_log_info')) {
                    fleekdash_log_info("Growth Score: Monthly snapshot created successfully for {$previous_month}");
                }

                // Also create snapshot for current month if it doesn't exist
                $calculator->createMonthlySnapshot($current_month);
            } else {
                if (function_exists('fleekdash_log_error')) {
                    fleekdash_log_error("Growth Score: Failed to create monthly snapshot for {$previous_month}");
                }
            }

            // Reschedule for next month
            self::schedule();

        } catch (\Exception $e) {
            if (function_exists('fleekdash_log_error')) {
                fleekdash_log_error('Growth Score: Error in monthly snapshot cron: ' . $e->getMessage());
            }
        }
    }

    /**
     * Manually trigger snapshot creation (for testing/admin)
     *
     * @param string|null $month_year Month to create snapshot for (defaults to current month)
     * @return bool Success status
     */
    public static function triggerManually($month_year = null)
    {
        try {
            $calculator = new GrowthCalculator();
            return $calculator->createMonthlySnapshot($month_year);
        } catch (\Exception $e) {
            if (function_exists('fleekdash_log_error')) {
                fleekdash_log_error('Growth Score: Error in manual snapshot creation: ' . $e->getMessage());
            }
            return false;
        }
    }
}
