<?php

/**
 * Plugin Name: Gift Cards Pro
 * Description: Let your customers buy gift cards/certificates for your services & products directly on your website.
 * Plugin URI: https://www.codemenschen.at/
 * Author: codemenschen
 * Author URI: https://www.codemenschen.at/
 * Version: 4.4.8
 * Text Domain: gift-voucher
 * Domain Path: /languages
 * License: GNU General Public License v2.0 or later
 * License URI: https://www.gnu.org/licenses/gpl-2.0.html
 *
 * Plugin Variable: wpgiftv
 *
 * @package         Gift Cards Pro
 * @author          Aakash Gupta
 * @copyright       Copyright (c) 2020
 *
 */

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

define('WPGIFT_VERSION', '4.4.8');
define('WPGIFT__MINIMUM_WP_VERSION', '4.0');
define('WPGIFT__PLUGIN_DIR', untrailingslashit(plugin_dir_path(__FILE__)));
define('WPGIFT__PLUGIN_URL', untrailingslashit(plugins_url(basename(plugin_dir_path(__FILE__)), basename(__FILE__))));
define('WPGIFT_FILE', basename(plugin_dir_path(__FILE__)) . '/' . basename(__FILE__));
define('WPGIFT_PLUGIN_ROOT', plugin_dir_path(__FILE__));
define('WPGIFT_SESSION_KEY', 'wpgv-gift-voucher-data');
define('WPGIFT_INSTALL_DATE', 'wpgv-install-date');
define('WPGIFT_ADMIN_NOTICE_KEY', 'wpgv-hide-notice');

define('WPGV_PRODUCT_TYPE_SLUG', 'gift_voucher');
define('WPGV_PRODUCT_TYPE_NAME', 'Gift Voucher');
define('WPGV_DENOMINATION_ATTRIBUTE_SLUG', 'gift-voucher-amount');
define('WPGV_MAX_MESSAGE_CHARACTERS', 500);
define('WPGV_RECIPIENT_LIMIT', 999);
define('WPGV_GIFT_VOUCHER_NUMBER_META_KEY', 'wpgv_gift_voucher_number');
define('WPGV_AMOUNT_META_KEY', 'wpgv_gift_voucher_amount');
define('WPGV_YOUR_NAME_META_KEY', 'wpgv_your_name');
define('WPGV_RECIPIENT_NAME_META_KEY', 'wpgv_recipient_name');
define('WPGV_RECIPIENT_EMAIL_META_KEY', 'wpgv_recipient_email');
define('WPGV_YOUR_EMAIL_META_KEY', 'wpgv_your_email');
define('WPGV_MESSAGE_META_KEY', 'wpgv_message');

if (!class_exists('WP_List_Table')) {
	require_once(ABSPATH . 'wp-admin/includes/class-wp-list-table.php');
}

// Force load Stripe library immediately to prevent conflicts
require_once(WPGIFT__PLUGIN_DIR . '/include/stripe-force-loader.php');

// Early Stripe library loading to prevent conflicts with other plugins
function wpgv_early_stripe_loader()
{
	// Force load our Stripe library early to prevent conflicts
	wpgv_force_load_stripe_library();
}
// Load Stripe library as early as possible
wpgv_early_stripe_loader();

// Hook to load Stripe library before other plugins
add_action('plugins_loaded', 'wpgv_early_stripe_loader', 1);

function wpgiftv_plugin_init()
{
	$langOK = load_plugin_textdomain('gift-voucher', false, dirname(plugin_basename(__FILE__)) . '/languages');
}
add_action('plugins_loaded', 'wpgiftv_plugin_init');

function wpgv_is_woocommerce_enable()
{
	$settings = wpgv_get_settings();
	if ( false === $settings ) {
		return false;
	}

	return ! empty( $settings->is_woocommerce_enable );
}

/**
 * Retrieve plugin settings row (cached) from DB.
 * Returns settings object or false if not available.
 */
function wpgv_get_settings() {
	static $cached = null;
	if ( $cached !== null ) {
		return $cached;
	}

	global $wpdb;
	$setting_table_name = $wpdb->prefix . 'giftvouchers_setting';

	// Ensure the table exists before querying to avoid notices during activation
	$table_exists = $wpdb->get_var( $wpdb->prepare( "SHOW TABLES LIKE %s", $wpdb->esc_like( $setting_table_name ) ) );
	if ( ! $table_exists ) {
		$cached = false;
		return $cached;
	}

	$options = $wpdb->get_row( "SELECT * FROM $setting_table_name WHERE id = 1" );

	if ( empty( $options ) || ! is_object( $options ) ) {
		$cached = false;
	} else {
		$cached = $options;
	}

	return $cached;
}
require_once(WPGIFT__PLUGIN_DIR . '/upgrade.php');

// Temporarily suppress deprecation notices from vendor libraries (PHP 8+)
// Some bundled vendor libraries (Stripe, etc.) surface E_DEPRECATED/E_USER_DEPRECATED
// which are printed during plugin activation and break header operations.
// We mask these notices during vendor loading and restore settings afterwards.
$wpgv_prev_error_reporting = error_reporting();
$wpgv_prev_display_errors = ini_get('display_errors');
error_reporting($wpgv_prev_error_reporting & ~E_DEPRECATED & ~E_USER_DEPRECATED);
@ini_set('display_errors', '0');

require_once(WPGIFT__PLUGIN_DIR . '/vendor/autoload.php');
require_once(WPGIFT__PLUGIN_DIR . '/vendor/sofort/payment/sofortLibSofortueberweisung.inc.php');
require_once(WPGIFT__PLUGIN_DIR . '/vendor/multisafepaygift/models/API/Autoloader.php');

// Restore previous error reporting and display settings
error_reporting($wpgv_prev_error_reporting);
@ini_set('display_errors', $wpgv_prev_display_errors);
require_once(WPGIFT__PLUGIN_DIR . '/classes/rotation.php');
require_once(WPGIFT__PLUGIN_DIR . '/admin.php');
require_once(WPGIFT__PLUGIN_DIR . '/front.php');
require_once(WPGIFT__PLUGIN_DIR . '/giftitems.php');
require_once(WPGIFT__PLUGIN_DIR . '/giftcard.php');
require_once(WPGIFT__PLUGIN_DIR . '/classes/fpdf.php');
require_once(WPGIFT__PLUGIN_DIR . '/classes/voucher.php');
require_once(WPGIFT__PLUGIN_DIR . '/classes/template.php');
require_once(WPGIFT__PLUGIN_DIR . '/classes/page_template.php');
require_once(WPGIFT__PLUGIN_DIR . '/include/stripe-debug.php');
require_once(WPGIFT__PLUGIN_DIR . '/include/klarna-webhook.php');
require_once(WPGIFT__PLUGIN_DIR . '/include/klarna-push-notification.php'); // Must be before klarna-authorize.php (contains helper functions)
require_once(WPGIFT__PLUGIN_DIR . '/include/klarna-authorize.php');
require_once(WPGIFT__PLUGIN_DIR . '/include/wpgv_voucher_pdf.php');
// Receipt helper functions (regenerating receipt PDFs)
require_once(WPGIFT__PLUGIN_DIR . '/include/receipt-functions.php');
require_once(WPGIFT__PLUGIN_DIR . '/include/wpgv_giftcard_pdf.php');
require_once(WPGIFT__PLUGIN_DIR . '/include/admin_wpgv_voucher_pdf.php');
require_once(WPGIFT__PLUGIN_DIR . '/include/wpgv_item_pdf.php');
require_once(WPGIFT__PLUGIN_DIR . '/include/voucher_posttype.php');
require_once(WPGIFT__PLUGIN_DIR . '/include/voucher_metabox.php');
require_once(WPGIFT__PLUGIN_DIR . '/include/voucher-shortcodes.php');
require_once(WPGIFT__PLUGIN_DIR . '/include/giftcard_standard.php');
require_once(WPGIFT__PLUGIN_DIR . '/include/giftcard_modern.php');
require_once(WPGIFT__PLUGIN_DIR . '/include/cron_recipients_email.php');
require_once(WPGIFT__PLUGIN_DIR . '/include/wpgc-product-detail-custom.php');
require_once(WPGIFT__PLUGIN_DIR . '/classes/wpgv-gift-voucher.php');
require_once(WPGIFT__PLUGIN_DIR . '/classes/wpgv-gift-voucher-activity.php');

if (wpgv_is_woocommerce_enable()) {
	require_once(WPGIFT__PLUGIN_DIR . '/classes/wpgv-voucher-product-list.php');
	require_once(WPGIFT__PLUGIN_DIR . '/include/wc_wpgv_voucher_pdf.php');
	require_once(WPGIFT__PLUGIN_DIR . '/classes/wpgv-check-plugin-active.php');
	// Product Page Gift Checkbox Feature
	require_once(WPGIFT__PLUGIN_DIR . '/include/product-page-gift-checkbox.php');
}

add_action('plugins_loaded', function () {
	WPGiftVoucherAdminPages::get_instance();
});


add_action('admin_init', function () {
	if (!current_user_can('manage_options')) {
		return;
	}

	global $wpdb;

	// Include nag class
	require_once(WPGIFT__PLUGIN_DIR . '/classes/class-nag.php');
	(new WPGIFT_Nag())->setup();

	// === Helper function to add column if not exists ===
	$add_column_if_not_exists = function ($table, $column, $definition) use ($wpdb) {
		$exists = $wpdb->get_var(
			$wpdb->prepare("SHOW COLUMNS FROM `$table` LIKE %s", $column)
		);
		if (!$exists) {
			$wpdb->query("ALTER TABLE `$table` ADD `$column` $definition");
		}
	};

	// Add 'check_send_mail' column to giftvouchers_list
	$table_list = $wpdb->prefix . 'giftvouchers_list';
	$add_column_if_not_exists(
		$table_list,
		'check_send_mail',
		"VARCHAR(30) NOT NULL DEFAULT 'unsent'"
	);

	// Convert 'couponcode' from BIGINT to VARCHAR if needed
	$couponcode_column = $wpdb->get_row("SHOW COLUMNS FROM `$table_list` LIKE 'couponcode'");
	if ($couponcode_column && stripos($couponcode_column->Type, 'bigint') !== false) {
		$wpdb->query("ALTER TABLE `$table_list` MODIFY `couponcode` VARCHAR(255) NOT NULL");
	}

	// Replace ',' with '|' in shipping_method
	$table_setting = $wpdb->prefix . 'giftvouchers_setting';
	$table_exists = $wpdb->get_var($wpdb->prepare("SHOW TABLES LIKE %s", $table_setting));
	if ($table_exists) {
		$shipping_method = $wpdb->get_var("SELECT `shipping_method` FROM `$table_setting` LIMIT 1");
		if (!empty($shipping_method) && strpos((string)$shipping_method, ',') !== false) {
			$updated_method = str_replace(',', '|', (string)$shipping_method);
			$wpdb->update(
				$table_setting,
				['shipping_method' => $updated_method],
				['shipping_method' => $shipping_method]
			);
		}
	}

	// Add Mollie columns to giftvouchers_setting
	$add_column_if_not_exists($table_setting, 'mollie', "VARCHAR(255)");
	$add_column_if_not_exists($table_setting, 'mollie_api_key', "VARCHAR(255)");

	// Add woo_order_id to giftvouchers_activity
	$table_activity = $wpdb->prefix . 'giftvouchers_activity';
	$add_column_if_not_exists(
		$table_activity,
		'woo_order_id',
		"BIGINT(20) UNSIGNED DEFAULT NULL COMMENT 'WooCommerce Order ID'"
	);

	// Update portrait_mode_templates data only once
	$portrait_templates_updated = get_option('wpgv_portrait_templates_updated', false);

	if (!$portrait_templates_updated) {
		$portrait_templates = 'template-custom-portail.png, template-voucher-portail-1.png, template-voucher-portail-2.png, template-voucher-portail-3.png, template-voucher-portail-4.png, template-voucher-portail-5.png, template-voucher-portail-6.png, template-voucher-portail-7.png, template-voucher-portail-8.png, template-voucher-portail-9.png, template-voucher-portail-10.png, template-voucher-portail-11.png, template-voucher-portail-12.png, template-voucher-portail-13.png, template-voucher-portail-14.png, template-voucher-portail-15.png, template-voucher-portail-16.png, template-voucher-portail-17.png, template-voucher-portail-18.png, template-voucher-portail-19.png, template-voucher-portail-20.png, template-voucher-portail-21.png, template-voucher-portail-22.png, template-voucher-portail-23.png, template-voucher-portail-24.png, template-voucher-portail-25.png, template-voucher-portail-26.png, template-voucher-portail-27.png, template-voucher-portail-28.png, template-voucher-portail-29.png, template-voucher-portail-30.png, template-voucher-portail-31.png, template-voucher-portail-32.png, template-voucher-portail-33.png, template-voucher-portail-34.png, template-voucher-portail-35.png, template-voucher-portail-36.png, template-voucher-portail-37.png, template-voucher-portail-38.png, template-voucher-portail-39.png, template-voucher-portail-40.png, template-voucher-portail-41.png, template-voucher-portail-42.png, template-voucher-portail-43.png, template-voucher-portail-44.png, template-voucher-portail-45.png';

		$wpdb->update(
			$table_setting,
			array('portrait_mode_templates' => $portrait_templates),
			array('id' => 1)
		);

		// Mark as updated to prevent future updates
		update_option('wpgv_portrait_templates_updated', true);
	}
	if (get_option('wpgv_coupon_code_type') === false) {
		update_option('wpgv_coupon_code_type', 'random');
	}

	// Seed default quotes JSON if not exists
	$existing_quotes = get_option('wpgv_quotes', '');
	if ($existing_quotes === '' || $existing_quotes === false) {
		$default_quotes = array(
			__('Happy Birthday! Wishing you a day filled with joy and laughter.', 'gift-voucher'),
			__('Congratulations on your special day! Enjoy this little treat.', 'gift-voucher'),
			__('Thank you for everything you do. Hope you love this gift!', 'gift-voucher'),
			__('Wishing you all the best—may this gift bring a smile to your face!', 'gift-voucher'),
			__('With love and warm wishes—enjoy every moment!', 'gift-voucher'),
		);
		update_option('wpgv_quotes', wp_json_encode($default_quotes));
	}
});

add_action('woocommerce_init', 'wpgv_files_loaded', 10, 1);
function wpgv_files_loaded()
{
	global $wpdb;
	$setting_table_name = $wpdb->prefix . 'giftvouchers_setting';
	$options = $wpdb->get_row("SELECT * FROM $setting_table_name WHERE id = 1");
	if ($options->is_woocommerce_enable) {
		require_once(WPGIFT__PLUGIN_DIR . '/include/redeem-voucher.php');
		require_once(WPGIFT__PLUGIN_DIR . '/classes/wpgv-gift-voucher-product.php');
		require_once(WPGIFT__PLUGIN_DIR . '/classes/wc-order-item-wpgv-gift-voucher.php');
		require_once(WPGIFT__PLUGIN_DIR . '/classes/wpgv-wc-product-gift-voucher.php');
		require_once(WPGIFT__PLUGIN_DIR . '/classes/data-stores/wc-order-item-wpgv-gift-voucher-data-store.php');
		require_once(WPGIFT__PLUGIN_DIR . '/include/wpgv-product-settings.php');
		if (is_admin()) {
			require_once(WPGIFT__PLUGIN_DIR . '/admin/wpgv-gift-voucher-admin.php');
		}
		add_action('wcml_is_variable_product', 'wcml_is_variable_product', 10, 2);
		add_filter('wpgv_to_current_currency', 'wpgv_to_current_currency');
		add_filter('wpgv_to_default_currency', 'wpgv_to_default_currency');
	}
}

function wpgv_to_default_currency($amount)
{
	// WooCommerce Currency Switcher by realmag777
	if (isset($GLOBALS['WOOCS']) && method_exists($GLOBALS['WOOCS'], 'get_currencies') && method_exists($GLOBALS['WOOCS'], 'back_convert')) {
		$cs = $GLOBALS['WOOCS'];
		$default_currency = false;
		$currencies = $cs->get_currencies();

		foreach ($currencies as $currency) {
			if ($currency['is_etalon'] === 1) {
				$default_currency = $currency;
				break;
			}
		}

		if ($default_currency) {
			if ($cs->current_currency != $default_currency['name']) {
				return (float) $cs->back_convert($amount, $currencies[$cs->current_currency]['rate']);
			}
		}
	}

	// Aelia Currency Switcher
	if (class_exists('WC_Aelia_CurrencySwitcher') && isset($GLOBALS['woocommerce-aelia-currencyswitcher'])) {
		$cs = $GLOBALS['woocommerce-aelia-currencyswitcher'];

		$current_currency = $cs->get_selected_currency();
		$base_currency = $cs->base_currency();

		if ($current_currency != $base_currency && !empty($cs->current_exchange_rate())) {
			return (float) number_format((1 / $cs->current_exchange_rate()) * $amount, 6, '.', '');
		}
	}

	// WooCommerce Ultimate Multi Currency Suite
	if (class_exists('WooCommerce_Ultimate_Multi_Currency_Suite_Main') && isset($GLOBALS['woocommerce_ultimate_multi_currency_suite'])) {
		$cs = $GLOBALS['woocommerce_ultimate_multi_currency_suite'];
		if (is_object($cs) && property_exists($cs, 'frontend') && !empty($cs->frontend)) {
			return $cs->frontend->unconvert_price($amount);
		}
	}

	// WPML (WooCommerce Multilingual plugin)
	if (isset($GLOBALS['woocommerce_wpml'])) {
		$wpml = $GLOBALS['woocommerce_wpml'];
		if (is_object($wpml) && property_exists($wpml, 'multi_currency') && is_object($wpml->multi_currency) && property_exists($wpml->multi_currency, 'prices')) {
			$cs = $wpml->multi_currency->prices;
			return $cs->unconvert_price_amount($amount);
		}
	}

	// Multi Currency for WooCommerce by VillaTheme
	if (function_exists('wmc_get_price')) {
		$exchange = wmc_get_price('1');
		return (float) number_format((1 / $exchange) * $amount, 6, '.', '');
	}

	// WooCommerce Price Based on Country by Oscar Gare
	if (function_exists('wcpbc_get_zone_by_country')) {
		$zone = wcpbc_get_zone_by_country();
		if (!empty($zone) && method_exists($zone, 'get_base_currency_amount')) {
			$amount = $zone->get_base_currency_amount($amount);
		}
	}

	// Multi-Currency for WooCommerce by TIV.NET INC
	if (class_exists('WOOMC\App')) {
		$currency_detector = new WOOMC\Currency\Detector();
		$rate_storage = new WOOMC\Rate\Storage();
		$price_rounder = new WOOMC\Price\Rounder();
		$price_calculator = new WOOMC\Price\Calculator($rate_storage, $price_rounder);

		$to = $currency_detector->getDefaultCurrency();
		$from = $currency_detector->currency();

		return $price_calculator->calculate((float) $amount, $to, $from);
	}

	return $amount;
}

function wcml_is_variable_product($is_variable_product, $product_id)
{
	$product = wc_get_product($product_id);
	if (is_a($product, 'wpgv_wc_product_gift_voucher')) {
		$is_variable_product = true;
	}

	return $is_variable_product;
}

function wpgv_to_current_currency($amount)
{
	// WooCommerce Currency Switcher by realmag777
	if (isset($GLOBALS['WOOCS']) && method_exists($GLOBALS['WOOCS'], 'woocs_convert_price')) {
		return $GLOBALS['WOOCS']->woocs_convert_price($amount);
	}

	// Aelia Currency Switcher
	if (class_exists('WC_Aelia_CurrencySwitcher') && isset($GLOBALS['woocommerce-aelia-currencyswitcher'])) {
		$cs = $GLOBALS['woocommerce-aelia-currencyswitcher'];
		return $cs->convert($amount, $cs->base_currency(), $cs->get_selected_currency());
	}

	// WooCommerce Ultimate Multi Currency Suite
	if (class_exists('WooCommerce_Ultimate_Multi_Currency_Suite_Main') && isset($GLOBALS['woocommerce_ultimate_multi_currency_suite'])) {
		$cs = $GLOBALS['woocommerce_ultimate_multi_currency_suite'];
		if (is_object($cs) && property_exists($cs, 'frontend') && !empty($cs->frontend)) {
			return $cs->frontend->convert_price($amount);
		}
	}

	// WPML (WooCommerce Multilingual plugin)
	if (isset($GLOBALS['woocommerce_wpml'])) {
		$wpml = $GLOBALS['woocommerce_wpml'];
		if (is_object($wpml) && property_exists($wpml, 'multi_currency') && is_object($wpml->multi_currency) && property_exists($wpml->multi_currency, 'prices')) {
			$cs = $wpml->multi_currency;
			return $cs->prices->convert_price_amount($amount);
		}
	}

	// Multi Currency for WooCommerce by VillaTheme
	if (function_exists('wmc_get_price')) {
		return wmc_get_price($amount);
	}

	// WooCommerce Price Based on Country by Oscar Gare
	if (function_exists('wcpbc_the_zone')) {
		$zone = wcpbc_the_zone();
		if (!empty($zone) && method_exists($zone, 'get_exchange_rate_price')) {
			return $zone->get_exchange_rate_price($amount);
		}
	}

	// Multi-Currency for WooCommerce by TIV.NET INC
	if (class_exists('WOOMC\App')) {
		$user = WOOMC\App::instance()->getUser();

		$currency_detector = new WOOMC\Currency\Detector();
		$rate_storage = new WOOMC\Rate\Storage();
		$price_rounder = new WOOMC\Price\Rounder();
		$price_calculator = new WOOMC\Price\Calculator($rate_storage, $price_rounder);

		$to = $currency_detector->currency();
		$from = $currency_detector->getDefaultCurrency();

		return $price_calculator->calculate((float) $amount, $to, $from);
	}

	return $amount;
}


add_action('plugins_loaded', 'wpgv_voucher_imagesize_setup');
function wpgv_voucher_imagesize_setup()
{
	add_image_size('voucher-thumb', 300);
	add_image_size('voucher-medium', 450);
}

/** Setting menu link */
add_filter('plugin_action_links_' . plugin_basename(__FILE__), 'wpgv_settings_page_link');
function wpgv_settings_page_link($links)
{
	$links[] = '<a href="' . admin_url('admin.php?page=voucher-setting') . '">' . __('Settings', 'gift-voucher') . '</a>';
	$links[] = '<a href="https://codemenschen.at/docs/wordpress-gift-vouchers-documentation/" target="_blank">' . __('Documentation', 'gift-voucher') . '</a>';
	return $links;
}

function wpgv_front_enqueue()
{
	global $wpdb;
	$setting_table = $wpdb->prefix . 'giftvouchers_setting';
	$text_preview = get_option('wpgv_voucher_text_preview') ? get_option('wpgv_voucher_text_preview') : __('This is preview voucher', 'gift-voucher');
	// number format new
	$wpgv_select_number_format = get_option('wpgv_select_number_format') ? get_option('wpgv_select_number_format') : '';
	$wpgv_company_logo = get_option('wpgv_company_logo') ? get_option('wpgv_company_logo') : '';
	$isRecaptchaEnabled = get_option('wpgv_enable_recaptcha') ? get_option('wpgv_enable_recaptcha') : '';
	$recaptcha_site_key = get_option('wpgv_recaptcha_site_key') ? get_option('wpgv_recaptcha_site_key') : '';
	$recaptcha_secret_key = get_option('wpgv_recaptcha_secret_key') ? get_option('wpgv_recaptcha_secret_key') : '';
	$translations = array(
		'logo_company' => $wpgv_company_logo,
		'number_format' => esc_attr($wpgv_select_number_format),
		'isRecaptchaEnabled' => esc_attr($isRecaptchaEnabled),
		'recaptcha_site_key' => esc_attr($recaptcha_site_key),
		'recaptcha_secret_key' => esc_attr($recaptcha_secret_key),
		'ajaxurl' => admin_url('admin-ajax.php'),
		'barcode_url' => plugins_url() . '/gift-voucher-pro/assets/img/barcode.png',
		'not_equal_email' => __('This email must be different from above email.', 'gift-voucher'),
		'select_template' => __('Please select voucher template', 'gift-voucher'),
		'accept_terms' => __('Please accept the terms and conditions', 'gift-voucher'),
		'accept_recaptcha' => __('Please complete the reCAPTCHA verification.', 'gift-voucher'),
		'finish' => __('Finish', 'gift-voucher'),
		'next' => __('Continue', 'gift-voucher'),
		'previous' => __('Back', 'gift-voucher'),
		'submitted' => __('Submitted!', 'gift-voucher'),
		'error_occur' => __('Error occurred', 'gift-voucher'),
		'total_character' => __('Total Characters', 'gift-voucher'),
		'via_post' => __('Shipping via Post', 'gift-voucher'),
		'via_email' => __('Shipping via Email', 'gift-voucher'),
		'checkemail' => __('Please check email address.', 'gift-voucher'),
		'required' => __('This field is required.', 'gift-voucher'),
		'remote' => __('Please fix this field.', 'gift-voucher'),
		'maxlength' => __('Please enter no more than {0} characters.', 'gift-voucher'),
		'email' => __('Please enter a valid email address.', 'gift-voucher'),
		'max' => __('Please enter a value less than or equal to {0}.', 'gift-voucher'),
		'min' => __('Please enter a value greater than or equal to {0}.', 'gift-voucher'),
		'preview' => $text_preview,
		'text_value' => __('Value', 'gift-voucher'),
		'error_cardnumber' => __('Enter a card number.', 'gift-voucher'),
		'your_name' => __('Your Name', 'gift-voucher'),
		'gift_to' => __('Gift To', 'gift-voucher'),
		'gift_from' => __('Gift From', 'gift-voucher'),
		'min_value' => __('Min value', 'gift-voucher'),
		'future_date' => __('Send on a future date :', 'gift-voucher'),
		'instantly' => __('Send Instantly', 'gift-voucher'),
		'languages' => get_locale(),

	);
	wp_register_style('wpgv-voucher-style',  WPGIFT__PLUGIN_URL . '/assets/css/voucher-style.css');
	wp_register_style('wpgv-item-style',  WPGIFT__PLUGIN_URL . '/assets/css/item-style.css');
	wp_register_style('wpgv-bootstrap-css',  WPGIFT__PLUGIN_URL . '/assets/css/bootstrap.min.css');
	wp_register_style('wpgv-fontawesome-css',  WPGIFT__PLUGIN_URL . '/assets/css/font-awesome.min.css');
	wp_register_style('wpgv-bootstrap-datetimepicker-css',  WPGIFT__PLUGIN_URL . '/assets/css/bootstrap-datetimepicker.min.css');
	wp_register_style('wpgv-slick-css',  WPGIFT__PLUGIN_URL . '/assets/css/slick.css');
	wp_register_style('wpgv-voucher-template-fonts-css',  WPGIFT__PLUGIN_URL . '/assets/css/voucher-template-fonts.css');
	wp_register_style('wpgv-voucher-template-style-css',  WPGIFT__PLUGIN_URL . '/assets/css/voucher-template-style.css');
	wp_register_script('wpgv-bootstrap-js', WPGIFT__PLUGIN_URL  . '/assets/js/bootstrap.min.js', array('jquery'), '1.17.0', true);
	wp_register_script('wpgv-moment-js', WPGIFT__PLUGIN_URL  . '/assets/js/moment.min.js', array('jquery'), '1.17.0', true);
	wp_register_script('wpgv-konva-min-js', WPGIFT__PLUGIN_URL  . '/assets/js/konva.min.js', array('jquery'), '1.17.0', true);
	wp_register_script('wpgv-jspdf-js', 'https://cdnjs.cloudflare.com/ajax/libs/jspdf/1.5.3/jspdf.debug.js', array('jquery'), '1.5.3', true);
	wp_register_script('wpgv-bootstrap-datetimepicker-js', WPGIFT__PLUGIN_URL  . '/assets/js/bootstrap-datetimepicker.min.js', array('jquery'), '1.17.0', true);
	wp_register_script('wpgv-jquery-validate', WPGIFT__PLUGIN_URL  . '/assets/js/jquery.validate.min.js', array('jquery'), '1.17.0', true);
	wp_register_script('wpgv-jquery-steps', WPGIFT__PLUGIN_URL  . '/assets/js/jquery.steps.min.js', array('jquery'), '1.1.0', true);
	wp_register_script('wpgv-datetimepicker-language', WPGIFT__PLUGIN_URL  . '/assets/js/bootstrap-datetimepicker.languages.js', array('jquery'), '1.1.0', true);

	$setting_options = $wpdb->get_row("SELECT * FROM $setting_table WHERE id = 1");
	if ($setting_options->stripe) {
		wp_register_script('wpgv-stripe-js', 'https://js.stripe.com/v3/', array('jquery'), NULL, true);
	}
	wp_register_script('wpgv-slick-script', WPGIFT__PLUGIN_URL  . '/assets/js/slick.min.js', array('jquery'), WPGIFT_VERSION, true);
	wp_register_script('wpgv-voucher-script', WPGIFT__PLUGIN_URL  . '/assets/js/voucher-script.js', array('jquery'), WPGIFT_VERSION, true);
	wp_register_script('wpgv-voucher-template-script', WPGIFT__PLUGIN_URL  . '/assets/js/voucher-template-script.js', array('jquery'), WPGIFT_VERSION, true);

	wp_register_script('wpgv-item-script', WPGIFT__PLUGIN_URL  . '/assets/js/item-script.js', array('jquery'), WPGIFT_VERSION, true);
	wp_register_script('wpgv-woocommerce-script', WPGIFT__PLUGIN_URL  . '/assets/js/woocommerce-script.js', array('jquery'), WPGIFT_VERSION, true);
	wp_register_script('wpgv-voucher-product', WPGIFT__PLUGIN_URL  . '/assets/js/wpgv-voucher-product.js', array('jquery'), WPGIFT_VERSION, true);
	// Klarna helper for handling Payments v1 authorization
	wp_register_script('wpgv-klarna', WPGIFT__PLUGIN_URL . '/assets/js/wpgv-klarna.js', array('jquery'), WPGIFT_VERSION, true);
	wp_enqueue_script('wpgv-klarna');
	wp_localize_script('wpgv-klarna', 'wpgv_klarna_vars', array(
		'ajaxurl' => admin_url('admin-ajax.php'),
		'nonce' => wp_create_nonce('wpgv_klarna_authorize')
	));
	wp_register_script('wpgv-klarna-debug', WPGIFT__PLUGIN_URL . '/assets/js/wpgv-klarna-debug.js', array(), WPGIFT_VERSION, true);
	wp_enqueue_script('wpgv-klarna-debug');

	wp_localize_script('wpgv-voucher-script', 'frontend_ajax_object', $translations);
	wp_localize_script('wpgv-voucher-template-script', 'frontend_ajax_object', $translations);
	wp_localize_script('wpgv-item-script', 'frontend_ajax_object', $translations);
	wp_localize_script('wpgv-woocommerce-script', 'frontend_ajax_object', $translations);
	if (wpgv_is_woocommerce_enable()) {
		$check_plugin = new WPGV_Check_Plugin_Active();
		if ($check_plugin->wpgv_check_woo_active()) {
			wp_localize_script('wpgv-voucher-product', 'wpgv', array(
				'ajaxurl'                       => admin_url('admin-ajax.php', 'relative'),
				'denomination_attribute_slug'   => WPGV_DENOMINATION_ATTRIBUTE_SLUG,
				'decimal_places'                => wc_get_price_decimals(),
				'max_message_characters'        => WPGV_MAX_MESSAGE_CHARACTERS,
				'i18n'                          => array(
					'custom_amount_required_error' => __('Required', 'gift-voucher'),
					'min_amount_error'          => sprintf(__('Minimum amount is %s', 'gift-voucher'), get_woocommerce_currency_symbol()),
					'max_amount_error'          => sprintf(__('Maximum amount is %s', 'gift-voucher'), get_woocommerce_currency_symbol()),
					'invalid_recipient_error'   => __('The "To" field should only contain email addresses. The following recipients do not look like valid email addresses:', 'gift-voucher'),
				),
				'nonces' => array(
					'check_balance'             => wp_create_nonce('wpgv-gift-cards-check-balance'),
					'apply_gift_card'           => wp_create_nonce('wpgv-gift-cards-apply-gift-card'),
					'remove_card'               => wp_create_nonce('wpgv-gift-cards-remove-card'),
				)
			));
		}
	}
}
add_action('wp_enqueue_scripts', 'wpgv_front_enqueue');

// Conditional asset loading to prevent conflicts with other plugins
function wpgv_conditional_asset_loading()
{
	// Only load assets when needed to prevent conflicts with other plugins
	if (
		is_admin() ||
		is_page('gift-voucher') ||
		is_singular('voucher_template') ||
		(isset($_GET['post_type']) && $_GET['post_type'] == 'voucher_template') ||
		(function_exists('is_woocommerce') && is_woocommerce() && is_checkout()) ||
		(isset($_GET['action']) && $_GET['action'] == 'preview')
	) {

		// Load fonts with conditional loading
		wp_enqueue_style('wpgv-voucher-template-fonts-css', WPGIFT__PLUGIN_URL . '/assets/css/voucher-template-fonts.css');

		// Load Font Awesome with conditional loading
		wp_enqueue_style('wpgv-fontawesome-css', WPGIFT__PLUGIN_URL . '/assets/css/font-awesome.min.css');

		// Load jsPDF with conditional loading
		wp_enqueue_script('wpgv-jspdf-js', 'https://cdnjs.cloudflare.com/ajax/libs/jspdf/1.5.3/jspdf.debug.js', array('jquery'), '1.5.3', true);

		// Load PDF isolation script to prevent conflicts
		wp_enqueue_script('wpgv-pdf-isolation', WPGIFT__PLUGIN_URL . '/assets/js/wpgv-pdf-isolation.js', array('wpgv-jspdf-js'), WPGIFT_VERSION, true);
	}
}
add_action('wp_enqueue_scripts', 'wpgv_conditional_asset_loading', 999);

function wpgv_plugin_activation()
{
	global $wpdb;
	global $jal_db_version;

	$giftvouchers_setting = $wpdb->prefix . 'giftvouchers_setting';
	$giftvouchers_list = $wpdb->prefix . 'giftvouchers_list';
	$giftvouchers_template = $wpdb->prefix . 'giftvouchers_template';
	$giftvouchers_activity = $wpdb->prefix . 'giftvouchers_activity';
	$giftvouchers_invoice_settings = $wpdb->prefix . 'giftvouchers_invoice_settings';
	$charset_collate = $wpdb->get_charset_collate();

	$giftvouchers_setting_sql = "CREATE TABLE $giftvouchers_setting (
        id int(11) NOT NULL AUTO_INCREMENT,
        is_woocommerce_enable int(1) DEFAULT 0,
        is_stripe_enable int(1) DEFAULT 0,
		is_order_form_enable int(1) DEFAULT 1,
        is_style_choose_enable int(1) DEFAULT 0,
        voucher_style varchar(100) DEFAULT 0,
        company_name varchar(255) DEFAULT NULL,
        currency_code varchar(10) DEFAULT NULL,
        currency varchar(10) DEFAULT NULL,
        currency_position varchar(10) DEFAULT NULL,
        voucher_bgcolor varchar(6) DEFAULT NULL,
        voucher_color varchar(6) DEFAULT NULL,
        template_col int(2) DEFAULT 3,
        voucher_min_value int(4) DEFAULT NULL,
        voucher_max_value int(6) DEFAULT NULL,
        voucher_expiry_type varchar(6) DEFAULT NULL,
        voucher_expiry varchar(10) DEFAULT NULL,
        voucher_terms_note text DEFAULT NULL,
        custom_loader text DEFAULT NULL,
        pdf_footer_url varchar(255) DEFAULT NULL,
        pdf_footer_email varchar(255) DEFAULT NULL,
        post_shipping int(1) DEFAULT NULL,
        shipping_method text DEFAULT NULL,
        preview_button int(1) DEFAULT 1,
        paypal int(11) DEFAULT NULL,
        sofort int(11) DEFAULT NULL,
        stripe int(11) DEFAULT NULL,
        paypal_email varchar(100) DEFAULT NULL,
        sofort_configure_key varchar(255) DEFAULT NULL,
        reason_for_payment varchar(255) DEFAULT NULL,
        stripe_publishable_key varchar(255) DEFAULT NULL,
        stripe_secret_key varchar(255) DEFAULT NULL,
        sender_name varchar(255) DEFAULT NULL,
        sender_email varchar(255) DEFAULT NULL,
        test_mode int(10) NOT NULL,
        per_invoice int(10) NOT NULL,
        bank_info longtext,
        landscape_mode_templates text DEFAULT NULL,
        portrait_mode_templates text DEFAULT NULL,
        PRIMARY KEY (id)
    ) $charset_collate;";

	$giftvouchers_list_sql = "CREATE TABLE $giftvouchers_list (
        id int(11) NOT NULL AUTO_INCREMENT,
		order_type enum('items', 'vouchers','gift_voucher_product') NOT NULL DEFAULT 'vouchers',
        template_id int(11) NOT NULL,
		product_id int(11) NOT NULL,
        order_id int(11) NOT NULL,
        itemcat_id int(11) NOT NULL,
        item_id int(11) NOT NULL,
        buying_for enum('someone_else', 'yourself') NOT NULL DEFAULT 'someone_else',
        from_name varchar(255) NOT NULL,
        to_name varchar(255) NOT NULL,
        amount float NOT NULL,
        message text NOT NULL,
        firstname varchar(255) NOT NULL,
        lastname varchar(255) NOT NULL,
        email varchar(255) NOT NULL,
        address text NOT NULL,
        postcode varchar(30) NOT NULL,
        pay_method varchar(255) NOT NULL,
        shipping_type enum('shipping_as_email', 'shipping_as_post') NOT NULL DEFAULT 'shipping_as_email',
        shipping_email varchar(255) NOT NULL,
        shipping_method varchar(255) NOT NULL,
        expiry varchar(100) NOT NULL,
        couponcode bigint(25) NOT NULL,
        voucherpdf_link text NOT NULL,
        voucheradd_time timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP,
        status varchar(10) NOT NULL DEFAULT 'unused',
        payment_status varchar(10) NOT NULL DEFAULT 'Not Pay',
        email_send_date_time varchar(30) NOT NULL DEFAULT 'send_instantly',
        check_send_mail varchar(30) NOT NULL DEFAULT 'unsent',
        PRIMARY KEY (id)
    ) $charset_collate;";

	$giftvouchers_template_sql = "CREATE TABLE $giftvouchers_template (
        id int(11) NOT NULL AUTO_INCREMENT,
        title text NOT NULL,
        image int(11) DEFAULT NULL,
        image_style varchar(100) DEFAULT NULL,
        orderno int(11) NOT NULL DEFAULT '0',
        active int(11) NOT NULL DEFAULT '0',
        templateadd_time timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP,
		check_update int(11) NOT NULL DEFAULT '0',
        PRIMARY KEY (id)
    ) $charset_collate;";

	$giftvouchers_activity_sql = "CREATE TABLE $giftvouchers_activity (
        id int(11) NOT NULL AUTO_INCREMENT,
        voucher_id int(11) NOT NULL,
        user_id int(11) NOT NULL,
        action varchar(60) DEFAULT NULL,
        amount decimal(15,6),
        note text NOT NULL,
        activity_date timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP,
        PRIMARY KEY (id)
    ) $charset_collate;";

	$giftvouchers_invoice_settings_sql = "CREATE TABLE $giftvouchers_invoice_settings (
        id int(11) NOT NULL AUTO_INCREMENT,
        is_invoice_active int(11) NOT NULL DEFAULT 0,
        company_name varchar(255) DEFAULT NULL,
        invoice_color varchar(255) DEFAULT NULL,
        company_logo varchar(255) DEFAULT NULL,
        address_line1 varchar(255) DEFAULT NULL,
        address_line2 varchar(255) DEFAULT NULL,
        address_line3 varchar(255) DEFAULT NULL,
        address_line4 varchar(255) DEFAULT NULL,
        bottom_line varchar(255) DEFAULT NULL,
        PRIMARY KEY (id)
    ) $charset_collate;";
	require_once(ABSPATH . 'wp-admin/includes/upgrade.php');
	dbDelta($giftvouchers_setting_sql);
	dbDelta($giftvouchers_list_sql);
	dbDelta($giftvouchers_template_sql);
	dbDelta($giftvouchers_activity_sql);
	dbDelta($giftvouchers_invoice_settings_sql);
	add_option('jal_db_version', $jal_db_version);

	$demoimageurl = get_option('wpgv_demoimageurl') ? get_option('wpgv_demoimageurl') : WPGIFT__PLUGIN_URL . '/assets/img/demo.png';
	update_option('wpgv_demoimageurl', $demoimageurl);
	// set template lanscape
	$template_lanscape = 'template-custom-lanscape.png, template-voucher-lanscape-1.png, template-voucher-lanscape-2.png, template-voucher-lanscape-3.png, template-voucher-lanscape-4.png, template-voucher-lanscape-5.png, template-voucher-lanscape-6.png, template-voucher-lanscape-7.png, template-voucher-lanscape-8.png, template-voucher-lanscape-9.png, template-voucher-lanscape-10.png, template-voucher-lanscape-11.png, template-voucher-lanscape-12.png, template-voucher-lanscape-13.png, template-voucher-lanscape-14.png, template-voucher-lanscape-15.png, template-voucher-lanscape-16.png, template-voucher-lanscape-17.png, template-voucher-lanscape-18.png, template-voucher-lanscape-19.png, template-voucher-lanscape-20.png, template-voucher-lanscape-21.png, template-voucher-lanscape-22.png, template-voucher-lanscape-23.png, template-voucher-lanscape-24.png, template-voucher-lanscape-25.png, template-voucher-lanscape-26.png, template-voucher-lanscape-27.png, template-voucher-lanscape-28.png, template-voucher-lanscape-29.png, template-voucher-lanscape-30.png, template-voucher-lanscape-31.png, template-voucher-lanscape-32.png, template-voucher-lanscape-33.png, template-voucher-lanscape-34.png, template-voucher-lanscape-35.png, template-voucher-lanscape-36.png, template-voucher-lanscape-37.png, template-voucher-lanscape-37.png, template-voucher-lanscape-38.png, template-voucher-lanscape-39.png, template-voucher-lanscape-40.png, template-voucher-lanscape-41.png, template-voucher-lanscape-42.png, template-voucher-lanscape-43.png, template-voucher-lanscape-44.png, template-voucher-lanscape-45.png, template-voucher-lanscape-46.png, template-voucher-lanscape-47.png, template-voucher-lanscape-48.png, template-voucher-lanscape-49.png, template-voucher-lanscape-50.png, template-voucher-lanscape-51.png, template-voucher-lanscape-52.png, template-voucher-lanscape-53.png';
	$template_portail = 'template-custom-portail.png, template-voucher-portail-1.png, template-voucher-portail-2.png, template-voucher-portail-3.png, template-voucher-portail-4.png, template-voucher-portail-5.png, template-voucher-portail-6.png, template-voucher-portail-7.png, template-voucher-portail-8.png, template-voucher-portail-9.png, template-voucher-portail-10.png, template-voucher-portail-11.png, template-voucher-portail-12.png, template-voucher-portail-13.png, template-voucher-portail-14.png, template-voucher-portail-15.png, template-voucher-portail-16.png, template-voucher-portail-17.png, template-voucher-portail-18.png, template-voucher-portail-19.png, template-voucher-portail-20.png, template-voucher-portail-21.png, template-voucher-portail-22.png, template-voucher-portail-23.png, template-voucher-portail-24.png, template-voucher-portail-25.png, template-voucher-portail-26.png, template-voucher-portail-27.png, template-voucher-portail-28.png, template-voucher-portail-29.png, template-voucher-portail-30.png, template-voucher-portail-31.png, template-voucher-portail-32.png, template-voucher-portail-33.png, template-voucher-portail-34.png, template-voucher-portail-35.png, template-voucher-portail-36.png, template-voucher-portail-37.png, template-voucher-portail-38.png, template-voucher-portail-39.png, template-voucher-portail-40.png, template-voucher-portail-41.png, template-voucher-portail-42.png, template-voucher-portail-43.png, template-voucher-portail-44.png, template-voucher-portail-45.png';
	$company_name = get_bloginfo('name');
	$paypal_email = get_option('admin_email');

	if (!$wpdb->get_var("SELECT * FROM $giftvouchers_setting WHERE id = 1")) {
		$wpdb->insert(
			$giftvouchers_setting,
			array(
				'is_woocommerce_enable' => 0,
				'is_stripe_enable' => 0,
				'is_order_form_enable' => 1,
				'is_style_choose_enable' => 0,
				'voucher_style'      => 0,
				'company_name'       => $company_name,
				'paypal_email'       => $paypal_email,
				'reason_for_payment' => 'Payment for Gift Cards',
				'sender_name'        => $company_name,
				'sender_email'       => $paypal_email,
				'currency_code'      => 'USD',
				'currency'           => '$',
				'paypal'             => 1,
				'sofort'             => 0,
				'stripe'             => 0,
				'voucher_bgcolor'    => '81c6a9',
				'voucher_color'      => '555555',
				'template_col'       => 4,
				'voucher_min_value'  => 0,
				'voucher_max_value'  => 10000,
				'voucher_expiry_type' => 'days',
				'voucher_expiry'     => 60,
				'voucher_terms_note' => 'Note: The voucher is valid for 60 days and can be redeemed at ' . $company_name . '. A cash payment is not possible.',
				'custom_loader'      => WPGIFT__PLUGIN_URL . '/assets/img/loader.gif',
				'pdf_footer_url'     => get_site_url(),
				'pdf_footer_email'   => $paypal_email,
				'post_shipping'      => 1,
				'shipping_method'    => '5.99 : Express Shipping - $5.99, 3.99 : Standard Shipping - $3.99',
				'preview_button'     => 1,
				'currency_position'  => 'Left',
				'test_mode'          => 0,
				'per_invoice'        => 0,
				'landscape_mode_templates' => $template_lanscape,
				'portrait_mode_templates' => $template_portail,
			)
		);
		$wpdb->insert(
			$giftvouchers_template,
			array(
				'title'  => "Demo Template",
				'active' => 1,
			)
		);
	}
	// Check and update template
	$data_setting = $wpdb->get_row("SELECT * FROM $giftvouchers_setting WHERE id = 1");
	if (empty($data_setting->landscape_mode_templates)) {
		$wpdb->update(
			$giftvouchers_setting,
			array(
				'landscape_mode_templates' => $template_lanscape,
				'portrait_mode_templates' => $template_portail,
			),
			array('id' => 1)
		);
	} else {
		$wpdb->update(
			$giftvouchers_setting,
			array(
				'landscape_mode_templates' => $template_lanscape,
				'portrait_mode_templates' => $template_portail,
			),
			array('id' => 1)
		);
	}
	//setting database json
	$upload = wp_upload_dir();
	$upload_dir = $upload['basedir'];
	$upload_dir = $upload_dir . '/voucherpdfuploads';
	if (!is_dir($upload_dir)) {
		mkdir($upload_dir, 0755);
		$file = fopen($upload_dir . '/index.html', "wb");
		fwrite($file, "Silence is golden.");
		fclose($file);
	}

	if (!wp_next_scheduled('wpgv_check_voucher_status')) {
		wp_schedule_event(time(), 'hourly', 'wpgv_check_voucher_status');
	}
	set_transient('wpgv_activated', 1);
	require_once(WPGIFT__PLUGIN_DIR . '/classes/class-nag.php');
	WPGIFT_Nag::insert_install_date();
	wpgv_check_template_fields();
}
register_activation_hook(__FILE__, 'wpgv_plugin_activation');

function wpgv_upgrade_completed($upgrader_object, $options)
{
	// The path to our plugin's main file
	$our_plugin = plugin_basename(__FILE__);
	// If an update has taken place and the updated type is plugins and the plugins element exists
	if ($options['action'] == 'update' && $options['type'] == 'plugin' && isset($options['plugins'])) {

		// Iterate through the plugins being updated and check if ours is there
		foreach ($options['plugins'] as $plugin) {
			if ($plugin == $our_plugin) {
				global $wpdb;
				$giftvouchers_setting = $wpdb->prefix . 'giftvouchers_setting';
				$giftvouchers_list = $wpdb->prefix . 'giftvouchers_list';
				$giftvouchers_template = $wpdb->prefix . 'giftvouchers_template';
				$giftvouchers_activity = $wpdb->prefix . 'giftvouchers_activity';
				$giftvouchers_invoice_settings = $wpdb->prefix . 'giftvouchers_invoice_settings';
				$charset_collate = $wpdb->get_charset_collate();
				$giftvouchers_activity_sql = "CREATE TABLE IF NOT EXISTS $giftvouchers_activity (
					id int(11) NOT NULL AUTO_INCREMENT,
					voucher_id int(11) NOT NULL,
					user_id int(11) NOT NULL,
					action varchar(60) DEFAULT NULL,
					amount decimal(15,6),
					note text NOT NULL,
					activity_date timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP,
					PRIMARY KEY (id)
				) $charset_collate;";

				require_once(ABSPATH . 'wp-admin/includes/upgrade.php');
				dbDelta($giftvouchers_activity_sql);

				// Helper: add column only if it does not exist
				$add_column_if_not_exists = function ($table, $column, $sql) use ($wpdb) {
					$col = $wpdb->get_row("SHOW COLUMNS FROM `$table` LIKE '$column'");
					if (!$col) {
						$wpdb->query($sql);
					}
				};

				// Helper: modify column only if the column already exists (safer for different schema versions)
				$modify_column_if_exists = function ($table, $column, $sql) use ($wpdb) {
					$col = $wpdb->get_row("SHOW COLUMNS FROM `$table` LIKE '$column'");
					if ($col) {
						$wpdb->query($sql);
					}
				};

				$add_column_if_not_exists($giftvouchers_template, 'image_style', "ALTER TABLE $giftvouchers_template ADD image_style varchar(100) DEFAULT NULL");
				$add_column_if_not_exists($giftvouchers_template, 'check_update', "ALTER TABLE $giftvouchers_template ADD check_update int(11) DEFAULT 0");
				$add_column_if_not_exists($giftvouchers_setting, 'is_woocommerce_enable', "ALTER TABLE $giftvouchers_setting ADD is_woocommerce_enable int(1) DEFAULT 0");
				$add_column_if_not_exists($giftvouchers_setting, 'post_shipping', "ALTER TABLE $giftvouchers_setting ADD post_shipping int(1) DEFAULT 0");
				$add_column_if_not_exists($giftvouchers_setting, 'preview_button', "ALTER TABLE $giftvouchers_setting ADD preview_button int(1) DEFAULT 1");
				$add_column_if_not_exists($giftvouchers_setting, 'pdf_footer_url', "ALTER TABLE $giftvouchers_setting ADD pdf_footer_url varchar(255) DEFAULT NULL");
				$add_column_if_not_exists($giftvouchers_setting, 'is_woocommerce_enable', "ALTER TABLE $giftvouchers_setting ADD is_woocommerce_enable varchar(255) DEFAULT NULL");
				$add_column_if_not_exists($giftvouchers_setting, 'is_style_choose_enable', "ALTER TABLE $giftvouchers_setting ADD is_style_choose_enable int(1) DEFAULT 0");
				$add_column_if_not_exists($giftvouchers_setting, 'voucher_style', "ALTER TABLE $giftvouchers_setting ADD voucher_style varchar(100) DEFAULT NULL");
				$add_column_if_not_exists($giftvouchers_setting, 'currency', "ALTER TABLE $giftvouchers_setting ADD currency varchar(10) DEFAULT NULL");
				$add_column_if_not_exists($giftvouchers_setting, 'currency_code', "ALTER TABLE $giftvouchers_setting ADD currency_code varchar(10) DEFAULT NULL");
				$add_column_if_not_exists($giftvouchers_list, 'email_send_date_time', "ALTER TABLE $giftvouchers_list ADD email_send_date_time varchar(30) NOT NULL DEFAULT 'send_instantly'");

				$add_column_if_not_exists($giftvouchers_setting, 'is_stripe_enable', "ALTER TABLE $giftvouchers_setting ADD COLUMN is_stripe_enable int(1) DEFAULT 0");
				$add_column_if_not_exists($giftvouchers_setting, 'is_order_form_enable', "ALTER TABLE $giftvouchers_setting ADD COLUMN is_order_form_enable int(1) DEFAULT 1");

				// For MODIFY statements, only run if the target column exists (to avoid SQL errors on missing tables/columns)
				$modify_column_if_exists($giftvouchers_list, 'order_type', "ALTER TABLE $giftvouchers_list MODIFY COLUMN order_type enum('items','vouchers','gift_voucher_product')");
				$modify_column_if_exists($giftvouchers_setting, 'stripe_publishable_key', "ALTER TABLE $giftvouchers_setting MODIFY COLUMN stripe_publishable_key varchar(255) DEFAULT NULL");
				$modify_column_if_exists($giftvouchers_setting, 'stripe_secret_key', "ALTER TABLE $giftvouchers_setting MODIFY COLUMN stripe_secret_key varchar(255) DEFAULT NULL");

				// Make sure invoice settings table is defined and exists before attempting MODIFY on it
				if ($giftvouchers_invoice_settings && $wpdb->get_var($wpdb->prepare("SHOW TABLES LIKE %s", $giftvouchers_invoice_settings))) {
					$modify_column_if_exists($giftvouchers_invoice_settings, 'company_name', "ALTER TABLE $giftvouchers_invoice_settings MODIFY COLUMN company_name varchar(255) DEFAULT NULL");
					$modify_column_if_exists($giftvouchers_invoice_settings, 'invoice_color', "ALTER TABLE $giftvouchers_invoice_settings MODIFY COLUMN invoice_color varchar(255) DEFAULT NULL");
					$modify_column_if_exists($giftvouchers_invoice_settings, 'company_logo', "ALTER TABLE $giftvouchers_invoice_settings MODIFY COLUMN company_logo varchar(255) DEFAULT NULL");
					$modify_column_if_exists($giftvouchers_invoice_settings, 'address_line1', "ALTER TABLE $giftvouchers_invoice_settings MODIFY COLUMN address_line1 varchar(255) DEFAULT NULL");
					$modify_column_if_exists($giftvouchers_invoice_settings, 'address_line2', "ALTER TABLE $giftvouchers_invoice_settings MODIFY COLUMN address_line2 varchar(255) DEFAULT NULL");
					$modify_column_if_exists($giftvouchers_invoice_settings, 'address_line3', "ALTER TABLE $giftvouchers_invoice_settings MODIFY COLUMN address_line3 varchar(255) DEFAULT NULL");
					$modify_column_if_exists($giftvouchers_invoice_settings, 'address_line4', "ALTER TABLE $giftvouchers_invoice_settings MODIFY COLUMN address_line4 varchar(255) DEFAULT NULL");
					$modify_column_if_exists($giftvouchers_invoice_settings, 'bottom_line', "ALTER TABLE $giftvouchers_invoice_settings MODIFY COLUMN bottom_line varchar(255) DEFAULT NULL");
				}

				$orders = $wpdb->get_results("SELECT id,from_name,amount FROM $giftvouchers_list WHERE id NOT IN (SELECT voucher_id FROM $giftvouchers_activity) AND `status` = 'unused' AND `payment_status` = 'Paid'");
				foreach ($orders as $order) {
					WPGV_Gift_Voucher_Activity::record($order->id, 'create', '', 'Voucher ordered by' . $order->from_name);
					WPGV_Gift_Voucher_Activity::record($order->id, 'transaction', $order->amount, 'Voucher payment recieved.');
				}

				$templates = $wpdb->get_results("SELECT id,image FROM $giftvouchers_template WHERE `image_style` IS NULL");
				foreach ($templates as $template) {
					$wpdb->update(
						$giftvouchers_template,
						array(
							'image_style' => '["' . $template->image . '","",""]',
						),
						array('id' => $template->id)
					);
				}

				// Set a transient to record that our plugin has just been updated
				set_transient('wpgv_updated', 1);
			}
			wpgv_check_template_fields();
		}
	}
}
add_action('upgrader_process_complete', 'wpgv_upgrade_completed', 10, 2);


function wpgv_check_template_fields()
{
	global $wpdb;

	$giftvouchers_template = $wpdb->prefix . 'giftvouchers_template';
	$wp_posts = $wpdb->prefix . 'posts';
	$wp_postmeta = $wpdb->prefix . 'postmeta';

	// Get all posts with post_type = 'wpgv_voucher_product'
	$posts = get_posts(array(
		'post_type' => 'wpgv_voucher_product',
		'posts_per_page' => -1
	));

	foreach ($posts as $post) {
		// Create 'gift_items' meta_key for each post
		add_post_meta($post->ID, 'wpgv_templates_style', 'gift_items');
	}

	// Select all fields from giftvouchers_template where check_update = 0
	$templates = $wpdb->get_results("SELECT * FROM $giftvouchers_template WHERE check_update = 0");

	foreach ($templates as $template) {
		// Check if all fields have check_update = 0
		if ($template->check_update == 0) {
			// Create new post
			$post_title = $template->title;
			$post_status = $template->active == 1 ? 'publish' : 'draft';
			$post_type = 'wpgv_voucher_product';

			$post_data = array(
				'post_title' => $post_title,
				'post_status' => $post_status,
				'post_type' => $post_type
			);

			// Insert new post
			$post_id = wp_insert_post($post_data);

			if ($post_id) {
				// Update check_update field to 1 in giftvouchers_template
				$wpdb->update(
					$giftvouchers_template,
					array('check_update' => 1),
					array('id' => $template->id)
				);

				// Update image_style to wp_postmeta
				$image_styles = json_decode($template->image_style);

				if (is_array($image_styles)) {
					foreach ($image_styles as $index => $image_style) {
						$meta_key = 'style' . ($index + 1) . '_image';
						$meta_value = $image_style;

						// Insert post meta
						add_post_meta($post_id, $meta_key, $meta_value);
					}
				}
				add_post_meta($post_id, 'wpgv_templates_style', 'gift_voucher');
			}
		}
	}
}

function wpgv_check_template_fields_column()
{
	if (is_user_logged_in()) {
		global $wpdb;
		$giftvouchers_template = $wpdb->prefix . 'giftvouchers_template';

		// Check if the 'check_update' column exists in the 'giftvouchers_template' table
		$check_update_column_exists = $wpdb->get_var("SHOW COLUMNS FROM $giftvouchers_template LIKE 'check_update'");

		if (!$check_update_column_exists) {
			// The 'check_update' column does not exist, so add it to the table
			$wpdb->query("ALTER TABLE $giftvouchers_template ADD check_update int(11) DEFAULT 0");

			$wp_posts = $wpdb->prefix . 'posts';
			$wp_postmeta = $wpdb->prefix . 'postmeta';

			// Get all posts with post_type = 'wpgv_voucher_product'
			$posts = get_posts(array(
				'post_type' => 'wpgv_voucher_product',
				'posts_per_page' => -1
			));

			foreach ($posts as $post) {
				// Create 'gift_items' meta_key for each post
				add_post_meta($post->ID, 'wpgv_templates_style', 'gift_items');
			}

			// Select all fields from giftvouchers_template where check_update = 0
			$templates = $wpdb->get_results("SELECT * FROM $giftvouchers_template WHERE check_update = 0");

			foreach ($templates as $template) {
				// Check if all fields have check_update = 0
				if ($template->check_update == 0) {
					// Create new post
					$post_title = $template->title;
					$post_status = $template->active == 1 ? 'publish' : 'draft';
					$post_type = 'wpgv_voucher_product';

					$post_data = array(
						'post_title' => $post_title,
						'post_status' => $post_status,
						'post_type' => $post_type
					);

					// Insert new post
					$post_id = wp_insert_post($post_data);

					if ($post_id) {
						// Update check_update field to 1 in giftvouchers_template
						$wpdb->update(
							$giftvouchers_template,
							array('check_update' => 1),
							array('id' => $template->id)
						);

						// Update image_style to wp_postmeta
						$image_styles = json_decode($template->image_style);

						if (is_array($image_styles)) {
							foreach ($image_styles as $index => $image_style) {
								$meta_key = 'style' . ($index + 1) . '_image';
								$meta_value = $image_style;

								// Insert post meta
								add_post_meta($post_id, $meta_key, $meta_value);
							}
						}
						add_post_meta($post_id, 'wpgv_templates_style', 'gift_voucher');
					}
				}
			}
		}
	}
}

// Hook the function to the appropriate action hook
add_action('init', 'wpgv_check_template_fields_column');



function wpgv_display_update_notice()
{
	if (get_transient('wpgv_updated')) {
		$current_user_id = get_current_user_id();
		$dismissed = is_user_logged_in() ? get_user_meta($current_user_id, 'wpgv_dismissed_notices', true) : array();
		if (!is_array($dismissed)) {
			$dismissed = array();
		}

		$class = 'notice notice-info';
		$message = sprintf('Thanks for Updating <b>Gift Cards</b> plugin. Please see the new plugin settings features from <a href="%s" target="_blank">here</a>. We upgraded PayPal (New Checkout) and Stripe (SCA-ready) payment process so you need to update the fields of these payment methods in the settings page. Please see here the documentation of new payment settings <a href="%s" target="_blank">here</a>.<br><br>We have noticed that you have been using Gift Cards plugin from long time. We hope you love it, and we would really appreciate it if you would <a href="%s" target="_blank">give us a 5 stars rating</a>.', admin_url('admin.php') . '?page=voucher-setting', 'https://www.codemenschen.at/docs/wordpress-gift-vouchers-documentation/plugin-settings/payment-settings/', 'https://wordpress.org/support/plugin/gift-voucher/reviews/#new-post');

		$notice_id = 'wpgv_update_notice';
		if (!in_array($notice_id, $dismissed)) {
			printf('<div id="%1$s" class="%2$s is-dismissible"><p>%3$s</p></div>', esc_attr($notice_id), esc_attr($class), $message);
		}

		delete_transient('wpgv_updated');
	}
}
add_action('admin_notices', 'wpgv_display_update_notice');

function wpgv_display_install_notice()
{
	if (get_transient('wpgv_activated')) {
		$current_user_id = get_current_user_id();
		$dismissed = is_user_logged_in() ? get_user_meta($current_user_id, 'wpgv_dismissed_notices', true) : array();
		if (!is_array($dismissed)) {
			$dismissed = array();
		}

		$class = 'notice notice-info';
		$message = sprintf('Thanks for Installing <b>Gift Cards</b> plugin. Please setup your plugin settings from <a href="%s" target="_blank">here</a>.', admin_url('admin.php') . '?page=voucher-setting');

		$notice_id = 'wpgv_install_notice';
		if (!in_array($notice_id, $dismissed)) {
			printf('<div id="%1$s" class="%2$s is-dismissible"><p>%3$s</p></div>', esc_attr($notice_id), esc_attr($class), $message);
		}

		delete_transient('wpgv_activated');
	}
}
add_action('admin_notices', 'wpgv_display_install_notice');

function wpgv_plugin_deactivation()
{
	wp_clear_scheduled_hook('wpgv_check_voucher_status');
}
register_deactivation_hook(__FILE__, 'wpgv_plugin_deactivation');

add_action('init', 'wpgv_do_output_buffer');
function wpgv_do_output_buffer()
{
	ob_start();
}

// Filter page template
add_filter('page_template', 'wpgv_catch_plugin_template');

// Page template filter callback
function wpgv_catch_plugin_template($template)
{
	if (is_page_template('wpgv_voucher_pdf.php')) {
		$template = WPGIFT__PLUGIN_DIR . '/templates/wpgv_voucher_pdf.php';
	} elseif (is_page_template('wpgv_item_pdf.php')) {
		$template = WPGIFT__PLUGIN_DIR . '/templates/wpgv_item_pdf.php';
	}
	return $template;
}

function wpgv_hex2rgb($color)
{
	if (empty($color) || !is_string($color)) {
		return false;
	}
	if ($color[0] == '#') {
		$color = substr($color, 1);
	}

	if (strlen($color) == 6) {
		list($r, $g, $b) = array(
			$color[0] . $color[1],
			$color[2] . $color[3],
			$color[4] . $color[5]
		);
	} elseif (strlen($color) == 3) {
		list($r, $g, $b) = array(
			$color[0] . $color[0],
			$color[1] . $color[1],
			$color[2] . $color[2]
		);
	} else {
		return false;
	}

	$r = hexdec($r);
	$g = hexdec($g);
	$b = hexdec($b);

	return array($r, $g, $b);
}

//conversion pixel -> millimeter at 72 dpi
function wpgv_px2mm($px)
{
	return $px * 25.4 / 72;
}

function wpgv_txtentities($html)
{
	$trans = get_html_translation_table(HTML_ENTITIES);
	$trans = array_flip($trans);
	return strtr($html, $trans);
}


function wpgv_em_cs_CZ($word)
{
	// Ensure input is a string
	$word = (string) $word;
	// If mbstring is available, try to detect encoding; otherwise assume UTF-8
	$source_encoding = 'UTF-8';
	if (function_exists('mb_check_encoding')) {
		if (!mb_check_encoding($word, 'UTF-8')) {
			$detected = mb_detect_encoding($word, array('UTF-8', 'WINDOWS-1250', 'ISO-8859-2', 'ISO-8859-1', 'CP1252'), true);
			if ($detected) {
				$source_encoding = $detected;
			}
		}
	}
	// Convert to Windows-1250 (Central European) for Czech/Slovak templates
	$converted = @iconv($source_encoding, 'WINDOWS-1250//IGNORE', $word);
	return $converted === false ? '' : $converted;
}

function wpgv_em($word)
{
	$word = html_entity_decode(strip_tags(stripslashes((string) $word)), ENT_NOQUOTES, 'UTF-8');

	// Determine source encoding if mbstring available. Many users store data in UTF-8,
	// but some environments may have legacy encodings. Detecting avoids double-encoding.
	$source_encoding = 'UTF-8';
	if (function_exists('mb_check_encoding')) {
		if (!mb_check_encoding($word, 'UTF-8')) {
			$detected = mb_detect_encoding($word, array('UTF-8', 'WINDOWS-1252', 'ISO-8859-1', 'CP1252'), true);
			if ($detected) {
				$source_encoding = $detected;
			}
		}
	}

	if (get_locale() == "el") {
		// Greek: use ISO-8859-7, ignore illegal characters
		$converted = @iconv($source_encoding, 'ISO-8859-7//IGNORE', $word);
	} else {
		// Default: Windows-1252 (Western European)
		$converted = @iconv($source_encoding, 'WINDOWS-1252//IGNORE', $word);
	}

	return $converted === false ? '' : $converted;
}
function wpgv_mailvarstr_multiple_admin($string, $setting_options, $voucher_options_results)
{

	$get_link_pdf = array();
	$get_order_number = array();
	$from_name = null;
	$to_name = null;
	$email = null;
	$amount = null;
	foreach ($voucher_options_results as $get_value) {
		$get_link_pdf[] = get_home_url() . '/wp-content/uploads/voucherpdfuploads/' . $get_value->voucherpdf_link . '.pdf';
		$get_order_number[] = $get_value->id;
		$from_name = $get_value->from_name;
		$to_name = $get_value->to_name;
		if ($get_value->email) {
			$email = $get_value->email;
		} else {
			$email = $get_value->shipping_email;
		}
		$amount = $get_value->amount;
	}
	// Build a combined payment status from all voucher items (avoid -> on array)
	$payment_statuses = array();
	foreach ($voucher_options_results as $pv) {
		if (isset($pv->payment_status) && $pv->payment_status !== '') {
			$payment_statuses[] = $pv->payment_status;
		}
	}
	$payment_status = implode(', ', array_unique($payment_statuses));

	$vars = array(
		'{order_type}'        => ($voucher_options_results->order_type) ? $voucher_options_results->order_type : 'vouchers',
		'{company_name}'      => ($setting_options->company_name) ? stripslashes($setting_options->company_name) : '',
		'{website_url}'       => get_site_url(),
		'{sender_email}'      => $setting_options->sender_email,
		'{sender_name}'       => stripslashes($setting_options->sender_name),
		'{order_number}'      => implode(', ', $get_order_number),
		'{amount}'            => $amount,
		'{customer_name}'     => stripslashes($from_name),
		'{recipient_name}'    => stripslashes($to_name),
		'{customer_email}'    => $email,
		'{customer_address}'  => $voucher_options_results->address,
		'{customer_postcode}' => $voucher_options_results->postcode,
		'{coupon_code}'       => $voucher_options_results->couponcode,
		'{payment_method}'    => $voucher_options_results->pay_method,
		'{payment_status}'    => $payment_status,
		'{pdf_link}'          => implode(', ', $get_link_pdf),
		'{receipt_link}'      => get_home_url() . '/wp-content/uploads/voucherpdfuploads/' . $voucher_options_results->voucherpdf_link . '-receipt.pdf',
	);
	return strtr($string, $vars);
}

function wpgv_mailvarstr_multiple($string, $setting_options, $voucher_options_results, $voucherpdf_link)
{

	$get_link_pdf = array();
	$get_order_number = array();
	$from_name = null;
	$to_name = null;
	$email = null;
	$amount = null;
	foreach ($voucher_options_results as $get_value) {
		$get_link_pdf[] = get_home_url() . '/wp-content/uploads/voucherpdfuploads/' . $get_value->voucherpdf_link . '.pdf';
		$get_order_number[] = $get_value->id;
		$from_name = $get_value->from_name;
		$to_name = $get_value->to_name;
		if ($get_value->email) {
			$email = $get_value->email;
		} else {
			$email = $get_value->shipping_email;
		}
		$amount = $get_value->amount;
	}
	// Build a combined payment status from all voucher items
	$payment_statuses = array();
	foreach ($voucher_options_results as $pv) {
		if (isset($pv->payment_status) && $pv->payment_status !== '') {
			$payment_statuses[] = $pv->payment_status;
		}
	}
	$payment_status = implode(', ', array_unique($payment_statuses));

	$vars = array(
		'{order_type}'        => ($voucher_options_results->order_type) ? $voucher_options_results->order_type : 'vouchers',
		'{company_name}'      => ($setting_options->company_name) ? stripslashes($setting_options->company_name) : '',
		'{website_url}'       => get_site_url(),
		'{sender_email}'      => $setting_options->sender_email,
		'{sender_name}'       => stripslashes($setting_options->sender_name),
		'{order_number}'      => $voucher_options_results->id,
		'{amount}'            => $amount,
		'{customer_name}'     => stripslashes($from_name),
		'{recipient_name}'    => stripslashes($to_name),
		'{customer_email}'    => $email,
		'{customer_address}'  => $voucher_options_results->address,
		'{customer_postcode}' => $voucher_options_results->postcode,
		'{coupon_code}'       => $voucher_options_results->couponcode,
		'{payment_method}'    => $voucher_options_results->pay_method,
		'{payment_status}'    => $payment_status,
		'{pdf_link}'          => get_home_url() . '/wp-content/uploads/voucherpdfuploads/' . $voucherpdf_link . '.pdf',
		'{receipt_link}'      => get_home_url() . '/wp-content/uploads/voucherpdfuploads/' . $voucher_options_results->voucherpdf_link . '-receipt.pdf',
	);
	return strtr($string, $vars);
}
function wpgv_mailvarstr($string, $setting_options, $voucher_options)
{

	$vars = array(
		'{order_type}'        => ($voucher_options->order_type) ? $voucher_options->order_type : 'vouchers',
		'{company_name}'      => ($setting_options->company_name) ? stripslashes($setting_options->company_name) : '',
		'{website_url}'       => get_site_url(),
		'{sender_email}'      => $setting_options->sender_email,
		'{sender_name}'       => stripslashes($setting_options->sender_name),
		'{order_number}'      => $voucher_options->id,
		'{amount}'            => $voucher_options->amount,
		'{customer_name}'     => stripslashes($voucher_options->from_name),
		'{recipient_name}'    => stripslashes($voucher_options->to_name),
		'{customer_email}'    => ($voucher_options->email) ? $voucher_options->email : $voucher_options->shipping_email,
		'{customer_address}'  => $voucher_options->address,
		'{customer_postcode}' => $voucher_options->postcode,
		'{coupon_code}'       => $voucher_options->couponcode,
		'{payment_method}'    => $voucher_options->pay_method,
		'{payment_status}'    => $voucher_options->payment_status,
		'{pdf_link}'          => get_home_url() . '/wp-content/uploads/voucherpdfuploads/' . $voucher_options->voucherpdf_link . '.pdf',
		'{receipt_link}'      => get_home_url() . '/wp-content/uploads/voucherpdfuploads/' . $voucher_options->voucherpdf_link . '-receipt.pdf',
	);

	return strtr($string, $vars);
}
// This function is use for Multisite WP environment
function wpgv_new_blog($blog_id, $user_id, $domain, $path, $site_id, $meta)
{
	if (is_plugin_active_for_network('gift-voucher-pro/gift-voucher-pro.php')) {
		switch_to_blog($blog_id);
		wpgv_plugin_activation();
		restore_current_blog();
	}
}

add_action('wpmu_new_blog', 'wpgv_new_blog', 10, 6);

add_action('wpgv_check_voucher_status', 'do_wpgv_check_voucher_status');

function do_wpgv_check_voucher_status()
{
	global $wpdb;
	$setting_table_name = $wpdb->prefix . 'giftvouchers_setting';
	$options = $wpdb->get_row("SELECT * FROM $setting_table_name WHERE id = 1");
	if ($options->is_woocommerce_enable) {
		$vouchers = $wpdb->get_results("SELECT id, couponcode FROM {$wpdb->prefix}giftvouchers_list WHERE `status` = 'unused' AND `payment_status` = 'Paid'");
		foreach ($vouchers as $voucher) {
			$gift_voucher = new WPGV_Gift_Voucher($voucher->couponcode);
			$balance = $gift_voucher->get_balance();
			if (empty($balance) || ($balance == 0)) {
				$wpdb->update(
					"{$wpdb->prefix}giftvouchers_list",
					array('id' => $voucher->id, 'status' => 'used'),
					array('id' => $voucher->id)
				);
			}
		}
	}
}
add_action('wp_ajax_wpgv_redeem_voucher', 'wpgv_redeem_voucher');

function wpgv_redeem_voucher()
{
	global $wpdb;
	$setting_table_name = $wpdb->prefix . 'giftvouchers_setting';
	$setting_options = $wpdb->get_row("SELECT * FROM $setting_table_name WHERE id = 1");

	$voucher_id = isset($_POST['voucher_id']) ? $_POST['voucher_id'] : '';
	$voucher_amount = isset($_POST['voucher_amount']) ? $_POST['voucher_amount'] : '';
	WPGV_Gift_Voucher_Activity::record($voucher_id, 'transaction', '-' . $voucher_amount, 'Voucher amount ' . $setting_options->currency . $voucher_amount . ' used directly by administrator.');

	echo 'Successfully redeemed voucher amount ' . $setting_options->currency . $voucher_amount;
	wp_die(); // this is required to terminate immediately and return a proper response
}

function wpgv_price_format_cs_CZ($price)
{
	global $wpdb;
	$setting_table_name = $wpdb->prefix . 'giftvouchers_setting';
	$setting_options = $wpdb->get_row("SELECT * FROM $setting_table_name WHERE id = 1");
	$currency_code =  $setting_options->currency;
	$converted_text = iconv('UTF-8', 'windows-1250', $currency_code);
	$price = number_format((float)$price, 0, '', '');
	$currency = ($setting_options->currency_position == 'Left') ? $converted_text . ' ' . $price : $price . ' ' . $converted_text;
	return $currency;
}

function wpgv_price_format($price)
{
	global $wpdb;

	// Get plugin settings from the database
	$setting_table_name = $wpdb->prefix . 'giftvouchers_setting';
	$setting_options = $wpdb->get_row("SELECT * FROM $setting_table_name WHERE id = 1");

	// Clean up the price value by removing HTML tags, special characters, and extra slashes
	$price = html_entity_decode(strip_tags(stripslashes($price)), ENT_NOQUOTES, 'UTF-8');

	// Remove any non-numeric characters except comma and dot (e.g., currency symbols like £, $, etc.)
	$price = preg_replace('/[^\d.,]/', '', $price);

	// Convert string to float (e.g., "20,000.50" becomes 20000.50)
	$price = floatval(str_replace(',', '', (string)$price));

	// Get selected number format option from WordPress settings
	$wpgv_select_number_format = get_option('wpgv_select_number_format', '');

	// Format the number based on the selected format (comma or dot)
	if ($wpgv_select_number_format == "comma") {
		$price = number_format($price, 2, '.', ','); // e.g., 1,000.00
	} elseif ($wpgv_select_number_format == "dot") {
		$price = number_format($price, 2, ',', '.'); // e.g., 1.000,00
	} else {
		$price = number_format($price, 2); // Default format
	}

	// Attach currency symbol based on the position setting (Left or Right)
	$currency = ($setting_options->currency_position == 'Left')
		? $setting_options->currency . ' ' . $price
		: $price . ' ' . $setting_options->currency;

	return $currency;
}

function wpgv_price_format_dot_cs($price)
{
	global $wpdb;
	$setting_table_name = $wpdb->prefix . 'giftvouchers_setting';
	$setting_options = $wpdb->get_row("SELECT * FROM $setting_table_name WHERE id = 1");
	$price = html_entity_decode(strip_tags(stripslashes($price)), ENT_NOQUOTES, 'UTF-8');
	$price = iconv('UTF-8', 'windows-1252', $price);
	$price = number_format((float)$price, 0, '', '');
	$currency = ($setting_options->currency_position == 'Left') ? $setting_options->currency . ' ' . $price : $price . ' ' . $setting_options->currency;
	return $currency;
}

function wpgv_create_plugin_pages()
{
	$category_name = 'Giftcard modern Categories';
	$category_slug = sanitize_title($category_name);
	$category_description = 'Giftcard modern Categories Description'; // Add a description if needed

	$args = array(
		'description' => $category_description,
		'slug' => $category_slug,
	);

	$category = get_term_by('name', $category_name, 'category_voucher_template');
	$category_id = "";
	if (!$category) {
		$result = wp_insert_term($category_name, 'category_voucher_template', $args);
		if (!is_wp_error($result)) {
			$category_id = $result['term_id'];
			echo 'Created category: ' . $category_name . '<br>';
		} else {
			echo 'Failed to create category: ' . $category_name . '. Error: ' . $result->get_error_message() . '<br>';
		}
	} else {
		// Category already exists — capture its term_id so we can assign it to created posts
		$category_id = isset($category->term_id) ? $category->term_id : '';
		echo 'Category already exists: ' . $category_name . '<br>';
	}
	/// Create page demo
	$pages = array(
		array(
			'post_title'    => 'GiftCard Standard List View',
			'post_content'  => '[wpgv_giftcard_standard style="list"]',
			'post_status'   => 'publish',
			'post_author'   => get_current_user_id(),
			'post_type'     => 'page',
		),
		array(
			'post_title'    => 'GiftCard Standard Grid View',
			'post_content'  => '[wpgv_giftcard_standard style="grid"]',
			'post_status'   => 'publish',
			'post_author'   => get_current_user_id(),
			'post_type'     => 'page',
		),
		array(
			'post_title'    => 'GiftCard Standard(Grid) PDF Preview',
			'post_content'  => ' ',
			'post_status'   => 'publish',
			'post_author'   => get_current_user_id(),
			'post_type'     => 'page',
			'comment_status' => 'closed',
			'ping_status'    => 'closed',
			'template'      => 'wpgv_voucher_pdf.php',
			'post_name'     => 'voucher-pdf-preview'
		),
		array(
			'post_title'    => 'GiftCard Standard(List) PDF Preview',
			'post_content'  => ' ',
			'post_status'   => 'publish',
			'post_author'   => get_current_user_id(),
			'post_type'     => 'page',
			'comment_status' => 'closed',
			'ping_status'    => 'closed',
			'template'      => 'wpgv_item_pdf.php',
			'post_name'     => 'gift-item-pdf-preview'
		),
		array(
			'post_title'    => 'Voucher Payment Successful',
			'post_content'  => '[wpgv_giftvouchersuccesspage]',
			'post_status'   => 'publish',
			'post_author'   => get_current_user_id(),
			'post_type'     => 'page',
			'comment_status' => 'closed',
			'ping_status'    => 'closed',
		),
		array(
			'post_title'    => 'Voucher Payment Cancel',
			'post_content'  => '[wpgv_giftvouchercancelpage]',
			'post_status'   => 'publish',
			'post_author'   => get_current_user_id(),
			'post_type'     => 'page',
			'comment_status' => 'closed',
			'ping_status'    => 'closed',
		),
		array(
			'post_title'    => 'Voucher Check Balance',
			'post_content'  => '[wpgv-check-voucher-balance]',
			'post_status'   => 'publish',
			'post_author'   => get_current_user_id(),
			'post_type'     => 'page',
			'comment_status' => 'closed',
			'ping_status'    => 'closed',
		),
		array(
			'post_title'    => 'Giftcard modern',
			'post_content'  => '[wpgv_giftcard_modern]',
			'post_status'   => 'publish',
			'post_author'   => get_current_user_id(),
			'post_type'     => 'page',
		),
	);

	$lastpageIds = array();
	foreach ($pages as $page_data) {
		// Avoid deprecated get_page_by_title() — perform a small search and match exact title.
		$page = null;
		$search_posts = get_posts(array(
			'post_type'      => 'page',
			'post_status'    => array('publish','draft','pending','private'),
			'posts_per_page' => -1,
			's'              => $page_data['post_title'],
		));
		if (!empty($search_posts)) {
			foreach ($search_posts as $p) {
				if (trim($p->post_title) === trim($page_data['post_title'])) {
					$page = $p;
					break;
				}
			}
		}

		if (!$page) {
			$page_id = wp_insert_post($page_data);
			if (isset($page_data['template']) && !empty($page_data['template'])) {
				update_post_meta($page_id, '_wp_page_template', $page_data['template']);
			}
			$lastpageIds[] = $page_id;
		} else {
			$lastpageIds[] = $page->ID;
		}
	}
	/// Create page demo

	/// Create data Giftcard standard demo
	$category_name = 'Demo Category';
	$category_slug = 'demo-category';
	$category_description = 'Demo Category Description';

	$args = array(
		'description' => $category_description,
		'slug' => $category_slug,
	);

	$lastCategoryID = wp_insert_term($category_name, 'wpgv_voucher_category', $args);

	if (is_wp_error($lastCategoryID)) {
		// Attempt to recover by finding an existing term by name or slug.
		$existing = get_term_by('name', $category_name, 'wpgv_voucher_category');
		if (!$existing) {
			$existing = get_term_by('slug', sanitize_title($category_name), 'wpgv_voucher_category');
		}

		if ($existing && isset($existing->term_id)) {
			$lastCategoryID = array('term_id' => $existing->term_id);
		} else {
			// Could not determine an existing term id — set to 0 and continue (no category assignment)
			$lastCategoryID = array('term_id' => 0);
			// Only log full errors when debugging — avoid noisy logs for 'term exists' cases
			if (defined('WP_DEBUG') && WP_DEBUG) {
				error_log('wpgv_create_plugin_pages: wp_insert_term error: ' . $lastCategoryID->get_error_message());
			}
		}
	}

	$demoItem = array(
		'post_title'    => 'Demo Item',
		'post_status'   => 'publish',
		'post_author'   => get_current_user_id(),
		'post_type'     => 'wpgv_voucher_product',
	);
	$lastItemID = wp_insert_post($demoItem);

	add_post_meta($lastItemID, 'description', 'Demo Description');
	add_post_meta($lastItemID, 'price', '100');
	add_post_meta($lastItemID, 'special_price', '80');
	add_post_meta($lastItemID, 'wpgv_templates_style', 'gift_items');
	wp_set_object_terms($lastItemID, $lastCategoryID['term_id'], 'wpgv_voucher_category');


	$demoVoucher = array(
		'post_title'    => 'Demo Voucher',
		'post_status'   => 'publish',
		'post_author'   => get_current_user_id(),
		'post_type'     => 'wpgv_voucher_product',
	);

	$lastVoucherID = wp_insert_post($demoVoucher);

	if ($lastVoucherID) {
		add_post_meta($lastVoucherID, 'description', null);
		add_post_meta($lastVoucherID, 'price', null);
		add_post_meta($lastVoucherID, 'special_price', null);
		add_post_meta($lastVoucherID, 'wpgv_templates_style', 'gift_voucher');
	}
	/// Create data Giftcard standard demo

	/// Create data Giftcard modern demo


	$json_files = array(
		'template-voucher-lanscape-1.json',
		'template-voucher-lanscape-2.json',
		'template-voucher-lanscape-3.json',
		'template-voucher-lanscape-4.json',
		'template-voucher-portail-1.json',
		'template-voucher-portail-2.json',
		'template-voucher-portail-3.json',
		'template-voucher-portail-4.json',
	);
	$svg_files = array(
		'template-voucher-lanscape-1.svg',
		'template-voucher-lanscape-2.svg',
		'template-voucher-lanscape-3.svg',
		'template-voucher-lanscape-4.svg',
		'template-voucher-portail-1.svg',
		'template-voucher-portail-2.svg',
		'template-voucher-portail-3.svg',
		'template-voucher-portail-4.svg',
	);
	$png_files = array(
		'template-voucher-lanscape-1.png',
		'template-voucher-lanscape-2.png',
		'template-voucher-lanscape-3.png',
		'template-voucher-lanscape-4.png',
		'template-voucher-portail-1.png',
		'template-voucher-portail-2.png',
		'template-voucher-portail-3.png',
		'template-voucher-portail-4.png',
	);

	$number_of_posts = 8;

	for ($i = 1; $i <= $number_of_posts; $i++) {
		$title = 'Giftcard modern ' . $i;

		$post_meta_values = array(
			'wpgv_customize_template_json_template' => '',
			'wpgv_customize_template_id_bg_template' => '',
			'wpgv_customize_template_bg_result' => '',
			'wpgv_customize_template_check_temp_custom' => 0,
			'wpgv_customize_template_template-style' => '',
			'wpgv_customize_template_chosse_template' => '',
			'wpgv_customize_template_status' => 'Active',
			'wpgv_customize_template_voucher_expiry_value' => 60,
			'wpgv_customize_template_select_template' => 'default',
		);

		$json_file_index = ($i - 1) % count($json_files);
		$json_file_url = 'https://gift-card-pro.s3.eu-central-1.amazonaws.com/templates/version-1.2/json/' . $json_files[$json_file_index];

		$json_data = @file_get_contents($json_file_url);

		if ($json_data !== false) {
			$post_meta_values['wpgv_customize_template_json_template'] = $json_data;
		} else {
			// Could not fetch remote JSON — log and continue with empty JSON so post is still created
			echo 'Warning: Failed to retrieve JSON data from URL: ' . esc_url($json_file_url) . '<br>';
			$post_meta_values['wpgv_customize_template_json_template'] = '';
		}

		$svg_file_index = ($i - 1) % count($svg_files);
		$bg_template_url = 'https://gift-card-pro.s3.eu-central-1.amazonaws.com/templates/version-1.2/svg/' . $svg_files[$svg_file_index];
		$svg_file_name = download_svg_to_directory($bg_template_url);

		if ($svg_file_name) {
			$svg_file_path = plugin_dir_url(__FILE__) . 'assets/img/template-images-v2/' . $svg_file_name;
			$post_meta_values['wpgv_customize_template_id_bg_template'] = $svg_file_path;
		} else {
			// Could not download SVG — log warning but continue creating post with empty bg value
			echo 'Warning: Failed to download SVG file from URL: ' . esc_url($bg_template_url) . '<br>';
			$post_meta_values['wpgv_customize_template_id_bg_template'] = '';
		}

		if (strpos((string)$svg_file_name, 'template-voucher-portail') !== false) {
			$post_meta_values['wpgv_customize_template_chosse_template'] = 'portail';
		} elseif (strpos((string)$svg_file_name, 'template-voucher-lanscape') !== false) {
			$post_meta_values['wpgv_customize_template_chosse_template'] = 'lanscape';
		} else {
			$post_meta_values['wpgv_customize_template_chosse_template'] = 'default';
		}


		$png_file_index = ($i - 1) % count($png_files);

		$bg_template_url = 'https://gift-card-pro.s3.eu-central-1.amazonaws.com/templates/png/' . $png_files[$png_file_index];
		$png_file_name = download_png_to_directory($bg_template_url);
		if ($png_file_name) {
			$post_meta_values['wpgv_customize_template_template-style'] = $png_files[$png_file_index];
			$post_meta_values['wpgv_customize_template_bg_result'] = $png_file_name;
		} else {
			// Could not download PNG — log warning but continue creating post without bg result
			echo 'Warning: Failed to download PNG file from URL: ' . esc_url($bg_template_url) . '<br>';
			$post_meta_values['wpgv_customize_template_template-style'] = '';
			$post_meta_values['wpgv_customize_template_bg_result'] = '';
		}

		$post_id = create_voucher_template_post($title, $post_meta_values);

		if ($post_id) {
			echo 'Created post: ' . $title . ' (ID: ' . $post_id . ')<br>';
			wp_set_object_terms($post_id, $category_id, 'category_voucher_template');
		} else {
			echo 'Failed to create post: ' . $title . '<br>';
		}
	}
	/// Create data Giftcard modern demo
	return $lastpageIds;
}


// Function to download an SVG file from the specified URL and store it in a custom directory.
function download_svg_to_directory($image_url)
{
	$ch = curl_init($image_url);
	// Configure cURL request options
	curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
	curl_setopt($ch, CURLOPT_HEADER, 0);

	// Execute the cURL request
	$svg_data = curl_exec($ch);
	$http_code = curl_getinfo($ch, CURLINFO_HTTP_CODE);

	// Check the HTTP status code to verify if the file was successfully retrieved
	if ($http_code !== 200) {
		echo 'Failed to retrieve SVG file from URL: ' . $image_url . ', HTTP Error: ' . $http_code . '<br>';
		curl_close($ch);
		return false;
	}

	curl_close($ch);

	// Define the custom directory path for storing the SVG files
	$upload_dir = WPGIFT__PLUGIN_DIR . '/assets/img/template-images-v2/';
	$image_name = basename($image_url);
	$image_path = $upload_dir . $image_name;

	// Check if the SVG file already exists in the custom directory
	if (!file_exists($image_path)) {
		// Save the SVG data into the custom directory
		file_put_contents($image_path, $svg_data);
	}

	return $image_name; // Return the name of the downloaded SVG file
}

// Create Giftcard modern Templates
function create_voucher_template_post($title, $post_meta_values)
{
	$post_data = array(
		'post_title'    => $title,
		'post_type'     => 'voucher_template',
		'post_status'   => 'publish',
	);

	$post_id = wp_insert_post($post_data);

	if ($post_id) {
		foreach ($post_meta_values as $meta_key => $meta_value) {
			update_post_meta($post_id, $meta_key, $meta_value);
		}
	}

	return $post_id;
}


// Hàm tải file PNG vào thư mục tùy chỉnh và lấy tên file
function download_png_to_directory($image_url)
{
	$ch = curl_init($image_url);

	// Cấu hình yêu cầu cURL
	curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
	curl_setopt($ch, CURLOPT_HEADER, 0);

	// Thực hiện yêu cầu cURL
	$png_data = curl_exec($ch);
	$http_code = curl_getinfo($ch, CURLINFO_HTTP_CODE);

	// Kiểm tra mã HTTP
	if ($http_code !== 200) {
		echo 'Failed to retrieve PNG file from URL: ' . $image_url . ', HTTP Error: ' . $http_code . '<br>';
		curl_close($ch);
		return false;
	}

	curl_close($ch);

	$upload_dir = wp_upload_dir();
	$upload_path = $upload_dir['path'];
	$image_name = basename($image_url);
	$image_path = $upload_path . '/' . $image_name;

	// Kiểm tra xem file PNG đã tồn tại trong thư mục tùy chỉnh chưa
	if (!file_exists($image_path)) {
		file_put_contents($image_path, $png_data);
	}

	// Tải ảnh vào media library và lấy ID ảnh
	$attachment = array(
		'guid'           => $upload_dir['url'] . '/' . $image_name,
		'post_mime_type' => 'image/png',
		'post_title'     => preg_replace('/\.[^.]+$/', '', $image_name),
		'post_content'   => '',
		'post_status'    => 'inherit'
	);

	$attach_id = wp_insert_attachment($attachment, $image_path);

	// Tạo metadata cho ảnh
	require_once(ABSPATH . 'wp-admin/includes/image.php');
	$attach_data = wp_generate_attachment_metadata($attach_id, $image_path);
	wp_update_attachment_metadata($attach_id, $attach_data);

	return $attach_id;
}

// Send gift voucher email event
add_action("send_gift_voucher_email_event", "send_gift_voucher_email_event_fun", 1, 5);
function send_gift_voucher_email_event_fun($recipientto, $recipientsub, $recipientmsg, $headers, $attachments)
{
	wp_mail($recipientto, $recipientsub, $recipientmsg, $headers, $attachments);
}

function wpgv_display_testmode_notice()
{
	$setting_options = wpgv_get_settings();
	$wpgv_paypal_client_id = get_option('wpgv_paypal_client_id') ? get_option('wpgv_paypal_client_id') : '';
	$wpgv_paypal_secret_key = get_option('wpgv_paypal_secret_key') ? get_option('wpgv_paypal_secret_key') : '';
	$current_user_id = get_current_user_id();
	$dismissed = is_user_logged_in() ? get_user_meta($current_user_id, 'wpgv_dismissed_notices', true) : array();
	if (!is_array($dismissed)) {
		$dismissed = array();
	}

	if ( $setting_options && ! empty( $setting_options->paypal ) && ! empty( $setting_options->test_mode ) ) {
		$class = 'notice notice-info';
		$message = sprintf('PayPal Testmode has enabled in the <a href="%s" target="_blank">plugin settings</a> in <b>Gift Cards</b> plugin.', admin_url('admin.php') . '?page=voucher-setting#payment');
		$notice_id = 'paypal_testmode_notice';
		if (!in_array($notice_id, $dismissed)) {
			printf('<div id="%1$s" class="%2$s is-dismissible"><p>%3$s</p></div>', esc_attr($notice_id), esc_attr($class), $message);
		}
	}
	if ( $setting_options && ! empty( $setting_options->paypal ) && ( ! $wpgv_paypal_client_id || ! $wpgv_paypal_secret_key ) ) {
		$class = 'notice notice-info';
		$message = sprintf('PayPal has enabled but empty client id or secret key in the <a href="%s" target="_blank">plugin settings</a> in <b>Gift Cards</b> plugin.', admin_url('admin.php') . '?page=voucher-setting#payment');
		$notice_id = 'paypal_empty_keys_notice';
		if (!in_array($notice_id, $dismissed)) {
			printf('<div id="%1$s" class="%2$s is-dismissible"><p>%3$s</p></div>', esc_attr($notice_id), esc_attr($class), $message);
		}
	}

	if ( $setting_options && ! empty( $setting_options->stripe ) && ( ! $setting_options->stripe_publishable_key || ! $setting_options->stripe_secret_key ) ) {
		$class = 'notice notice-info';
		$message = sprintf('Stripe has enabled but empty Publishable key or Secret key in the <a href="%s" target="_blank">plugin settings</a> in <b>Gift Cards</b> plugin.', admin_url('admin.php') . '?page=voucher-setting#payment');
		$notice_id = 'stripe_empty_keys_notice';
		if (!in_array($notice_id, $dismissed)) {
			printf('<div id="%1$s" class="%2$s is-dismissible"><p>%3$s</p></div>', esc_attr($notice_id), esc_attr($class), $message);
		}
	}
	if ( $setting_options && ! empty( $setting_options->sofort ) && ( ! $setting_options->sofort_configure_key ) ) {
		$class = 'notice notice-info';
		$message = sprintf('Sofort has enabled but empty Configuration Key in the <a href="%s" target="_blank">plugin settings</a> in <b>Gift Cards</b> plugin.', admin_url('admin.php') . '?page=voucher-setting#payment');
		$notice_id = 'sofort_empty_key_notice';
		if (!in_array($notice_id, $dismissed)) {
			printf('<div id="%1$s" class="%2$s is-dismissible"><p>%3$s</p></div>', esc_attr($notice_id), esc_attr($class), $message);
		}
	}
}
add_action('admin_notices', 'wpgv_display_testmode_notice');

// Add JavaScript code to handle the dismissal of notices
function add_dismiss_notice_script()
{
?>
	<script>
		(function(){
			var ajaxUrl = '<?php echo admin_url('admin-ajax.php'); ?>';
			var nonce = '<?php echo wp_create_nonce('wpgv_dismiss_notice_nonce'); ?>';

			// Helper to send dismissal via AJAX
			function sendDismissal(noticeId) {
				if (!noticeId) return;
				var data = new FormData();
				data.append('action','wpgv_dismiss_notice');
				data.append('notice', noticeId);
				data.append('nonce', nonce);

				fetch(ajaxUrl, {
					method: 'POST',
					credentials: 'same-origin',
					body: data
				}).catch(function(){});
			}

			// Expose global function for inline onclick handlers (backward compatibility)
			window.dismissNotice = function(noticeId) {
				try {
					var el = document.getElementById(noticeId);
					if (el) el.style.display = 'none';
				} catch (e) {}
				sendDismissal(noticeId);
			};

			// Delegate click on WP dismiss button and persist dismissal server-side
			document.addEventListener('click', function(e){
				var t = e.target;
				if (!t) return;
				if (t.classList && t.classList.contains('notice-dismiss')) {
					var notice = t.closest('.notice');
					if (!notice) return;
					var noticeId = notice.id;
					if (!noticeId) return;

					sendDismissal(noticeId);
				}
			}, false);
		})();
	</script>
<?php
}
add_action('admin_footer', 'add_dismiss_notice_script');

// AJAX handler to record dismissed admin notices per-user
add_action('wp_ajax_wpgv_dismiss_notice', 'wpgv_ajax_dismiss_notice');
function wpgv_ajax_dismiss_notice()
{
	if (!is_user_logged_in()) {
		wp_send_json_error('not_logged_in');
	}

	check_ajax_referer('wpgv_dismiss_notice_nonce', 'nonce');

	$notice = isset($_POST['notice']) ? sanitize_text_field(wp_unslash($_POST['notice'])) : '';
	if (empty($notice)) {
		wp_send_json_error('missing_notice');
	}

	$user_id = get_current_user_id();
	$dismissed = get_user_meta($user_id, 'wpgv_dismissed_notices', true);
	if (!is_array($dismissed)) {
		$dismissed = array();
	}

	if (!in_array($notice, $dismissed, true)) {
		$dismissed[] = $notice;
		update_user_meta($user_id, 'wpgv_dismissed_notices', $dismissed);
	}

	wp_send_json_success();
}


function load_media_files()
{
	wp_enqueue_media();
}
add_action('admin_enqueue_scripts', 'load_media_files');

//columns Name Customer
function wpgv_customer_name_columns($columns)
{
	unset($columns['date']);
	unset($columns['title']);
	unset($columns['taxonomy-category_voucher_template']);
	$new_columns = array(
		'images' => __('', 'gift-voucher'),
		'title' => __('Title', 'gift-voucher'),
		'category' => __('Card Categories', 'gift-voucher'),
		'status' => __('Status', 'gift-voucher'),
		'date' => __('Date', 'gift-voucher'),

	);
	return array_merge($columns, $new_columns);
}
// Show content columns Phone customer
function wpgv_customer_columns_content($column, $post_ID)
{
	global $post;
	switch ($column) {

		case 'status':
			$values = get_post_custom($post->ID);
			$status = isset($values["wpgv_customize_template_status"]) ? $values["wpgv_customize_template_status"]['0'] : __('Inactive', 'gift-voucher');
			if ($status == 'Active') {
				echo '<p class="wpgv-status-active" style="font-weight: 500; "><span>' . $status . '</span></p>';
			} else {
				echo '<p class="wpgv-status-unactive" style="font-weight: 500; "><span>' . $status . '</span></p>';
			}

			break;
		case 'images':

			$values = get_post_custom($post->ID);
			$images_s3 = isset($values["wpgv_customize_template_template-style"]) ? $values["wpgv_customize_template_template-style"]['0'] : __('', 'gift-voucher');
			$images_media = isset($values["wpgv_customize_template_bg_result"]) ? wp_get_attachment_image_url($values["wpgv_customize_template_bg_result"]['0'], 'full') : __('', 'gift-voucher');
			$chosse_template = isset($values["wpgv_customize_template_chosse_template"]) ? $values["wpgv_customize_template_chosse_template"]['0'] : __('', 'gift-voucher');

			if ($chosse_template != "0") {
				if (isset($values["wpgv_customize_template_template-style"])) {
					if (isset($values["wpgv_customize_template_select_template"])) {
						if ($values["wpgv_customize_template_select_template"]["0"] == "custom") {
							echo '<img class="" src="' . $images_media . '" width="79px" height="auto" />';
						} else {
							if ($values["wpgv_customize_template_template-style"]["0"] != "0") {
								echo '<img class="2" src="https://gift-card-pro.s3.eu-central-1.amazonaws.com/templates/png/' . $images_s3 . '" width="79px" height="auto" />';
							}
						}
					} else {
						echo '<img class="2" src="https://gift-card-pro.s3.eu-central-1.amazonaws.com/templates/png/' . $images_s3 . '" width="79px" height="auto" />';
					}
				}
			}


			break;
		case 'category':
			$term_list = get_the_terms($post->ID, 'category_voucher_template');
			$types = '';
			if (!empty($term_list)) {
				foreach ($term_list as $term_single) {
					$term_link = get_term_link($term_single);
					$types .= '<a href="' . admin_url() . 'edit.php?post_type=voucher_template&category_voucher_template=' . ucfirst($term_single->slug) . '">' . ucfirst($term_single->slug) . ',' . '</a> ';
				}
			}
			$typesz = rtrim($types, ', ');
			echo $types;
			break;

		default:
			break;
	}
}

add_filter('manage_voucher_template_posts_columns', 'wpgv_customer_name_columns');
add_action('manage_voucher_template_posts_custom_column', 'wpgv_customer_columns_content', 10, 2);

// save image from canvas voucher_metabox.php
function wpgv_save_image()
{

	$base64_img = (isset($_POST['base64_img'])) ? esc_attr($_POST['base64_img']) : '';
	$title = (isset($_POST['title'])) ? esc_attr($_POST['title']) : '';
	$get_id_bg_result = (isset($_POST['get_id_bg_result'])) ? esc_attr($_POST['get_id_bg_result']) : '';
	$data_id_result = (isset($_POST['data_id_result'])) ? esc_attr($_POST['data_id_result']) : '';

	$upload_dir = wp_upload_dir();
	$upload_path = str_replace('/', DIRECTORY_SEPARATOR, (string)($upload_dir['path'] ?? '')) . DIRECTORY_SEPARATOR;
	// Validate base64 input
	$image_parts = explode(";base64,", $base64_img);
	if (!is_array($image_parts) || count($image_parts) < 2) {
		wp_send_json_error('invalid_base64');
	}
	$decoded = base64_decode($image_parts[1]);
	if ($decoded === false || strlen($decoded) === 0) {
		wp_send_json_error('invalid_base64_decode');
	}
	$filename = $title . '.png';
	$hashed_filename = md5($filename . microtime()) . '_' . $filename;
	$image_upload = file_put_contents($upload_path . $hashed_filename, $decoded);
	if ($image_upload === false) {
		wp_send_json_error('file_write_failed');
	}
	require_once(ABSPATH . 'wp-admin/includes/image.php');
	require_once(ABSPATH . 'wp-admin/includes/media.php');
	require_once(ABSPATH . 'wp-admin/includes/file.php');

	$file             = array();
	$file['error']    = '';
	$file['tmp_name'] = $upload_path . $hashed_filename;
	$file['name']     = $hashed_filename;
	$file['type']     = 'image/png';
	$file['size']     = filesize($upload_path . $hashed_filename);
	// upload file to server

	// use $file instead of $image_upload
	$file_return = wp_handle_sideload($file, array('test_form' => false));
	if (empty($file_return) || !isset($file_return['file'])) {
		// cleanup temp file
		@unlink($upload_path . $hashed_filename);
		wp_send_json_error('sideload_failed');
	}
	$filename = $file_return['file'];
	$attachment = array(
		'post_mime_type' => $file_return['type'],
		'post_title'     => preg_replace('/\.[^.]+$/', '', basename($filename)),
		'post_content'   => '',
		'post_status'    => 'inherit',
		'guid'           => $upload_dir['url'] . '/' . basename($filename)
	);

	$attach_id = wp_insert_attachment($attachment, $filename);
	if ($attach_id && !is_wp_error($attach_id)) {
		// Remove previous attachment if provided and numeric
		if (!empty($data_id_result) && is_numeric($data_id_result)) {
			wp_delete_attachment(intval($data_id_result), true);
		}


		// Ensure image editor can read the file before generating metadata
		$editor = wp_get_image_editor($filename);
		if (is_wp_error($editor)) {
			// cleanup attachment and file
			wp_delete_attachment($attach_id, true);
			wp_send_json_error('image_editor_unavailable');
		}

		// Generate attachment metadata and update
		$attachment_meta = wp_generate_attachment_metadata($attach_id, $filename);
		if (is_wp_error($attachment_meta) || empty($attachment_meta)) {
			// Attempt to regenerate once
			$attachment_meta = wp_generate_attachment_metadata($attach_id, $filename);
		}
		if (!is_wp_error($attachment_meta) && !empty($attachment_meta)) {
			wp_update_attachment_metadata($attach_id, $attachment_meta);
		} else {
			// If metadata generation fails, remove attachment and file to avoid corrupted entries
			wp_delete_attachment($attach_id, true);
			wp_send_json_error('metadata_generation_failed');
		}

		// Get attachment URL
		$image_url = wp_get_attachment_url($attach_id);

		// Return JSON with id and URL
		wp_send_json_success(array('id' => $attach_id, 'url' => $image_url));
	} else {
		wp_send_json_error('upload_failed');
	}
	// wp_send_json_* already exits
}
add_action('wp_ajax_wpgv_save_image', 'wpgv_save_image');
add_action('wp_ajax_nopriv_wpgv_save_image', 'wpgv_save_image');


function wpgv_generate_incremental_coupon_code($length, $starting_number, $current_number)
{
	if (!preg_match('/^\d+$/', $starting_number)) {
		return new WP_Error('invalid_format', 'Starting coupon number must be numeric.');
	}

	if (strlen($starting_number) !== $length) {
		return new WP_Error('invalid_length', 'Starting coupon number length does not match coupon code length.');
	}

	$code_number = !empty($current_number) ? intval($current_number) : intval($starting_number);
	return str_pad($code_number, $length, '0', STR_PAD_LEFT);
}

function wpgv_update_next_incremental_coupon($current_code, $length)
{
	$next = intval($current_code) + 1;
	$next_formatted = str_pad($next, $length, '0', STR_PAD_LEFT);
	update_option('wpgv_current_coupon_number', $next_formatted);
}

// Load PDF wrapper functions
require_once WPGIFT__PLUGIN_DIR . '/includes/pdf-wrapper.php';

// Load FPDF isolation class
require_once WPGIFT__PLUGIN_DIR . '/includes/fpdf-isolation.php';

// Load WPGV_PDF class for barcode support
require_once WPGIFT__PLUGIN_DIR . '/classes/fpdf.php';

/**
 * One-time migration: detect existing Success Pages by shortcode and persist to options.
 * Runs once after update/activation to preserve customer-configured pages.
 */
function wpgv_migrate_success_pages()
{
	// Only run once
	if (get_option('wpgv_success_pages_migrated')) {
		return;
	}

	// Map option name => array of shortcode tokens to search for.
	// Some gateways (MultiSafepay, Per Invoice) reuse the generic gift-voucher shortcode,
	// so include that as an alternative token to detect existing pages.
	$map = array(
		'wpgv_giftvouchersuccesspage'   => array('wpgv_giftvouchersuccesspage'),
		'wpgv_stripesuccesspage'        => array('wpgv_stripesuccesspage'),
		'wpgv_klarna_success_page'      => array('wpgv_klarnasuccesspage'),
		'wpgv_molliesuccesspage'        => array('wpgv_molliesuccesspage'),
		'wpgv_multisafepaysuccesspage'  => array('wpgv_multisafepaysuccesspage', 'wpgv_giftvouchersuccesspage'),
		'wpgv_perinvoicesuccesspage'    => array('wpgv_perinvoicesuccesspage', 'wpgv_giftvouchersuccesspage'),
	);

	// Only search published pages for shortcodes
	$pages = get_posts(array(
		'post_type'      => 'page',
		'post_status'    => 'publish',
		'posts_per_page' => -1,
		'fields'         => 'ids',
	));

	if (empty($pages)) {
		update_option('wpgv_success_pages_migrated', 1);
		return;
	}

	$report = array();

	foreach ($map as $option_name => $shortcodes) {
		// Skip if option already set
		$existing = get_option($option_name);
		if (!empty($existing)) {
			$report[$option_name] = array('status' => 'skipped', 'page_id' => $existing);
			continue;
		}

		$found = false;
		foreach ($pages as $page_id) {
			$content = get_post_field('post_content', $page_id);
			if ($content === null) {
				continue;
			}

			// check each possible shortcode token for this option
			foreach ($shortcodes as $shortcode) {
				if (strpos($content, '[' . $shortcode) !== false || strpos($content, '[' . $shortcode . ']') !== false) {
					update_option($option_name, intval($page_id));
					$report[$option_name] = array('status' => 'updated', 'page_id' => intval($page_id), 'matched_shortcode' => $shortcode);
					$found = true;
					break 2; // found for this option; stop scanning pages
				}
			}
		}

		if (! $found) {
			$report[$option_name] = array('status' => 'not_found', 'page_id' => 0);
		}
	}

	// Mark migration complete
	update_option('wpgv_success_pages_migrated', 1);
	// Save report so admin notice can display it once
	update_option('wpgv_success_pages_migration_report', $report);
	// Also write debug log (if WP_DEBUG enabled) so developer can inspect debug.log

}
add_action('admin_init', 'wpgv_migrate_success_pages', 20);


