<?php

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

if ( ! function_exists( 'bwdk_can_auto_move_to_processing' ) ) {
    function bwdk_is_admin_manual_status_change_to_final( \WC_Order $order ): bool {
        if ( ! is_admin() ) {
            return false;
        }

        if ( ! $order->get_meta( '_bwdk_order_uuid' ) ) {
            return false;
        }

        $posted_status = '';
        if ( isset( $_POST['order_status'] ) ) {
            $posted_status = wc_clean( wp_unslash( $_POST['order_status'] ) );
        } elseif ( isset( $_POST['status'] ) ) {
            // Some admin screens / integrations may post "status" instead.
            $posted_status = wc_clean( wp_unslash( $_POST['status'] ) );
        }

        $posted_status = preg_replace( '/^wc-/', '', $posted_status );

        $final_statuses = array(
            'completed',
            'cancelled',
            'refunded',
            'failed',
        );

        return in_array( $posted_status, $final_statuses, true );
    }

    function bwdk_has_recent_admin_manual_status_lock( \WC_Order $order, int $ttl_seconds = 300 ): bool {
        if ( ! $order->get_meta( '_bwdk_order_uuid' ) ) {
            return false;
        }

        $lock_time = (int) $order->get_meta( '_bwdk_admin_manual_status_lock', true );
        if ( $lock_time <= 0 ) {
            return false;
        }

        return ( time() - $lock_time ) < $ttl_seconds;
    }

    function bwdk_can_auto_move_to_processing( \WC_Order $order ): bool {
        if ( ! $order->get_meta( '_bwdk_order_uuid' ) ) {
            return false;
        }

        if ( function_exists( 'bwdk_is_admin_manual_status_change_to_final' ) && bwdk_is_admin_manual_status_change_to_final( $order ) ) {
            return false;
        }

        if ( function_exists( 'bwdk_has_recent_admin_manual_status_lock' ) && bwdk_has_recent_admin_manual_status_lock( $order, 300 ) ) {
            return false;
        }

        if ( $order->get_meta( '_bwdk_auto_processing_done' ) === 'yes' ) {
            return false;
        }

        $current_status = $order->get_status();

        $blocked_statuses = array(
            'processing',
            'completed',
            'cancelled',
            'refunded',
            'failed',
        );

        if ( in_array( $current_status, $blocked_statuses, true ) ) {
            return false;
        }

        $allowed_statuses = array(
            'pending',
            'on-hold',
            'bwdk-verifying',
            'bwdk-verified',
        );

        return in_array( $current_status, $allowed_statuses, true );
    }
}

