<?php
/**
 * Cron Scheduler Engine
 *
 * @package Invizo\SubscriptionsLite\Core
 */

namespace Invizo\SubscriptionsLite\Core;

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

class Scheduler {

    public static function init() {
        add_action( 'init', array( __CLASS__, 'schedule_events' ) );
        add_action( 'invizo_daily_billing_check', array( __CLASS__, 'perform_daily_checks' ) );

        // Clean up on deactivation
        register_deactivation_hook( INVIZO_LITE_PATH . 'invizo-subscriptions-lite.php', array( __CLASS__, 'unschedule_events' ) );
    }

    public static function schedule_events() {
        if ( ! wp_next_scheduled( 'invizo_daily_billing_check' ) ) {
            wp_schedule_event( time(), 'daily', 'invizo_daily_billing_check' );
        }
    }

    public static function unschedule_events() {
        wp_clear_scheduled_hook( 'invizo_daily_billing_check' );
    }

    public static function perform_daily_checks() {
        // Find subscriptions that are "past_due" and haven't been touched in a while
        $args = array(
            'post_type'      => 'invizo_sub',
            'posts_per_page' => 100,
            'meta_query'     => array(
                array(
                    'key'   => '_status',
                    'value' => 'past_due',
                )
            )
        );

        $past_due_subs = get_posts( $args );

        foreach ( $past_due_subs as $sub ) {
            // Placeholder: Here we would trigger Dunning emails or run a targeted Stripe API retry
            $stripe_sub_id = get_post_meta( $sub->ID, '_stripe_subscription_id', true );
            if ( $stripe_sub_id ) {
                // Call Stripe gateway to check if it's completely cancelled
                // If cancelled in Stripe, update local
                // StripeGateway::sync_status( $stripe_sub_id );
            }
        }
    }
}
