<?php
if ( ! defined( 'ABSPATH' ) ) exit;
class SBPAI_Action_Scheduler {
    public function init() {
        add_action( 'sbpai_generate_dummy_data_job', array( $this, 'process_job' ), 10, 5 );
    }

    public function schedule_job( $type, $amount, $niche, $ai, $safe_args = array() ) {
        if ( function_exists( 'as_enqueue_async_action' ) ) {
            for ( $i = 0; $i < $amount; $i++ ) {
                as_enqueue_async_action( 'sbpai_generate_dummy_data_job', array( 'type' => $type, 'index' => $i, 'niche' => $niche, 'ai' => $ai, 'args' => $safe_args ), 'sbpai_dummy_data' );
            }
            return true;
        }
        return false;
    }

    public function process_job( $type, $index, $niche = 'General', $ai = 1, $args = array() ) {
        update_option( 'sbpai_active_niche', $niche );
        update_option( 'sbpai_active_ai', $ai );

        $module = null;
        switch ( $type ) {
            case 'posts':    $module = new SBPAI_Module_Posts( $args ); break;
            case 'pages':    $module = new SBPAI_Module_Pages( $args ); break;
            case 'users':    $module = new SBPAI_Module_Users( $args ); break;
            case 'products': $module = new SBPAI_Module_Products( $args ); break;
            case 'orders':   $module = new SBPAI_Module_Orders( $args ); break;
            case 'coupons':  $module = new SBPAI_Module_Coupons( $args ); break;
        }

        if ( $module ) {
            do_action( 'sbpai_before_generate', $type, $args );
            $generated_id = $module->generate();
            
            if ( $generated_id ) {
                do_action( 'sbpai_after_generate', $generated_id );
                
                $use_acf = isset( $args['acf'] ) ? intval( $args['acf'] ) : 1; // Default 1 for backwards compatibility
                if ( $use_acf && class_exists( 'ACF' ) && in_array( $type, ['posts', 'pages', 'products'] ) ) {
                    $acf_module = new SBPAI_Module_ACF();
                    $acf_module->populate_all_fields( $generated_id, 'post' );
                }
            }
        }
    }
}
