<?php

namespace PaychefPaymentGateway\Helper;

// Exit if accessed directly
if ( ! defined( 'ABSPATH' ) ) {
    exit;
}

use PayChef_Gateway;
use PaychefPaymentGateway\Service\OrderService;
use WC_Order;

class PaymentHelper
{
    /**
     * @return void
     */
	public static function handleError(): void {
        if (!isset($_GET['order_id']) || !isset($_GET['order_hash'])) {
            return;
        }

        // Verify nonce
        if ( ! isset( $_GET['_wpnonce'] ) || ! wp_verify_nonce( sanitize_text_field( wp_unslash( $_GET['_wpnonce'] ) ), 'paychef_handle_error' ) ) {
            wp_die( esc_html__( 'Security verification failed.', 'paychef-payments-for-woocommerce' ) );
        }

        $order_id = intval(sanitize_text_field( wp_unslash( $_GET['order_id'] ) ));
        $requestHash = sanitize_text_field( wp_unslash( $_GET['order_hash'] ) );

		$order = new WC_Order( $order_id );

        // Check if request valid
        if (self::getOrderTimeHash($order) !== $requestHash) {
            return;
        }

        $orderService = PayChef_Gateway::getOrderService();

        // Set order status to cancelled
		if ( $orderService->transition_allowed( OrderService::WC_STATUS_CANCELLED, $order ) ) {
			$orderService->transitionOrder( $order, OrderService::WC_STATUS_CANCELLED );
		}

        $paychefApiService = PayChef_Gateway::getPaychefApiService();

        // Delete old Gateway using order metadata
        $gatewayId = intval($order->get_meta('paychef_gateway_id', true));
        $paychefApiService->deleteGatewayById($gatewayId);
    }

    /**
     * @param $order
     * @return string
     */
	public static function getCancelUrl( WC_Order $order ): string  {
		return wp_nonce_url(
			add_query_arg([
				'paychef_error' => '1',
				'order_id'      => $order->get_id(),
				'order_hash'    => self::getOrderTimeHash( $order )
			], $order->get_checkout_payment_url() ),
			'paychef_handle_error'
		);
	}

	private static function getOrderTimeHash( WC_Order $order ): string {
		return hash( 'sha256', AUTH_SALT . $order->get_date_created()->__toString() );
	}
}