<?php

namespace BexioConnectorByHelvy;

/**
 * Handle cron jobs (recurring tasks performmed by the plugin)
 *
 * @since 0.2.0
 */

defined('ABSPATH') || exit;

class Crons
{
    use Singleton;

    public function __construct()
    {
        add_action('batch_products_sync_event', array($this, 'sync_products_to_bexio'));
    }

    public function register_batch_products_sync_event()
    {
        wp_clear_scheduled_hook('batch_products_sync_event');
        if (!wp_next_scheduled('batch_products_sync_event')) {
            wp_schedule_event(strtotime('02:00:00'), 'daily', 'batch_products_sync_event');
        }
    }

    public function clear_batch_products_sync_event()
    {
        $timestamp = wp_next_scheduled('batch_products_sync_event');
        wp_unschedule_event($timestamp, 'batch_products_sync_event');
    }

    public function sync_products_to_bexio()
    {
        _bcbh_log("[Scheduled Event] Syncing products to bexio");

        if (!get_option(AdminAPISettings::$prefix . 'sync_products') && !get_option(AdminAPISettings::$prefix . 'sync_stocks')) {
            _bcbh_log("Product sync and stocks sync are disabled in plugin settings. Skipping...");
            return;
        }

        $args = array(
            'status' => 'publish',
            'orderby' => 'date',
            'order' => 'DESC',
            'limit' => -1, // Fetch all products
        );

        // Fetch products
        $products = wc_get_products($args);
        foreach ($products as $product) {
            if ($product && $product instanceof \WC_Product) {
                // Sync product and all its variations (if applicable)

                $bexio_product = null;
                if (get_option(AdminAPISettings::$prefix . 'sync_products')) {
                    $result = WCToBexio::instance()->sync_product($product, true);
                    if (is_wp_error($result)) {
                        _bcbh_log("Error syncing product ID {$product->get_id()}: " . $result->get_error_message());
                    } else {
                        $bexio_product = $result['bexio_product'];
                        _bcbh_log("Product ID {$product->get_id()} synced to bexio ID #{$bexio_product['id']}");
                        usleep(800000); // Sleep for 0.8 seconds
                    }
                } else if ($product->get_sku()) {
                    $bexio_product = API::instance()->get_article_by_sku($product->get_sku());
                    _bcbh_log("Products: " . json_encode($bexio_product));
                    if ($bexio_product instanceof \WP_Error) {
                        _bcbh_log("Error fetching bexio product by SKU {$product->get_sku()}: " . $bexio_product->get_error_message());
                    }
                } else {
                    _bcbh_log("Products sync disabled and no SKU for product ID {$product->get_id()}. Skipping...");
                }

                // Update WooCommerce stock if sync_stocks is set to BEXIO_TO_WOOCOMMERCE
                if (get_option(AdminAPISettings::$prefix . 'sync_stocks') === 'BEXIO_TO_WOOCOMMERCE' && $bexio_product && $bexio_product['is_stock']) {
                    $bexio_stock = $bexio_product['stock_available_nr'];
                    $product->set_stock_quantity($bexio_stock);
                    $product->save();
                    _bcbh_log("Updated WooCommerce stock for product ID {$product->get_id()} to {$bexio_stock}");
                }

                if ($product->is_type('variable')) {
                    $variations = $product->get_children();
                    _bcbh_log("Variations of product ID {$product->get_id()}: " . json_encode($variations));
                    foreach ($variations as $variation_id) {
                        $variation = wc_get_product($variation_id);
                        $bexio_product = null;
                        if (get_option(AdminAPISettings::$prefix . 'sync_products')) {
                            $result = WCToBexio::instance()->sync_product($variation, true);
                            if (is_wp_error($result)) {
                                _bcbh_log("Error syncing variation ID {$variation->get_id()}: " . $result->get_error_message());
                            } else {
                                $bexio_product = $result['bexio_product'];
                                _bcbh_log("Variation ID {$variation->get_id()} synced to bexio ID #{$bexio_product['id']}");
                                usleep(800000); // Sleep for 0.8 seconds
                            }
                        } else if ($variation->get_sku()) {
                            $bexio_product = API::instance()->get_article_by_sku($variation->get_sku());
                            _bcbh_log("Variation product: " . json_encode($bexio_product));
                            if ($bexio_product instanceof \WP_Error) {
                                _bcbh_log("Error fetching bexio product by SKU {$variation->get_sku()}: " . $variation->get_error_message());
                            }
                        } else {
                            _bcbh_log("Products sync disabled and no SKU for product ID {$variation->get_id()}. Skipping...");
                        }

                        // Update WooCommerce stock if sync_stocks is set to BEXIO_TO_WOOCOMMERCE
                        if (get_option(AdminAPISettings::$prefix . 'sync_stocks') === 'BEXIO_TO_WOOCOMMERCE'
                            && $bexio_product && $bexio_product['is_stock'] && $bexio_product['stock_available_nr'] > 0) {
                            $bexio_stock = $bexio_product['stock_available_nr'];
                            $variation->set_stock_quantity($bexio_stock);
                            $variation->save();
                            _bcbh_log("Updated WooCommerce stock for variation ID {$variation->get_id()} to {$bexio_stock}");
                        }
                    }
                }
            }
        }

        _bcbh_log("Done syncing products to bexio");
    }
}
