<?php
/**
 * Credit System Bootstrap
 *
 * Initializes the credit system and provides backward compatibility.
 *
 * @package AIPT\Core\CreditSystem
 */

namespace AIPT\Core\CreditSystem;

if (!defined('ABSPATH')) {
    exit;
}

/**
 * Credit System Bootstrap
 */
class CreditSystemBootstrap
{
    private static bool $initialized = false;

    /**
     * Initialize the credit system
     */
    public static function init(): void
    {
        if (self::$initialized) {
            return;
        }

        CreditMigration::maybeRun();

        $rest = new CreditRest();
        $rest->register();

        self::registerCronHooks();

        self::$initialized = true;
    }

    /**
     * Register cron hooks for periodic sync
     */
    private static function registerCronHooks(): void
    {
        add_action('aipt_credit_sync', [self::class, 'handleCronSync']);

        $isRegistered = CreditCredentials::isRegistered();

        if ($isRegistered) {
            if (!wp_next_scheduled('aipt_credit_sync')) {
                wp_schedule_event(time(), 'hourly', 'aipt_credit_sync');
            }
        } else {
            wp_clear_scheduled_hook('aipt_credit_sync');
        }
    }

    /**
     * Handle cron sync
     */
    public static function handleCronSync(): void
    {
        try {
            CreditManager::getInstance()->sync();
        } catch (\Throwable $e) {

        }
    }

    /**
     * Deactivate - clear cron hooks
     */
    public static function deactivate(): void
    {
        wp_clear_scheduled_hook('aipt_credit_sync');
    }

    /**
     * Check if initialized
     *
     * @return bool
     */
    public static function isInitialized(): bool
    {
        return self::$initialized;
    }
}
