<?php
namespace ARCHM\Helpers;

use ARCHM\Features\BackgroundProcess;

trait BGProcessHelper {

    /**
     * Push orders to queue (no save/dispatch). Used when queueing multiple batches in one request.
     *
     * @param BackgroundProcess $background_process
     * @param array $orders Order IDs
     * @return bool
     */
    // phpcs:ignore PHPCompatibility.FunctionDeclarations.NewReturnTypeDeclarations.boolFound
    final public function push_orders_batch( BackgroundProcess $background_process, array $orders ): bool {
        if ( empty($orders) ) {
            return false;
        }
        foreach ( $orders as $order ) {
            $background_process->push_to_queue([
                'post_id' => $order,
            ]);
        }
        return true;
    }

    /**
     * Start Background process
     *
     * @param BackgroundProcess $backgroundProcess
     * @param $orders
     * @return bool
     * @since 1.0
     * @author Siam Maruf
     */
    // phpcs:ignore PHPCompatibility.FunctionDeclarations.NewReturnTypeDeclarations.boolFound
    final public function start_background_process( BackgroundProcess $background_process, $orders ): bool {
        if ( ! empty($orders) ) {
            $this->push_orders_batch($background_process, (array) $orders);
            $background_process->save()->dispatch();
            return true;
        }
        return false;
    }

    /**
     * Check if order-sync-with-google-sheets-for-woocommerce plugin is active
     *
     * @return bool True if plugin is active, false otherwise
     */
    final public function is_order_sync_plugin_active() {
        // Check if WordPress function exists (might not be available in all contexts)
        if ( ! function_exists('is_plugin_active') ) {
            require_once ABSPATH . 'wp-admin/includes/plugin.php';
        }

        // Check if plugin is active
        $plugin_path = 'order-sync-with-google-sheets-for-woocommerce/order-sync-with-google-sheets-for-woocommerce.php';
        if ( ! is_plugin_active($plugin_path) ) {
            return false;
        }

        // Also verify the class exists as an additional check
        if ( ! class_exists('\OrderSyncWithGoogleSheetForWooCommerce\Hooks') ) {
            return false;
        }

        return true;
    }

    /**
     * Sync orders to Google Sheets using the same batch mechanism as manual sync
     * This ensures Google Sheets is updated after archiving/unarchiving orders
     * Only executes when order-sync-with-google-sheets-for-woocommerce plugin is active
     *
     * @return void
     */
    final public function sync_orders_to_google_sheets() {
        // Check if order-sync plugin is active
        if ( ! $this->is_order_sync_plugin_active() ) {
            return;
        }

        // Check if osgsw_order_count function exists
        if ( ! function_exists('osgsw_order_count') ) {
            return;
        }

        // Check if Order and Sheet classes exist
        if ( ! class_exists('\OrderSyncWithGoogleSheetForWooCommerce\Order') ||
            ! class_exists('\OrderSyncWithGoogleSheetForWooCommerce\Sheet') ) {
            return;
        }

        try {
            // Get total order count using the exact same function as manual sync
            $total_orders = osgsw_order_count();

            if ( ! $total_orders || $total_orders <= 0 ) {
                return;
            }

            // Initialize Order and Sheet instances
            $order = new \OrderSyncWithGoogleSheetForWooCommerce\Order();
            $sheet = new \OrderSyncWithGoogleSheetForWooCommerce\Sheet();

            // Set license sync flag (same as sync_batch_to_sheet_callback)
            // Note: sync_batch_all() will check if plugin is ready internally
            update_option('osgsw_license_sync', false);

            // Process in batches of 1500 (same as manual sync)
            $batch_size    = 1500;
            $total_batches = ceil($total_orders / $batch_size);

            // Process each batch
            for ( $batch = 0; $batch < $total_batches; $batch++ ) {
                $offset        = $batch * $batch_size;
                $is_last_batch = ( $batch === $total_batches - 1 );

                // Use the exact same sync logic as sync_batch_to_sheet_callback()
                // This calls sync_batch_all() which:
                // 1. Checks if plugin is ready (internal check)
                // 2. Formats order information
                // 3. Gets header with values for batch
                // 4. Appends to Google Sheet
                // 5. Updates sorting
                $update_result = $order->sync_batch_all($offset, $batch_size);

                if ( $update_result ) {
                    // Update dropdowns and sorting (same as sync_batch_to_sheet_callback)
                    $sheet->update_google_sheet_dropdowns();
                    $sheet->update_google_sheet_sorting();

                    // Clear batch cache if this is the last batch (same as sync_batch_to_sheet_callback)
                    if ( $is_last_batch ) {
                        $order->clear_batch_cache();
                    }
                }
            }
		} catch ( \Exception $e ) {
            // Silently handle errors - sync will be retried on next operation if needed
            // phpcs:ignore Generic.CodeAnalysis.EmptyStatement.DetectedCatch -- Errors are handled silently to allow retry on next operation
            unset($e);
        }
    }

    /**
     * Temporarily disable order-sync plugin hooks during unarchiving
     * This prevents Google Sheets API calls from slowing down the unarchiving process
     */
    private function disable_order_sync_hooks() {
        // Check if order-sync plugin is active
        if ( ! class_exists('\OrderSyncWithGoogleSheetForWooCommerce\Hooks') ) {
            return false;
        }

        // Store original hook priorities before removing
        $hooks_to_disable = [
            'woocommerce_update_order'         => 10,
            'woocommerce_order_status_changed' => 10,
            'woocommerce_trash_order'          => 10,
        ];

        // Remove hooks temporarily
        foreach ( $hooks_to_disable as $hook => $priority ) {
            remove_action($hook, [ \OrderSyncWithGoogleSheetForWooCommerce\Hooks::$instance, 'update_order_callback' ], $priority);
            remove_action($hook, [ \OrderSyncWithGoogleSheetForWooCommerce\Hooks::$instance, 'order_status_changed_callback' ], $priority);
            remove_action($hook, [ \OrderSyncWithGoogleSheetForWooCommerce\Hooks::$instance, 'save_post_callback_trash' ], $priority);
        }

        // Set flag to indicate hooks are disabled
        update_option('arcm_order_sync_hooks_disabled', true);

        return true;
    }

    /**
     * Re-enable order-sync plugin hooks after unarchiving
     */
    private function enable_order_sync_hooks() {
        // Check if order-sync plugin is active
        if ( ! class_exists('\OrderSyncWithGoogleSheetForWooCommerce\Hooks') ) {
            return false;
        }

        // Re-add hooks (they will be re-registered by the plugin's add_actions method)
        // The plugin re-registers hooks on each page load, so we just need to clear the flag
        delete_option('arcm_order_sync_hooks_disabled');

        return true;
    }
}
