<?php

namespace includes\api;

use includes\WTV_Plugin;
use includes\WTV_Settings_Validator;
use WC_Order;

class WTV_Sync_Controller{

	/** Adds hooks
	 *
	 */
	public static function woocommerce_init_handler() {
		add_action( 'woocommerce_order_status_changed', function ( $wc_order_id, $status_transition_from, $status_transition_to, $wc_order ) {
			$sync_settings = get_option( 'visma_order_sync_settings_' . $wc_order->get_payment_method(), [] );
			if ( array_key_exists( 'sync_on_status', $sync_settings ) && 'processing' === $status_transition_to && $sync_settings[ 'sync_on_status' ] == $status_transition_to ) {
				self::schedule_sync_action( $wc_order_id );
			}
			else{
				try {
					if ( array_key_exists( 'sync_on_status', $sync_settings ) && $sync_settings[ 'sync_on_status' ] == $status_transition_to ) {
						WTV_Sync_Controller::sync( $wc_order_id );
					}
				} catch ( Exception $error ) {
					wtv_write_log( $error->getMessage() . ' (Felkod: ' . $error->getCode() . ')' );
					wp_die( $error->getMessage() . ' (Felkod: ' . $error->getCode() . ')' );
				}
			}

		}, 10, 4 );
		add_action('wetail_visma_sync_order', [__CLASS__,'sync'], 10, 1 );
	}

	/**
	 * https://app.clickup.com/t/8694fy1c8
	 * @since 0.9.1
	 */
	public static function schedule_sync_action( $wc_order_id ){
		$param  = [ $wc_order_id ];
		$delay  = 30;
		$ts     = time() + $delay;

		if ( function_exists( 'as_schedule_single_action' ) ){
			return as_schedule_single_action( $ts, 'wetail_visma_sync_order', $param, '_wse' );
		}

		return wp_schedule_single_event( $ts, 'wetail_visma_sync_order', $param );
	}

    /**
     * Handles all syncing for an order
     *
     * @param int $wc_order_id
     * @param bool $force Optional. Whether to force the creation of a voucher for the order. Default is false.
     *
     * @return bool
     * @throws \Exception
     */
    public static function sync( $wc_order_id, $force = false ){
		try{
			$wc_order = wc_get_order( $wc_order_id );
			WTV_Settings_Validator::validate_settings_payment_method( $wc_order );

			if( self::should_create_order() ){
				WTV_Orders::sync( $wc_order );

				if ( self::should_convert_order_to_invoice( $wc_order->get_payment_method() ) ){
					WTV_Orders::convert_order_to_invoice( $wc_order );
					if ( self::should_add_payment_to_invoice( $wc_order->get_payment_method() ) ){
						WTV_Invoice_Payment::create_invoice_payment( $wc_order, $wc_order->get_total(), $wc_order->get_date_created() );
					}
				}
			}
			elseif( self::should_create_voucher() && ! WTV_Vouchers::is_voucher_created( $wc_order ) ){
				$voucher = new WTV_Vouchers( $wc_order );
				$voucher->create_order_voucher( $force );
				WTV_Orders::set_order_as_synced( $wc_order, WTV_Plugin::SYNC_STATUS_VOUCHER_SYNCED );
			}
			return true;
		}
		catch (\Throwable $t){
			WTV_Error_Handling::remember_exception($t);
			return false;
		}
    }

    public static function should_add_payment_to_invoice( $payment_method ){
        $settings = get_option( 'visma_order_sync_settings_' . $payment_method );
        if( isset( $settings['order_add_invoice_payment'] ) ){
            return intval( $settings['order_add_invoice_payment'] ) == 1;
        }

    }

    public static function should_convert_order_to_invoice( $payment_method ){
        $settings = get_option( 'visma_order_sync_settings_' . $payment_method );
        if( isset( $settings['order_convert_to_invoice'] ) ){
            return intval( $settings['order_convert_to_invoice'] ) == 1;
        }

    }

    public static function should_create_order(){
        return get_option( 'visma_sync_order_method' ) && get_option( 'visma_sync_order_method' ) === 'create_orders';
    }

    public static function should_create_voucher(){
        return get_option( 'visma_sync_order_method' ) && get_option( 'visma_sync_order_method' ) === 'create_vouchers';
    }
}
