<?php

namespace Simplyin\Simplyin_W_Plugin\Payments\Gateway\Model;

use Exception;

abstract class Abstract_Card_Payment extends Abstract_Payment {

	private static bool $modal_rendered = false;
	public ?string $customer_error_message = null;

	public function order_received_actions(
		Order_Data $order_data
	) {

		$this->order_id = $order_data->get_order()->get_id();

		// Always render widget on thank-you page and enqueue assets via plugin hook
		add_action( 'woocommerce_before_thankyou',
			[ $this, 'output_card_modal' ] );
		// Fallback to broaden theme compatibility
		add_action( 'woocommerce_thankyou', [ $this, 'output_card_modal' ] );
		// Extra fallback used by some themes/templates (order details area)
		add_action( 'woocommerce_order_details_after_order_table',
			[ $this, 'output_card_modal' ] );
		add_action( 'wp_footer',
			[ $this, 'enqueue_scripts' ] );
	}

	protected function handle_error_customer_message( Exception $e ): string {
		if ( method_exists( $e, 'getResponseBody' ) ) {
			$response_body                = $e->getResponseBody();
			$message                      = $response_body;
			$this->customer_error_message = $this->find_customer_message_error( $message );
		} else {
			$message = $e->getMessage();
		}

		return $message;
	}


	private function find_customer_message_error( string $response_body
	): string {

		$decoded = (array) json_decode( $response_body, true );

		if ( isset( $decoded['message'] ) ) {
			return $decoded['message'];
		}

		return "Card transaction FAILED";
	}

	public function output_card_modal() {


		if ( self::$modal_rendered ) {
			return;
		}
		self::$modal_rendered = true;

		simplyin()->locate_template( 'card.php',
			[ 'card_payment' => $this ],
			'src/Payments/views/order_received' );
	}

	public function enqueue_scripts() {

		$public_url = simplyin()->get_plugin_url() . 'public';
		
		// Enqueue main status checking script
		wp_enqueue_script(
			'SimplyInThankYouPageJs',
			$public_url . '/thankyoupage/status/status.js',
			[ 'jquery' ],
			wp_rand(),
			true
		);

		// Enqueue 3DS redirect script if needed
		if ( ! empty( $this->redirect_url ) && $this->payment_status === 'PENDING' ) {
			// Debug: Log 3DS redirect attempt
			simplyin()->get_simplyin_logger()->log_if_wpdebug_on(
				sprintf( "[Abstract_Card_Payment] [enqueue_scripts] Enqueuing 3DS redirect script. Redirect URL: %s, Status: %s", 
					$this->redirect_url, 
					$this->payment_status 
				),
				'payments'
			);
			
			wp_enqueue_script(
				'SimplyIn3DSRedirectJs',
				$public_url . '/thankyoupage/status/3ds-redirect.js',
				[],
				wp_rand(),
				true
			);
		} else {
			// Debug: Log why 3DS script is not enqueued
			simplyin()->get_simplyin_logger()->log_if_wpdebug_on(
				sprintf( "[Abstract_Card_Payment] [enqueue_scripts] NOT enqueuing 3DS redirect script. Redirect URL: %s, Status: %s", 
					$this->redirect_url ?? 'empty', 
					$this->payment_status ?? 'empty' 
				),
				'payments'
			);
		}

		wp_localize_script( 'SimplyInThankYouPageJs',
			'simplyInStatus',
			[
				'nonce'   => wp_create_nonce( 'simplyin_card_status' ),
				'ajaxUrl' => esc_url( admin_url( 'admin-ajax.php' ) ),
				'orderId' => esc_attr( $this->order_id ),
			]
		);


	}

}
