<?php

namespace Sibs\Stargate\Cron;

use Sibs\Stargate\Config\SibsConfig;
use Sibs\Stargate\Constants\Logs;
use Sibs\Stargate\Constants\WoocommerceOrderStatus;
use Sibs\Stargate\Constants\WoocommercePaymentMethods;
use Sibs\Stargate\Loggers\SibsLogger;

defined('ABSPATH') || exit;

class CancelOnholdOrders
{
    /**
     * Process.
     */
    public static function process()
    {
        $held_duration = SibsConfig::getWoocommerceOption('woocommerce_hold_stock_minutes');
        $manage_stock = SibsConfig::getWoocommerceOption('woocommerce_manage_stock');

        if ($held_duration < 1 || 'yes' !== $manage_stock) {
            return;
        }

        $seconds_delay = $held_duration * 60;
        $today = strtotime(SibsConfig::getStoreCurrentTime());

        // Get unpaid orders
        $unpaid_orders = (array) wc_get_orders([
            'limit' => -1,
            'status' => WoocommerceOrderStatus::ON_HOLD,
            'date_created' => '<'.($today - $seconds_delay),
        ]);

        if (sizeof($unpaid_orders) > 0) {
            $cancelled_text = __('The order was cancelled due to no payment from customer', 'sibs-woo-stg');

            // Loop through orders
            foreach ($unpaid_orders as $unpaid_order) {
                SibsLogger::debug('sibs cancel on-hold order id: '.SibsLogger::prettify($unpaid_order->get_id()), Logs::CRON);

                $payments_method_on_hold_to_cancel = [
                    WoocommercePaymentMethods::BLIK,
                    WoocommercePaymentMethods::PAY_BY_LINK,
                    WoocommercePaymentMethods::PAY_BY_LINK_KEVIN,
                ];

                if (in_array($unpaid_order->get_payment_method(), $payments_method_on_hold_to_cancel)) {
                    try {
                        $unpaid_order->update_status(WoocommerceOrderStatus::CANCELLED, $cancelled_text);
                    } catch (\Throwable $t) {
                        SibsLogger::critical($t->getMessage(), Logs::CRON);
                    }
                }
            }
        }

        wp_clear_scheduled_hook('woocommerce_cancel_unpaid_orders');
        wp_schedule_single_event(time() + (absint($held_duration) * 60), 'woocommerce_cancel_unpaid_orders');
    }
}
