<?php
/**
 * WC oxygen payment gateway
 *
 * @package Oxygen Payments
 * @version 2.0.38
 * @author Oxygen
 * @since 1.0.0
 *
 * This file creates oxygen payment gateway and add it in available payments of wc
 * Construct function creates all necessary fields and process payment -- throws a modal with everypay form
 */

/**
 * Check for active plugins --- if wc is enabled then oxygen payments are available
 */

$active_plugins = (array) get_option( 'active_plugins', array() );
// if woocommerce is disabled not run this code for payment.
if ( ! in_array( 'woocommerce/woocommerce.php', $active_plugins, true ) ) {
	return;
}

add_action( 'plugins_loaded', 'init_oxygen_payment_gateway', 11 );


/**
 * This function initialize payment way
 */
function init_oxygen_payment_gateway() {

	if ( class_exists( 'WC_Payment_Gateway' ) ) {

		/**
		 * This function adds the new payment in wc available gateways
		 */
		class WC_OxygenPayment_Gateway extends WC_Payment_Gateway {

			const ID = 'oxygen_payment';

			public string $instructions = '';
			public $title = '';
			public $description = '';
			/**
			 * This function constructs the oxygen payment required fields and settings
			 * Let enable payments only if there are oxygen payments in admin's account in pelatologio app
			 * Throws messages for enable/disable and write status in debug.log file
			 */
			public function __construct() {

				$this->setup_properties();

				$this->init_form_fields();
				$this->init_settings();

				$this->title        = $this->get_option( 'title', $this->method_title );
				$this->description  = $this->get_option( 'description', $this->method_description );
				$this->instructions = $this->get_option( 'instructions' );

				$this->icon = apply_filters( 'woocommerce_payment_icon', plugins_url( '../assets/images/icon_payment.png', __FILE__ ) );

				add_action( 'woocommerce_update_options_payment_gateways_' . $this->id, array( $this, 'process_admin_options' ) );
			}

			/**
			 * Setup general properties for the gateway.
			 */
			protected function setup_properties() {
				$this->id                 = self::ID;
				$this->icon               = apply_filters( 'woocommerce_payment_icon', '' );
				$this->method_title       = __( 'Oxygen Payments (Debit/Credit card)', 'oxygen' );
				$this->method_description = __( 'Enable Oxygen Payments plugin for processing online card payments.', 'oxygen' );
				$this->has_fields         = false;
			}

			/**
			 * This function init oxygen payment required fields and settings on admin panel
			 */
			public function init_form_fields() {
				$this->form_fields =
					array(
						'enabled'      => array(
							'title'   => __( 'Enable/Disable', 'woocommerce' ),
							'type'    => 'checkbox',
							'label'   => __( 'Enable or Disable Oxygen Payment Gateway', 'oxygen' ),
							'default' => 'no',
						),
						'title'        => array(
							'title'       => __( 'Title', 'woocommerce' ),
							'type'        => 'text',
							'description' => __( 'Add a new title for Oxygen Payments (Debit/Credit card)', 'oxygen' ),
							'default'     => __( 'Oxygen Payments (Debit/Credit card)', 'oxygen' ),
							'desc_tip'    => true,
						),
						'description'  => array(
							'title'       => __( 'Description', 'woocommerce' ),
							'type'        => 'textarea',
							'css'         => 'width:500px;',
							'default'     => __( 'You will be redirected to a secure payment environment. Please wait until the transaction is completed.', 'oxygen' ),
							'desc_tip'    => true,
							'description' => __( 'Add a description for the Oxygen Payment Gateway that will be displayed to customers at checkout.', 'oxygen' ),
						),
						'instructions' => array(
							'title'       => __( 'Instructions', 'woocommerce' ),
							'type'        => 'textarea',
							'css'         => 'width:500px;',
							'desc_tip'    => true,
							'description' => __( 'Instructions on how to pay via Oxygen Payments', 'oxygen' ),
						),
					);
			}

			/**
			 * This function process oxygen payment from the moment that make an order and press place order button
			 * at woo checkout page.
			 * Get order id,amount,customer data (process_customer_data)
			 * Make a request with post_to_oxygen_payment_api at pelatologio api in order to create a payment link
			 * Concat ?type=eshop variable to payment link in order to print the right everypay form in modal via pay file
			 * Set redirect url to thank you page session variable
			 * Build modal according to width window (desktop or mobile)
			 * Returns a message that include custom_payment.js file to handle on frontend payment
			 *
			 * @param int $order_id The WooCommerce order ID.
			 * @return Array|Null
			 */
			public function process_payment( $order_id ) {

				$order        = wc_get_order( $order_id );
				$amount       = $order->get_total();
				$order_number = $order->get_order_number();

				$customer_api_id = process_customer_data( $order );
				$response        = post_to_oxygen_payment_api( $order_id, $amount, $customer_api_id );

				OxygenHelperFunctions::debug( array( 'customer_api_id  ' . $customer_api_id ), 'info' );

				if ( ! is_wp_error( $response ) ) {

					$data = $response['body'];
					OxygenHelperFunctions::debug( array( 'payment data  ' . wp_json_encode( $data ) ), 'info' );

					if ( ! empty( $data ) ) {

						$array_data = json_decode( $data, true );

						if ( isset( $array_data['message'] ) ) {
							$message = $array_data['message'];
							OxygenHelperFunctions::debug( array( 'Error from pelatologio api  ' . $message ) );
							return null;
						}
						$payment_link = $array_data['url'];

						OxygenHelperFunctions::debug( array( 'payment link is ' . $payment_link ), 'info' );

						$payment_link = str_replace( '?form=eshop', '/', $payment_link );
						$payment_link = $payment_link . '?form=eshop';
						$payment_link = preg_replace( '/^http:/i', 'https:', $payment_link );

						if ( ! empty( $payment_link ) ) {

							WC()->session->set( 'payment_link', $payment_link );

							$checkout_url = $this->get_return_url( $order );

							OxygenHelperFunctions::debug( array( '---- checkout url is ' . $checkout_url ), 'info' );

							$redirect_url = add_query_arg(
								array(
									'order-pay' => $order_id,
									'key'       => $order->get_order_key(),
								),
								$checkout_url
							);

							OxygenHelperFunctions::debug( array( '---- redirect url is ' . $redirect_url ), 'info' );

							WC()->session->set( 'thankyou_link', $redirect_url );
							WC()->session->set( 'order_id', $order_id );

							$modal_payment = '<div class="my_modal" id="openOxyPayment" tabindex="-1" role="dialog" aria-labelledby="openOxyPaymentTitle" aria-hidden="true" style="display:none;z-index: 9999;">
                                                <div class="overlay_loader" style="display: none;">
                                                    <div class="overlay__inner">
                                                        <div class="overlay__content">
                                                            <span class="spinner"></span>
                                                            <div class="response_payment"></div>
                                                        </div>
                                                    </div>
                                                </div>
                                                  <div class="my_modal-dialog" role="document">
                                                    <div class="my_modal-content">
                                                      <div class="my_modal-body">
                                                        <div class="close_payment"><img src="' . OXYGEN_PLUGIN_URL . 'assets/images/icon-delete-active.svg" alt="delete"/></div>
                                                        <div class="left_side_oxy_woo">
                                                        	<div style="padding:20px 64px;">
                                                                <div class="mainlogo" style="padding-bottom: 48px;">
                                                                    <a href="https://www.pelatologio.gr" target="_blank"><img src="' . OXYGEN_PLUGIN_URL . 'assets/images/logo-oxygen-payments-negative.svg" alt="Oxygen"></a>
                                                                </div>
                                                            	<div style="font-weight:normal;font-size:14px;">' . __( 'Order\'s Number:', 'oxygen' ) . '</div>
                                                                <div style="font-weight:bold;font-size:14px;padding-bottom:40px;box-shadow: inset 0 -1px 0 0 #fcfcfc;">' . $order_number . '</div>
                                                                <div style="font-weight:800;display:flex; justify-content:space-between;padding:40px 0;"">
                                                               		<p>' . __( 'Total', 'oxygen' ) . '</p>
                                                                   <p>' . $amount . '€</p>
                                                                </div>
                                                            </div>
                                                            <div class="payment_footer parent">
                                                                <div class="payment_footer">Powered by <a href="https://www.pelatologio.gr" target="_blank">
                                                                    <img src="' . OXYGEN_PLUGIN_URL . 'assets/images/logo-horizontal-negative.webp" style="margin-left:5px;max-width:80px!important;width: 80px!important;" alt="Oxygen"/></a>
                                                                </div>
                                                                <div class="payment_footer">
                                                                    <a href="https://www.pelatologio.gr/page.php?id=71&sub1=4&sub2=70&lang=1" target="_blank"><p style="margin-right:10px;">Terms</p></a>
                                                                    <a href="https://www.pelatologio.gr/page.php?id=78&sub1=4&sub2=70&lang=1" target="_blank"><p>Privacy Policy</p></a>
                                                                </div>
                                                            </div>
                                                        </div>
                                                        <iframe id="iframe" src="' . $payment_link . '" width="100%" height="auto" style="min-height:608px;" allow="payment"></iframe>
                                                      </div>
                                                    </div>
                                                  </div>
                                                </div>
                                                <div class="full_cover_mobile" style="display:none;">
                                                    <div class="overlay_loader" style="display: none;">
                                                        <div class="overlay__inner">
                                                            <div class="overlay__content">
                                                                <span class="spinner"></span>
                                                                <div class="response_payment"></div>
                                                            </div>
                                                        </div>
                                                    </div>
                                                    <div class="mainlogo">
                                                        <a href="https://www.pelatologio.gr" target="_blank"><img src="' . OXYGEN_PLUGIN_URL . 'assets/images/logo-oxygen-payments-negative.svg" alt="Oxygen"></a>
                                                        <div class="close_payment"><img src="' . OXYGEN_PLUGIN_URL . 'assets/images/icon-delete-active-white.svg" alt="close"/></div>
                                                    </div>
                                                    <iframe id="iframe" allow="payment" src="' . $payment_link . '" width="100%" height="auto" style="min-height:800px;"></iframe>
                                                    <div class="left_side_oxy_woo">
                                                        <div class="first_left">
                                                            <div style="font-weight:normal;font-size:14px;">' . __( 'Order\'s Number:', 'oxygen' ) . '</div>
                                                            <div style="font-weight:bold;font-size:14px;padding-bottom:40px;box-shadow: inset 0 -1px 0 0 #fcfcfc;">' . $order_number . '</div>
                                                            <div style="font-weight:800;display:flex; justify-content:space-between;padding:40px 0;">
                                                               <p>' . __( 'Total', 'oxygen' ) . '</p>
                                                               <p>' . $amount . '€</p>
                                                            </div>
                                                             <div class="payment_footer mob">
                                                                <div class="payment_footer">
                                                                    Powered by <a href="https://www.pelatologio.gr" target="_blank">
                                                                    <img alt="OXYEGN" src="' . OXYGEN_PLUGIN_URL . 'assets/images/logo-horizontal-negative.webp" style="margin-left:5px;width:80px; margin-top: 3px;"/></a>
                                                                </div>
                                                                <div class="payment_footer">
                                                                    <a href="https://www.pelatologio.gr/page.php?id=71&sub1=4&sub2=70&lang=1" target="_blank"><p style="margin-right:10px;">Terms</p></a>
                                                                    <a href="https://www.pelatologio.gr/page.php?id=78&sub1=4&sub2=70&lang=1" target="_blank"><p>Privacy Policy</p></a>
                                                                </div>
                                                            </div>
                                                        </div>
                                                    </div>
                                                </div>';

							if ( is_wc_endpoint_url( 'order-pay' ) && isset( $_GET['pay_for_order'] ) && 'true' === $_GET['pay_for_order'] ) {

								echo '<script src="' . esc_url( includes_url( 'js/jquery/jquery.js' ) ) . '"></script>'; 				// phpcs:ignore
								echo '<script src="' . esc_url( OXYGEN_PLUGIN_URL . 'js/bootstrap.min.js' ) . '"></script>';// phpcs:ignore
								echo '<script src="' . esc_url( OXYGEN_PLUGIN_URL . 'js/custom_payment.js' ) . '"></script>';// phpcs:ignore
								echo wp_kses_post( $modal_payment );
								echo '<link rel="stylesheet" href="' . esc_url( OXYGEN_PLUGIN_URL . 'assets/css/my_styles.css' ) . '">';// phpcs:ignore

								$pay_for_order_url = $order->get_checkout_payment_url( true );

								$redirect_url = add_query_arg(
									array(
										'pay_for_order' => 'true',
										'key'           => $order->get_order_key(),
										'show_modal'    => 'true',
									),
									$pay_for_order_url
								);

								return array(
									'result'   => 'success',
									'redirect' => $redirect_url,
									'messages' => '<script src=' . OXYGEN_PLUGIN_URL . 'js/bootstrap.min.js></script><script src=' . OXYGEN_PLUGIN_URL . 'js/custom_payment.js></script>' . $modal_payment,// phpcs:ignore

								);

							}

							return array(
								'result'   => 'success',
								'messages' => '<script src=' . OXYGEN_PLUGIN_URL . 'js/bootstrap.min.js></script><script src=' . OXYGEN_PLUGIN_URL . 'js/custom_payment.js></script>' . $modal_payment, // phpcs:ignore
							);

						} else {
							wc_add_notice( 'Not valid payment link', 'error' );
						}
					} else {
						wc_add_notice( 'Please try again.', 'error' );
						return null;
					}
				} else {
					wc_add_notice( 'Connection error.', 'error' );
					return null;
				}

				return array(
					'fail' => 'failure!',
				);
			}
		}
	}
}

add_filter( 'woocommerce_payment_gateways', 'add_to_woo_oxygen_payment_gateway' );

/**
 * This function adds oxygen payment to wc payments ways
 *
 * @param Array $gateways array of selected gateways.
 * @return Array
 */
function add_to_woo_oxygen_payment_gateway( $gateways ) {

	$gateways[] = 'WC_OxygenPayment_Gateway';
	return $gateways;
}

/**
 * This function return_api_url_by_status
 */
function return_api_url_by_status() {

	$oxygen_status = OxygenHelperFunctions::get_option( 'oxygen_status' );

	if ( 'live' === $oxygen_status ) {
		$api_url = 'https://api.oxygen.gr/v1';
	} else {
		$api_url = 'https://sandbox-api.oxygen.gr/v1';
	}

	return $api_url;
}

/**
 * This function post_to_oxygen_payment_api
 *
 * @param Number $order_id order id.
 * @param Number $amount amount of order.
 * @param String $customer_api_id customer id connected with pelatologio app.
 * @return array|WP_Error
 */
function post_to_oxygen_payment_api( $order_id, $amount, string $customer_api_id ) {

	$api_key = OxygenHelperFunctions::get_option( 'oxygen_api_key' );
	$api_url = return_api_url_by_status();

	$endpoint     = $api_url . '/oxygen-payments';
	$expired_date = gmdate( 'Y-m-d', strtotime( 'tomorrow' ) );
	$order        = wc_get_order( $order_id );
	$email        = $order->get_billing_email();
	$store_name   = get_bloginfo( 'name' );

	$body = array(
		'form'        => 'eshop',
		'description' => 'Νέα πληρωμή No ' . $order_id, /* add order id to request */
		'comments'    => 'Παραγγελία από eshop ' . $store_name . ' - ' . $email . ' No ' . $order_id,
		'amount'      => $amount,
		'expire_date' => $expired_date,
		'contact_id'  => $customer_api_id,
		'logo_id'     => ( ! empty( OxygenHelperFunctions::get_option( 'oxygen_logo' ) ) ? OxygenHelperFunctions::get_option( 'oxygen_logo' ) : OxygenHelperFunctions::get_default_logo_id() ),
		'language'    => 'el',
	);

	$api_headers = array(
		'Authorization' => 'Bearer ' . $api_key,
		'Accept'        => 'application/json',
	);

	$options = array(
		'headers' => $api_headers,
		'body'    => $body,
	);

	$response = wp_remote_post( $endpoint, $options );

	return $response;
}

/**
 * This function process_customer_data
 *
 * @param WC_Order $order this is selected order.
 * @return String
 */
function process_customer_data( $order ): string {
	$oxygen_customer_id = '';
	$is_invoice         = get_post_meta( $order->get_id(), '_billing_invoice', true );

	OxygenHelperFunctions::debug( array( 'process_customer_data ', $is_invoice ), 'info' );

	if ( '1' === $is_invoice || 1 === $is_invoice ) {

		OxygenHelperFunctions::debug( array( '------- you asked to create an invoice via oxygen payments -------- ' ), 'info' );
		$get_billing_vat_info = OxygenHelperFunctions::get_billing_vat_info( $order->get_id() );
		OxygenHelperFunctions::debug( array( 'get billing vat info --' . wp_json_encode( $get_billing_vat_info ) ), 'info' );

		$checkout_email = $order->get_billing_email();
		$checkout_vat   = $get_billing_vat_info['billing_vat'];

		if ( ! empty( $checkout_vat ) && ! empty( $checkout_email ) ) {

			$contact_by_vat = OxygenApi::get_contact_by_vat( $checkout_vat );

			if ( empty( $contact_by_vat['data'] ) ) {

				$new_contact = OxygenHelperFunctions::create_new_contact( $order, $get_billing_vat_info );
				if ( $new_contact ) {
					$oxygen_customer_id = $new_contact['id'];
					OxygenHelperFunctions::debug( array( 'new customer id is ONE' ), 'info' );
				}
				return $oxygen_customer_id;

			} elseif ( count( $contact_by_vat['data'] ) > 1 ) {
				// Multiple contacts for the same VAT.
				OxygenHelperFunctions::debug( array( 'Multiple contacts found for VAT ' ), 'info' );

				foreach ( $contact_by_vat['data'] as $item ) {
					// Check if contact type is a company.
					if ( isset( $item['type'] ) && 2 === $item['type'] ) {
						if ( ! empty( $checkout_email ) && $checkout_email !== $item['email'] && $checkout_vat !== $item['vat_number'] ) {
							// Checkout email differs from contact's email and VAT number.

							$new_contact = OxygenHelperFunctions::create_new_contact( $order, $get_billing_vat_info );
							if ( $new_contact ) {
								$oxygen_customer_id = $new_contact['id'];
								OxygenHelperFunctions::debug( array( "Checkout email '{$checkout_email}' differs from contact's email or VAT. Created new contact with ID: {$oxygen_customer_id}" ), 'info' );
							}
							return $oxygen_customer_id;
						} else { // Contact VAT data are filled AND checkout email matches.

							$oxygen_customer_id = $item['id'];
							OxygenHelperFunctions::debug( array( "Existing contact found with matching VAT and email. Using contact ID: {$oxygen_customer_id}" ), 'info' );

							return $oxygen_customer_id;
						}
					} else { // Contact type is not 'C' .

						$new_contact = OxygenHelperFunctions::create_new_contact( $order, $get_billing_vat_info );
						if ( $new_contact ) {
							$oxygen_customer_id = $new_contact['id'];
							OxygenHelperFunctions::debug( array( "Contact type is not 'C'. Created new contact with ID: {$oxygen_customer_id}" ), 'info' );
						}
						return $oxygen_customer_id;
					}
				}
			} else { // Only one contact.

				$existing_contact = $contact_by_vat['data'][0];
				if ( ! empty( $checkout_email ) && $checkout_email !== $existing_contact['email'] && $checkout_vat !== $existing_contact['vat_number'] ) {
					// Checkout email differs from contact's email and VAT number.

					$new_contact = OxygenHelperFunctions::create_new_contact( $order, $get_billing_vat_info );
					if ( $new_contact ) {
						$oxygen_customer_id = $new_contact['id'];
						OxygenHelperFunctions::debug( array( "Checkout email '{$checkout_email}' differs from contact's email or VAT. Created new contact with ID: {$oxygen_customer_id}" ), 'info' );
					}
					return $oxygen_customer_id;
				} else { // Contact VAT data are filled AND checkout email matches.

					$oxygen_customer_id = $existing_contact['id'];
					OxygenHelperFunctions::debug( array( "Existing contact found with matching VAT and email. Using contact ID: {$oxygen_customer_id}" ), 'info' );

					return $oxygen_customer_id;
				}
			}
		}
	} elseif ( '' === $is_invoice || '0' === $is_invoice || 0 === $is_invoice ) {

			OxygenHelperFunctions::debug( array( 'Processing ALP/APY invoice with doc_key ' ) );

			$get_billing_vat_info = OxygenHelperFunctions::get_billing_vat_info( $order->get_id() );
			OxygenHelperFunctions::debug( array( 'Retrieved billing VAT info: ' . wp_json_encode( $get_billing_vat_info ) ), 'info' );

			$checkout_email = $order->get_billing_email();

		if ( ! empty( $checkout_email ) ) {

			$is_identical = OxygenHelperFunctions::check_identical_contact( $order->get_id() );

			if ( empty( $is_identical ) ) {

				$get_billing_vat_info = OxygenHelperFunctions::get_billing_vat_info( $order->get_id() );
				$new_contact          = OxygenHelperFunctions::create_new_contact( $order, $get_billing_vat_info );
				if ( $new_contact ) {
					$oxygen_customer_id = $new_contact['id'];
					OxygenHelperFunctions::debug( array( "Is not identical - Created new contact with ID: {$oxygen_customer_id}" ), 'info' );
				}
				return $oxygen_customer_id;
			} else {
				OxygenHelperFunctions::debug( array( "Is identical - return contact with ID: {$is_identical}" ), 'info' );
				// epistrefei to contact_id tis epafhs poy einai tautosimh.
				return $is_identical;
			}
		} else { /* Empty checkout email */

				OxygenHelperFunctions::debug( array( 'Checkout email is empty. Creating new contact.' ), 'info' );

				$new_contact = OxygenHelperFunctions::create_new_contact( $order, $get_billing_vat_info );
			if ( $new_contact ) {
				$oxygen_customer_id = $new_contact['id'];
				OxygenHelperFunctions::debug( array( "Created new contact with ID: {$oxygen_customer_id}" ), 'info' );
			}
				return $oxygen_customer_id;
		}
	}
	return $oxygen_customer_id;
}


/**
 * Add order-pay variable in redirection url after payment
 *
 * @param Array $vars this is array of vars.
 * @return Array
 */
function my_add_query_vars( $vars ) {
	$vars[] = 'order-pay';
	return $vars;
}

add_filter( 'query_vars', 'my_add_query_vars' );

/**
 * Payment oxygen load scripts css
 */
function payment_oxygen_load_scripts() {
	wp_enqueue_style( 'my_style_css', OXYGEN_PLUGIN_URL . 'assets/css/my_styles.css', array(), null );
}

add_action( 'wp_enqueue_scripts', 'payment_oxygen_load_scripts' );

/**
 * Enqueues the custom payment script on the WooCommerc``e 'order-pay' endpoint when the modal should be shown.
 *
 * This ensures that the `custom_payment.js` script is only loaded on the checkout payment confirmation page
 * when the `show_modal=true` parameter is present in the URL.
 *
 * @return void
 */
function enqueue_custom_payment_script() {

	if ( is_wc_endpoint_url( 'order-pay' ) && isset( $_GET['show_modal'] ) && 'true' === $_GET['show_modal'] ) {
		wp_enqueue_script( 'custom_payment_js', OXYGEN_PLUGIN_URL . 'js/custom_payment.js', array( 'jquery' ), null, true );
	}
}
add_action( 'wp_enqueue_scripts', 'enqueue_custom_payment_script' );


/**
 * Displays the Oxygen Payments modal in the footer on the 'order-pay' endpoint.
 *
 * This function checks if the `show_modal=true` query parameter is set,
 * and if so, renders the payment modal with the iframe containing the Oxygen payment form.
 * It retrieves the order information and payment link from the WooCommerce session.
 *
 * @hook wp_footer
 *
 * @return void
 */
function display_custom_div_on_pay_for_order() {

	// Check if `show_modal=true` is in the URL.
	if ( isset( $_GET['show_modal'] ) && 'true' === $_GET['show_modal'] ) {

		$order_id = get_query_var( 'order-pay' );
		OxygenHelperFunctions::debug( array( 'oxygen payment via pay_for_order customer page , order id is ' . $order_id ), 'info' );

		$order        = wc_get_order( $order_id );
		$amount       = $order->get_total();
		$order_number = $order->get_order_number();
		$payment_link = WC()->session->get( 'payment_link' );

		echo '<div class="my_modal" id="openOxyPayment" tabindex="-1" role="dialog" aria-labelledby="openOxyPaymentTitle" aria-hidden="true" style="display:none;z-index: 9999;">
            <div class="overlay_loader" style="display: none;">
                <div class="overlay__inner">
                    <div class="overlay__content">
                        <span class="spinner"></span>
                        <div class="response_payment"></div>
                    </div>
                </div>
            </div>
              <div class="my_modal-dialog" role="document">
                <div class="my_modal-content">
                  <div class="my_modal-body">
                    <div class="close_payment">
                    	<img src="' . esc_url( OXYGEN_PLUGIN_URL . 'assets/images/icon-delete-active.svg' ) . '" alt="' . esc_attr( 'delete' ) . '" />
                    </div>
                    <div class="left_side_oxy_woo">
                        <div style="padding:20px 64px;">
                            <div class="mainlogo" style="padding-bottom: 48px;">
								<a href="' . esc_url( 'https://www.pelatologio.gr' ) . '" target="_blank">
                                    <img src="' . esc_url( OXYGEN_PLUGIN_URL . 'assets/images/logo-oxygen-payments-negative.svg' ) . '" alt="' . esc_attr( 'Oxygen' ) . '">
      							</a>                            
                            </div>
                            <div style="font-weight:normal;font-size:14px;">' . esc_html__( 'Order\'s Number:', 'oxygen' ) . '</div>
                            <div style="font-weight:bold;font-size:14px;padding-bottom:40px;box-shadow: inset 0 -1px 0 0 #fcfcfc;">' . esc_html( $order_number ) . '</div>
                            <div style="font-weight:800;display:flex; justify-content:space-between;padding:40px 0;"">
                                <p>' . esc_html__( 'Total', 'oxygen' ) . '</p>
                               <p>' . esc_html( $amount ) . '€</p>
                            </div>
                        </div>
                        <div class="payment_footer parent">
                            <div class="payment_footer">Powered by <a href="' . esc_url( 'https://www.pelatologio.gr' ) . '" target="_blank">
						        <img src="' . esc_url( OXYGEN_PLUGIN_URL . 'assets/images/logo-horizontal-negative.webp' ) . '" style="margin-left:5px;max-width:80px!important;width: 80px!important;" alt="' . esc_attr( 'Oxygen' ) . '" />
						      </a>
                            </div>
                            <div class="payment_footer">
        						<a href="' . esc_url( 'https://www.pelatologio.gr/page.php?id=71&sub1=4&sub2=70&lang=1' ) . '" target="_blank">' . esc_html__( 'Terms', 'oxygen' ) . '</a>
       							<a href="' . esc_url( 'https://www.pelatologio.gr/page.php?id=78&sub1=4&sub2=70&lang=1' ) . '" target="_blank">' . esc_html__( 'Privacy Policy', 'oxygen' ) . '</a>
                            </div>
                        </div>
                    </div>
                    <iframe id="iframe" src="' . esc_html( $payment_link ) . '" width="100%" height="auto" style="min-height:608px;" allow="payment"></iframe>
                  </div>
                </div>
              </div>
            </div>
            <div class="full_cover_mobile" style="display:none;">
                <div class="overlay_loader" style="display: none;">
                    <div class="overlay__inner">
                        <div class="overlay__content">
                            <span class="spinner"></span>
                            <div class="response_payment"></div>
                        </div>
                    </div>
                </div>
                <div class="mainlogo">
					<a href="' . esc_url( 'https://www.pelatologio.gr' ) . '" target="_blank">
				        <img src="' . esc_url( OXYGEN_PLUGIN_URL . 'assets/images/logo-oxygen-payments-negative.svg' ) . '" alt="' . esc_html( 'Oxygen' ) . '">
			      	</a>                    
			      	<div class="close_payment">
			      		<img src="' . esc_url( OXYGEN_PLUGIN_URL . 'assets/images/icon-delete-active-white.svg' ) . '" alt="' . esc_html( 'Oxygen' ) . '" />
					</div>
                </div>
                <iframe id="iframe" allow="payment" src="' . esc_html( $payment_link ) . '" width="100%" height="auto" style="min-height:800px;"></iframe>
                <div class="left_side_oxy_woo">
                    <div class="first_left">
                        <div style="font-weight:normal;font-size:14px;">' . esc_html__( 'Order\'s Number:', 'oxygen' ) . '</div>
                        <div style="font-weight:bold;font-size:14px;padding-bottom:40px;box-shadow: inset 0 -1px 0 0 #fcfcfc;">' . esc_html( $order_number ) . '</div>
                        <div style="font-weight:800;display:flex; justify-content:space-between;padding:40px 0;">
                           <p>' . esc_html__( 'Total', 'oxygen' ) . '</p>
                           <p>' . esc_html( $amount ) . '€</p>
                        </div>
                         <div class="payment_footer mob">
                            <div class="payment_footer">
                                Powered by <a href="' . esc_url( 'https://www.pelatologio.gr' ) . '" target="_blank">
						        <img alt="' . esc_attr( 'OXYEGN' ) . '" src="' . esc_url( OXYGEN_PLUGIN_URL . 'assets/images/logo-horizontal-negative.webp' ) . '" style="margin-left:5px;width:80px; margin-top: 3px;" />
						      </a>
                            </div>
                            <div class="payment_footer">
                                <a href="' . esc_url( 'https://www.pelatologio.gr/page.php?id=71&sub1=4&sub2=70&lang=1' ) . '" target="_blank">' . esc_html__( 'Terms', 'oxygen' ) . '</a>
       							<a href="' . esc_url( 'https://www.pelatologio.gr/page.php?id=78&sub1=4&sub2=70&lang=1' ) . '" target="_blank">' . esc_html__( 'Privacy Policy', 'oxygen' ) . '</a>
                            </div>
                        </div>
                    </div>
                </div>
            </div>';
	}
}
add_action( 'wp_footer', 'display_custom_div_on_pay_for_order' );


add_action( 'admin_enqueue_scripts', 'oxygen_add_payment_logos_admin_script' );

function oxygen_add_payment_logos_admin_script() {
	if (
		is_admin() &&
		isset($_GET['page'], $_GET['tab']) &&
		$_GET['page'] === 'wc-settings' &&
		$_GET['tab'] === 'checkout'
	) {
		wp_add_inline_script( 'jquery-core', oxygen_get_inline_logo_script() );
	}
}

add_action( 'update_option_woocommerce_oxygen_payment_settings', 'custom_action_on_gateway_save', 10, 1 );
/**
 * Validates Oxygen Payments gateway settings on save and triggers activation checks.
 *
 * Hooked to the `update_option_woocommerce_oxygen_payment_settings` action, this function is executed
 * when the Oxygen Payments gateway settings are saved in the WooCommerce admin panel.
 * It checks if the gateway is enabled and if an API key exists. If so, it pings the Oxygen Payments API
 * to confirm availability and activation status.
 *
 * Displays admin notices based on the response and disables the gateway if activation fails.
 *
 * @hook update_option_woocommerce_oxygen_payment_settings
 *
 * @return void
 */
function custom_action_on_gateway_save() {

	$api_key = OxygenHelperFunctions::get_option( 'oxygen_api_key' );

	if ( ! empty( $api_key ) ) {

		$oxygen_payments_settings = get_option( 'woocommerce_oxygen_payment_settings' );

		if ( 'yes' === $oxygen_payments_settings['enabled'] ) {

			$api_url  = return_api_url_by_status();
			$endpoint = $api_url . '/oxygen-payments';

			$api_headers = array(
				'Authorization' => 'Bearer ' . $api_key,
				'Accept'        => 'application/json',
			);

			$options = array(
				'headers' => $api_headers,
			);

			$response = wp_remote_get( $endpoint, $options );

			if ( is_wp_error( $response ) ) {
				$error_message = $response->get_error_message();
				OxygenHelperFunctions::debug( array( 'Something get wrong with api request to pelatologio ' . $error_message ), 'info' );

			} else {
				$data = $response['response'];

				if ( ! empty( $data ) ) {
					$status = $data['code'];
					OxygenHelperFunctions::debug( array( 'response code for oxygen payments is status  ' . $status ) );

					if ( 200 !== $status ) {
						OxygenHelperFunctions::debug( array( 'Cannot enable oxygen payments. You have to sign up on service here.' ) );

						WC_Admin_Notices::add_custom_notice(
							'oxygen_payments_saved',
							sprintf(
								'<p>%s <a href="https://app.pelatologio.gr/settings_marketplace.php?m=500" target="_blank">%s</a></p>',
								esc_html__(
									'Oxygen Payments are not activated. Sign up here to enable them.',
									'oxygen'
								),
								esc_html__( 'Oxygen Payments', 'oxygen' )
							)
						);

						$settings['enabled'] = 'no';
						update_option( 'woocommerce_oxygen_payment_settings', $settings );

					} else {
						OxygenHelperFunctions::debug( array( 'Gateway status updated successfully. Oxygen Payments Gateway has been enabled.' ), 'info' );
						WC_Admin_Notices::add_custom_notice( 'oxygen_payments_saved', esc_html__( 'Oxygen Payments enabled successfully.', 'oxygen' ) );
					}
				}
			}
		} else {
			OxygenHelperFunctions::debug( array( 'The gateway has been disabled successfully.' ), 'info' );
		}
	}
}

function oxygen_get_inline_logo_script() {
	$visa   = OXYGEN_PLUGIN_URL . 'assets/banks/visa.svg';
	$master = OXYGEN_PLUGIN_URL . 'assets/banks/master.svg';
	$apple  = OXYGEN_PLUGIN_URL . 'assets/banks/apple_pay.svg';

	return <<<JS
jQuery(document).ready(function($) {
	// Look for the payment gateway row by ID (plugin ID = oxygen_payment)
	setTimeout(function() {
		if ($('#oxygen_payment').length) {

			const logos = '<div class="woocommerce-woopayments-payment-methods-logos" style="margin-top:6px;">' +
				'<img src="{$visa}" alt="Visa" style="width:38px;height:24px;margin-right:8px;border: 1px solid #f2f2f2;border-radius: 4px;" />' +
				'<img src="{$master}" alt="Mastercard" style="width:38px;height:24px;margin-right:8px;border: 1px solid #f2f2f2;border-radius: 4px;" />' +
				'<img src="{$apple}" alt="Apple Pay" style="width:38px;height:24px;border: 1px solid #f2f2f2;border-radius: 4px;" />' +
				'</div>';
	
			$('#oxygen_payment div.woocommerce-list__item-inner div.woocommerce-list__item-text').append(logos);
        }
    }, 300);
});
JS;
}