<?php
/**
 * templates/form-submit-handler.php
 * Form submit handler (EXECVITR only)
 */
if (!defined('ABSPATH'))
	exit;

/**
 * -------------------------------------------------------------------------
 * AJAX actions — execvitr only
 * -------------------------------------------------------------------------
 */
add_action('wp_ajax_execvitr_form_submit', 'execvitr_form_submit_handler');
add_action('wp_ajax_nopriv_execvitr_form_submit', 'execvitr_form_submit_handler');

function execvitr_form_submit_handler()
{
	// WP Ajax nonce
	if (!check_ajax_referer('execvitr-ajax', '_ajax_nonce', false)) {
		wp_send_json_error(__('Security check failed.', 'executive-vip-transfer-service'));
	}
	if (empty($_SERVER['REQUEST_METHOD']) || 'POST' !== $_SERVER['REQUEST_METHOD']) {
		wp_send_json_error(__('Invalid request.', 'executive-vip-transfer-service'));
	}
	// Form nonce
	if (empty($_POST['cc_nonce']) || !wp_verify_nonce(sanitize_text_field(wp_unslash($_POST['cc_nonce'])), 'execvitr_form_submit')) {
		wp_send_json_error(__('Security check failed.', 'executive-vip-transfer-service'));
	}
	// Zorunlu alanlar
	if (empty($_POST['address_from']) || empty($_POST['address_to'])) {
		wp_send_json_error(__('Address fields are required.', 'executive-vip-transfer-service'));
	}

	$api_key = get_option('execvitr_google_api_key', '');
	if (!$api_key) {
		wp_send_json_error(__('Google API Key is missing. Please add it in settings.', 'executive-vip-transfer-service'));
	}

	// Girişler
	$origin = sanitize_text_field(wp_unslash($_POST['address_from']));
	$destination = sanitize_text_field(wp_unslash($_POST['address_to']));
// Phone (prefer E.164 built on frontend)
$dial_code = isset($_POST['dial_code']) ? preg_replace('/\D+/', '', (string) wp_unslash($_POST['dial_code'])) : '';
$pickup_phone_raw = isset($_POST['pickup_phone']) ? sanitize_text_field(wp_unslash($_POST['pickup_phone'])) : '';
$pickup_phone_e164 = isset($_POST['pickup_phone_e164']) ? sanitize_text_field(wp_unslash($_POST['pickup_phone_e164'])) : '';

// normalize raw (keep digits only)
$pickup_phone_digits = preg_replace('/\D+/', '', $pickup_phone_raw);

// If E.164 missing, build from dial+raw
if ($pickup_phone_e164 === '') {
	$pickup_phone_digits = ltrim($pickup_phone_digits, '0'); // common local leading zero
	if ($dial_code !== '' && $pickup_phone_digits !== '') {
		$pickup_phone_e164 = '+' . $dial_code . $pickup_phone_digits;
	}
}

// Final phone to use across order/meta/email
$pickup_phone = $pickup_phone_e164 !== '' ? $pickup_phone_e164 : $pickup_phone_raw;

// (Optional) keep delivery_phone if you still use it somewhere
$delivery_phone = isset($_POST['delivery_phone']) ? sanitize_text_field(wp_unslash($_POST['delivery_phone'])) : '';


	$sender_name = isset($_POST['sender_name']) ? sanitize_text_field(wp_unslash($_POST['sender_name'])) : '';
	$sender_surname = isset($_POST['sender_surname']) ? sanitize_text_field(wp_unslash($_POST['sender_surname'])) : '';
	$user_name = isset($_POST['user_name']) ? sanitize_text_field(wp_unslash($_POST['user_name'])) : '';
	$user_email = isset($_POST['user_email']) ? sanitize_email(wp_unslash($_POST['user_email'])) : '';
	$billing_address_1 = isset($_POST['billing_address_1']) ? sanitize_text_field(wp_unslash($_POST['billing_address_1'])) : '';
	$billing_city      = isset($_POST['billing_city']) ? sanitize_text_field(wp_unslash($_POST['billing_city'])) : '';
	$billing_postcode  = isset($_POST['billing_postcode']) ? sanitize_text_field(wp_unslash($_POST['billing_postcode'])) : '';
	$billing_country   = isset($_POST['billing_country']) ? sanitize_text_field(wp_unslash($_POST['billing_country'])) : '';

	// If billing address not provided (hidden fields empty), fall back to pickup address
	if ($billing_address_1 === '' && !empty($origin)) {
		$billing_address_1 = $origin;
	}
	// Country: if not provided, fall back to base country
	if ($billing_country === '') {
		try {
			$billing_country = function_exists('WC') && WC() && WC()->countries ? WC()->countries->get_base_country() : '';
		} catch (Throwable $e) {
			$billing_country = '';
		}
	}

$pickup_details = isset($_POST['pickup_details']) ? sanitize_textarea_field(wp_unslash($_POST['pickup_details'])) : '';

	$weight = isset($_POST['weight']) ? sanitize_text_field(wp_unslash($_POST['weight'])) : '';
	$package_content = isset($_POST['package_content']) ? sanitize_text_field(wp_unslash($_POST['package_content'])) : '';
	$payment_method = isset($_POST['payment']) ? sanitize_text_field(wp_unslash($_POST['payment'])) : '';

	$passenger_count = 0;
	if (!isset($_POST['passenger_count']) || wp_unslash($_POST['passenger_count']) === '') {
		wp_send_json_error(__('Please enter the number of passengers.', 'executive-vip-transfer-service'));
	}
	$passenger_count = (int) filter_var(wp_unslash($_POST['passenger_count']), FILTER_SANITIZE_NUMBER_INT);
	$passenger_count = max(1, $passenger_count);


	$luggage_count = 0;
	if (!isset($_POST['luggage_count']) || wp_unslash($_POST['luggage_count']) === '') {
		wp_send_json_error(__('Please enter the number of bags.', 'executive-vip-transfer-service'));
	}
	$luggage_count = (int) filter_var(wp_unslash($_POST['luggage_count']), FILTER_SANITIZE_NUMBER_INT);
	$luggage_count = max(0, $luggage_count);

	$luggage_count = max(0, $luggage_count);


	// Raw inputs (pickup/return) - needed for validation
	$pickup_date_raw = isset($_POST['pickup_date']) ? sanitize_text_field(wp_unslash($_POST['pickup_date'])) : '';
	$pickup_time_raw = isset($_POST['pickup_time']) ? sanitize_text_field(wp_unslash($_POST['pickup_time'])) : '';

	// Return booking (optional)
	$is_return = isset($_POST['is_return']) && (string) wp_unslash($_POST['is_return']) === '1';
	$return_date_raw = isset($_POST['return_date']) ? sanitize_text_field(wp_unslash($_POST['return_date'])) : '';
	$return_time_raw = isset($_POST['return_time']) ? sanitize_text_field(wp_unslash($_POST['return_time'])) : '';
	$return_datetime_raw = trim($return_date_raw . ' ' . $return_time_raw);


	// -----------------------------------------------------------------
	// Required fields validation (server-side)
	// -----------------------------------------------------------------
	$missing = [];

	$car_choice = isset($_POST['car_choice']) ? sanitize_text_field(wp_unslash($_POST['car_choice'])) : '';

	$req = [
		'sender_name'      => $sender_name,
		'sender_surname'   => $sender_surname,
		'address_from'     => $origin,
		'address_to'       => $destination,
		'pickup_phone'     => $pickup_phone,
		'user_email'       => $user_email,
		'car_choice'       => $car_choice,
		'passenger_count'  => $passenger_count,
		'luggage_count'    => $luggage_count,
	];

	// Stronger phone sanity (at least 6 digits)
$phone_digits_check = preg_replace('/\D+/', '', (string) $pickup_phone);
if (strlen($phone_digits_check) < 6) {
	$missing[] = 'pickup_phone';
}


	$pro_active = (function_exists('execvitr_is_pro_active') && execvitr_is_pro_active());
	if ($pro_active) {
		$pickup_date_req = isset($_POST['pickup_date']) ? sanitize_text_field(wp_unslash($_POST['pickup_date'])) : '';
		$pickup_time_req = isset($_POST['pickup_time']) ? sanitize_text_field(wp_unslash($_POST['pickup_time'])) : '';
		$req['pickup_date'] = $pickup_date_req;
		$req['pickup_time'] = $pickup_time_req;

		if ( $is_return ) {
			$req['return_date'] = $return_date_raw;
			$req['return_time'] = $return_time_raw;
		}
	}

	foreach ($req as $k => $v) {
		if (is_string($v) && trim($v) === '') {
			$missing[] = $k;
		}
	}

	// Basic sanity: passenger_count must be >=1
	if ((int)$passenger_count < 1) $missing[] = 'passenger_count';
	if ($car_choice === '') $missing[] = 'car_choice';

	$missing = array_values(array_unique($missing));

	if (!empty($missing)) {
		wp_send_json_error([
			'code'    => 'execvitr_required_fields_missing',
			'message' => __('Required information fields are missing.', 'executive-vip-transfer-service'),
			'missing' => $missing,
		]);
	}


	/**
	 * Timezone helper
	 */
	if (!function_exists('execvitr_get_timezone')) {
		function execvitr_get_timezone(): DateTimeZone
		{
			if (function_exists('wp_timezone'))
				return wp_timezone();
			$tz_string = get_option('timezone_string');
			if ($tz_string) {
				try {
					return new DateTimeZone($tz_string);
				} catch (Exception $e) {
				}
			}
			$offset = (float) get_option('gmt_offset', 0);
			$hours = (int) $offset;
			$mins = abs(($offset - $hours) * 60);
			$sign = $offset < 0 ? '-' : '+';
			$tz_name = sprintf('UTC%s%02d:%02d', $sign, abs($hours), $mins);
			try {
				return new DateTimeZone($tz_name);
			} catch (Exception $e) {
			}
			return new DateTimeZone('UTC');
		}
	}

	// PRO kontrolü
	$is_pro = function_exists('execvitr_is_pro_active') && execvitr_is_pro_active();
	$arrival_time_iso = '';

	if (!$is_pro) {
		$pickup_date_raw = '';
		$pickup_time_raw = '';
	} else {
		if ($pickup_date_raw === '' || $pickup_time_raw === '') {
			wp_send_json_error(__('Pickup date and time are required.', 'executive-vip-transfer-service'));
		}
		$date_ok = (bool) preg_match('/^\d{4}-\d{2}-\d{2}$/', $pickup_date_raw);
		$time_ok = (bool) preg_match('/^\d{2}:\d{2}$/', $pickup_time_raw);
		if (!$date_ok || !$time_ok) {
			wp_send_json_error(__('Invalid pickup date/time format.', 'executive-vip-transfer-service'));
		}
		try {
			$site_tz = execvitr_get_timezone();
			$dt_local = new DateTimeImmutable("$pickup_date_raw $pickup_time_raw:00", $site_tz);
			$now_local = new DateTimeImmutable('now', $site_tz);
			$mins = (int) $dt_local->format('i');
			$rounded_m = $mins % 30 === 0 ? $mins : ($mins < 30 ? 30 : 0);
			$dt_local = $dt_local->setTime((int) $dt_local->format('H'), $rounded_m, 0);

			if (!defined('EXECVITR_ALLOWED_SKEW_MIN'))
				define('EXECVITR_ALLOWED_SKEW_MIN', 60);
			$skew_interval = new DateInterval('PT' . max(0, (int) EXECVITR_ALLOWED_SKEW_MIN) . 'M');

			$now_with_skew_floor = $now_local->sub($skew_interval);
			if ($dt_local < $now_with_skew_floor) {
				wp_send_json_error(__('Pickup date/time cannot be in the past.', 'executive-vip-transfer-service'));
			}
			
			// Minimum advance booking hours (admin setting)
			$lead_hours = (int) get_option('execvitr_min_booking_hours', 0);
			if ($lead_hours > 0) {
				$min_allowed = $now_local->add(new DateInterval('PT' . $lead_hours . 'H'));
				if ($dt_local < $min_allowed) {
					wp_send_json_error(sprintf(
						__('Please select a pickup time at least %d hours from now.', 'executive-vip-transfer-service'),
						$lead_hours
					));
				}
			}

			// Return booking validation (required if selected)
			if ($is_return) {
				if ($return_date_raw === '' || $return_time_raw === '') {
					wp_send_json_error([
						'code'    => 'execvitr_required_fields_missing',
						'message' => __('Return date and time are required.', 'executive-vip-transfer-service'),
						'missing' => ['return_date','return_time'],
					]);
				}
				$r_date_ok = (bool) preg_match('/^\d{4}-\d{2}-\d{2}$/', $return_date_raw);
				$r_time_ok = (bool) preg_match('/^\d{2}:\d{2}$/', $return_time_raw);
				if (!$r_date_ok || !$r_time_ok) {
					wp_send_json_error(__('Invalid return date/time format.', 'executive-vip-transfer-service'));
				}
				try {
					$dt_return_local = new DateTimeImmutable("$return_date_raw $return_time_raw:00", $site_tz);
					$mins_r = (int) $dt_return_local->format('i');
					$rounded_m_r = $mins_r % 30 === 0 ? $mins_r : ($mins_r < 30 ? 30 : 0);
					$dt_return_local = $dt_return_local->setTime((int) $dt_return_local->format('H'), $rounded_m_r, 0);
					if ($dt_return_local < $now_with_skew_floor) {
						wp_send_json_error(__('Return date/time cannot be in the past.', 'executive-vip-transfer-service'));
					}
					// Return cannot be earlier than pickup
					if (isset($dt_local) && $dt_return_local < $dt_local) {
						wp_send_json_error(__('Return date/time cannot be earlier than pickup date/time.', 'executive-vip-transfer-service'));
					}
				} catch (Exception $e) {
					wp_send_json_error(__('Invalid return date/time.', 'executive-vip-transfer-service'));
				}
			}

			$arrival_time_iso = $dt_local->setTimezone(new DateTimeZone('UTC'))->format('c');
		} catch (Exception $e) {
			wp_send_json_error(__('Invalid pickup date/time.', 'executive-vip-transfer-service'));
		}
	}

	// Araç seçimi
	$car_index = isset($_POST['car_choice']) ? (int) $_POST['car_choice'] : -1;
	$cars_opt = get_option('execvitr_cars', []);

	$car_km_price = 0.0;
	$car_meta = [
		'_cc_car_index' => $car_index,
		'_cc_car_brand' => '',
		'_cc_car_passengers' => 0,
		'_cc_car_luggage' => 0,
		'_cc_car_image_id' => 0,
	];
	if (is_array($cars_opt) && $car_index >= 0 && isset($cars_opt[$car_index]) && is_array($cars_opt[$car_index])) {
		$car = $cars_opt[$car_index];
		$car_meta['_cc_car_brand'] = isset($car['brand']) ? sanitize_text_field($car['brand']) : '';
		$car_meta['_cc_car_passengers'] = isset($car['passenger']) ? (int) $car['passenger'] : 0;
		$car_meta['_cc_car_luggage'] = isset($car['luggage']) ? (int) $car['luggage'] : 0;
		$car_meta['_cc_car_image_id'] = isset($car['image_id']) ? (int) $car['image_id'] : 0;
		if (isset($car['km_price']) && (float) $car['km_price'] > 0) {
			$car_km_price = (float) $car['km_price'];
		}
	}

	// -----------------------------------------------------------------
	// Vehicle label (single source of truth)
	// -----------------------------------------------------------------
	// IMPORTANT:
	// - We must ALWAYS derive a stable vehicle label for storage/display.
	// - If _cc_car_index meta is missing later, Woo will cast '' to 0 and
	//   the first car will appear for all orders ("always Maybach" bug).
	$car_name = '';
	if ( ! empty( $car_meta['_cc_car_brand'] ) ) {
		$car_name = (string) $car_meta['_cc_car_brand'];
	}
	if ( $car_name === '' ) {
		$car_name = __( 'Vehicle', 'executive-vip-transfer-service' );
	}

	// Capacity validation (passengers / luggage) for selected vehicle
	if ($car_index >= 0) {
		$cap_p = (int) ($car_meta['_cc_car_passengers'] ?? 0);
		$cap_b = (int) ($car_meta['_cc_car_luggage'] ?? 0);
		if ($cap_p > 0 && $passenger_count > $cap_p) {
			wp_send_json_error([
				'message' => sprintf(__('Selected vehicle allows max %d passengers.', 'executive-vip-transfer-service'), $cap_p),
				'code' => 'capacity_passengers',
			]);
		}
		if ($cap_b >= 0 && $luggage_count > $cap_b) {
			wp_send_json_error([
				'message' => sprintf(__('Selected vehicle allows max %d luggage.', 'executive-vip-transfer-service'), $cap_b),
				'code' => 'capacity_luggage',
			]);
		}
	}

	// Capacity validation (server-side safety)
	if ($car_meta['_cc_car_passengers'] > 0 && $passenger_count > (int) $car_meta['_cc_car_passengers']) {
		wp_send_json_error(array(
			'message' => sprintf(__('Passenger count exceeds vehicle capacity (max %d).', 'executive-vip-transfer-service'), (int) $car_meta['_cc_car_passengers']),
			'code' => 'capacity_passengers',
		));
	}
	if ($car_meta['_cc_car_luggage'] >= 0 && $luggage_count > (int) $car_meta['_cc_car_luggage']) {
		wp_send_json_error(array(
			'message' => sprintf(__('Luggage count exceeds vehicle capacity (max %d).', 'executive-vip-transfer-service'), (int) $car_meta['_cc_car_luggage']),
			'code' => 'capacity_luggage',
		));
	}

	// Mesafe (JS tarafında hesaplanmış değerleri kullan)
	$distance_km = isset($_POST['distance_km']) ? (float) $_POST['distance_km'] : 0;
	$distance_txt = isset($_POST['distance_text']) ? sanitize_text_field(wp_unslash($_POST['distance_text'])) : '';
	$duration_txt = isset($_POST['duration_text']) ? sanitize_text_field(wp_unslash($_POST['duration_text'])) : '';

	if ($distance_km <= 0 || empty($distance_txt)) {
		wp_send_json_error(array(
			'message' => __('Distance could not be calculated. Please make sure both pickup and drop-off addresses are selected from the suggestions.', 'executive-vip-transfer-service'),
			'code' => 'no_distance',
		));
	}

	// PHP tarafında tek bir struct halinde kullanalım
	$distance = [
		'distance_km' => $distance_km,
		'distance_text' => $distance_txt,
		'duration' => $duration_txt,
	];


	if (!function_exists('wc_create_order')) {
		wp_send_json_error(__('WooCommerce is not active.', 'executive-vip-transfer-service'));
	}

	// Fiyat
	$km_price = (float) get_option('execvitr_km_price', 0);
	$min_price = (float) get_option('execvitr_minimum_price', 0);
	if ($car_km_price > 0)
		$km_price = $car_km_price;

	$distance_unit = get_option('execvitr_distance_unit', 'km');
	$distance_units = $distance['distance_km'];
	if ($distance_unit === 'mi') {
		$distance_units = $distance['distance_km'] / 1.609344;
	}
	$base_fee = round(max($min_price, $distance_units * $km_price), 2);
	$total_fee = $base_fee;
	if ( $is_return ) {
		$total_fee = round($base_fee * 2, 2);
	}


	// ------------------------------------------------------------------
// NEW FLOW (Order-Pay): Create WooCommerce order directly (NO checkout),
// then redirect to Summary (optional) and finally to Woo order-pay page.
// booking -> summary -> order-pay -> thankyou
// ------------------------------------------------------------------

// Build booking payload (store on order meta + (optional) line item meta)
$booking_data = [
	'pickup_location'    => $origin,
	'dropoff_location'   => $destination,
	'pickup_datetime'    => trim($pickup_date_raw . ' ' . $pickup_time_raw),
	'is_return'          => (bool) $is_return,
	'return_datetime'    => $is_return ? $return_datetime_raw : '',
	'car_index'          => $car_index,
	'car_name'           => $car_name,
	'passengers'         => $passenger_count,
	'luggage'            => $luggage_count,
	'user_email'         => $user_email,
	'phone'              => $pickup_phone,        // E.164 preferred
  'phone_raw'          => $pickup_phone_raw,    // optional
  'dial_code'          => $dial_code,
	'notes'              => $pickup_details,
	'payment_method'     => $payment_method,
	// pricing + route
	'distance_km'        => (float) $distance['distance_km'],
	'distance_text'      => (string) $distance_txt,
	'duration'           => (string) $duration_txt,
	'base_fee'           => (float) $base_fee,
	'total_fee'          => (float) $total_fee,
];

// Create order
$product_id = (int) get_option('execvitr_product_id', 0);
if ($product_id <= 0) {
	wp_send_json_error(['message' => 'Booking product is not configured.']);
}

$order = wc_create_order();
if (!$order || !is_a($order, 'WC_Order')) {
	wp_send_json_error(['message' => 'Could not create order.']);
}

// Add our booking product with custom total
$product = wc_get_product($product_id);
if (!$product) {
	wp_send_json_error(['message' => 'Booking product not found.']);
}

$item_id = $order->add_product($product, 1, [
  'subtotal' => $total_fee,
  'total'    => $total_fee,
]);

if ($item_id) {
  $item = $order->get_item($item_id);

  if ($item && is_a($item, 'WC_Order_Item_Product')) {

    // --- Human-readable booking details (shows under Product in order-pay) ---
    $item->add_meta_data(__('Pickup', 'executive-vip-transfer-service'), $origin, true);
    $item->add_meta_data(__('Dropoff', 'executive-vip-transfer-service'), $destination, true);

    if (!empty($booking_data['pickup_datetime'])) {
      $item->add_meta_data(__('Pickup Date & Time', 'executive-vip-transfer-service'), $booking_data['pickup_datetime'], true);
    }

    if (!empty($booking_data['return_datetime']) && !empty($booking_data['is_return'])) {
      $item->add_meta_data(__('Return Date & Time', 'executive-vip-transfer-service'), $booking_data['return_datetime'], true);
    }

    // Vehicle (always write)
    $item->add_meta_data(__('Vehicle', 'executive-vip-transfer-service'), $car_name, true);

    $item->add_meta_data(__('Passengers', 'executive-vip-transfer-service'), (int)$passenger_count, true);
    $item->add_meta_data(__('Bags', 'executive-vip-transfer-service'), (int)$luggage_count, true);

    if (!empty($distance_txt)) {
      $item->add_meta_data(__('Distance', 'executive-vip-transfer-service'), $distance_txt, true);
    }
    if (!empty($duration_txt)) {
      $item->add_meta_data(__('Duration', 'executive-vip-transfer-service'), $duration_txt, true);
    }

    // Notes (opsiyonel – çok uzunsa istersen ekleme)
    if (!empty($pickup_details)) {
      $item->add_meta_data(__('Notes', 'executive-vip-transfer-service'), $pickup_details, true);
    }

    // --- Keep JSON for internal use, but hide from customer via filter below ---
    $item->add_meta_data('_execvitr_booking_json', wp_json_encode($booking_data), true);

    $item->save();
  }
}


// Minimal billing info (address fields are intentionally skipped)
if (!empty($sender_name)) {
	$order->set_billing_first_name($sender_name);
}
if (!empty($sender_surname)) {
	$order->set_billing_last_name($sender_surname);
}
if (!empty($user_email)) {
	$order->set_billing_email($user_email);
}
if (!empty($pickup_phone)) {
	$order->set_billing_phone($pickup_phone);
}

// Order meta (legacy + current keys for templates/ticket/email compatibility)
$order->update_meta_data('_execvitr_booking_flow', 1);
$order->update_meta_data('_execvitr_booking_json', wp_json_encode($booking_data));
$order->update_meta_data('_execvitr_pickup', $origin);
$order->update_meta_data('_execvitr_drop', $destination);
$order->update_meta_data('_execvitr_date', $booking_data['pickup_datetime']);
$order->update_meta_data('_execvitr_distance_km', (float) $distance['distance_km']);
$order->update_meta_data('_execvitr_total_fee', (float) $total_fee);

$order->update_meta_data('_cc_address_from', $origin);
$order->update_meta_data('_cc_address_to', $destination);
$order->update_meta_data('_cc_distance_text', $distance_txt);
$order->update_meta_data('_cc_duration', $duration_txt);
$order->update_meta_data('_cc_pickup_datetime', $booking_data['pickup_datetime']);
$order->update_meta_data('_execvitr_is_return', $booking_data['is_return'] ? '1' : '0');
if ( ! empty( $booking_data['return_datetime'] ) ) {
	$order->update_meta_data('_execvitr_return_datetime', (string) $booking_data['return_datetime']);
}

	// Car meta (critical for Orders page + emails)
	$order->update_meta_data('_cc_car_index', (int) $car_index);
	$order->update_meta_data('_cc_car_brand', (string) $car_name);
	$order->update_meta_data('_execvitr_vehicle', (string) $car_name);

// Calculate totals and set status pending
$order->calculate_totals();
$order->set_status('pending');
$order->save();

// Build redirect URL: prefer Summary page if exists
$summary_page = get_page_by_path('execvitr-summary');
if ($summary_page) {
	// Pass order id + order key to summary so it can load safely
	$redirect_url = add_query_arg([
		'order_id' => $order->get_id(),
		'key'      => $order->get_order_key(),
	], get_permalink($summary_page));
} else {
	$redirect_url = $order->get_checkout_payment_url(); // order-pay
}

// Debug trace
if (defined('WP_DEBUG') && WP_DEBUG) {
	error_log('[ExecVITR] order created #' . $order->get_id() . '; redirect -> ' . $redirect_url);
}


	// JSON yanıt
	wp_send_json_success(['redirect_url' => esc_url_raw($redirect_url)]);
}
