<?php

namespace StoreEngine\Addons\Razorpay;

use StoreEngine;
use StoreEngine\Classes\Order;
use StoreEngine\Utils\Formatting;
use StoreEngine\Utils\Helper;

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

class Assets {

	protected GatewayRazorpay $gateway;

	public static function init( $gateway ) {
		$self          = new self();
		$self->gateway = $gateway;
		if ( $self->gateway->is_available() ) {
			add_action( 'storeengine/enqueue_frontend_scripts', [ $self, 'load_js_frontend' ] );
			add_filter( 'storeengine/frontend_scripts_payment_method_data', [ $self, 'gateway_javascript_params' ] );
		}
	}

	public function load_js_frontend() {
		if ( Helper::is_checkout() ) {
			wp_enqueue_script( 'storeengine-razorpay-script', 'https://checkout.razorpay.com/v1/checkout.js', [], false, true ); // phpcs:ignore WordPress.WP.EnqueuedResourceParameters.NoExplicitVersion
		}
	}

	public function gateway_javascript_params( $payment_method ) {
		global $storeengine_settings;

		if ( $this->gateway->is_available() ) {
			$cart       = StoreEngine::init()->get_cart();
			$order      = Helper::get_recent_draft_order( 0, null, false );
			$cart_total = $cart ? $cart->get_total( 'razorpay-js' ) : 0;
			$order_id   = $order ? $order->get_id() : null;

			if ( Formatting::string_to_bool( get_query_var( 'order_pay' ) ) ) {
				$order = Helper::get_order( absint( get_query_var( 'order_id' ) ) );
				if ( ! is_wp_error( $order ) && $order->get_id() ) {
					$cart_total = $order->get_total( 'razorpay-js' );
					$order_id   = $order->get_id();
				}
			}

			$payment_method['razorpay'] = [
				'key_id'              => $this->gateway->get_option( 'key_id' ),
				'cart_total'          => RazorpayService::get_razorpay_amount( $cart_total ),
				'store_name'          => $storeengine_settings->store_name,
				'store_logo'          => wp_get_attachment_url( $storeengine_settings->store_logo ),
				'order_id'            => $order_id,
				'store_primary_color' => $storeengine_settings->global_primary_color,
			];
		}

		return $payment_method;
	}
}
