<?php
/**
 * Plugin Name: Executive VIP Transfer Service
 * Description: Complete VIP transfer booking plugin for luxury chauffeur services, airport pickups, and private tours with distance-based pricing.
 * Version: 1.2.3
 * Author: GKSoft Dev Team
 * Author URI: https://gksoft.dev
 * License: GPLv2 or later
 * License URI: https://www.gnu.org/licenses/gpl-2.0.html
 * Text Domain: executive-vip-transfer-service
 */

if (!defined('ABSPATH'))
	exit;

/**
 * -------------------------------------------------------------------------
 * Constants
 * -------------------------------------------------------------------------
 */
define('EXECVITR_URL', plugin_dir_url(__FILE__));
define('EXECVITR_PATH', plugin_dir_path(__FILE__));
define('EXECVITR_VERSION', '1.2.3');

/**
 * -------------------------------------------------------------------------
 * Requires
 * -------------------------------------------------------------------------
 */
if (!defined('EXECVITR_LICENSE_CHECK_URL'))
	define('EXECVITR_LICENSE_CHECK_URL', 'https://licenses.gksoft.dev/check-license-vip.php');

if (!defined('EXECVITR_OPT_LICENSE_STATUS'))
	define('EXECVITR_OPT_LICENSE_STATUS', 'execvitr_license_status');

if (!defined('EXECVITR_OPT_LICENSE_LASTCHECK'))
	define('EXECVITR_OPT_LICENSE_LASTCHECK', 'execvitr_license_lastcheck');

if (!defined('EXECVITR_OPT_LICENSE_META'))
	define('EXECVITR_OPT_LICENSE_META', 'execvitr_license_meta');

if (!defined('EXECVITR_TFPDF_PATH')) {
	define('EXECVITR_TFPDF_PATH', trailingslashit(EXECVITR_PATH) . 'includes/lib/tfpdf.php');
}

/* -------------------------------------------------------------------------
 * Booking product setup (safe, WooCommerce-aware)
 * ------------------------------------------------------------------------- */
if (!function_exists('execvitr_maybe_create_booking_product')) {
	/**
	 * Ensures a WooCommerce product exists for the booking flow.
	 *
	 * @return int Product ID (0 if not available)
	 */
	function execvitr_maybe_create_booking_product(): int
	{
		if (!class_exists('WooCommerce')) {
			return 0;
		}

		$product_id = (int) get_option('execvitr_product_id', 0);
		if ($product_id > 0) {
			$post = get_post($product_id);
			if ($post && $post->post_type === 'product' && $post->post_status !== 'trash') {
				return $product_id;
			}
		}

		// Try to find an existing hidden booking product created previously.
		$existing = get_posts([
			'post_type' => 'product',
			'post_status' => ['publish', 'private', 'draft'],
			'posts_per_page' => 1,
			'fields' => 'ids',
			'meta_query' => [
				[
					'key' => '_execvitr_booking_product',
					'value' => 'yes',
					'compare' => '='
				]
			]
		]);
		if (!empty($existing)) {
			$product_id = (int) $existing[0];
			update_option('execvitr_product_id', $product_id);
			return $product_id;
		}

		// Create a minimal virtual product.
		$title = 'VIP Transfer Booking';
		$new_id = wp_insert_post([
			'post_title' => $title,
			'post_content' => '',
			'post_status' => 'publish',
			'post_type' => 'product',
		], true);

		if (is_wp_error($new_id) || !$new_id) {
			return 0;
		}
		$new_id = (int) $new_id;

		// Ensure product type.
		if (function_exists('wp_set_object_terms')) {
			wp_set_object_terms($new_id, 'simple', 'product_type');
		}

		// Mark as our booking product.
		update_post_meta($new_id, '_execvitr_booking_product', 'yes');
		update_post_meta($new_id, '_virtual', 'yes');
		update_post_meta($new_id, '_sold_individually', 'yes');
		update_post_meta($new_id, '_manage_stock', 'no');
		update_post_meta($new_id, '_stock_status', 'instock');
		update_post_meta($new_id, '_regular_price', '0');
		update_post_meta($new_id, '_price', '0');
		update_post_meta($new_id, '_tax_status', 'none');

		// Hide from catalog/search.
		update_post_meta($new_id, '_visibility', 'hidden');
		wp_set_object_terms($new_id, ['exclude-from-catalog', 'exclude-from-search'], 'product_visibility');

		update_option('execvitr_product_id', $new_id);
		return $new_id;
	}
}

// Run product setup on first request after activation (when WC is loaded).
add_action('plugins_loaded', function () {
	if ((int) get_option('execvitr_needs_product_setup', 0) !== 1) {
		return;
	}
	if (!class_exists('WooCommerce')) {
		return;
	}
	$pid = execvitr_maybe_create_booking_product();
	if ($pid > 0) {
		delete_option('execvitr_needs_product_setup');
	}
});

if (!defined('EXECVITR_TFPDF_FONT_TTF')) {
	define('EXECVITR_TFPDF_FONT_TTF', trailingslashit(EXECVITR_PATH) . 'includes/lib/font/unifont/DejaVuSans.ttf');
}

/* -------------------------------------------------------------------------
 * Requires
 * ------------------------------------------------------------------------- */
require_once EXECVITR_PATH . 'admin/settings-page.php';
require_once EXECVITR_PATH . 'includes/class-distance.php';
require_once EXECVITR_PATH . 'templates/form-submit-handler.php';
require_once EXECVITR_PATH . 'includes/class-license.php';
require_once EXECVITR_PATH . 'admin/license-page.php';

/* -------------------------------------------------------------------------
 * Cron Setup
 * ------------------------------------------------------------------------- */
add_action('execvitr_license_cron', ['EXECVITR_License', 'maybe_ping']);

register_activation_hook(__FILE__, function () {
	// License cron
	if (!wp_next_scheduled('execvitr_license_cron')) {
		wp_schedule_event(time() + HOUR_IN_SECONDS, 'twicedaily', 'execvitr_license_cron');
	}

	// Booking product setup is performed on the next request when WooCommerce is loaded.
	// This avoids activation-time issues when WC classes are not available.
	update_option('execvitr_needs_product_setup', 1);
});

register_deactivation_hook(__FILE__, function () {
	wp_clear_scheduled_hook('execvitr_license_cron');
});

/* -------------------------------------------------------------------------
 * Smart Auto License Verification
 * ------------------------------------------------------------------------- */
add_action('admin_init', function () {
	if (!current_user_can('manage_options'))
		return;
	if (!defined('EXECVITR_LICENSE_CHECK_URL'))
		return;

	$lastCheck = (int) get_option(EXECVITR_OPT_LICENSE_LASTCHECK, 0);
	$elapsed = time() - $lastCheck;

	$screen = function_exists('get_current_screen') ? get_current_screen() : null;
	$isLicensePage = $screen && strpos((string) $screen->id, 'execvitr-license') !== false;

	if ($isLicensePage || $elapsed > HOUR_IN_SECONDS) {
		$domain = strtolower(preg_replace('/^www\./i', '', (string) wp_parse_url(home_url(), PHP_URL_HOST)));
		$url = add_query_arg('domain', rawurlencode($domain), EXECVITR_LICENSE_CHECK_URL);

		$res = wp_remote_get($url, [
			'timeout' => 8,
			'headers' => ['Accept' => 'application/json']
		]);

		if (!is_wp_error($res) && wp_remote_retrieve_response_code($res) === 200) {
			$data = json_decode(wp_remote_retrieve_body($res), true);
			if (is_array($data) && isset($data['status'])) {
				$status = strtolower(trim($data['status']));
				$expires = strtotime($data['expires'] ?? '');
				$expired = $expires && $expires < time();

				$new_status = (!$expired && $status === 'valid') ? 'valid' : 'invalid';

				update_option(EXECVITR_OPT_LICENSE_STATUS, $new_status);
				update_option(EXECVITR_OPT_LICENSE_META, wp_json_encode(['json' => $data]));
				update_option(EXECVITR_OPT_LICENSE_LASTCHECK, time());
			}
		}
	}
});

/* -------------------------------------------------------------------------
 * WooCommerce dependency check
 * ------------------------------------------------------------------------- */
add_action('admin_notices', function () {
	if (!class_exists('WooCommerce')) {
		echo '<div class="notice notice-error"><p><strong>Executive VIP Transfer Service:</strong> WooCommerce must be active for this plugin to work.</p></div>';
	}
});

/* -------------------------------------------------------------------------
 * Helper
 * ------------------------------------------------------------------------- */
if (!function_exists('execvitr_get_option')) {
	function execvitr_get_option(string $key, $default = '')
	{
		$val = get_option('execvitr_' . $key, null);
		if (null !== $val)
			return $val;
		$old = get_option('vts_' . $key, null);
		if (null !== $old) {
			update_option('execvitr_' . $key, $old);
			return $old;
		}
		return $default;
	}
}

/* -------------------------------------------------------------------------
 * Booking product auto-setup
 * ------------------------------------------------------------------------- */
if (!function_exists('execvitr_maybe_create_booking_product')) {
	/**
	 * Ensures a WooCommerce product exists for the booking flow.
	 * Returns product ID on success, 0 on failure.
	 */
	function execvitr_maybe_create_booking_product(): int
	{
		if (!class_exists('WooCommerce')) {
			return 0;
		}

		$current_id = (int) get_option('execvitr_product_id', 0);
		if ($current_id > 0) {
			$p = get_post($current_id);
			if ($p && $p->post_type === 'product' && $p->post_status !== 'trash') {
				return $current_id;
			}
		}

		// Create a hidden, virtual simple product used as a "container" for booking totals.
		$post_id = wp_insert_post([
			'post_title' => 'VIP Transfer Booking',
			'post_status' => 'publish',
			'post_type' => 'product',
		]);

		if (is_wp_error($post_id) || !$post_id) {
			return 0;
		}

		// Set product type.
		if (function_exists('wp_set_object_terms')) {
			wp_set_object_terms($post_id, 'simple', 'product_type');
		}

		// Make virtual, no shipping/stock complications.
		update_post_meta($post_id, '_virtual', 'yes');
		update_post_meta($post_id, '_sold_individually', 'yes');
		update_post_meta($post_id, '_regular_price', '0');
		update_post_meta($post_id, '_price', '0');
		update_post_meta($post_id, '_manage_stock', 'no');
		update_post_meta($post_id, '_stock_status', 'instock');
		update_post_meta($post_id, '_visibility', 'hidden'); // Legacy
		update_post_meta($post_id, '_catalog_visibility', 'hidden');

		update_option('execvitr_product_id', (int) $post_id);
		return (int) $post_id;
	}
}

add_action('plugins_loaded', function () {
	// After activation we set this flag; run setup when WC is loaded.
	if ((int) get_option('execvitr_needs_product_setup', 0) !== 1) {
		return;
	}
	if (!class_exists('WooCommerce')) {
		return;
	}

	$pid = execvitr_maybe_create_booking_product();
	if ($pid > 0) {
		delete_option('execvitr_needs_product_setup');
	}
});

/* -------------------------------------------------------------------------
 * Admin notices (license / header)
 * ------------------------------------------------------------------------- */
add_action('admin_notices', function () {
	if (!current_user_can('manage_options'))
		return;
	if (function_exists('execvitr_is_pro_active') && execvitr_is_pro_active())
		return;

	$screen = function_exists('get_current_screen') ? get_current_screen() : null;
	if (!$screen)
		return;

	if (strpos((string) $screen->id, 'execvitr-license') !== false)
		return;

	if (strpos((string) $screen->id, 'execvitr') !== false) {
		echo '<div class="notice notice-info is-dismissible"><p>'
			. esc_html__('This domain is not licensed. Pro features are disabled.', 'executive-vip-transfer-service')
			. '</p></div>';
	}
});

/**
 * -------------------------------------------------------------------------
 * Admin Menu
 * -------------------------------------------------------------------------
 */
add_action('admin_menu', function () {
	// WooCommerce odaklı yetki: Shop Manager da erişebilsin.
	$cap = function_exists('execvitr_admin_capability') ? execvitr_admin_capability() : 'manage_woocommerce';
	add_menu_page(
		esc_html__('Settings', 'executive-vip-transfer-service'),
		esc_html__('Executive VIP Transfer Service', 'executive-vip-transfer-service'),
		$cap,
		'execvitr-settings',
		'execvitr_settings_page_html',
		'dashicons-location',
		56
	);

	add_submenu_page(
		'execvitr-settings',
		esc_html__('Orders', 'executive-vip-transfer-service'),
		esc_html__('Orders', 'executive-vip-transfer-service'),
		$cap,
		'execvitr-orders',
		'execvitr_orders_page_html'
	);

	// Hidden: custom reservation edit page (opened from Orders -> Edit)
	add_submenu_page(
		null,
		esc_html__('Edit Reservation', 'executive-vip-transfer-service'),
		esc_html__('Edit Reservation', 'executive-vip-transfer-service'),
		$cap,
		'execvitr-order-edit',
		'execvitr_order_edit_page_html'
	);

	add_submenu_page(
		'execvitr-settings',
		esc_html__('Cars', 'executive-vip-transfer-service'),
		esc_html__('Cars', 'executive-vip-transfer-service'),
		$cap,
		'execvitr-cars',
		'execvitr_cars_page_html'
	);

	add_submenu_page(
		'execvitr-settings',
		esc_html__('Contact', 'executive-vip-transfer-service'),
		esc_html__('Contact', 'executive-vip-transfer-service'),
		$cap,
		'execvitr-contact',
		'execvitr_contact_page_html'
	);
});

/**
 * -------------------------------------------------------------------------
 * Admin capability helpers
 * -------------------------------------------------------------------------
 */
if (!function_exists('execvitr_admin_capability')) {
	/**
	 * Menü/ayar sayfaları için ana yetki.
	 * Varsayılan: manage_woocommerce (Shop Manager uyumlu)
	 */
	function execvitr_admin_capability(): string
	{
		return (string) apply_filters('execvitr_admin_capability', 'manage_woocommerce');
	}
}

if (!function_exists('execvitr_user_can_manage')) {
	/**
	 * Yönetim aksiyonları için izin kontrolü (admin + shop manager).
	 */
	function execvitr_user_can_manage(): bool
	{
		return current_user_can(execvitr_admin_capability()) || current_user_can('manage_options');
	}
}

/**
 * -------------------------------------------------------------------------
 * Admin header helper (only execvitr pages)
 * -------------------------------------------------------------------------
 */
add_action('admin_notices', function () {
	if (!execvitr_user_can_manage())
		return;

	if (defined('EXECVITR_ADMIN_HEADER_PRINTED') && EXECVITR_ADMIN_HEADER_PRINTED)
		return;
	if (!defined('EXECVITR_ADMIN_HEADER_PRINTED'))
		define('EXECVITR_ADMIN_HEADER_PRINTED', true);

	$screen = function_exists('get_current_screen') ? get_current_screen() : null;
	if (!$screen)
		return;

	global $plugin_page;
	$current = isset($plugin_page) ? (string) $plugin_page : '';

	if (strpos($current, 'execvitr') === false)
		return;

	$is_pro = function_exists('execvitr_is_pro_active') && execvitr_is_pro_active();
	$badge = $is_pro
		? '<span class="cc-badge cc-badge-pro" title="' . esc_attr__('Pro active', 'executive-vip-transfer-service') . '">PRO</span>'
		: '<span class="cc-badge cc-badge-free" title="' . esc_attr__('Free mode', 'executive-vip-transfer-service') . '">FREE</span>';

	$logo_url = (defined('EXECVITR_URL') ? EXECVITR_URL : plugin_dir_url(__FILE__)) . 'assets/img/vts_logo.png';

	$menu_items = [
		'execvitr-settings' => [esc_html__('Settings', 'executive-vip-transfer-service'), '⚙️'],
		'execvitr-orders' => [esc_html__('Orders', 'executive-vip-transfer-service'), '📦'],
		'execvitr-cars' => [esc_html__('Cars', 'executive-vip-transfer-service'), '🚗'],
		'execvitr-license' => [esc_html__('License', 'executive-vip-transfer-service'), '🔑'],
	];

	echo '<div class="cc-header-bar" role="navigation" aria-label="' . esc_attr__('Executive VIP Transfer navigation', 'executive-vip-transfer-service') . '">';

	echo '<div class="cc-header-brand">';
	printf(
		'<img src="%1$s" alt="%2$s" loading="lazy" decoding="async" />',
		esc_url($logo_url),
		esc_attr__('Executive VIP Transfer Service Logo', 'executive-vip-transfer-service')
	);

	printf(
		'<div class="cc-header-title"><strong>%1$s</strong><br><span class="version">%2$s: %3$s</span> %4$s</div>',
		esc_html__('Executive VIP Transfer Service WP Plugin', 'executive-vip-transfer-service'),
		esc_html__('Version', 'executive-vip-transfer-service'),
		esc_html(defined('EXECVITR_VERSION') ? EXECVITR_VERSION : '1.0.0'),
		wp_kses_post($badge)
	);
	echo '</div>';

	echo '<nav class="cc-header-nav">';
	foreach ($menu_items as $slug => $data) {
		list($label, $icon) = $data;
		$url = admin_url('admin.php?page=' . $slug);
		$is_active = ($current === $slug);
		$active_class = $is_active ? 'active' : '';

		printf(
			'<a href="%1$s" class="%2$s"%3$s>%4$s %5$s</a>',
			esc_url($url),
			esc_attr($active_class),
			$is_active ? ' aria-current="page"' : '',
			esc_html($icon),
			esc_html($label)
		);
	}
	echo '</nav>';

	echo '<div class="cc-header-actions"><div class="cc-dropdown">';
	echo '<button class="cc-dropdown-toggle" aria-expanded="false" aria-haspopup="true" aria-label="' . esc_attr__('More actions', 'executive-vip-transfer-service') . '">⋯</button>';
	echo '<div class="cc-dropdown-menu" role="menu">';
	printf(
		'<a href="%1$s" target="_blank" rel="noopener" role="menuitem">❓ %2$s</a>',
		esc_url('https://gksoft.dev/contact'),
		esc_html__('Support', 'executive-vip-transfer-service')
	);
	printf(
		'<a href="%1$s" role="menuitem">💬 %2$s</a>',
		esc_url('mailto:plugins@gksoft.dev?subject=' . rawurlencode('Executive VIP Transfer Service Feedback')),
		esc_html__('Feedback', 'executive-vip-transfer-service')
	);
	echo '</div>';
	echo '</div></div>';

	echo '</div>';
});

/**
 * -------------------------------------------------------------------------
 * Shortcodes
 * -------------------------------------------------------------------------
 */
function execvitr_render_form_shortcode()
{
	// === GUARANTEED ENQUEUE ===
	execvitr_enqueue_front_assets_core();   // core + loader
	execvitr_enqueue_route_assets();        // route + css

	ob_start();
	require EXECVITR_PATH . 'templates/form-wrapper.php';
	return ob_get_clean();
}
add_shortcode('execvitr_form', 'execvitr_render_form_shortcode');

function execvitr_enqueue_front_assets_core(): void
{
	$api_key = execvitr_get_option('google_api_key', '');
	$base_url = EXECVITR_URL;
	$base_path = EXECVITR_PATH;

	// Loader (footer)
	wp_register_script(
		'execvitr-gmaps-loader',
		$base_url . 'assets/js/execvitr-gmaps-loader.js',
		['jquery'],
		EXECVITR_VERSION,
		true
	);
	wp_localize_script('execvitr-gmaps-loader', 'execvitrLoader', [
		'apiKey' => $api_key,
		'language' => substr(get_locale(), 0, 2),
		'region' => strtolower((string) execvitr_get_option('country', 'TR')),
	]);

	// Core (footer) – loader’a bağımlı
	wp_register_script(
		'execvitr-js',
		$base_url . 'assets/js/execvitr.js',
		['jquery', 'execvitr-gmaps-loader'],
		EXECVITR_VERSION,
		true
	);

	// Core style
	wp_register_style(
		'execvitr-style',
		$base_url . 'assets/css/style.css',
		[],
		EXECVITR_VERSION
	);

	wp_enqueue_script('execvitr-gmaps-loader');
	wp_enqueue_script('execvitr-js');
	wp_enqueue_style('execvitr-style');
}

function execvitr_enqueue_route_assets(): void
{
	wp_register_style(
		'execvitr-route-style',
		EXECVITR_URL . 'assets/css/route-summary.css',
		[],
		EXECVITR_VERSION
	);
	wp_register_script(
		'execvitr-route',
		EXECVITR_URL . 'assets/js/execvitr-route.js',
		['jquery', 'execvitr-js', 'execvitr-gmaps-loader'],
		EXECVITR_VERSION,
		true
	);
	wp_enqueue_style('execvitr-route-style');
	wp_enqueue_script('execvitr-route');
}

add_action('wp_enqueue_scripts', function () {
	$force = isset($_GET['execvitr_force']) && $_GET['execvitr_force'] === '1';

	$has_form = false;
	if (is_singular()) {
		$post_id = get_queried_object_id();
		if ($post_id) {
			$content = (string) get_post_field('post_content', $post_id);
			if ($content !== '') {
				$has_form = (strpos($content, '[execvitr_form]') !== false)
					|| (function_exists('has_shortcode') && has_shortcode($content, 'execvitr_form'));
			}
		}
	}

	// Elementor/Temalar bazen content’i farklı tutar; zorunlu bayrak
	if ($force) {
		$has_form = true;
	}

	if ($has_form) {
		execvitr_enqueue_front_assets_core();
		execvitr_enqueue_route_assets();
	}
}, 20);

/**
 * Front-end küçük “self-check” – footer yoksa/ API key boşsa konsol uyarısı.
 */
add_action('wp_head', function () {
	$api_key = execvitr_get_option('google_api_key', '');
	?>
	<script>
		(function () {
			// API key boşsa erken uyarı (sadece console)
			<?php if (empty($api_key)): ?>
				console.warn('[ExecVITR] Google Maps API key boş. Harita yüklenmez.');
			<?php endif; ?>

			// wp_footer() çalışmazsa footer scriptleri basılmayabilir
			window.addEventListener('load', function () {
				var hasLoader = !!document.querySelector('script[src*="execvitr-gmaps-loader"]');
				var hasCore = !!document.querySelector('script[src*="execvitr.js"]');
				if (!hasLoader || !hasCore) {
					console.warn('[ExecVITR] Footer scriptleri bulunamadı. Temanızda wp_footer() çağrılı mı?');
				}
			});
		})();
	</script>
	<?php
}, 1);

/**
 * Admin bar uyarısı: API key yoksa kolay teşhis.
 */
add_action('admin_notices', function () {
	if (!execvitr_user_can_manage())
		return;
	if (!execvitr_get_option('google_api_key', '')) {
		echo '<div class="notice notice-warning"><p><strong>Executive VIP Transfer:</strong> Google Maps API anahtarı ayarlı değil. Harita/rota yüklenmez. <em>Ayarlar → Google API Key</em></p></div>';
	}
});


function execvitr_render_tracking_shortcode()
{
	ob_start();
	$template = EXECVITR_PATH . 'templates/tracking-lite.php';
	if (file_exists($template))
		require $template;
	return ob_get_clean();
}
add_shortcode('execvitr_tracking', 'execvitr_render_tracking_shortcode');

/**
 * -------------------------------------------------------------------------
 * Tracking Template Loader
 * -------------------------------------------------------------------------
 */
add_filter('query_vars', function ($vars) {
	$vars[] = 'order_id';
	return $vars;
});

add_action('template_include', function ($template) {
	if (is_page('execvitr-tracking')) {
		$custom = EXECVITR_PATH . 'templates/tracking-lite.php';
		if (file_exists($custom))
			return $custom;
	}
	return $template;
});

/**
 * -------------------------------------------------------------------------
 * Admin-post: order status update (manual)
 * -------------------------------------------------------------------------
 */
add_action('admin_post_update_order_status', function () {
	if (isset($_POST['update_order_status_id'], $_POST['update_status_nonce'], $_POST['new_status'])) {
		$nonce = sanitize_text_field(wp_unslash($_POST['update_status_nonce']));
		if (!wp_verify_nonce($nonce, 'update_status_action')) {
			wp_safe_redirect(admin_url('admin.php?page=execvitr-orders&error=nonce'));
			exit;
		}

		$order_id = absint(wp_unslash($_POST['update_order_status_id']));
		$new_status = sanitize_text_field(wp_unslash($_POST['new_status']));
		$order = wc_get_order($order_id);
		$statuses = array_keys(wc_get_order_statuses());

		if ($order && in_array($new_status, $statuses, true)) {
			$order->update_status(str_replace('wc-', '', $new_status));
			$order->save();
			wp_safe_redirect(admin_url('admin.php?page=execvitr-orders&status_updated=1'));
			exit;
		}
		wp_safe_redirect(admin_url('admin.php?page=execvitr-orders&error=update'));
		exit;
	}
});

/**
 * -------------------------------------------------------------------------
 * Admin-post: delete (trash) a reservation (WooCommerce order)
 * -------------------------------------------------------------------------
 */
add_action('admin_post_execvitr_delete_order', function () {
	if (!execvitr_user_can_manage()) {
		wp_safe_redirect(admin_url('admin.php?page=execvitr-orders&error=cap'));
		exit;
	}

	// Accept both GET and POST (some hosts block admin-post GET actions).
	$order_id = 0;
	if (isset($_REQUEST['order_id'])) {
		$order_id = absint(wp_unslash($_REQUEST['order_id']));
	}
	if ($order_id <= 0) {
		wp_safe_redirect(admin_url('admin.php?page=execvitr-orders&error=missing'));
		exit;
	}

	$nonce = '';
	if (isset($_REQUEST['_wpnonce'])) {
		$nonce = sanitize_text_field(wp_unslash($_REQUEST['_wpnonce']));
	} elseif (isset($_REQUEST['execvitr_delete_nonce'])) {
		// Backward-compat (older versions)
		$nonce = sanitize_text_field(wp_unslash($_REQUEST['execvitr_delete_nonce']));
	}
	if (!wp_verify_nonce($nonce, 'execvitr_delete_order_' . $order_id)) {
		wp_safe_redirect(admin_url('admin.php?page=execvitr-orders&error=nonce'));
		exit;
	}

	/**
	 * IMPORTANT:
	 * Some sites use WooCommerce HPOS (High-Performance Order Storage).
	 * In that mode orders may not exist as wp_posts rows, so get_post/wp_trash_post
	 * can fail even for valid orders. Always resolve via wc_get_order.
	 */
	if (!function_exists('wc_get_order')) {
		wp_safe_redirect(admin_url('admin.php?page=execvitr-orders&error=woo'));
		exit;
	}

	$order = wc_get_order($order_id);
	if (!$order || !is_a($order, 'WC_Order')) {
		wp_safe_redirect(admin_url('admin.php?page=execvitr-orders&error=notfound'));
		exit;
	}

	// Move to trash (safer than permanent delete)
	$trashed = false;

	// 1) Preferred: WC CRUD delete(false) => trash when supported (works for CPT & HPOS)
	try {
		$order->delete(false);
		$trashed = true;
	} catch (Exception $e) {
		$trashed = false;
	}

	// 2) Fallback for legacy CPT storage: try wp_trash_post
	if (!$trashed && function_exists('wp_trash_post')) {
		$res = wp_trash_post($order_id);
		if ($res) {
			$trashed = true;
		}
	}

	// 3) Last fallback: directly update post_status (only for CPT storage)
	if (!$trashed && function_exists('get_post')) {
		$post = get_post($order_id);
		if ($post && isset($post->post_type) && $post->post_type === 'shop_order') {
			$u = wp_update_post([
				'ID' => $order_id,
				'post_status' => 'trash',
			], true);
			if (!is_wp_error($u)) {
				$trashed = true;
			}
		}
	}

	if (!$trashed) {
		wp_safe_redirect(admin_url('admin.php?page=execvitr-orders&error=trash_failed'));
		exit;
	}

	wp_safe_redirect(admin_url('admin.php?page=execvitr-orders&deleted=1'));
	exit;
});


/**
 * -------------------------------------------------------------------------
 * Admin-post: update reservation meta (custom edit page)
 * -------------------------------------------------------------------------
 */
add_action('admin_post_execvitr_update_order', function () {
	if (!execvitr_user_can_manage()) {
		wp_safe_redirect(admin_url('admin.php?page=execvitr-orders&error=cap'));
		exit;
	}

	$order_id = isset($_POST['order_id']) ? absint(wp_unslash($_POST['order_id'])) : 0;
	if ($order_id <= 0) {
		wp_safe_redirect(admin_url('admin.php?page=execvitr-orders&error=missing'));
		exit;
	}

	$nonce = isset($_POST['execvitr_update_nonce']) ? sanitize_text_field(wp_unslash($_POST['execvitr_update_nonce'])) : '';
	if (!wp_verify_nonce($nonce, 'execvitr_update_order_' . $order_id)) {
		wp_safe_redirect(admin_url('admin.php?page=execvitr-order-edit&order_id=' . $order_id . '&error=nonce'));
		exit;
	}

	$order = wc_get_order($order_id);
	if (!$order || !is_a($order, 'WC_Order')) {
		wp_safe_redirect(admin_url('admin.php?page=execvitr-orders&error=notfound'));
		exit;
	}

	// Current booking json
	$booking = [];
	$booking_json = (string) $order->get_meta('_execvitr_booking_json');
	if ($booking_json) {
		$decoded = json_decode($booking_json, true);
		if (is_array($decoded))
			$booking = $decoded;
	}

	// Read inputs
	$pickup_location = isset($_POST['pickup_location']) ? sanitize_text_field(wp_unslash($_POST['pickup_location'])) : '';
	$dropoff_location = isset($_POST['dropoff_location']) ? sanitize_text_field(wp_unslash($_POST['dropoff_location'])) : '';

	$pickup_date = isset($_POST['pickup_date']) ? sanitize_text_field(wp_unslash($_POST['pickup_date'])) : '';
	$pickup_time = isset($_POST['pickup_time']) ? sanitize_text_field(wp_unslash($_POST['pickup_time'])) : '';
	$pickup_datetime = trim($pickup_date . ' ' . $pickup_time);

	$is_return = isset($_POST['is_return']) && (string) wp_unslash($_POST['is_return']) === '1';
	$return_date = isset($_POST['return_date']) ? sanitize_text_field(wp_unslash($_POST['return_date'])) : '';
	$return_time = isset($_POST['return_time']) ? sanitize_text_field(wp_unslash($_POST['return_time'])) : '';
	$return_datetime = trim($return_date . ' ' . $return_time);

	$passengers = isset($_POST['passengers']) ? max(1, absint(wp_unslash($_POST['passengers']))) : 1;
	$luggage = isset($_POST['luggage']) ? max(0, absint(wp_unslash($_POST['luggage']))) : 0;

	$car_name = isset($_POST['car_name']) ? sanitize_text_field(wp_unslash($_POST['car_name'])) : '';
	$payment_method = isset($_POST['payment_method']) ? sanitize_text_field(wp_unslash($_POST['payment_method'])) : '';
	$phone = isset($_POST['phone']) ? sanitize_text_field(wp_unslash($_POST['phone'])) : '';
	$email = isset($_POST['email']) ? sanitize_email(wp_unslash($_POST['email'])) : '';
	$notes = isset($_POST['notes']) ? sanitize_textarea_field(wp_unslash($_POST['notes'])) : '';

	$distance_km = isset($_POST['distance_km']) ? (float) wp_unslash($_POST['distance_km']) : 0;
	$distance_text = isset($_POST['distance_text']) ? sanitize_text_field(wp_unslash($_POST['distance_text'])) : '';
	$duration = isset($_POST['duration']) ? sanitize_text_field(wp_unslash($_POST['duration'])) : '';

	$base_fee = isset($_POST['base_fee']) ? (float) wp_unslash($_POST['base_fee']) : 0;
	$total_fee = isset($_POST['total_fee']) ? (float) wp_unslash($_POST['total_fee']) : 0;

	if ($pickup_location !== '')
		$booking['pickup_location'] = $pickup_location;
	if ($dropoff_location !== '')
		$booking['dropoff_location'] = $dropoff_location;

	$booking['pickup_datetime'] = $pickup_datetime;
	$booking['is_return'] = (bool) $is_return;
	$booking['return_datetime'] = $is_return ? $return_datetime : '';

	$booking['passengers'] = $passengers;
	$booking['luggage'] = $luggage;
	$booking['car_name'] = $car_name;
	$booking['payment_method'] = $payment_method;
	$booking['phone'] = $phone;
	$booking['user_email'] = $email;
	$booking['notes'] = $notes;

	if ($distance_km > 0)
		$booking['distance_km'] = $distance_km;
	if ($distance_text !== '')
		$booking['distance_text'] = $distance_text;
	if ($duration !== '')
		$booking['duration'] = $duration;

	if ($base_fee > 0)
		$booking['base_fee'] = $base_fee;
	if ($total_fee > 0)
		$booking['total_fee'] = $total_fee;

	// Persist booking json
	$order->update_meta_data('_execvitr_booking_json', wp_json_encode($booking));

	// Keep compatibility metas used by Orders list
	$order->update_meta_data('_cc_pickup_location', $pickup_location);
	$order->update_meta_data('_cc_dropoff_location', $dropoff_location);
	$order->update_meta_data('_cc_pickup_datetime', $pickup_datetime);
	$order->update_meta_data('_execvitr_vehicle', $car_name);
	$order->update_meta_data('_cc_car_brand', $car_name);
	$order->update_meta_data('_execvitr_is_return', $is_return ? '1' : '0');
	if ($is_return && $return_datetime !== '') {
		$order->update_meta_data('_execvitr_return_datetime', $return_datetime);
	} else {
		$order->delete_meta_data('_execvitr_return_datetime');
	}

	// Update billing (for emails)
	if ($email !== '')
		$order->set_billing_email($email);
	if ($phone !== '')
		$order->set_billing_phone($phone);

	// Update line item totals to match total_fee if provided
	if ($total_fee > 0) {
		foreach ($order->get_items() as $item_id => $item) {
			if (!is_a($item, 'WC_Order_Item_Product'))
				continue;
			$item->set_subtotal($total_fee);
			$item->set_total($total_fee);
			$item->save();
			break;
		}
	}

	$order->calculate_totals();
	$order->save();

	wp_safe_redirect(admin_url('admin.php?page=execvitr-order-edit&order_id=' . $order_id . '&updated=1'));
	exit;
});



add_filter('woocommerce_get_order_item_totals', function (array $totals, WC_Order $order, $tax_display) {
	// Sadece order-pay sayfasında çalışsın
	if (!function_exists('is_checkout_pay_page') || !is_checkout_pay_page()) {
		return $totals;
	}

	// Subtotal 0 veya negatifse satırı kaldır
	$subtotal = (float) $order->get_subtotal(); // ürün satırları toplamı
	if (isset($totals['cart_subtotal']) && $subtotal <= 0) {
		unset($totals['cart_subtotal']);
	}

	/* İSTEĞE BAĞLI: Subtotal'ı değiştirmek isterseniz (örnek)
	if ( isset($totals['cart_subtotal']) ) {
		// Etiketi değiştir
		$totals['cart_subtotal']['label'] = __('Service subtotal', 'executive-vip-transfer-service') . ':';
		// Değeri değiştir (örnek: ücret (fees) toplamını göster)
		$fees_total = array_reduce( $order->get_fees(), fn($c, $fee) => $c + (float) $fee->get_total(), 0.0 );
		$totals['cart_subtotal']['value'] = wc_price( $fees_total, ['currency' => $order->get_currency()] );
	}
	*/

	return $totals;
}, 10, 3);

// add_action('wp_head', function () {
// 	if (function_exists('is_checkout_pay_page') && is_checkout_pay_page()) {
// 		echo '<style>
//         /* Quantity tamamen gizle */
//         .woocommerce table.shop_table th.product-quantity,
//         .woocommerce table.shop_table td.product-quantity { display:none !important; }

//         /* İki sütun arasında kalan çizgiyi söndür */
//         .woocommerce table.shop_table th.product-name,
//         .woocommerce table.shop_table td.product-name { border-right: none !important; }
//         .woocommerce table.shop_table th.product-total,
//         .woocommerce table.shop_table td.product-total { border-left: none !important; }

//         /* Genişlikleri iki sütuna böl */
//         .woocommerce table.shop_table thead th.product-name,
//         .woocommerce table.shop_table td.product-name { width: 70%; }
//         .woocommerce table.shop_table thead th.product-total,
//         .woocommerce table.shop_table td.product-total { width: 30%; text-align: right; }

//         /* Görsel düzen: boşluklar ve kalınlık */
//         .woocommerce table.shop_table th,
//         .woocommerce table.shop_table td { padding: 10px 12px; }
//         .woocommerce table.shop_table td.product-name { font-weight: 600; }
//         </style>';
// 	}
// });
/**
 * -------------------------------------------------------------------------
 * Admin assets
 * -------------------------------------------------------------------------
 */
add_action('admin_enqueue_scripts', function () {
	if (!execvitr_user_can_manage())
		return;

	$base_url = defined('EXECVITR_URL') ? EXECVITR_URL : plugin_dir_url(__FILE__);
	$base_path = defined('EXECVITR_PATH') ? EXECVITR_PATH : plugin_dir_path(__FILE__);
	$fallback_ver = defined('EXECVITR_VERSION') ? EXECVITR_VERSION : '1.0.0';

	$screen = function_exists('get_current_screen') ? get_current_screen() : null;
	global $plugin_page;
	$page_qs = isset($_GET['page']) ? sanitize_key($_GET['page']) : '';
	$page_glob = is_string($plugin_page ?? '') ? (string) $plugin_page : '';

	$is_execvitr_page =
		($page_qs !== '' && strpos($page_qs, 'execvitr') === 0) ||
		($page_glob !== '' && strpos($page_glob, 'execvitr') === 0) ||
		($screen && strpos((string) $screen->id, 'execvitr') !== false);

	if (!$is_execvitr_page)
		return;

	$our_pages = ['execvitr-settings', 'execvitr-orders', 'execvitr-order-edit', 'execvitr-cars', 'execvitr-contact', 'execvitr-license'];
	$current_page = $page_qs ?: $page_glob;
	if (!in_array($current_page, $our_pages, true))
		return;

	if ($current_page === 'execvitr-cars')
		wp_enqueue_media();

	$admin_css_files = [
		'execvitr-admin-style' => 'assets/css/admin-style.css',
		'execvitr-admin-frontend-style' => 'assets/css/style.css',
	];

	foreach ($admin_css_files as $handle => $rel) {
		if (file_exists($base_path . $rel)) {
			$css_ver = (string) (@filemtime($base_path . $rel) ?: $fallback_ver);
			wp_enqueue_style($handle, $base_url . $rel, [], $css_ver);
			wp_style_add_data($handle, 'rtl', 'replace');
		}
	}

	$js_rel = file_exists($base_path . 'assets/js/execvitr-admin.js')
		? 'assets/js/execvitr-admin.js'
		: 'assets/js/execvitr.js';

	$js_ver = (string) (@filemtime($base_path . $js_rel) ?: $fallback_ver);

	wp_enqueue_script('execvitr-admin', $base_url . $js_rel, ['jquery'], $js_ver, true);
	wp_localize_script('execvitr-admin', 'EXECVITR_Cars_i18n', [
		'selectImage' => __('Select Image', 'executive-vip-transfer-service'),
		'useImage' => __('Use this image', 'executive-vip-transfer-service'),
		'noImage' => __('No image', 'executive-vip-transfer-service'),
	]);
});

/**
 * -------------------------------------------------------------------------
 * Frontend Assets (+ Google Maps double-load prevention)
 * -------------------------------------------------------------------------
 */
add_action('wp_enqueue_scripts', function () {
	$api_key = execvitr_get_option('google_api_key', '');
	$deps = ['jquery'];

	// Yaygın GMaps handle’ları: başka eklenti zaten enqueued mu?
	$known_handles = ['google-maps', 'googlemaps', 'maps-googleapis', 'gmaps', 'gmap-api', 'google-maps-api'];
	$someone_loaded_maps = false;
	foreach ($known_handles as $h) {
		if (wp_script_is($h, 'enqueued') || wp_script_is($h, 'to_enqueue') || wp_script_is($h, 'registered')) {
			$someone_loaded_maps = true;
			break;
		}
	}


	// Loader: inject Maps API only if it's not already present in DOM/runtime
	wp_register_script(
		'execvitr-gmaps-loader',
		EXECVITR_URL . 'assets/js/execvitr-gmaps-loader.js',
		['jquery'],
		EXECVITR_VERSION,
		true
	);
	wp_localize_script(
		'execvitr-gmaps-loader',
		'execvitrLoader',
		[
			'apiKey' => $api_key,
			'language' => substr(get_locale(), 0, 2),
			'region' => strtolower((string) execvitr_get_option('country', 'TR')),
		]
	);
	$deps[] = 'execvitr-gmaps-loader';
	wp_enqueue_script(
		'execvitr-js',
		EXECVITR_URL . 'assets/js/execvitr.js',
		$deps,
		EXECVITR_VERSION,
		true
	);

	$currency_code = (string) execvitr_get_option('currency', 'USD');
	$symbols = ['USD' => '$', 'EUR' => '€', 'GBP' => '£', 'TRY' => '₺', 'CAD' => 'C$', 'AUD' => 'A$', 'CHF' => 'CHF', 'JPY' => '¥', 'CNY' => '¥', 'AED' => 'د.إ', 'INR' => '₹', 'BRL' => 'R$', 'ZAR' => 'R', 'KRW' => '₩', 'MXN' => '$'];
	$currency_symbol = $symbols[$currency_code] ?? '$';

	wp_localize_script('execvitr-js', 'execvitrData', [
		'km_price' => (float) execvitr_get_option('km_price', 0),
		'minimum_price' => (float) execvitr_get_option('minimum_price', 0),
		'currency_symbol' => $currency_symbol,
		'currency_code' => $currency_code,
		'distance_unit' => (string) get_option('execvitr_distance_unit', 'km'),
		'max_distance_km' => (float) ((get_option('execvitr_distance_unit', 'km') === 'mi') ? ((float) execvitr_get_option('max_distance', 0) * 1.609344) : (float) execvitr_get_option('max_distance', 0)),
		'min_booking_hours' => (int) get_option('execvitr_min_booking_hours', 0),
		'country' => (string) execvitr_get_option('country', 'TR'), // ← ülke
	]);

	wp_localize_script('execvitr-js', 'execvitr_ajax', [
		'ajax_url' => admin_url('admin-ajax.php'),
		'nonce' => wp_create_nonce('execvitr-ajax'),
	]);

	wp_enqueue_style('execvitr-style', EXECVITR_URL . 'assets/css/style.css', [], EXECVITR_VERSION);
});

add_action('wp_enqueue_scripts', function () {
	// Already enqueue 'execvitr-js' and 'execvitr-gmaps-loader' earlier in your plugin.
	// Enqueue route/summary only when our form shortcodes/templates are present.
	if (is_page()) {
		global $post;
		$content = is_a($post, 'WP_Post') ? ($post->post_content ?? '') : '';
		$should_load = (strpos($content, '[execvitr_form]') !== false)
			|| (function_exists('has_shortcode') && has_shortcode($content, 'execvitr_form'));

		if ($should_load) {
			wp_enqueue_style(
				'execvitr-route-style',
				EXECVITR_URL . 'assets/css/route-summary.css',
				[],
				EXECVITR_VERSION
			);
			wp_enqueue_script(
				'execvitr-route',
				EXECVITR_URL . 'assets/js/execvitr-route.js',
				['jquery', 'execvitr-js', 'execvitr-gmaps-loader'], // WHY: wait for core + loader
				EXECVITR_VERSION,
				true
			);
		}
	}
});

// JS-side guard: Google Maps init only once
add_action('wp_head', function () {
	?>
	<script>
		window.__execvitrMapInitDone = false;
		function execvitrSafeInitMap(fn) {
			if (window.google && window.google.maps) {
				if (!window.__execvitrMapInitDone) {
					window.__execvitrMapInitDone = true;
					try { fn(); } catch (e) { console.error(e); }
				}
			} else {
				setTimeout(function () { execvitrSafeInitMap(fn); }, 500);
			}
		}
	</script>
	<?php
});

/**
 * -------------------------------------------------------------------------
 * Activation: create pages
 * -------------------------------------------------------------------------
 */
register_activation_hook(__FILE__, function () {
	if (!function_exists('wp_insert_post')) {
		require_once ABSPATH . 'wp-admin/includes/post.php';
	}

	$pages = [
		'execvitr-form' => '[execvitr_form]',
		'execvitr-tracking' => '[execvitr_tracking]',
	];

	foreach ($pages as $slug => $shortcode) {
		if (!get_page_by_path($slug)) {
			wp_insert_post([
				'post_title' => ucwords(str_replace('-', ' ', $slug)),
				'post_name' => $slug,
				'post_content' => $shortcode,
				'post_status' => 'publish',
				'post_type' => 'page',
				'comment_status' => 'closed',
			]);
		}
	}
});


/** ------------------------------------------------------------------------
 *  Paths helper: uploads/execvitr/ticket-<id>.pdf + proxy URL
 * ------------------------------------------------------------------------- */
if (!function_exists('execvitr_ticket_paths')) {
	function execvitr_ticket_paths(int $order_id): array
	{
		$uploads = wp_upload_dir();
		$dir = trailingslashit($uploads['basedir']) . 'execvitr';
		$path = trailingslashit($dir) . 'ticket-' . $order_id . '.pdf';
		$url = trailingslashit($uploads['baseurl']) . 'execvitr/ticket-' . $order_id . '.pdf';

		$proxy = add_query_arg([
			'execvitr_pdf' => 1,
			'order_id' => $order_id,
			'nonce' => wp_create_nonce('cc_pdf_' . $order_id),
		], home_url('/'));

		return compact('dir', 'path', 'url', 'proxy');
	}
}

/** ------------------------------------------------------------------------
 *  Order data collector (pickup/drop/date/vehicle/distance/currency/email…)
 * ------------------------------------------------------------------------- */
if (!function_exists('execvitr_collect_order_data')) {
	function execvitr_collect_order_data(WC_Order $order): array
	{
		$raw_symbol = get_woocommerce_currency_symbol($order->get_currency());
		$symbol_utf = html_entity_decode((string) $raw_symbol, ENT_QUOTES, 'UTF-8');

		$first = trim((string) $order->get_billing_first_name());
		$last = trim((string) $order->get_billing_last_name());
		if ($first === '')
			$first = (string) $order->get_meta('_cc_sender_name');
		if ($last === '')
			$last = (string) $order->get_meta('_cc_sender_surname');

		$full_name = trim($first . ' ' . $last);
		$email = (string) ($order->get_billing_email()
			?: $order->get_meta('_cc_user_email')
			?: $order->get_meta('_execvitr_customer_email'));

		// Eski/yeni anahtarlar arasında uyumluluk
		$pickup = (string) (
			$order->get_meta('_execvitr_pickup')
			?: $order->get_meta('_cc_address_from')
			?: $order->get_meta('_cc_pickup_location')
			?: $order->get_meta('_cc_pickup')
		);
		$drop = (string) (
			$order->get_meta('_execvitr_drop')
			?: $order->get_meta('_cc_address_to')
			?: $order->get_meta('_cc_dropoff_location')
			?: $order->get_meta('_cc_drop')
		);
		$date = (string) (
			$order->get_meta('_execvitr_date')
			?: $order->get_meta('_cc_pickup_datetime')
			?: $order->get_meta('_cc_arrival_time')
			?: $order->get_meta('_cc_date')
		);

		// Return booking (optional)
		$is_return = false;
		$return_dt = '';
		$meta_is_return = (string) $order->get_meta('_execvitr_is_return');
		if ($meta_is_return !== '') {
			$is_return = ($meta_is_return === '1' || strtolower($meta_is_return) === 'yes');
		}
		$meta_return_dt = (string) $order->get_meta('_execvitr_return_datetime');
		if ($meta_return_dt !== '') {
			$return_dt = $meta_return_dt;
		}
		$booking_json = (string) $order->get_meta('_execvitr_booking_json');
		if ($booking_json) {
			$decoded = json_decode($booking_json, true);
			if (is_array($decoded)) {
				if (array_key_exists('is_return', $decoded)) {
					$is_return = (bool) $decoded['is_return'];
				}
				if ($return_dt === '' && !empty($decoded['return_datetime'])) {
					$return_dt = (string) $decoded['return_datetime'];
				}
			}
		}


		// Vehicle: booking_json > explicit meta > index->settings
		$vehicle = '';
		$booking_json = (string) $order->get_meta('_execvitr_booking_json');
		if ($booking_json) {
			$decoded = json_decode($booking_json, true);
			if (is_array($decoded) && !empty($decoded['car_name'])) {
				$vehicle = (string) $decoded['car_name'];
			}
		}
		if ($vehicle === '') {
			$vehicle = (string) ($order->get_meta('_execvitr_vehicle') ?: $order->get_meta('_cc_car_brand') ?: $order->get_meta('car_brand'));
		}
		if ($vehicle === '') {
			// IMPORTANT: WC_Order::get_meta() has no default parameter. Missing meta returns ''
			// and (int)'' becomes 0 -> first car for all orders.
			$car_index = -1;
			if ($booking_json) {
				$decoded = isset($decoded) && is_array($decoded) ? $decoded : json_decode($booking_json, true);
				if (is_array($decoded) && isset($decoded['car_index'])) {
					$car_index = (int) $decoded['car_index'];
				}
			}
			if ($car_index < 0) {
				$ci = $order->get_meta('_cc_car_index');
				$car_index = ($ci === '' || $ci === null) ? -1 : (int) $ci;
			}
			if ($car_index >= 0) {
				$cars = get_option('execvitr_cars', []);
				if (is_array($cars) && isset($cars[$car_index]['brand'])) {
					$vehicle = (string) $cars[$car_index]['brand'];
				}
			}
		}

		$distance_km = (string) ($order->get_meta('_execvitr_distance_km') ?: $order->get_meta('_cc_distance_km') ?: '');

		return [
			'order_id' => $order->get_id(),
			'pickup' => $pickup,
			'drop' => $drop,
			'date' => $date,
			'is_return' => $is_return,
			'return_datetime' => $return_dt,
			'vehicle' => $vehicle,
			'distance_km' => $distance_km,
			'price' => wc_format_decimal($order->get_total(), 2),
			'email' => $email,
			'customer' => $full_name,
			'currency' => $symbol_utf,
		];
	}
}

/** ------------------------------------------------------------------------
 *  Simple ASCII PDF fallback (kütüphane yoksa)
 * ------------------------------------------------------------------------- */
if (!function_exists('execvitr_generate_simple_pdf_raw')) {
	function execvitr_generate_simple_pdf_raw(string $filepath, array $data): bool
	{
		$currency = $data['currency'] ?? '';
		$lines = array_values(array_filter([
			'Executive VIP Transfer – Booking Ticket',
			'-------------------------------------------',
			'Pickup: ' . ($data['pickup'] ?? ''),
			'Drop: ' . ($data['drop'] ?? ''),
			'Date: ' . ($data['date'] ?? ''),
			(!empty($data['is_return']) && !empty($data['return_datetime'])) ? ('Return: ' . ($data['return_datetime'] ?? '')) : null,
			'Car: ' . ($data['vehicle'] ?? ''),
			'Distance: ' . (!empty($data['distance_text']) ? $data['distance_text'] : (($data['distance_km'] ?? '') . ' ' . ((get_option('execvitr_distance_unit', 'km') === 'mi') ? 'mi' : 'km'))),
			'Total Price: ' . ($currency . ' ' . ($data['price'] ?? '')),
			'Ticket No: ' . ($data['order_id'] ?? ''),
			'',
			'Note: This ticket was created automatically by the system.',
		]));

		$left = 50;
		$top = 800;
		$lead = 16;
		$content = "BT\n/F1 12 Tf\n{$left} {$top} Td\n{$lead} TL\n";
		foreach ($lines as $i => $line) {
			if ($i === 0)
				$content .= "/F1 16 Tf\n";
			elseif ($i === 1)
				$content .= "/F1 12 Tf\n";
			$safe = preg_replace('/[^\x09\x0A\x0D\x20-\x7E]/', '?', (string) $line); // ASCII
			$safe = str_replace(['\\', '(', ')'], ['\\\\', '\(', '\)'], $safe);
			$content .= "({$safe}) Tj\nT*\n";
		}
		$content .= "ET";
		$stream = "<< /Length " . strlen($content) . " >>\nstream\n{$content}\nendstream";

		$objs = [];
		$objs[] = "1 0 obj << /Type /Catalog /Pages 2 0 R >> endobj";
		$objs[] = "2 0 obj << /Type /Pages /Count 1 /Kids [3 0 R] >> endobj";
		$objs[] = "3 0 obj << /Type /Page /Parent 2 0 R /MediaBox [0 0 595 842] /Resources << /Font << /F1 4 0 R >> >> /Contents 5 0 R >> endobj";
		$objs[] = "4 0 obj << /Type /Font /Subtype /Type1 /BaseFont /Helvetica >> endobj";
		$objs[] = "5 0 obj {$stream} endobj";

		$pdf = "%PDF-1.4\n";
		$offs = [];
		foreach ($objs as $o) {
			$offs[] = strlen($pdf);
			$pdf .= $o . "\n";
		}
		$xref = strlen($pdf);
		$pdf .= "xref\n0 " . (count($offs) + 1) . "\n0000000000 65535 f \n";
		foreach ($offs as $o)
			$pdf .= sprintf("%010d 00000 n \n", $o);
		$pdf .= "trailer << /Size " . (count($offs) + 1) . " /Root 1 0 R >>\nstartxref\n{$xref}\n%%EOF";

		if (!file_exists(dirname($filepath)))
			wp_mkdir_p(dirname($filepath));
		return (bool) file_put_contents($filepath, $pdf);
	}
}

/** ------------------------------------------------------------------------
 *  Unicode PDF (tFPDF + DejaVu) — varsa kullan, yoksa fallback
 * ------------------------------------------------------------------------- */
if (!function_exists('execvitr_generate_ticket_pdf')) {
	function execvitr_generate_ticket_pdf(string $filepath, array $data): bool
	{
		// Bu sabitleri eklenti giriş dosyanda tanımlıyorsun:
		// define('EXECVITR_TFPDF_PATH', trailingslashit(EXECVITR_PATH).'includes/lib/tfpdf.php');
		// define('EXECVITR_TFPDF_FONT_TTF', trailingslashit(EXECVITR_PATH).'includes/lib/font/unifont/DejaVuSans.ttf');
		$has_lib = defined('EXECVITR_TFPDF_PATH') && file_exists(EXECVITR_TFPDF_PATH);
		$has_font = defined('EXECVITR_TFPDF_FONT_TTF') && file_exists(EXECVITR_TFPDF_FONT_TTF);

		if (!$has_lib || !$has_font) {
			return execvitr_generate_simple_pdf_raw($filepath, $data); // fallback
		}

		require_once EXECVITR_TFPDF_PATH;
		$pdf = new \tFPDF('P', 'mm', 'A4');
		$pdf->AddPage();
		$pdf->AddFont('DejaVu', '', 'DejaVuSans.ttf', true);
		$pdf->SetMargins(15, 15, 15);
		$pdf->SetAutoPageBreak(true, 15);

		$pdf->SetFont('DejaVu', '', 18);
		$pdf->Cell(0, 10, 'Executive VIP Transfer – Booking Ticket', 0, 2, 'L');
		$pdf->SetFont('DejaVu', '', 10);
		$pdf->SetTextColor(120, 120, 120);
		$pdf->Cell(0, 6, 'Created: ' . date_i18n('j F Y, H:i'), 0, 1, 'L');
		$pdf->SetTextColor(0, 0, 0);
		$pdf->Ln(2);
		$pdf->SetDrawColor(220, 220, 220);
		$pdf->Line(15, $pdf->GetY(), 195, $pdf->GetY());
		$pdf->Ln(6);

		$cur = html_entity_decode((string) ($data['currency'] ?? ''), ENT_QUOTES, 'UTF-8');
		// Distance label/value based on unit setting (km/mi)
		$distance_unit = (string) get_option('execvitr_distance_unit', 'km');
		$distance_label = ($distance_unit === 'mi') ? 'Distance (mi)' : 'Distance (km)';
		if (!empty($data['distance_text'])) {
			$distance_value = (string) $data['distance_text'];
		} else {
			$distance_km = isset($data['distance_km']) ? (float) $data['distance_km'] : 0.0;
			$distance_value = ($distance_unit === 'mi') ? (string) round($distance_km / 1.609344, 2) : (string) $distance_km;
		}


		$rows = [
			'Customer' => (string) ($data['customer'] ?? ''),
			'Mail' => (string) ($data['email'] ?? ''),
			'Pickup' => (string) ($data['pickup'] ?? ''),
			'Drop' => (string) ($data['drop'] ?? ''),
			'Date' => (string) ($data['date'] ?? ''),
			'Car' => (string) ($data['vehicle'] ?? ''),
			$distance_label => $distance_value,
			'Total Price' => trim($cur . ' ' . (string) ($data['price'] ?? '')),
			'Ticket No' => (string) ($data['order_id'] ?? ''),
		];
		if (!empty($data['is_return']) && !empty($data['return_datetime'])) {
			$rows['Return Date & Time'] = (string) $data['return_datetime'];
		}


		// (Opsiyonel) Firma alanları
		$company_name = get_option('execvitr_company_name', '');
		$company_tax = get_option('execvitr_company_taxno', '');
		$company_iban = get_option('execvitr_company_iban', '');
		if ($company_name || $company_tax || $company_iban) {
			$rows['Company'] = trim($company_name);
			if ($company_tax)
				$rows['Tax No'] = $company_tax;
			if ($company_iban)
				$rows['IBAN'] = $company_iban;
		}

		$pdf->SetFont('DejaVu', '', 12);
		$pdf->SetFillColor(245, 245, 245);
		$pdf->Cell(60, 9, 'Area', 1, 0, 'L', true);
		$pdf->Cell(0, 9, 'Value', 1, 1, 'L', true);
		$pdf->SetFont('DejaVu', '', 11);
		foreach ($rows as $k => $v) {
			$pdf->Cell(60, 8, $k, 1, 0, 'L');
			$pdf->Cell(0, 8, $v, 1, 1, 'L');
		}

		$pdf->Ln(6);
		$pdf->SetFont('DejaVu', '', 9);
		$pdf->SetTextColor(90, 90, 90);
		$pdf->MultiCell(0, 5, "Note: This ticket is automatically generated by the system. Please be ready 10 minutes before the transfer time.", 0, 'L');

		if (!file_exists(dirname($filepath)))
			wp_mkdir_p(dirname($filepath));
		$pdf->Output('F', $filepath);
		return file_exists($filepath);
	}
}


/** ------------------------------------------------------------------------
 *  Helper: is this order created by ExecVITR booking flow?
 * ------------------------------------------------------------------------- */
if (!function_exists('execvitr_is_booking_order')) {
	function execvitr_is_booking_order($order): bool
	{
		if (!$order instanceof WC_Order) {
			return false;
		}
		if ($order->get_meta('_execvitr_booking_flow')) {
			return true;
		}
		// Legacy fallbacks
		return (bool) ($order->get_meta('_execvitr_pickup')
			|| $order->get_meta('_cc_pickup_location')
			|| $order->get_meta('_cc_address_from'));
	}
}

/** ------------------------------------------------------------------------
 *  Mail sender (Woo mailer öncelik, yoksa wp_mail)
 * ------------------------------------------------------------------------- */
if (!function_exists('execvitr_send_html_mail')) {
	function execvitr_send_html_mail(string $to, string $subject, string $html, array $attachments = [], array $bcc = []): bool
	{
		$host = (string) wp_parse_url(home_url(), PHP_URL_HOST);
		$from_addr = 'no-reply@' . preg_replace('~^www\.~i', '', $host);
		$from_name = wp_specialchars_decode(get_bloginfo('name'), ENT_QUOTES);

		$headers = [
			'Content-Type: text/html; charset=UTF-8',
			'From: ' . $from_name . ' <' . $from_addr . '>',
			'Reply-To: ' . $from_name . ' <' . (get_option('admin_email') ?: $from_addr) . '>',
		];

		// Optional BCC (e.g., order notification email)
		if (!empty($bcc)) {
			$bcc = array_filter(array_map('sanitize_email', (array) $bcc));
			$bcc = array_values(array_unique(array_filter($bcc)));
			// Avoid duplicating the main recipient
			$bcc = array_values(array_filter($bcc, fn($e) => strtolower($e) !== strtolower($to)));
			if (!empty($bcc)) {
				$headers[] = 'Bcc: ' . implode(',', $bcc);
			}
		}

		try {
			if (function_exists('WC') && WC()->mailer()) {
				$mailer = WC()->mailer();
				return (bool) $mailer->send($to, $subject, $html, $headers, $attachments);
			}
		} catch (Throwable $e) {
			if (defined('WP_DEBUG') && WP_DEBUG)
				error_log('[ExecVITR][mailer] ' . $e->getMessage());
		}
		return (bool) wp_mail($to, $subject, $html, $headers, $attachments);
	}
}

add_action('wp_mail_failed', function ($wp_error) {
	if (defined('WP_DEBUG') && WP_DEBUG) {
		error_log('[ExecVITR][wp_mail_failed] ' . $wp_error->get_error_message());
	}
});

/** ------------------------------------------------------------------------
 *  Email HTML (müşteri/admin, paid rozeti opsiyonel)
 * ------------------------------------------------------------------------- */
if (!function_exists('execvitr_email_html')) {
	function execvitr_email_html(array $d, bool $is_admin = false, bool $paid = false, ?WC_Order $order = null): string
	{
		$badge = $paid
			? '<span style="background:#e6ffed;color:#0a8025;padding:2px 6px;border-radius:4px;font-size:12px">PAYMENT COMPLETED</span>'
			: '';

		// helper
		$get = static function ($v, $fallback = '') {
			$v = is_scalar($v) ? trim((string) $v) : '';
			return $v !== '' ? $v : (is_scalar($fallback) ? trim((string) $fallback) : '');
		};

		// Google Maps link helper (safe)
		$gmap = static function (string $address): string {
			$address = trim($address);
			if ($address === '')
				return '';
			$url = 'https://www.google.com/maps/search/?api=1&query=' . rawurlencode($address);
			return '<a href="' . esc_url($url) . '" target="_blank" rel="noopener noreferrer">' . esc_html($address) . '</a>';
		};


		// Distance unit (km/mi)
		$unit = get_option('execvitr_distance_unit', 'km');
		if (!empty($d['distance_unit'])) {
			$u = strtolower(trim((string) $d['distance_unit']));
			if (in_array($u, ['km', 'mi', 'mile', 'miles'], true))
				$unit = ($u === 'km') ? 'km' : 'mi';
		}
		if (!in_array($unit, ['km', 'mi'], true))
			$unit = 'km';

		$distance_label = 'Distance (' . ($unit === 'mi' ? 'mile' : 'km') . ')';

		// ---- ORDER fallback alanları
		$full_name = $phone = $email = '';
		$passengers = $bags = '';
		$arrival_time = '';
		$distance_value = '';

		if ($order instanceof WC_Order) {
			// Name
			$first = trim((string) $order->get_billing_first_name());
			$last = trim((string) $order->get_billing_last_name());
			if ($first === '')
				$first = (string) $order->get_meta('_cc_sender_name');
			if ($last === '')
				$last = (string) $order->get_meta('_cc_sender_surname');
			$full_name = trim($first . ' ' . $last);

			// Phone/Email (Woo default)
			$phone = (string) $order->get_billing_phone();
			if (trim($phone) === '')
				$phone = (string) $order->get_meta('_cc_sender_phone');

			$email = (string) $order->get_billing_email();
			if (trim($email) === '')
				$email = (string) $order->get_meta('_cc_sender_email');

			// Passengers/Bags (senin meta key’lerin)
			$p = (int) $order->get_meta('_cc_passenger_count');
			$b = (int) $order->get_meta('_cc_luggage_count');
			if ($p > 0)
				$passengers = (string) $p;
			if ($b > 0)
				$bags = (string) $b;

			// Arrival time
			$arrival_time_iso = (string) $order->get_meta('_cc_arrival_time');
			if ($arrival_time_iso !== '') {
				$ts = strtotime($arrival_time_iso);
				$arrival_time = $ts ? date_i18n(get_option('date_format') . ' ' . get_option('time_format'), $ts) : $arrival_time_iso;
			}

			// Distance fallback (eğer sen order meta’ya yazıyorsan buraya ekle)
			// Örn: _cc_distance_km / _cc_distance_mi gibi
			$distance_value = ($unit === 'mi')
				? (string) $order->get_meta('_cc_distance_mi')
				: (string) $order->get_meta('_cc_distance_km');
		}

		// Distance: önce $d, yoksa order meta, yoksa yine boş
		$distance_value = $get(
			($unit === 'mi')
			? ($d['distance_mi'] ?? $d['distance_miles'] ?? $d['distance'] ?? '')
			: ($d['distance_km'] ?? $d['distance'] ?? ''),
			$distance_value
		);

		$total_price = trim(($d['currency'] ?? '') . ' ' . ($d['price'] ?? ''));

		$pickup_raw = $get($d['pickup'] ?? '');
		$drop_raw = $get($d['drop'] ?? '');

		$rows = [
			'Name' => $get($full_name, $d['name'] ?? ''),
			'Pickup' => $gmap($pickup_raw),
			'Drop' => $gmap($drop_raw),
			'Date' => $get($d['date'] ?? ''),
			'Email' => $get($d['email'] ?? $d['customer_email'] ?? '', $email),
			'Phone' => $get($d['phone'] ?? $d['customer_phone'] ?? '', $phone),
			'Car' => $get($d['car'] ?? $d['vehicle'] ?? ''),
			$distance_label => $get($distance_value),
			'Passengers' => $get($d['passengers'] ?? $d['passangers'] ?? $d['pax'] ?? '', $passengers),
			'Bags' => $get($d['bags'] ?? '', $bags),
			'Arrival Time' => $get($arrival_time),
			'Notes' => $get($d['notes'] ?? $d['pickup_details'] ?? ''),
			'Total Price' => $get($total_price),
			'Ticket Id' => $get($d['ticket_id'] ?? $d['order_id'] ?? ''),
		];
		$return_dt = $get($d['return_datetime'] ?? '', ($order instanceof WC_Order) ? $order->get_meta('_execvitr_return_datetime') : '');
		$is_return_flag = !empty($d['is_return']);
		if (!$is_return_flag && ($order instanceof WC_Order)) {
			$is_return_flag = ((string) $order->get_meta('_execvitr_is_return') === '1');
		}
		if ($is_return_flag && $return_dt !== '') {
			$rows['Return Date & Time'] = $return_dt;
		}



		ob_start(); ?>
		<div style="font-family:Arial,Helvetica,sans-serif;line-height:1.5;color:#222">
			<h2 style="margin:0 0 8px">Executive VIP Transfer</h2>
			<p style="margin:0 0 12px"><?php echo $badge; ?></p>

			<table cellspacing="0" cellpadding="6" style="border-collapse:collapse;width:100%;max-width:580px">
				<?php foreach ($rows as $k => $v):
					$v = is_scalar($v) ? trim((string) $v) : '';
					if ($v === '')
						continue; ?>
					<tr>
						<td style="border:1px solid #eee;background:#fafafa;width:40%;font-weight:bold"><?php echo esc_html($k); ?>
						</td>
						<td style="border:1px solid #eee">
							<?php
							// Pickup/Drop rows contain HTML (<a>) - allow only safe tags.
							if ($k === 'Pickup' || $k === 'Drop') {
								echo wp_kses($v, [
									'a' => [
										'href' => [],
										'target' => [],
										'rel' => [],
									],
								]);
							} else {
								echo esc_html($v);
							}
							?>
						</td>

					</tr>
				<?php endforeach; ?>
			</table>

			<p style="margin-top:12px">
				<?php echo $is_admin ? 'New reservation information is above.' : 'Your reservation information is included in the attached PDF ticket.'; ?>
			</p>
		</div>
		<?php
		return ob_get_clean();
	}
}




/** ------------------------------------------------------------------------
 *  Güvenli PDF proxy endpoint: ?execvitr_pdf=1&order_id=###&nonce=...
 *  (Görüntüleme/indirme; mail tetiklemez)
 * ------------------------------------------------------------------------- */
add_action('init', function () {
	if (!isset($_GET['execvitr_pdf']))
		return;

	$order_id = absint($_GET['order_id'] ?? 0);
	$nonce = sanitize_text_field($_GET['nonce'] ?? '');

	if (!$order_id || !wp_verify_nonce($nonce, 'cc_pdf_' . $order_id)) {
		wp_die('Invalid link', 'PDF', ['response' => 403]);
	}

	$paths = execvitr_ticket_paths($order_id);
	$path = $paths['path'];

	// Dosya yoksa üret
	if (!file_exists($path)) {
		$order = wc_get_order($order_id);
		if ($order) {
			$data = execvitr_collect_order_data($order);
			if (!file_exists(dirname($path)))
				wp_mkdir_p(dirname($path));
			execvitr_generate_ticket_pdf($path, $data);
		}
	}

	if (!file_exists($path)) {
		wp_die('File not found', 'PDF', ['response' => 404]);
	}

	header('Content-Type: application/pdf');
	header('Content-Disposition: inline; filename="ticket-' . $order_id . '.pdf"');
	header('Content-Length: ' . filesize($path));
	header('Cache-Control: private, max-age=3600');
	readfile($path);
	exit;
});

/** ------------------------------------------------------------------------
 *  Tek-seferlik mail gönderici (initial/paid) — idempotent
 * ------------------------------------------------------------------------- */
if (!function_exists('execvitr_send_ticket_mail_once')) {
	function execvitr_send_ticket_mail_once(WC_Order $order, string $stage = 'initial'): void
	{
		if (!$order)
			return;

		// Sadece bizim rezervasyonlar (pickup meta varsa)
		if (!$order->get_meta('_execvitr_pickup') && !$order->get_meta('_cc_address_from') && !$order->get_meta('_cc_pickup_location'))
			return;

		// Idempotency flag
		$meta_key = ($stage === 'paid') ? '_execvitr_ticket_mail_paid' : '_execvitr_ticket_mail_initial';
		if ($order->get_meta($meta_key))
			return;

		// Data + PDF
		$data = execvitr_collect_order_data($order);
		$paths = execvitr_ticket_paths($order->get_id());
		if (!file_exists($paths['path'])) {
			if (!file_exists($paths['dir']))
				wp_mkdir_p($paths['dir']);
			execvitr_generate_ticket_pdf($paths['path'], $data);
		}


		// Order notification email (admin copy)
		$notify_to_raw = trim((string) get_option('execvitr_notify_admin'));
		$notify_to = sanitize_email($notify_to_raw);
		if (empty($notify_to)) {
			$notify_to = sanitize_email((string) get_option('admin_email'));
		}

		$subject = ($stage === 'paid') ? 'Reservation Confirmed (Paid)' : 'Reservation Received';

		// Customer email
		if (!empty($data['email'])) {
			$html = execvitr_email_html($data, false, $stage === 'paid', $order);
			execvitr_send_html_mail(
				$data['email'],
				$subject,
				$html,
				file_exists($paths['path']) ? [$paths['path']] : []
			);
		}

		// Admin copy
		if (!empty($notify_to)) {
			$html_admin = execvitr_email_html($data, true, $stage === 'paid', $order);
			execvitr_send_html_mail(
				$notify_to,
				$subject . ' (Admin)',
				$html_admin,
				file_exists($paths['path']) ? [$paths['path']] : []
			);
		}

		$order->update_meta_data($meta_key, current_time('mysql'));
		$order->add_order_note(sprintf('ExecVITR: Ticket mail sent (%s).', $stage));
		$order->save();
	}
}

/** ------------------------------------------------------------------------
 *  Tetikleyiciler
 *  1) Thank You (her gateway) → initial mail
 *  1b) Blocks fallback (order processed) → initial mail
 *  2) processing/completed → paid mail
 * ------------------------------------------------------------------------- */
add_action('woocommerce_thankyou', function ($order_id) {
	$order = wc_get_order($order_id);
	if (!$order)
		return;
	execvitr_send_ticket_mail_once($order, 'initial');
}, 20);

// Blocks checkout sometimes skips `woocommerce_thankyou` depending on templates.
add_action('woocommerce_checkout_order_processed', function ($order_id, $posted_data, $order) {
	if (!$order || !is_a($order, 'WC_Order')) {
		$order = wc_get_order($order_id);
	}
	if (!$order)
		return;
	execvitr_send_ticket_mail_once($order, 'initial');
}, 20, 3);

// Paid confirmation (send once when status becomes processing/completed)
if (!has_action('woocommerce_order_status_processing', 'execvitr_paid_mail_handler')) {
	add_action('woocommerce_order_status_processing', 'execvitr_paid_mail_handler', 20, 1);
}
if (!has_action('woocommerce_order_status_completed', 'execvitr_paid_mail_handler')) {
	add_action('woocommerce_order_status_completed', 'execvitr_paid_mail_handler', 20, 1);
}

function execvitr_paid_mail_handler($order_id)
{
	$order = wc_get_order($order_id);
	if (!$order)
		return;
	execvitr_send_ticket_mail_once($order, 'paid');
}

/** ------------------------------------------------------------------------
 *  Reduce email noise: for ExecVITR orders, disable default WooCommerce order emails.
 *  We send a single consolidated reservation email (with ticket) to customer + admin.
 * ------------------------------------------------------------------------- */
foreach ([
	'new_order',
	'customer_processing_order',
	'customer_on_hold_order',
	'customer_completed_order',
	'customer_invoice',
] as $email_id) {
	add_filter('woocommerce_email_enabled_' . $email_id, function ($enabled, $order) use ($email_id) {
		if ($order instanceof WC_Order && execvitr_is_booking_order($order)) {
			return false;
		}
		return $enabled;
	}, 20, 2);
}


// (removed broken paid-mail closures)



/** ------------------------------------------------------------------------
 *  Blocks checkout/order confirmation compatibility
 *  - Some block-based order confirmation pages don't trigger `woocommerce_thankyou`.
 *  - Ensure ticket emails and summary rendering still work.
 * ------------------------------------------------------------------------- */
if (!function_exists('execvitr_is_our_order')) {
	function execvitr_is_our_order($order)
	{
		if (!$order || !is_a($order, 'WC_Order'))
			return false;

		// Fast path: explicit flag / known meta
		if ($order->get_meta('_execvitr_booking_flow') || $order->get_meta('_execvitr_pickup') || $order->get_meta('_cc_address_from') || $order->get_meta('_cc_pickup_location')) {
			return true;
		}

		// Fallback: check if order contains our booking product or our line-item meta.
		$booking_product_id = (int) get_option('execvitr_product_id', 0);
		foreach ($order->get_items() as $item) {
			if (!is_a($item, 'WC_Order_Item_Product')) {
				continue;
			}
			if ($booking_product_id && (int) $item->get_product_id() === $booking_product_id) {
				return true;
			}
			// If we stored booking JSON on line items, treat it as our order.
			$bk_json = (string) $item->get_meta('_execvitr_booking_json', true);
			if ($bk_json !== '') {
				return true;
			}
		}

		return false;
	}

	/**
	 * -------------------------------------------------------------------------
	 * Order-Pay cleanup: remove billing/shipping address fields for ExecVITR flow
	 * -------------------------------------------------------------------------
	 * Goal: booking -> summary -> order-pay (payment methods only)
	 */
	add_filter('woocommerce_checkout_fields', function ($fields) {
		if (!function_exists('is_checkout') || !is_checkout()) {
			return $fields;
		}
		if (!function_exists('is_wc_endpoint_url') || !is_wc_endpoint_url('order-pay')) {
			return $fields;
		}
		$order_id = absint(get_query_var('order-pay'));
		if (!$order_id) {
			return $fields;
		}
		$order = function_exists('wc_get_order') ? wc_get_order($order_id) : null;
		if (!$order || !is_a($order, 'WC_Order')) {
			return $fields;
		}
		if (!function_exists('execvitr_is_our_order') || !execvitr_is_our_order($order)) {
			return $fields;
		}

		// Keep only minimal fields (optional) — email is helpful for some gateways/receipts.
		$keep = ['billing_email', 'billing_first_name', 'billing_last_name', 'billing_phone'];

		if (isset($fields['billing']) && is_array($fields['billing'])) {
			foreach (array_keys($fields['billing']) as $k) {
				if (!in_array($k, $keep, true)) {
					unset($fields['billing'][$k]);
				} else {
					$fields['billing'][$k]['required'] = false;
				}
			}
		}

		// Remove shipping + order comments entirely
		unset($fields['shipping']);
		unset($fields['order']);

		return $fields;
	}, 50);


}

/**
 * Ensure order has the expected booking meta for rendering/ticket/email.
 * Blocks checkout flows may skip some classic checkout actions depending on WC version.
 */
if (!function_exists('execvitr_ensure_order_booking_meta')) {
	function execvitr_ensure_order_booking_meta(WC_Order $order): void
	{
		// Already stamped
		if ($order->get_meta('_execvitr_booking_flow')) {
			return;
		}

		$booking = null;
		// Try session booking first
		if (function_exists('WC') && WC() && WC()->session) {
			$bk = WC()->session->get('execvitr_booking');
			if (is_array($bk) && !empty($bk)) {
				$booking = $bk;
			}
		}

		// If no session data, try order line item meta JSON
		if (!$booking) {
			foreach ($order->get_items() as $item) {
				if (!is_a($item, 'WC_Order_Item_Product')) {
					continue;
				}
				$bk_json = (string) $item->get_meta('_execvitr_booking_json', true);
				if ($bk_json !== '') {
					$decoded = json_decode($bk_json, true);
					if (is_array($decoded) && !empty($decoded)) {
						$booking = $decoded;
						break;
					}
				}
			}
		}

		if (!is_array($booking) || empty($booking)) {
			return;
		}

		// Mark order
		$order->update_meta_data('_execvitr_booking_flow', '1');

		// Legacy + current meta (keep templates + ticket generation stable)
		if (!empty($booking['pickup_location'])) {
			$order->update_meta_data('_execvitr_pickup', $booking['pickup_location']);
		}
		if (!empty($booking['dropoff_location'])) {
			$order->update_meta_data('_execvitr_drop', $booking['dropoff_location']);
		}
		if (!empty($booking['pickup_datetime'])) {
			$order->update_meta_data('_execvitr_date', $booking['pickup_datetime']);
		}
		if (isset($booking['distance_km'])) {
			$order->update_meta_data('_execvitr_distance_km', $booking['distance_km']);
		}
		if (isset($booking['total_fee'])) {
			$order->update_meta_data('_execvitr_total_fee', $booking['total_fee']);
		}

		if (!empty($booking['pickup_location'])) {
			$order->update_meta_data('_cc_pickup_location', $booking['pickup_location']);
		}
		if (!empty($booking['dropoff_location'])) {
			$order->update_meta_data('_cc_dropoff_location', $booking['dropoff_location']);
		}
		if (!empty($booking['pickup_datetime'])) {
			$order->update_meta_data('_cc_pickup_datetime', $booking['pickup_datetime']);
		}
		if (!empty($booking['vehicle_model'])) {
			$order->update_meta_data('_execvitr_vehicle', $booking['vehicle_model']);
		}
		if (isset($booking['passengers'])) {
			$order->update_meta_data('_cc_passengers', $booking['passengers']);
		}
		if (isset($booking['bags'])) {
			$order->update_meta_data('_cc_bags', $booking['bags']);
		}
		if (!empty($booking['distance_text'])) {
			$order->update_meta_data('_cc_distance_text', $booking['distance_text']);
		}
		if (!empty($booking['duration_text'])) {
			$order->update_meta_data('_cc_duration_text', $booking['duration_text']);
		}
		if (isset($booking['distance_km'])) {
			$order->update_meta_data('_cc_distance_km', $booking['distance_km']);
		}
		if (isset($booking['total_fee'])) {
			$order->update_meta_data('_cc_total_fee', $booking['total_fee']);
		}

		if (!empty($booking['billing_first_name'])) {
			$order->update_meta_data('_cc_sender_name', $booking['billing_first_name']);
		}
		if (!empty($booking['billing_last_name'])) {
			$order->update_meta_data('_cc_sender_surname', $booking['billing_last_name']);
		}
		if (!empty($booking['billing_email'])) {
			$order->update_meta_data('_cc_sender_email', $booking['billing_email']);
		}
		if (!empty($booking['billing_phone'])) {
			$order->update_meta_data('_cc_sender_phone', $booking['billing_phone']);
		}

		$order->save();
	}
}

if (!function_exists('execvitr_render_order_summary_and_ticket')) {
	function execvitr_render_order_summary_and_ticket($order)
	{
		if (!($order instanceof WC_Order))
			return;
		static $printed = false;
		if ($printed) {
			return;
		}
		$printed = true;
		$GLOBALS['execvitr_summary_printed'] = true;
		// Make sure booking meta exists (Blocks checkout can skip some classic actions).
		if (function_exists('execvitr_ensure_order_booking_meta')) {
			execvitr_ensure_order_booking_meta($order);
		}
		if (!execvitr_is_our_order($order))
			return;

		$data = execvitr_collect_order_data($order);
		$paths = execvitr_ticket_paths($order->get_id());

		// Ensure PDF exists
		if (!file_exists($paths['path'])) {
			if (!file_exists($paths['dir'])) {
				wp_mkdir_p($paths['dir']);
			}
			execvitr_generate_ticket_pdf($paths['path'], $data);
		}

		echo '<section class="woocommerce-order execvitr-summary" style="margin:24px 0">';
		echo '<h2>' . esc_html__('Reservation Summary', 'executive-vip-transfer-service') . '</h2>';
		echo '<table class="shop_table shop_table_responsive">';

		$unit = get_option('execvitr_distance_unit', 'km');

		if (!empty($data['distance_unit'])) {
			$u = strtolower(trim((string) $data['distance_unit']));
			if (in_array($u, ['km', 'mi', 'mile', 'miles'], true)) {
				$unit = ($u === 'km') ? 'km' : 'mi';
			}
		}
		if (!in_array($unit, ['km', 'mi'], true))
			$unit = 'km';

		$distance_label = sprintf(
			__('Distance (%s)', 'executive-vip-transfer-service'),
			($unit === 'mi' ? 'mile' : 'km')
		);

		$distance_value = ($unit === 'mi')
			? ($data['distance_mi'] ?? $data['distance_miles'] ?? $data['distance'] ?? '')
			: ($data['distance_km'] ?? $data['distance'] ?? '');

		// --- rows ---
		$rows = [
			__('Pickup', 'executive-vip-transfer-service') => $data['pickup'] ?? '',
			__('Drop', 'executive-vip-transfer-service') => $data['drop'] ?? '',
			__('Date', 'executive-vip-transfer-service') => $data['date'] ?? '',
			__('Vehicle', 'executive-vip-transfer-service') => $data['vehicle'] ?? '',
			$distance_label => $distance_value,
			__('Total', 'executive-vip-transfer-service') => trim(($data['currency'] ?? '') . ' ' . ($data['price'] ?? '')),
		];
		if (!empty($data['is_return']) && !empty($data['return_datetime'])) {
			$rows[__('Return Date & Time', 'executive-vip-transfer-service')] = $data['return_datetime'];
		}


		foreach ($rows as $k => $v) {
			if ($v === '')
				continue;
			echo '<tr><th style="width:30%">' . esc_html($k) . '</th><td>' . esc_html($v) . '</td></tr>';
		}

		echo '<tr><th>' . esc_html__('Ticket (PDF)', 'executive-vip-transfer-service') . '</th><td><a href="' . esc_url($paths['proxy']) . '" target="_blank" rel="noopener">' . esc_html__('Download', 'executive-vip-transfer-service') . '</a></td></tr>';
		echo '</table>';
		echo '</section>';
	}
}

// Ensure initial ticket email is sent even if thankyou hook doesn't fire (Blocks checkout)
add_action('woocommerce_checkout_order_processed', function ($order_id, $posted_data = [], $order = null) {
	if ($order instanceof WC_Order) {
		$wc_order = $order;
	} else {
		$wc_order = wc_get_order($order_id);
	}
	if (!$wc_order)
		return;
	if (function_exists('execvitr_ensure_order_booking_meta')) {
		execvitr_ensure_order_booking_meta($wc_order);
	}
	if (!execvitr_is_our_order($wc_order))
		return;
	execvitr_send_ticket_mail_once($wc_order, 'initial');
}, 25, 3);

// Store API / Blocks compatibility (signature varies across Woo versions)
add_action('woocommerce_store_api_checkout_order_processed', function (...$args) {
	$wc_order = null;
	foreach ($args as $a) {
		if ($a instanceof WC_Order) {
			$wc_order = $a;
			break;
		}
	}
	if (!$wc_order && isset($args[0]) && is_numeric($args[0])) {
		$wc_order = wc_get_order((int) $args[0]);
	}
	if (!$wc_order)
		return;
	if (function_exists('execvitr_ensure_order_booking_meta')) {
		execvitr_ensure_order_booking_meta($wc_order);
	}
	if (!execvitr_is_our_order($wc_order))
		return;
	execvitr_send_ticket_mail_once($wc_order, 'initial');
}, 25);

// Render summary + ticket link on order received page (works for both classic and some block templates)
add_action('woocommerce_order_details_after_order_table', function ($order) {
	if ($order instanceof WC_Order) {
		execvitr_render_order_summary_and_ticket($order);
	}
}, 20);

// Also render on thankyou when available
add_action('woocommerce_thankyou', function ($order_id) {
	$order = wc_get_order($order_id);
	if (!$order)
		return;
	execvitr_render_order_summary_and_ticket($order);
}, 30);

/**
 * Ultimate compatibility: append summary + ticket link to the order-received page content.
 * Some themes/Blocks setups do not run the classic thankyou hooks reliably.
 */
add_filter('the_content', function ($content) {
	if (!function_exists('is_order_received_page') || !is_order_received_page()) {
		return $content;
	}
	// Prevent duplicates
	if (is_string($content) && strpos($content, 'execvitr-reservation-summary') !== false) {
		return $content;
	}
	global $wp;
	$order_id = isset($wp->query_vars['order-received']) ? absint($wp->query_vars['order-received']) : 0;
	$order_key = isset($_GET['key']) ? wc_clean(wp_unslash($_GET['key'])) : '';
	if (!$order_id || !$order_key || !function_exists('wc_get_order')) {
		return $content;
	}
	$order = wc_get_order($order_id);
	if (!$order || !$order->key_is_valid($order_key)) {
		return $content;
	}
	ob_start();
	execvitr_render_order_summary_and_ticket($order);
	$extra = ob_get_clean();
	if (!$extra) {
		return $content;
	}
	return $content . $extra;
}, 50);


/** 1) execvitr_embed query var */
add_filter('query_vars', function ($vars) {
	if (!in_array('execvitr_embed', $vars, true))
		$vars[] = 'execvitr_embed';
	return $vars;
});

/** 2) embed modunda özel şablonları yükle */
add_filter('template_include', function ($template) {
	$embed_qv = get_query_var('execvitr_embed');
	$embed_qs = isset($_GET['execvitr_embed']) ? sanitize_text_field(wp_unslash($_GET['execvitr_embed'])) : '';
	$is_embed = ($embed_qv === '1' || $embed_qs === '1');

	if ($is_embed && function_exists('is_checkout_pay_page') && is_checkout_pay_page()) {
		$pay = trailingslashit(EXECVITR_PATH) . 'templates/embedded-order-pay.php';
		if (file_exists($pay))
			return $pay;
	}

	if ($is_embed && function_exists('is_order_received_page') && is_order_received_page()) {
		$ty = trailingslashit(EXECVITR_PATH) . 'templates/embedded-order-received.php';
		if (file_exists($ty))
			return $ty;
	}

	return $template;
}, 1);

/** 3) embed modunda admin bar kapalı */
add_filter('show_admin_bar', function ($show) {
	$embed_qv = get_query_var('execvitr_embed');
	$embed_qs = isset($_GET['execvitr_embed']) ? sanitize_text_field(wp_unslash($_GET['execvitr_embed'])) : '';
	return ($embed_qv === '1' || $embed_qs === '1') ? false : $show;
});

/** 4) Teşekkür URL'lerine embed paramını ekle (gateway yönlendirmeleri için kritik) */
add_filter('woocommerce_get_checkout_order_received_url', function ($url, $order) {
	if (isset($_GET['execvitr_embed']) && $_GET['execvitr_embed'] === '1') {
		$url = add_query_arg('execvitr_embed', '1', $url);
	}
	return $url;
}, 10, 2);

add_filter('woocommerce_get_return_url', function ($url, $order) {
	if (isset($_GET['execvitr_embed']) && $_GET['execvitr_embed'] === '1') {
		$url = add_query_arg('execvitr_embed', '1', $url);
	}
	return $url;
}, 10, 2);


/**
 * -------------------------------------------------------------------------
 * Summary Template Loader (page slug: execvitr-summary)
 * -------------------------------------------------------------------------
 */
add_action('template_include', function ($template) {
	if (is_page('execvitr-summary')) {
		$custom = EXECVITR_PATH . 'templates/summary.php';
		if (file_exists($custom)) {
			return $custom;
		}
	}
	return $template;
});

/**
 * -------------------------------------------------------------------------
 * Cart price override (use booking total_fee)
 * -------------------------------------------------------------------------
 */
add_action('woocommerce_before_calculate_totals', function ($cart) {
	if (is_admin() && !defined('DOING_AJAX')) {
		return;
	}
	if (!is_a($cart, 'WC_Cart')) {
		return;
	}

	foreach ($cart->get_cart() as $cart_item) {
		if (isset($cart_item['execvitr_total_fee']) && isset($cart_item['data']) && is_object($cart_item['data'])) {
			$price = (float) $cart_item['execvitr_total_fee'];
			if ($price > 0 && method_exists($cart_item['data'], 'set_price')) {
				$cart_item['data']->set_price($price);
			}
		}
	}
}, 20);

/**
 * -------------------------------------------------------------------------
 * Show booking details under product name in cart/checkout (order summary)
 * -------------------------------------------------------------------------
 */
add_filter('woocommerce_get_item_data', function ($item_data, $cart_item) {
	if (empty($cart_item['execvitr_booking']) || !is_array($cart_item['execvitr_booking'])) {
		return $item_data;
	}
	$bk = $cart_item['execvitr_booking'];
	$add = function ($label, $value) use (&$item_data) {
		$value = is_scalar($value) ? (string) $value : '';
		if ($value === '') {
			return;
		}
		$item_data[] = [
			'key' => $label,
			'value' => $value,
		];
	};

	$add(__('Pickup', 'executive-vip-transfer-service'), $bk['pickup_location'] ?? '');
	$add(__('Drop-off', 'executive-vip-transfer-service'), $bk['dropoff_location'] ?? '');
	$add(__('Pickup date/time', 'executive-vip-transfer-service'), $bk['pickup_datetime'] ?? '');
	if (!empty($bk['is_return']) && !empty($bk['return_datetime'])) {
		$add(__('Return date/time', 'executive-vip-transfer-service'), $bk['return_datetime']);
	}
	$add(__('Passengers', 'executive-vip-transfer-service'), isset($bk['passengers']) ? (int) $bk['passengers'] : '');
	$add(__('Bags', 'executive-vip-transfer-service'), isset($bk['bags']) ? (int) $bk['bags'] : '');
	$add(__('Vehicle', 'executive-vip-transfer-service'), $bk['car_brand'] ?? '');
	$add(__('Distance', 'executive-vip-transfer-service'), $bk['distance_text'] ?? '');
	$add(__('Duration', 'executive-vip-transfer-service'), $bk['duration_text'] ?? '');
	$add(__('Payment', 'executive-vip-transfer-service'), $bk['payment_method'] ?? '');

	return $item_data;
}, 10, 2);

/**
 * Persist booking payload onto order line items (JSON) for maximum compatibility.
 * This allows us to reconstruct booking data even if session data is not available.
 */
add_action('woocommerce_checkout_create_order_line_item', function ($item, $cart_item_key, $values, $order) {
	if (!($item instanceof WC_Order_Item_Product)) {
		return;
	}
	if (empty($values['execvitr_booking']) || !is_array($values['execvitr_booking'])) {
		return;
	}
	$item->add_meta_data('_execvitr_booking_json', wp_json_encode($values['execvitr_booking']), true);
}, 10, 4);

/**
 * -------------------------------------------------------------------------
 * Checkout autofill from booking session
 * -------------------------------------------------------------------------
 */
add_filter('woocommerce_checkout_get_value', function ($value, $input) {
	if (!function_exists('WC') || !WC() || !WC()->session) {
		return $value;
	}
	// In VIP Transfer booking flow we want to prefill checkout fields even if user has saved addresses.
	// We only force-prefill when our booking session flag is set.
	$force = (int) WC()->session->get('execvitr_force_prefill') === 1;
	if (!$force && !empty($value)) {
		return $value;
	} // don't overwrite user input

	$booking = WC()->session->get('execvitr_booking');
	if (empty($booking) || !is_array($booking)) {
		return $value;
	}

	$map = [
		'billing_first_name' => 'billing_first_name',
		'billing_last_name' => 'billing_last_name',
		'billing_email' => 'billing_email',
		'billing_phone' => 'billing_phone',
		'billing_address_1' => 'billing_address_1',
		'billing_city' => 'billing_city',
		'billing_postcode' => 'billing_postcode',
	];

	if (isset($map[$input]) && isset($booking[$map[$input]])) {
		return $booking[$map[$input]];
	}

	// Optional custom fields (if you add them later)
	if (isset($booking[$input])) {
		return $booking[$input];
	}

	return $value;
}, 10, 2);

/**
 * -------------------------------------------------------------------------
 * WooCommerce Blocks checkout prefill (Store API)
 * -------------------------------------------------------------------------
 * The Checkout block does not use woocommerce_checkout_get_value. For a stable
 * guest + logged-in experience, we also push booking values into the WC customer
 * session when we are in the booking flow.
 */
add_action('wp_loaded', function () {
	if (!function_exists('WC') || !WC() || !WC()->session) {
		return;
	}
	if (!function_exists('is_checkout') || !is_checkout()) {
		return;
	}
	$force = (int) WC()->session->get('execvitr_force_prefill') === 1;
	$booking = WC()->session->get('execvitr_booking');
	if (!$force || empty($booking) || !is_array($booking)) {
		return;
	}
	if (!WC()->customer) {
		return;
	}
	try {
		WC()->customer->set_billing_first_name($booking['billing_first_name'] ?? '');
		WC()->customer->set_billing_last_name($booking['billing_last_name'] ?? '');
		WC()->customer->set_billing_email($booking['billing_email'] ?? '');
		WC()->customer->set_billing_phone($booking['billing_phone'] ?? '');
		WC()->customer->set_billing_address_1($booking['billing_address_1'] ?? '');
		WC()->customer->set_billing_city($booking['billing_city'] ?? '');
		WC()->customer->set_billing_postcode($booking['billing_postcode'] ?? '');
		// Country is required for Blocks checkout validation
		if (!empty($booking['billing_country'])) {
			WC()->customer->set_billing_country($booking['billing_country']);
		} elseif (!WC()->customer->get_billing_country()) {
			WC()->customer->set_billing_country(WC()->countries->get_base_country());
		}
		WC()->customer->save();
	} catch (Throwable $e) {
		if (defined('WP_DEBUG') && WP_DEBUG) {
			error_log('[ExecVITR] checkout prefill (blocks) failed: ' . $e->getMessage());
		}
	}
}, 20);

/**
 * -------------------------------------------------------------------------
 * Save booking session/meta into the order
 * -------------------------------------------------------------------------
 */
add_action('woocommerce_checkout_create_order', function ($order, $data) {
	if (!function_exists('WC') || !WC() || !WC()->session) {
		return;
	}
	$booking = WC()->session->get('execvitr_booking');
	if (empty($booking) || !is_array($booking)) {
		return;
	}

	// Mark order as created by ExecVITR booking flow (used for Blocks compatibility + filtering)
	$order->update_meta_data('_execvitr_booking_flow', '1');

	// Legacy meta keys (keep old templates / ticket generation working)
	if (!empty($booking['pickup_location'])) {
		$order->update_meta_data('_execvitr_pickup', $booking['pickup_location']);
	}
	if (!empty($booking['dropoff_location'])) {
		$order->update_meta_data('_execvitr_drop', $booking['dropoff_location']);
	}
	if (!empty($booking['pickup_datetime'])) {
		$order->update_meta_data('_execvitr_date', $booking['pickup_datetime']);
	}
	if (isset($booking['distance_km'])) {
		$order->update_meta_data('_execvitr_distance_km', $booking['distance_km']);
	}
	if (isset($booking['total_fee'])) {
		$order->update_meta_data('_execvitr_total_fee', $booking['total_fee']);
	}

	// Store as order meta (keep existing keys for tracking compatibility)
	if (!empty($booking['pickup_location'])) {
		$order->update_meta_data('_cc_pickup_location', $booking['pickup_location']);
	}
	if (!empty($booking['dropoff_location'])) {
		$order->update_meta_data('_cc_dropoff_location', $booking['dropoff_location']);
	}
	if (!empty($booking['pickup_datetime'])) {
		$order->update_meta_data('_cc_pickup_datetime', $booking['pickup_datetime']);
	}
	if (!empty($booking['vehicle_model'])) {
		$order->update_meta_data('_execvitr_vehicle', $booking['vehicle_model']);
	}
	if (isset($booking['passengers'])) {
		$order->update_meta_data('_cc_passengers', $booking['passengers']);
	}
	if (isset($booking['bags'])) {
		$order->update_meta_data('_cc_bags', $booking['bags']);
	}
	if (!empty($booking['distance_text'])) {
		$order->update_meta_data('_cc_distance_text', $booking['distance_text']);
	}
	if (!empty($booking['duration_text'])) {
		$order->update_meta_data('_cc_duration_text', $booking['duration_text']);
	}
	if (isset($booking['distance_km'])) {
		$order->update_meta_data('_cc_distance_km', $booking['distance_km']);
	}
	if (isset($booking['total_fee'])) {
		$order->update_meta_data('_cc_total_fee', $booking['total_fee']);
	}

	// Also store sender data for tracking template fallback
	if (!empty($booking['billing_first_name'])) {
		$order->update_meta_data('_cc_sender_name', $booking['billing_first_name']);
	}
	if (!empty($booking['billing_last_name'])) {
		$order->update_meta_data('_cc_sender_surname', $booking['billing_last_name']);
	}
	if (!empty($booking['billing_email'])) {
		$order->update_meta_data('_cc_sender_email', $booking['billing_email']);
	}
	if (!empty($booking['billing_phone'])) {
		$order->update_meta_data('_cc_sender_phone', $booking['billing_phone']);
	}
}, 10, 2);

/**
 * Clear booking session after successful checkout
 */
add_action('woocommerce_thankyou', function ($order_id) {
	if (!function_exists('WC') || !WC() || !WC()->session) {
		return;
	}
	WC()->session->__unset('execvitr_booking');
	WC()->session->__unset('execvitr_force_prefill');
}, 10);


/**
 * Remove WooCommerce "guest order" warning on order-pay page
 * for ExecVITR booking flow orders only.
 */
add_filter('woocommerce_add_notice', function ($message, $notice_type) {
	if ($notice_type !== 'notice')
		return $message;

	if (!function_exists('is_checkout') || !is_checkout())
		return $message;
	if (empty($_GET['pay_for_order']))
		return $message;

	// Get order from query vars (order-pay endpoint)
	$order_id = absint(get_query_var('order-pay'));
	if (!$order_id)
		return $message;

	$order = wc_get_order($order_id);
	if (!$order)
		return $message;

	// Only our flow
	$is_execvitr = (bool) $order->get_meta('_execvitr_booking_flow');
	if (!$is_execvitr)
		return $message;

	// Remove that specific warning
	// Woo notice text can vary by language, so match loosely.
	if (stripos($message, 'guest order') !== false && stripos($message, 'recognize') !== false) {
		return '';
	}

	return $message;
}, 10, 2);
