<?php

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

use PayPalCheckoutSdk\Orders\OrdersCaptureRequest;
use Mollie\Api\MollieApiClient;

/**
 * Helper function to initialize common database variables
 */
function wpgv_init_voucher_data($voucheritem)
{
	global $wpdb;

	$voucher_table = $wpdb->prefix . 'giftvouchers_list';
	$setting_table = $wpdb->prefix . 'giftvouchers_setting';
	$setting_options = $wpdb->get_row("SELECT * FROM $setting_table WHERE id = 1");

	$voucher_item = sanitize_text_field($voucheritem);
	$voucher_options = $wpdb->get_row("SELECT * FROM $voucher_table WHERE id = $voucher_item");

	return array(
		'voucher_table' => $voucher_table,
		'setting_table' => $setting_table,
		'setting_options' => $setting_options,
		'voucher_item' => $voucher_item,
		'voucher_options' => $voucher_options,
		'send_instantly' => is_object($voucher_options) ? $voucher_options->email_send_date_time : null,
		'check_send_mail' => is_object($voucher_options) ? $voucher_options->check_send_mail : null
	);
}

/**
 * Helper function to get email settings
 */
function wpgv_get_email_settings()
{
	return array(
		'emailsubject' => get_option('wpgv_emailsubject') ?: 'Order Confirmation - Your Order with {company_name} (Voucher Order No: {order_number} ) has been successfully placed!',
		'recipientemailsubject' => get_option('wpgv_recipientemailsubject') ?: 'Gift Voucher - Your have received voucher from {company_name}',
		'recipientemailbody' => get_option('wpgv_recipientemailbody') ?: '<p>Dear <strong>{recipient_name}</strong>,</p><p>You have received gift voucher from <strong>{customer_name}</strong>.</p><p>You can download the voucher from {pdf_link}.</p><p>- For any clarifications please feel free to email us at {sender_email}.</p><p><strong>Warm Regards, <br /></strong> <strong>{company_name}<br />{website_url}</strong></p>',
		'emailbodyperinvoice' => get_option('wpgv_emailbodyperinvoice') ?: '<p>Dear <strong>{customer_name}</strong>,</p><p>Order successfully placed.</p><p>We are pleased to confirm your order no {order_number}</p><p>Thank you for shopping with <strong>{company_name}</strong>!</p><p>You can download the voucher from {pdf_link}.</p><p>You will pay us directly into bank. Our bank details are below:</p><p><strong>Account Number: </strong>XXXXXXXXXXXX<br /><strong>Bank Code: </strong>XXXXXXXX</p><p>- For any clarifications please feel free to email us at {sender_email}.</p><p><strong>Warm Regards, <br /></strong> <strong>{company_name}<br />{website_url}</strong></p>',
		'emailbody' => get_option('wpgv_emailbody') ?: '<p>Dear <strong>{customer_name}</strong>,</p><p>Order successfully placed.</p><p>We are pleased to confirm your order no {order_number}</p><p>Thank you for shopping with <strong>{company_name}</strong>!</p><p>You can download the voucher from {pdf_link}.</p><p>- For any clarifications please feel free to email us at {sender_email}.</p><p><strong>Warm Regards, <br /></strong> <strong>{company_name}<br />{website_url}</strong></p>',
		'adminemailsubject' => get_option('wpgv_adminemailsubject') ?: 'New Voucher Order Received from {customer_name}  (Order No: {order_number})!',
		'adminemailbody' => get_option('wpgv_adminemailbody') ?: '<p>Hello, New Voucher Order received.</p><p><strong>Order Id:</strong> {order_number}</p><p><strong>Name:</strong> {customer_name}<br /><strong>Email:</strong> {customer_email}<br /><strong>Address:</strong> {customer_address}<br /><strong>Postcode:</strong> {customer_postcode}</p>',
		'successpagemessage' => get_option('wpgv_successpagemessage') ?: 'We have got your order! <br>E-Mail Sent Successfully to %s'
	);
}

/**
 * Helper function to setup email headers
 */
function wpgv_setup_email_headers($setting_options, $from_email = null)
{
	$headers = 'Content-type: text/html;charset=utf-8' . "\r\n";
	$headers .= 'From: ' . stripslashes($setting_options->sender_name) . ' <' . $setting_options->sender_email . '>' . "\r\n";
	$reply_to = !empty($from_email) ? $from_email : $setting_options->sender_email;
	$headers .= 'Reply-to: ' . stripslashes($setting_options->sender_name) . ' <' . $reply_to . '>' . "\r\n";
	return $headers;
}

/**
 * Helper function to handle timezone for scheduled emails
 */
function wpgv_get_scheduled_email_time($email_send_date_time)
{
	$save_zone = date_default_timezone_get();

	if (get_option('timezone_string') != "") {
		date_default_timezone_set(get_option('timezone_string'));
		$scheduled_time = strtotime($email_send_date_time);
	} else {
		date_default_timezone_set($save_zone);
		$scheduled_time = strtotime($email_send_date_time);
	}

	date_default_timezone_set($save_zone);
	return $scheduled_time;
}

/**
 * Helper function to get upload directory and attachment paths
 */
function wpgv_get_attachment_paths($voucher_options, $include_invoice = false)
{
	$upload = wp_upload_dir();
	$upload_dir = $upload['basedir'];

	$attachments = array();

	// Add main PDF attachment if it exists
	$main_pdf = $upload_dir . '/voucherpdfuploads/' . $voucher_options->voucherpdf_link . '.pdf';
	if (file_exists($main_pdf)) {
		$attachments[] = $main_pdf;
	}

	// Add receipt PDF attachment if it exists
	$receipt_pdf = $upload_dir . '/voucherpdfuploads/' . $voucher_options->voucherpdf_link . '-receipt.pdf';
	if (file_exists($receipt_pdf)) {
		$attachments[] = $receipt_pdf;
	}

	// Add invoice PDF attachment if requested and exists
	if ($include_invoice) {
		$invoice_pdf = $upload_dir . '/voucherpdfuploads/' . $voucher_options->voucherpdf_link . '-invoice.pdf';
		if (file_exists($invoice_pdf)) {
			$attachments[] = $invoice_pdf;
		}
	}

	return array(
		'upload_dir' => $upload_dir,
		'attachments' => $attachments
	);
}

/**
 * Helper function to update payment status and generate PDF
 */
function wpgv_update_payment_and_pdf($wpdb, $voucher_table, $voucher_item, &$voucher_options)
{
	$voucher_table_prefix = $wpdb->prefix . 'giftvouchers_list';

	$wpdb->update(
		$voucher_table_prefix,
		array(
			'payment_status' => __('Paid'),
			'voucheradd_time' => current_time('mysql')
		),
		array('id' => $voucher_item),
		array('%s', '%s'),
		array('%d')
	);

	if (is_object($voucher_options)) {
		$voucher_options->payment_status = __('Paid');
		$voucher_options->voucheradd_time = current_time('mysql');
	}

	if (function_exists('wpgv_generate_receipt_pdf_for_voucher')) {
		wpgv_generate_receipt_pdf_for_voucher($voucher_item);
	}
}

/**
 * Process a successful voucher order (idempotent).
 * Updates payment status, generates PDFs, records activity and sends emails.
 * Returns true on success, false on failure or if already processed.
 */
if (!function_exists('wpgv_process_successful_order')) {
	function wpgv_process_successful_order($voucher_item)
	{
		global $wpdb;

		// Idempotency: avoid double-processing
		$already = get_post_meta($voucher_item, 'wpgv_payment_processed', true);
		if ($already) {
			return true;
		}

		$data = wpgv_init_voucher_data($voucher_item);
		extract($data);

		// Update payment status and generate PDFs
		wpgv_update_payment_and_pdf($wpdb, $voucher_table, $voucher_item, $voucher_options);

		// Record activity (first transaction)
		$voucherrow = $wpdb->get_row($wpdb->prepare("SELECT * FROM `{$wpdb->prefix}giftvouchers_list` WHERE `id` = %d", $voucher_item));
		if ($voucherrow) {
			WPGV_Gift_Voucher_Activity::record($voucher_item, 'firsttransact', $voucherrow->amount, 'Voucher payment received.');
		}

		// Email workflow
		$invoice_setting_table = $wpdb->prefix . 'giftvouchers_invoice_settings';
		$invoice_options = $wpdb->get_row("SELECT * FROM $invoice_setting_table WHERE id = 1");
		$is_invoice_active = (is_object($invoice_options) && isset($invoice_options->is_invoice_active)) ? $invoice_options->is_invoice_active : 0;

		$attachment_data = wpgv_get_attachment_paths($voucher_options, $is_invoice_active);
		$attachments = $attachment_data['attachments'];
		$headers = wpgv_setup_email_headers($setting_options ?? get_option('wpgv_setting_options'));

		$email_settings = wpgv_get_email_settings();

		// Send recipient email
		$recipient_data = array(
			'recipientemailsubject' => $email_settings['recipientemailsubject'],
			'recipientemailbody' => $email_settings['recipientemailbody'],
			'shipping_type' => $voucher_options->shipping_type,
			'shipping_email' => $voucher_options->shipping_email,
			'buying_for' => $voucher_options->buying_for,
			'setting_options' => $setting_options,
			'voucher_options' => $voucher_options,
			'check_send_mail' => $check_send_mail ?? $voucher_options->check_send_mail,
			'send_instantly' => $send_instantly ?? $voucher_options->email_send_date_time,
			'email_send_date_time' => $voucher_options->email_send_date_time,
			'headers' => $headers,
			'attachments' => $attachments
		);
		wpgv_send_recipient_email($recipient_data);

		// Send buyer email
		$buyer_data = array(
			'emailsubject' => $email_settings['emailsubject'],
			'emailbody' => $email_settings['emailbody'],
			'setting_options' => $setting_options,
			'voucher_options' => $voucher_options,
			'check_send_mail' => $check_send_mail ?? $voucher_options->check_send_mail,
			'headers' => $headers,
			'attachments' => $attachments
		);
		$mail_sent = wpgv_send_buyer_email($buyer_data);

		// Send admin email
		$admin_email_data = array(
			'setting_options' => $setting_options,
			'voucher_options' => $voucher_options,
			'voucher_item' => $voucher_item,
			'check_send_mail' => $check_send_mail ?? $voucher_options->check_send_mail,
			'send_instantly' => $send_instantly ?? $voucher_options->email_send_date_time,
			'email_settings' => $email_settings,
			'attachments' => $attachments
		);
		wpgv_send_admin_email($admin_email_data);

		// Mark processed to avoid duplicates
		update_post_meta($voucher_item, 'wpgv_payment_processed', 1);

		return true;
	}
}

/**
 * Helper function to send recipient email
 */
function wpgv_send_recipient_email($recipients_email_data)
{
	extract($recipients_email_data);

	if ($shipping_type != 'shipping_as_post') {
		$recipientsub = wpgv_mailvarstr($recipientemailsubject, $setting_options, $voucher_options);
		$recipientmsg = wpgv_mailvarstr($recipientemailbody, $setting_options, $voucher_options);
		$recipientto = stripslashes($voucher_options->to_name) . '<' . $shipping_email . '>';
		if ($buying_for == 'yourself') {
			$recipientto = stripslashes($voucher_options->from_name) . '<' . $voucher_options->email . '>';
		}

		// Verify attachments exist before sending
		// Recipients (the voucher receiver) should NOT receive the receipt or invoice PDFs.
		$valid_attachments = array();
		if (!empty($attachments) && is_array($attachments)) {
			foreach ($attachments as $attachment) {
				if (empty($attachment) || !file_exists($attachment)) {
					continue;
				}

				// Only include the main voucher PDF for recipients. Exclude receipt and invoice files.
				$basename = basename($attachment);
				if (stripos($basename, '-receipt.pdf') !== false || stripos($basename, '-invoice.pdf') !== false) {
					continue;
				}

				$valid_attachments[] = $attachment;
			}
		}

		if ($check_send_mail == "unsent" && $send_instantly == "send_instantly") {
			wp_mail($recipientto, $recipientsub, $recipientmsg, $headers, $valid_attachments);
		} else {
			$scheduled_time = wpgv_get_scheduled_email_time($email_send_date_time);
			$send_gift_voucher_email_event_args = array($recipientto, $recipientsub, $recipientmsg, $headers, $valid_attachments);
			wp_schedule_single_event($scheduled_time, 'send_gift_voucher_email_event', $send_gift_voucher_email_event_args);
		}
	}
}

/**
 * Helper function to send buyer email
 */
function wpgv_send_buyer_email($buyer_email_data)
{
	global $wpdb;
	extract($buyer_email_data);

	$voucher_table_prefix = $wpdb->prefix . 'giftvouchers_list';

	$buyersub = wpgv_mailvarstr($emailsubject, $setting_options, $voucher_options);
	$buyermsg = wpgv_mailvarstr($emailbody, $setting_options, $voucher_options);
	$buyerto = $voucher_options->email;

	if ($check_send_mail == "unsent") {
		// Verify attachments exist before sending
		$valid_attachments = array();
		if (!empty($attachments) && is_array($attachments)) {
			foreach ($attachments as $attachment) {
				if (!empty($attachment) && file_exists($attachment)) {
					$valid_attachments[] = $attachment;
				}
			}
		}

		$mail_sent = wp_mail($buyerto, $buyersub, $buyermsg, $headers, $valid_attachments);

		// Log mail sending for debugging
		if (!$mail_sent) {
			error_log('WPGV: Email sending failed for: ' . $buyerto . ' | Subject: ' . $buyersub . ' | Attachments: ' . json_encode($valid_attachments));
		}
	} else {
		$mail_sent = false;
	}

	return $mail_sent;
}

/**
 * Helper function to send admin email
 */
function wpgv_send_admin_email($admin_email_data)
{
	global $wpdb;
	extract($admin_email_data);

	$voucher_table_prefix = $wpdb->prefix . 'giftvouchers_list';

	$toadmin = stripslashes($setting_options->sender_name) . ' <' . $setting_options->sender_email . '>';
	$subadmin = wpgv_mailvarstr($email_settings['adminemailsubject'], $setting_options, $voucher_options);
	$bodyadmin = wpgv_mailvarstr($email_settings['adminemailbody'], $setting_options, $voucher_options);
	$headersadmin = wpgv_setup_email_headers($setting_options, $voucher_options->email);

	if ($check_send_mail == "unsent") {
		// Verify attachments exist before sending
		$valid_attachments = array();
		if (!empty($attachments) && is_array($attachments)) {
			foreach ($attachments as $attachment) {
				if (!empty($attachment) && file_exists($attachment)) {
					$valid_attachments[] = $attachment;
				}
			}
		}

		wp_mail($toadmin, $subadmin, $bodyadmin, $headersadmin, $valid_attachments);

		if ($send_instantly == "send_instantly") {
			$new_send_date_time = "sent";
		} else {
			$new_send_date_time = "schedule";
		}

		$wpdb->update(
			$voucher_table_prefix,
			array('check_send_mail' => $new_send_date_time),
			array('id' => $voucher_item),
			array('%s'),
			array('%d')
		);
	}
}

// Function for mollie Payment Successful Shortcode
function mollie_successful_shortcode()
{
	global $wpdb;
	$return = '';

	if (!isset($_GET['voucheritem'])) {
		return '<div class="error"><p>' . __('This URL is invalid. You can not access this page directly.', 'gift-voucher') . '</p></div>';
	}

	$data = wpgv_init_voucher_data($_GET['voucheritem']);
	extract($data);

	$mollie_api_key = $setting_options->mollie_api_key;
	$mollie = new MollieApiClient();
	$mollie->setApiKey($mollie_api_key);

	session_start();
	$paymentId = $_SESSION['payment_id'] ?? null;

	if ($check_send_mail == "unsent") {
		if (!$paymentId) {
			return '<div class="error"><p>' . __('This URL is invalid. You can not access this page directly.', 'gift-voucher') . '</p></div>';
		}

		if ((strtotime($voucher_options->voucheradd_time) + 3600) < strtotime(current_time('mysql'))) {
			return '<div class="error"><p>' . __('This URL is invalid. You can not access this page directly.', 'gift-voucher') . '</p></div>';
		}

		$payment = $mollie->payments->get($paymentId);
		if ($payment->isPaid()) {
			$voucherrow = $wpdb->get_row("SELECT * FROM `{$wpdb->prefix}giftvouchers_list` WHERE `id` = $voucher_item AND `pay_method` <> 'Per Invoice'");
			if ($voucherrow) {
				wpgv_update_payment_and_pdf($wpdb, $voucher_table, $voucher_item, $voucher_options);
				WPGV_Gift_Voucher_Activity::record($voucher_item, 'firsttransact', $voucherrow->amount, 'Voucher payment recieved.');
			}

			$wpgv_invoice_mail_enable = (get_option('wpgv_invoice_mail_enable') != '') ? get_option('wpgv_invoice_mail_enable') : 1;
			$email_settings = wpgv_get_email_settings();

			if (isset($_GET['per_invoice']) && $_GET['per_invoice'] == 1 && $wpgv_invoice_mail_enable == 0) {
				$attachment_data = wpgv_get_attachment_paths($voucher_options);
				$attachments = $attachment_data['attachments'];

				$admin_email_data = array(
					'setting_options' => $setting_options,
					'voucher_options' => $voucher_options,
					'voucher_item' => $voucher_item,
					'check_send_mail' => $check_send_mail,
					'send_instantly' => $send_instantly,
					'email_settings' => $email_settings,
					'attachments' => $attachments
				);
				wpgv_send_admin_email($admin_email_data);

				$return .= '<div class="success">' . sprintf(stripslashes($email_settings['successpagemessage']), $voucher_options->email) . '</div>';
				if ($setting_options->bank_info != '') {
					$return .= $setting_options->bank_info;
				}
			} else {
				// Process full email workflow
				$attachment_data = wpgv_get_attachment_paths($voucher_options);
				$attachments = $attachment_data['attachments'];
				$upload_dir = $attachment_data['upload_dir'];

				// Determine email body
				$emailbody = $email_settings['emailbody'];
				if (isset($_GET['per_invoice']) && $_GET['per_invoice'] == 1) {
					$emailbody = $email_settings['emailbodyperinvoice'];
					$attachments[2] = $upload_dir . '/voucherpdfuploads/' . $voucher_options->voucherpdf_link . '-invoice.pdf';
				}

				$headers = wpgv_setup_email_headers($setting_options);

				// Send recipient email
				$recipient_data = array(
					'recipientemailsubject' => $email_settings['recipientemailsubject'],
					'recipientemailbody' => $email_settings['recipientemailbody'],
					'shipping_type' => $voucher_options->shipping_type,
					'shipping_email' => $voucher_options->shipping_email,
					'buying_for' => $voucher_options->buying_for,
					'setting_options' => $setting_options,
					'voucher_options' => $voucher_options,
					'check_send_mail' => $check_send_mail,
					'send_instantly' => $send_instantly,
					'email_send_date_time' => $voucher_options->email_send_date_time,
					'headers' => $headers,
					'attachments' => $attachments
				);
				wpgv_send_recipient_email($recipient_data);

				// Send buyer email
				$buyer_data = array(
					'emailsubject' => $email_settings['emailsubject'],
					'emailbody' => $emailbody,
					'setting_options' => $setting_options,
					'voucher_options' => $voucher_options,
					'check_send_mail' => $check_send_mail,
					'headers' => $headers,
					'attachments' => $attachments
				);
				$mail_sent = wpgv_send_buyer_email($buyer_data);

				if ($mail_sent) {
					$return .= '<div class="success">' . sprintf(stripslashes($email_settings['successpagemessage']), $voucher_options->email) . '</div>';
					if (isset($_GET['per_invoice']) && $_GET['per_invoice'] == 1) {
						$return .= $setting_options->bank_info;
					}

					// Send admin email
					$admin_email_data = array(
						'setting_options' => $setting_options,
						'voucher_options' => $voucher_options,
						'voucher_item' => $voucher_item,
						'check_send_mail' => $check_send_mail,
						'send_instantly' => $send_instantly,
						'email_settings' => $email_settings,
						'attachments' => $attachments
					);
					wpgv_send_admin_email($admin_email_data);
				} else {
					$return .= '<div class="error"><p>' . __('Some Error Occurred From Sending this Email! <br>(Reload and Retry Again!) or Contact Us', 'gift-voucher') . '</p></div>';
				}
			}
		} elseif ($payment->isOpen()) {
			$return .= '<div class="error"><p>' . __('Payment is still open.', 'gift-voucher') . '</p></div>';
		} elseif ($payment->isCanceled()) {
			$return .= '<div class="error"><p>' . __('Payment was canceled.', 'gift-voucher') . '</p></div>';
		} elseif ($payment->isFailed()) {
			$return .= '<div class="error"><p>' . __('Payment failed.', 'gift-voucher') . '</p></div>';
		}
	} else {
		$email_settings = wpgv_get_email_settings();
		$return .= '<div class="success">' . sprintf(stripslashes($email_settings['successpagemessage']), $voucher_options->email) . '</div>';
	}

	return $return;
}
add_shortcode('wpgv_molliesuccesspage', 'mollie_successful_shortcode');

// Function for Voucher Payment Successful Shortcode
function wpgv_voucher_successful_shortcode()
{
	global $wpdb;
	$return = '';

	if (!isset($_GET['voucheritem'])) {
		return '<div class="error"><p>' . __('This URL is invalid. You can not access this page directly.', 'gift-voucher') . '</p></div>';
	}

	$data = wpgv_init_voucher_data($_GET['voucheritem']);
	extract($data);

	$invoice_setting_table = $wpdb->prefix . 'giftvouchers_invoice_settings';
	$invoice_options = $wpdb->get_row("SELECT * FROM $invoice_setting_table WHERE id = 1");
	$is_invoice_active = (is_object($invoice_options) && isset($invoice_options->is_invoice_active)) ? $invoice_options->is_invoice_active : 0;

	if ($check_send_mail == "unsent" && isset($_GET['voucheritem'])) {
		if ((strtotime($voucher_options->voucheradd_time) + 3600) < strtotime(current_time('mysql'))) {
			return '<div class="error"><p>' . __('This URL is invalid. You can not access this page directly.', 'gift-voucher') . '</p></div>';
		}

		if (!isset($_GET['per_invoice']) || $_GET['per_invoice'] != 1) {
			$voucherrow = $wpdb->get_row($wpdb->prepare(
				"SELECT * FROM `{$wpdb->prefix}giftvouchers_list` WHERE `id` = %d AND `pay_method` <> 'Per Invoice'",
				$voucher_item
			));

			if ($voucherrow) {
				wpgv_update_payment_and_pdf($wpdb, $voucher_table, $voucher_item, $voucher_options);

				// Process PayPal payment if token and PayerID are present and status is not 'Paid'
				if (!empty($_GET['token']) && !empty($_GET['PayerID']) && $voucherrow->payment_status != 'Paid') {
					require_once WPGIFT__PLUGIN_DIR . '/vendor/autoload.php';
					require_once WPGIFT__PLUGIN_DIR . '/include/PayPalAuth.php';

					// Determine PayPal order id: prefer session, fallback to stored post meta
					$paypal_order_id = '';
					if (session_status() == PHP_SESSION_NONE) {
						session_start();
					}
					if (!empty($_SESSION['paypal_order_id'])) {
						$paypal_order_id = sanitize_text_field($_SESSION['paypal_order_id']);
					}
					if (empty($paypal_order_id) && !empty($voucher_item)) {
						$paypal_order_id = get_post_meta($voucher_item, 'wpgv_paypal_order_id', true);
						if (empty($paypal_order_id)) {
							$paypal_order_id = get_post_meta($voucher_item, 'paypal_order_id', true);
						}
					}

					$result_getId = null;
					if (empty($paypal_order_id)) {
						error_log('WPGV: Missing PayPal order id for voucher ' . intval($voucher_item));
					} else {
						$client = PayPalAuth::client();
						$request = new OrdersCaptureRequest($paypal_order_id);
						$request->prefer('return=representation');

						try {
							$response = $client->execute($request);
							$result_getId = $response->result->id ?? null;
						} catch (\Throwable $ex) {
							// Log details for debugging but avoid fatal errors for users
							error_log('WPGV PayPal capture error for voucher ' . intval($voucher_item) . ': ' . $ex->getMessage());
							$result_getId = null;
						}
					}

					update_post_meta($voucher_item, 'wpgv_paypal_payment_key', $result_getId, true);
					update_post_meta($voucher_item, 'wpgv_paypal_mode_for_transaction', (!$setting_options->test_mode) ? 'Livemode' : 'Testmode', true);
				}

				WPGV_Gift_Voucher_Activity::record($voucher_item, 'firsttransact', $voucherrow->amount, 'Voucher payment received.');
			}
		}

		$wpgv_invoice_mail_enable = (get_option('wpgv_invoice_mail_enable') != '') ? get_option('wpgv_invoice_mail_enable') : 1;
		$email_settings = wpgv_get_email_settings();

		if (isset($_GET['per_invoice']) && $_GET['per_invoice'] == 1 && $wpgv_invoice_mail_enable == 0) {
			$attachment_data = wpgv_get_attachment_paths($voucher_options);
			$attachments = $attachment_data['attachments'];

			$admin_email_data = array(
				'setting_options' => $setting_options,
				'voucher_options' => $voucher_options,
				'voucher_item' => $voucher_item,
				'check_send_mail' => $check_send_mail,
				'send_instantly' => $send_instantly,
				'email_settings' => $email_settings,
				'attachments' => $attachments
			);
			wpgv_send_admin_email($admin_email_data);

			$return .= '<div class="success">' . sprintf(stripslashes($email_settings['successpagemessage']), $voucher_options->email) . '</div>';
			if ($setting_options->bank_info != '') {
				$return .= $setting_options->bank_info;
			}
		} else {
			// Process full email workflow
			$attachment_data = wpgv_get_attachment_paths($voucher_options, $is_invoice_active);
			$attachments = $attachment_data['attachments'];
			$upload_dir = $attachment_data['upload_dir'];

			// Determine email body
			$emailbody = $email_settings['emailbody'];
			if (isset($_GET['per_invoice']) && $_GET['per_invoice'] == 1) {
				$emailbody = $email_settings['emailbodyperinvoice'];
			}

			$headers = wpgv_setup_email_headers($setting_options);

			// Send recipient email
			$recipient_data = array(
				'recipientemailsubject' => $email_settings['recipientemailsubject'],
				'recipientemailbody' => $email_settings['recipientemailbody'],
				'shipping_type' => $voucher_options->shipping_type,
				'shipping_email' => $voucher_options->shipping_email,
				'buying_for' => $voucher_options->buying_for,
				'setting_options' => $setting_options,
				'voucher_options' => $voucher_options,
				'check_send_mail' => $check_send_mail,
				'send_instantly' => $send_instantly,
				'email_send_date_time' => $voucher_options->email_send_date_time,
				'headers' => $headers,
				'attachments' => $attachments
			);
			wpgv_send_recipient_email($recipient_data);

			// Send buyer email
			$buyer_data = array(
				'emailsubject' => $email_settings['emailsubject'],
				'emailbody' => $emailbody,
				'setting_options' => $setting_options,
				'voucher_options' => $voucher_options,
				'check_send_mail' => $check_send_mail,
				'headers' => $headers,
				'attachments' => $attachments
			);
			$mail_sent = wpgv_send_buyer_email($buyer_data);

			if ($mail_sent) {
				$return .= '<div class="success">' . sprintf(stripslashes($email_settings['successpagemessage']), $voucher_options->email) . '</div>';
				if (isset($_GET['per_invoice']) && $_GET['per_invoice'] == 1) {
					$return .= $setting_options->bank_info;
				}

				// Send admin email
				$admin_email_data = array(
					'setting_options' => $setting_options,
					'voucher_options' => $voucher_options,
					'voucher_item' => $voucher_item,
					'check_send_mail' => $check_send_mail,
					'send_instantly' => $send_instantly,
					'email_settings' => $email_settings,
					'attachments' => $attachments
				);
				wpgv_send_admin_email($admin_email_data);
			} else {
				$return .= '<div class="error"><p>' . __('Some Error Occurred From Sending this Email! <br>(Reload and Retry Again!) or Contact Us', 'gift-voucher') . '</p></div>';
			}
		}
	} elseif ($check_send_mail != "unsent") {
		$email_settings = wpgv_get_email_settings();
		$return .= '<div class="success">' . sprintf(stripslashes($email_settings['successpagemessage']), $voucher_options->email) . '</div>';
	} else {
		return '<div class="error"><p>' . __('This URL is invalid. You can not access this page directly.', 'gift-voucher') . '</p></div>';
	}

	return $return;
}
add_shortcode('wpgv_giftvouchersuccesspage', 'wpgv_voucher_successful_shortcode');

// Function for Stripe Success Page
function wpgv_stripe_success_page_shortcode()
{
	global $wpdb;
	$return = '';

	if (!isset($_GET['voucheritem'])) {
		return '<div class="error"><p>' . __('This URL is invalid. You can not access this page directly.', 'gift-voucher') . '</p></div>';
	}

	$data = wpgv_init_voucher_data($_GET['voucheritem']);
	extract($data);

	$orderid = $voucher_item;

	$invoice_setting_table = $wpdb->prefix . 'giftvouchers_invoice_settings';
	$invoice_options = $wpdb->get_row("SELECT * FROM $invoice_setting_table WHERE id = 1");
	$is_invoice_active = (is_object($invoice_options) && isset($invoice_options->is_invoice_active)) ? $invoice_options->is_invoice_active : 0;

	$statusMsg = '';

	if ($check_send_mail == "unsent") {
		if (empty($_GET['sessionid'])) {
			$statusMsg = "Form submission error.......";
		} else {
			if ((strtotime($voucher_options->voucheradd_time) + 3600) < strtotime(current_time('mysql'))) {
				return '<div class="error"><p>' . __('This URL is invalid. You can not access this page directly.', 'gift-voucher') . '</p></div>';
			}

			$stripe = array(
				"publishable_key" => $setting_options->stripe_publishable_key,
				"secret_key"      => $setting_options->stripe_secret_key,
			);

			\Stripe\Stripe::setApiKey($stripe['secret_key']);
			\Stripe\Stripe::setVerifySslCerts(true);

			$checkout_session = \Stripe\Checkout\Session::retrieve($_GET['sessionid']);
			$sessionJson = $checkout_session->jsonSerialize();

			\Stripe\PaymentIntent::update(
				$sessionJson['payment_intent'],
				['metadata' => ['order_id' => $orderid]]
			);

                try {
                    $payment_intent = \Stripe\PaymentIntent::retrieve($sessionJson['payment_intent']);

                    // Idempotency: if already processed, return success message
                    $already = get_post_meta($orderid, 'wpgv_payment_processed', true);
                    if ($already) {
                        $email_settings = wpgv_get_email_settings();
                        $statusMsg = '<div class="success">' . sprintf(stripslashes($email_settings['successpagemessage']), $voucher_options->email) . '</div>';
                    } else {
                        // If PaymentIntent requires capture (manual capture), attempt to capture
                        if ($payment_intent->status === 'requires_capture') {
                            try {
                                \Stripe\PaymentIntent::capture($sessionJson['payment_intent']);
                                // re-retrieve
                                $payment_intent = \Stripe\PaymentIntent::retrieve($sessionJson['payment_intent']);
                            } catch (\Exception $captureEx) {
                                // Log and continue to allow webhook to handle later
                                error_log('WPGV: Stripe capture attempt failed: ' . $captureEx->getMessage());
                            }
                        }

                        if ($payment_intent->status === 'succeeded') {
                            update_post_meta($orderid, 'wpgv_stripe_session_key', $_GET['sessionid'], true);
                            update_post_meta($orderid, 'wpgv_stripe_mode_for_transaction', $setting_options->stripe_publishable_key, true);

                            // Centralized processing (idempotent)
                            wpgv_process_successful_order($orderid);

                            $email_settings = wpgv_get_email_settings();
                            $statusMsg = '<div class="success">' . sprintf(stripslashes($email_settings['successpagemessage']), $voucher_options->email) . '</div>';
                        } else {
                            $statusMsg = __("Transaction has been failed", 'gift-voucher');
                        }
                    }
                } catch (\Exception $e) {
                    $statusMsg = __("Transaction has been failed!", 'gift-voucher');
                }
		}
	} else {
		$email_settings = wpgv_get_email_settings();
		$statusMsg = '<div class="success">' . sprintf(stripslashes($email_settings['successpagemessage']), $voucher_options->email) . '</div>';
	}

	return $statusMsg;
}
add_shortcode('wpgv_stripesuccesspage', 'wpgv_stripe_success_page_shortcode');

/**
 * Helper function to get Klarna API credentials
 * Note: This function is also defined in klarna-push-notification.php
 * The function_exists check ensures no conflict
 */
if (!function_exists('wpgv_get_klarna_credentials')) {
	function wpgv_get_klarna_credentials()
	{
		$klarna_mode = get_option('wpgv_klarna_mode') ?: 'sandbox';

		if ($klarna_mode === 'live') {
			return array(
				'merchant_id' => get_option('wpgv_klarna_live_merchant_id'),
				'shared_secret' => get_option('wpgv_klarna_live_shared_secret'),
				'api_url' => 'https://api.klarna.com',
				'mode' => 'live'
			);
		}

		return array(
			'merchant_id' => get_option('wpgv_klarna_demo_merchant_id'),
			'shared_secret' => get_option('wpgv_klarna_demo_shared_secret'),
			'api_url' => 'https://api.playground.klarna.com',
			'mode' => 'sandbox'
		);
	}
}

/**
 * Helper function to check Klarna order status
 * Note: This function is also defined in klarna-push-notification.php
 *
 * @param string $order_id Klarna order ID
 * @return array|false Order data or false on failure
 */
if (!function_exists('wpgv_check_klarna_order_status')) {
	function wpgv_check_klarna_order_status($order_id)
	{
		$credentials = wpgv_get_klarna_credentials();


		if (empty($credentials['merchant_id']) || empty($credentials['shared_secret'])) {
			error_log('Klarna: credentials not configured');
			return false;
		}

		// Klarna Order Management API endpoint
		$order_url = $credentials['api_url'] . '/ordermanagement/v1/orders/' . $order_id;

		$args = array(
			'headers' => array(
				'Authorization' => 'Basic ' . base64_encode($credentials['merchant_id'] . ':' . $credentials['shared_secret']),
				'Content-Type' => 'application/json'
			),
			'timeout' => 30,
		);

		$response = wp_remote_get($order_url, $args);

		if (is_wp_error($response)) {
			error_log('Klarna: API request failed - ' . $response->get_error_message());
			return false;
		}

		$code = wp_remote_retrieve_response_code($response);
		$body = wp_remote_retrieve_body($response);
		$data = json_decode($body, true);

		if ($code >= 200 && $code < 300 && !empty($data)) {
			return $data;
		}

		error_log('Klarna: failed to get order status - HTTP ' . $code . ' - ' . $body);
		return false;
	}
}

/**
 * Capture a Klarna order (collect the authorized payment)
 * Note: This function is also defined in klarna-push-notification.php
 *
 * @param string $klarna_order_id Klarna order ID
 * @param array $klarna_order Order data from wpgv_check_klarna_order_status (contains order_lines, amounts)
 * @return array Result with 'success', 'code', 'body', 'message' keys
 */
if (!function_exists('wpgv_klarna_capture_order')) {
	function wpgv_klarna_capture_order($klarna_order_id, $klarna_order = null)
	{
		if (empty($klarna_order_id)) {
			return array('success' => false, 'message' => 'Missing Klarna order ID');
		}

		$credentials = wpgv_get_klarna_credentials();
		if (empty($credentials['merchant_id']) || empty($credentials['shared_secret'])) {
			return array('success' => false, 'message' => 'Klarna credentials not configured');
		}

		// If order data not provided, fetch it
		if (empty($klarna_order)) {
			$klarna_order = wpgv_check_klarna_order_status($klarna_order_id);
			if (!$klarna_order) {
				return array('success' => false, 'message' => 'Could not retrieve Klarna order data');
			}
		}

		// Check if already captured
		$status = isset($klarna_order['status']) ? strtoupper($klarna_order['status']) : '';
		if (in_array($status, array('CAPTURED', 'PART_CAPTURED'))) {
			return array('success' => true, 'message' => 'Order already captured', 'already_captured' => true);
		}

		// Only AUTHORIZED orders can be captured
		if ($status !== 'AUTHORIZED') {
			return array('success' => false, 'message' => 'Order status is ' . $status . ', cannot capture');
		}

		// Build capture URL
		$api_base = rtrim($credentials['api_url'], '/');
		$capture_url = $api_base . '/ordermanagement/v1/orders/' . rawurlencode($klarna_order_id) . '/captures';

		// Get amount and order_lines from klarna_order
		$captured_amount = isset($klarna_order['remaining_authorized_amount']) ? intval($klarna_order['remaining_authorized_amount']) : (isset($klarna_order['order_amount']) ? intval($klarna_order['order_amount']) : 0);
		$order_lines = isset($klarna_order['order_lines']) ? $klarna_order['order_lines'] : array();

		if ($captured_amount <= 0) {
			return array('success' => false, 'message' => 'Invalid capture amount');
		}

		// Build capture payload
		$payload = array(
			'captured_amount' => $captured_amount,
			'order_lines' => $order_lines,
		);

		$args = array(
			'headers' => array(
				'Authorization' => 'Basic ' . base64_encode($credentials['merchant_id'] . ':' . $credentials['shared_secret']),
				'Content-Type' => 'application/json',
			),
			'body' => wp_json_encode($payload),
			'timeout' => 30,
		);

		error_log('Klarna Capture: Attempting capture for order ' . $klarna_order_id . ' - Amount: ' . $captured_amount);

		$response = wp_remote_post($capture_url, $args);

		if (is_wp_error($response)) {
			error_log('Klarna Capture: API request failed - ' . $response->get_error_message());
			return array('success' => false, 'message' => $response->get_error_message());
		}

		$code = wp_remote_retrieve_response_code($response);
		$body = wp_remote_retrieve_body($response);
		$data = json_decode($body, true);

		// Klarna returns 201 Created on successful capture
		if ($code >= 200 && $code < 300) {
			error_log('Klarna Capture: Success for order ' . $klarna_order_id);
			return array(
				'success' => true,
				'code' => $code,
				'body' => $data,
				'message' => 'Captured successfully',
				'capture_id' => isset($data['capture_id']) ? $data['capture_id'] : null
			);
		}

		$error_msg = '';
		if (!empty($data['error_messages'])) {
			$error_msg = implode(', ', $data['error_messages']);
		} elseif (!empty($data['error_message'])) {
			$error_msg = $data['error_message'];
		} elseif (!empty($data['error_code'])) {
			$error_msg = $data['error_code'];
		} else {
			$error_msg = $body;
		}

		error_log('Klarna Capture: Failed for order ' . $klarna_order_id . ' - HTTP ' . $code . ' - ' . $error_msg);
		return array('success' => false, 'code' => $code, 'body' => $data ?: $body, 'message' => $error_msg);
	}
}

/**
 * Function for Klarna Payment Success Page Shortcode
 */
function wpgv_klarna_success_page_shortcode()
{
	global $wpdb;
	$statusMsg = '';

	// Get order_id from URL (from Klarna redirect or klarna-authorize.php redirect)
	$klarna_order_id = isset($_GET['order_id']) ? sanitize_text_field($_GET['order_id']) : '';

	if (empty($klarna_order_id)) {
		return '<div class="error"><p>' . __('This URL is invalid. You can not access this page directly.', 'gift-voucher') . '</p></div>';
	}

	// Find the voucher by Klarna order ID in post meta
	$postmeta_table = $wpdb->postmeta;
	$records = $wpdb->get_results($wpdb->prepare(
		"SELECT pm.post_id FROM $postmeta_table pm
		WHERE pm.meta_key = %s AND pm.meta_value = %s",
		'wpgv_klarna_order_id',
		$klarna_order_id
	));



	if (empty($records)) {
		return '<div class="error"><p>' . __('Order not found. Please contact support.', 'gift-voucher') . '</p></div>';
	}

	$voucher_item = $records[0]->post_id;

	// Initialize voucher data
	$data = wpgv_init_voucher_data($voucher_item);
	extract($data);

	if (!$voucher_options) {
		return '<div class="error"><p>' . __('Voucher not found.', 'gift-voucher') . '</p></div>';
	}

	// Get invoice settings
	$invoice_setting_table = $wpdb->prefix . 'giftvouchers_invoice_settings';
	$invoice_options = $wpdb->get_row("SELECT * FROM $invoice_setting_table WHERE id = 1");
	$is_invoice_active = (is_object($invoice_options) && isset($invoice_options->is_invoice_active)) ? $invoice_options->is_invoice_active : 0;

	// Check if email already sent

	if ($check_send_mail != "unsent") {
		$email_settings = wpgv_get_email_settings();
		return '<div class="success">' . sprintf(stripslashes($email_settings['successpagemessage']), $voucher_options->email) . '</div>';
	}

	// Check URL timing validity
	if ((strtotime($voucher_options->voucheradd_time) + 3600) < strtotime(current_time('mysql'))) {
		return '<div class="error"><p>' . __('This URL is invalid. You can not access this page directly.', 'gift-voucher') . '</p></div>';
	}

	// Verify Klarna order status via API
	$klarna_order = wpgv_check_klarna_order_status($klarna_order_id);

	if (!$klarna_order) {
		return '<div class="error"><p>' . __('Unable to verify payment status. Please contact support.', 'gift-voucher') . '</p></div>';
	}

	// Check if order status is valid for processing
	$order_status = isset($klarna_order['status']) ? strtoupper($klarna_order['status']) : '';
	if (!in_array($order_status, array('AUTHORIZED', 'CAPTURED', 'PART_CAPTURED'))) {
		$status_message = '';
		switch ($order_status) {
			case 'PENDING':
				$status_message = __('Payment is still pending. Please wait for confirmation.', 'gift-voucher');
				break;
			case 'CANCELLED':
				$status_message = __('Payment was cancelled.', 'gift-voucher');
				break;
			case 'EXPIRED':
				$status_message = __('Payment authorization has expired.', 'gift-voucher');
				break;
			default:
				$status_message = sprintf(__('Payment status: %s. Please contact support.', 'gift-voucher'), $order_status);
		}
		return '<div class="error"><p>' . $status_message . '</p></div>';
	}

	// Auto-capture if status is AUTHORIZED (not yet captured)
	if ($order_status === 'AUTHORIZED') {
		$capture_result = wpgv_klarna_capture_order($klarna_order_id, $klarna_order);
		if (!$capture_result['success'] && empty($capture_result['already_captured'])) {
			error_log('Klarna auto-capture failed: ' . $capture_result['message']);
			return '<div class="error"><p>' . sprintf(__('Payment capture failed: %s. Please contact support.', 'gift-voucher'), esc_html($capture_result['message'])) . '</p></div>';
		}
		// Update status after successful capture
		$order_status = 'CAPTURED';
	}

	// Payment is CAPTURED - process the order
	try {
		// Update payment status and generate PDF
		wpgv_update_payment_and_pdf($wpdb, $voucher_table, $voucher_item, $voucher_options);

		// Update Klarna-specific meta
		update_post_meta($voucher_item, 'wpgv_klarna_payment_status', $order_status);
		update_post_meta($voucher_item, 'wpgv_klarna_mode_for_transaction', wpgv_get_klarna_credentials()['mode']);
		update_post_meta($voucher_item, 'wpgv_klarna_captured_at', current_time('mysql'));

		// Record activity
		$voucherrow = $wpdb->get_row("SELECT * FROM `{$wpdb->prefix}giftvouchers_list` WHERE `id` = $voucher_item");
		if ($voucherrow) {
			WPGV_Gift_Voucher_Activity::record($voucher_item, 'firsttransact', $voucherrow->amount, 'Voucher payment received via Klarna.');
		}

		// Get email settings and attachments
		$email_settings = wpgv_get_email_settings();
		$attachment_data = wpgv_get_attachment_paths($voucher_options, $is_invoice_active);
		$attachments = $attachment_data['attachments'];
		$headers = wpgv_setup_email_headers($setting_options);

		// Send recipient email
		$recipient_data = array(
			'recipientemailsubject' => $email_settings['recipientemailsubject'],
			'recipientemailbody' => $email_settings['recipientemailbody'],
			'shipping_type' => $voucher_options->shipping_type,
			'shipping_email' => $voucher_options->shipping_email,
			'buying_for' => $voucher_options->buying_for,
			'setting_options' => $setting_options,
			'voucher_options' => $voucher_options,
			'check_send_mail' => $check_send_mail,
			'send_instantly' => $send_instantly,
			'email_send_date_time' => $voucher_options->email_send_date_time,
			'headers' => $headers,
			'attachments' => $attachments
		);
		wpgv_send_recipient_email($recipient_data);

		// Send buyer email
		$buyer_data = array(
			'emailsubject' => $email_settings['emailsubject'],
			'emailbody' => $email_settings['emailbody'],
			'setting_options' => $setting_options,
			'voucher_options' => $voucher_options,
			'check_send_mail' => $check_send_mail,
			'headers' => $headers,
			'attachments' => $attachments
		);
		$mail_sent = wpgv_send_buyer_email($buyer_data);

		if ($mail_sent) {
			$statusMsg = '<div class="success">' . sprintf(stripslashes($email_settings['successpagemessage']), $voucher_options->email) . '</div>';

			// Send admin email
			$admin_email_data = array(
				'setting_options' => $setting_options,
				'voucher_options' => $voucher_options,
				'voucher_item' => $voucher_item,
				'check_send_mail' => $check_send_mail,
				'send_instantly' => $send_instantly,
				'email_settings' => $email_settings,
				'attachments' => $attachments
			);
			wpgv_send_admin_email($admin_email_data);
		} else {
			$statusMsg = '<div class="error"><p>' . __('Some Error Occurred From Sending this Email! <br>(Reload and Retry Again!) or Contact Us', 'gift-voucher') . '</p></div>';
		}
	} catch (\Exception $e) {
		error_log('Klarna success page error: ' . $e->getMessage());
		$statusMsg = '<div class="error"><p>' . __('An error occurred while processing your order. Please contact support.', 'gift-voucher') . '</p></div>';
	}

	return $statusMsg;
}
add_shortcode('wpgv_klarnasuccesspage', 'wpgv_klarna_success_page_shortcode');

// Function for Checking Voucher Balance Shortcode
function wpgv_check_voucher_balance_shortcode()
{
	ob_start();

	// Retrieve the voucher code from the request and sanitize it
	$voucher_code = isset($_REQUEST['voucher_code']) ? sanitize_text_field($_REQUEST['voucher_code']) : '';

?>
	<form action="" method="post" id="scrollVoucherBalance">
		<input type="text" name="voucher_code" autocomplete="off" placeholder="<?php echo esc_attr(__('Search by Gift voucher code', 'gift-voucher')); ?>" value="<?php echo esc_attr($voucher_code); ?>" style="width: 400px;" required>
		<input type="submit" class="button button-primary" value="<?php echo esc_attr(__('Check Balance', 'gift-voucher')); ?>">
	</form>
	<?php

	if ($voucher_code) {
		global $wpdb;

		// Create a new WPGV_Gift_Voucher instance
		$gift_voucher = new WPGV_Gift_Voucher($voucher_code);

		if ($gift_voucher->get_id()) {
			// Output CSS for styling
			echo '<style type="text/css">
                .wpgv-balance-activity-negative {
                    color: #f00;
                }
                .wpgv-balance-activity-table {
                    font-size: 14px;
                }
                .wpgv-balance-activity-table td,
                .wpgv-balance-activity-table th {
                    padding: 10px;
                }
            </style>';

			// Display current voucher balance and activity
	?>
			<h4>
				<strong><?php echo esc_html(__('Current Voucher Balance:', 'gift-voucher') . ' ' . wpgv_price_format($gift_voucher->get_balance())); ?></strong>
			</h4>
			<table class="wpgv-balance-activity-table">
				<tr>
					<th><?php _e('Date', 'gift-voucher'); ?></th>
					<th><?php _e('Action', 'gift-voucher'); ?></th>
					<th><?php _e('Note', 'gift-voucher'); ?></th>
					<th><?php _e('Amount', 'gift-voucher'); ?></th>
					<th><?php _e('Balance', 'gift-voucher'); ?></th>
					<th><?php _e('Expiry Date', 'gift-voucher'); ?></th>
				</tr>
				<?php
				$running_balance = $gift_voucher->get_balance();
				foreach ($gift_voucher->get_activity() as $activity) {
				?>
					<tr>
						<td><?php echo esc_html(date_i18n(get_option('wpgv_expiry_date_format', 'd.m.Y') . ' ' . get_option('time_format'), strtotime($activity->activity_date))); ?></td>
						<td><?php echo esc_html($activity->action == 'create' ? __('Create', 'gift-voucher') : ($activity->action == 'transaction' ? __('Transaction', 'gift-voucher') : ucwords($activity->action))); ?></td>
						<td><?php echo esc_html(
								$activity->note == 'Voucher payment received.' ? __('Voucher payment received.', 'gift-voucher') : ($activity->note == 'Voucher payment recieved.' ? __('Voucher payment received.', 'gift-voucher') : ($activity->note == 'Voucher used completely.' ? __('Voucher used completely.', 'gift-voucher') : (preg_match('/^Voucher amount .* used directly by administrator\.$/', $activity->note) ?
									sprintf(
										__('Voucher amount %s used directly by administrator.', 'gift-voucher'),
										preg_replace('/^Voucher amount (.*) used directly by administrator\.$/', '$1', $activity->note)
									) :
									$activity->note)))
							); ?></td>
						<td class="wpgv-balance-activity <?php echo ($activity->amount < 0) ? 'wpgv-balance-activity-negative' : ''; ?>"><?php echo ($activity->amount != 0) ? wpgv_price_format($activity->amount) : ''; ?></td>
						<td class="wpgv-balance-activity"><?php echo wpgv_price_format($running_balance); ?></td>
						<td class="expiry_date"><?php echo esc_html($gift_voucher->get_expiration_date()); ?></td>
					</tr>
				<?php
				}
				?>
			</table>
		<?php
		} else {
			echo esc_html(__('This is an invalid voucher code.', 'gift-voucher'));
		}

		// Output JavaScript for smooth scrolling
		?>
		<script>
			jQuery(document).ready(function($) {
				$('html, body').animate({
					scrollTop: $("#scrollVoucherBalance").offset().top
				}, 1000);
			});
		</script>
<?php
	}

	return ob_get_clean();
}

// Register the shortcode
add_shortcode('wpgv-check-voucher-balance', 'wpgv_check_voucher_balance_shortcode');

// Function for Voucher Payment Cancel Shortcode
function wpgv_voucher_cancel_shortcode()
{
	global $wpdb;
	$return = '';

	// Define the table name
	$voucher_table = $wpdb->prefix . 'giftvouchers_list';

	// Check if the 'voucheritem' parameter is set
	if (isset($_GET['voucheritem'])) {
		// Get the cancel page message option
		$cancel_page_message = get_option('wpgv_cancelpagemessage', 'You cancelled your order. Please place your order again from <a href="' . esc_url(get_site_url() . '/gift-voucher') . '">here</a>.');

		// Escape the message for safe output
		$return .= wp_kses_post($cancel_page_message);
	}

	return $return;
}

// Register the shortcode
add_shortcode('wpgv_giftvouchercancelpage', 'wpgv_voucher_cancel_shortcode');
