PluginProbe
Yatra – Travel Booking & Tour Operator Software / 3.0.11
Yatra – Travel Booking & Tour Operator Software v3.0.11
3.0.16 3.0.15 3.0.14 3.0.14.1 3.0.14.2 3.0.12 3.0.13 3.0.11 3.0.10 3.0.9 3.0.8 3.0.7 3.0.6 3.0.5 3.0.5.1 3.0.4 3.0.3 3.0.2.9 3.0.2.7 3.0.2.8 3.0.2.6 trunk 1.0.0 2.0.0 2.0.1 All 84 releases
yatra / includes / helpers.php

helpers.php in Yatra – Travel Booking & Tour Operator Software 3.0.11, at includes/helpers.php

3,088 lines 98.9 KB
No matching file
Up and down to move Enter to open Esc to close
Raw Download Zip
1 <?php
2 /**
3 * Yatra Helper Functions
4 *
5 * @package Yatra
6 */
7
8 // Prevent direct access
9 if (!defined('ABSPATH')) {
10 exit;
11 }
12
13 use Yatra\Database\Tables\BookingsTable;
14 use Yatra\Database\Tables\ClassificationsTable;
15 use Yatra\Database\Tables\ReviewsTable;
16 use Yatra\Database\Tables\TripsTable;
17 use Yatra\Services\SettingsService;
18 use Yatra\Constants\ClassificationTypes;
19
20 /**
21 * Get a plugin setting value
22 *
23 * @param string $key Setting key
24 * @param mixed $default Default value
25 * @return mixed
26 */
27 function yatra_get_setting(string $key, $default = null)
28 {
29 return SettingsService::get($key, $default);
30 }
31
32 /**
33 * Check if a setting is enabled
34 *
35 * @param string $key Setting key
36 * @return bool
37 */
38 function yatra_setting_enabled(string $key): bool
39 {
40 return SettingsService::isEnabled($key);
41 }
42
43 /**
44 * Check if reviews are enabled
45 *
46 * @return bool
47 */
48 function yatra_reviews_enabled(): bool
49 {
50 return SettingsService::reviewsEnabled();
51 }
52
53 /**
54 * Get booking form configuration
55 *
56 * @return array
57 */
58 function yatra_get_booking_form_config(): array
59 {
60 // Check if Dynamic Form Field module is enabled via Pro plugin
61 $is_dynamic_enabled = apply_filters('yatra_dynamic_form_field_enabled', false);
62
63 if ($is_dynamic_enabled) {
64 // Pro module is active — merged config from options (filtered in SettingsService::getBookingFormConfig)
65 return SettingsService::getBookingFormConfig();
66 }
67
68 // Module off: still allow filters to adjust defaults (tests / edge integrations)
69 return apply_filters(
70 'yatra_booking_form_config',
71 SettingsService::getDefaultBookingFormConfig()
72 );
73 }
74
75 /**
76 * Translate a booking-form display string (label / title / description /
77 * placeholder / option label) at render time.
78 *
79 * The default booking-form strings are registered for translation in
80 * SettingsService::getDefaultBookingFormConfig() (literal __() calls, so they
81 * land in the .pot for Loco Translate). This runtime pass additionally lets a
82 * SAVED or CUSTOM label (Pro Dynamic Form module) resolve against the active
83 * locale when a matching translation exists, and returns the original string
84 * unchanged otherwise. Safe for empty/non-string input.
85 *
86 * @param mixed $string
87 * @return string
88 */
89 function yatra_translate_form_string($string): string
90 {
91 $string = is_scalar($string) ? (string) $string : '';
92 if ($string === '') {
93 return '';
94 }
95
96 // Dynamic gettext: the literal source strings are registered for extraction
97 // in SettingsService; this resolves them (and any matching custom label) at
98 // runtime against the loaded 'yatra' text domain.
99 return __($string, 'yatra'); // phpcs:ignore WordPress.WP.I18n.NonSingularStringLiteralText, WordPress.WP.I18n.NonSingularStringLiteralDomain
100 }
101
102 /**
103 * Check if user can leave a review for a trip
104 *
105 * @param int $trip_id Trip ID
106 * @param int|null $user_id User ID (defaults to current user)
107 * @return bool
108 */
109 function yatra_can_review(int $trip_id, ?int $user_id = null): bool
110 {
111 // Reviews must be enabled
112 if (!SettingsService::reviewsEnabled()) {
113 return false;
114 }
115
116 // Get user ID
117 if ($user_id === null) {
118 $user_id = get_current_user_id();
119 }
120
121 // If booking required, check if user has booked this trip
122 if (SettingsService::requireBookingForReview()) {
123 if ($user_id === 0) {
124 return false; // Guest can't review if booking required
125 }
126
127 // Check if user has a completed booking for this trip
128 global $wpdb;
129 $table = BookingsTable::getTableName();
130 $has_booking = $wpdb->get_var($wpdb->prepare(
131 "SELECT COUNT(*) FROM {$table}
132 WHERE trip_id = %d AND customer_id = %d AND status = 'completed'",
133 $trip_id,
134 $user_id
135 ));
136
137 if (!$has_booking) {
138 return false;
139 }
140 }
141
142 // Check if user already reviewed this trip (but allow if within edit window)
143 if ($user_id > 0) {
144 $existing_review = yatra_get_user_review($trip_id, $user_id);
145 if ($existing_review && !yatra_can_edit_review($existing_review)) {
146 return false;
147 }
148 }
149
150 return true;
151 }
152
153 /**
154 * Get user's existing review for a trip
155 *
156 * @param int $trip_id Trip ID
157 * @param int|null $user_id User ID (defaults to current user)
158 * @return object|null Review object or null
159 */
160 function yatra_get_user_review(int $trip_id, ?int $user_id = null): ?object
161 {
162 if ($user_id === null) {
163 $user_id = get_current_user_id();
164 }
165
166 if ($user_id === 0) {
167 return null;
168 }
169
170 global $wpdb;
171 $table = ReviewsTable::getTableName();
172 $review = $wpdb->get_row($wpdb->prepare(
173 "SELECT * FROM {$table} WHERE trip_id = %d AND user_id = %d ORDER BY created_at DESC LIMIT 1",
174 $trip_id,
175 $user_id
176 ));
177
178 return $review ?: null;
179 }
180
181 /**
182 * Check if a review can be edited (within 24 hours of creation and not approved)
183 *
184 * @param object $review Review object with created_at and status fields
185 * @return bool
186 */
187 function yatra_can_edit_review(object $review): bool
188 {
189 if (empty($review->created_at)) {
190 return false;
191 }
192
193 // Don't allow editing if review is approved
194 if (isset($review->status) && $review->status === 'approved') {
195 return false;
196 }
197
198 $created_time = strtotime($review->created_at);
199 $current_time = current_time('timestamp');
200 $hours_since_creation = ($current_time - $created_time) / 3600;
201
202 // Allow editing within 24 hours (only for pending/rejected reviews)
203 return $hours_since_creation <= 24;
204 }
205
206 /**
207 * Get time remaining to edit a review
208 *
209 * @param object $review Review object with created_at field
210 * @return string Human-readable time remaining (e.g., "5 hours", "30 minutes")
211 */
212 function yatra_get_review_edit_time_remaining(object $review): string
213 {
214 if (empty($review->created_at)) {
215 return '';
216 }
217
218 $created_time = strtotime($review->created_at);
219 $current_time = current_time('timestamp');
220 $seconds_since_creation = $current_time - $created_time;
221 $seconds_remaining = (24 * 3600) - $seconds_since_creation;
222
223 if ($seconds_remaining <= 0) {
224 return '';
225 }
226
227 $hours = floor($seconds_remaining / 3600);
228 $minutes = floor(($seconds_remaining % 3600) / 60);
229
230 if ($hours > 0) {
231 /* translators: %d: number of hours remaining. */
232 return sprintf(_n('%d hour', '%d hours', $hours, 'yatra'), $hours);
233 }
234
235 /* translators: %d: number of minutes remaining. */
236 return sprintf(_n('%d minute', '%d minutes', $minutes, 'yatra'), $minutes);
237 }
238
239 /**
240 * Get the booking URL for a trip
241 *
242 * @param string $trip_slug The trip slug
243 * @param array $params Optional URL parameters (date, adults, children, price)
244 * @return string The booking URL
245 */
246 function yatra_get_booking_url(string $trip_slug, array $params = []): string
247 {
248 $permalink_structure = get_option('permalink_structure');
249 $is_plain = empty($permalink_structure);
250
251 // Check if using custom booking page via SettingsService
252 if (SettingsService::useCustomBookingPage()) {
253 $page_url = get_permalink(SettingsService::getBookingPageId());
254 if ($page_url) {
255 $params['trip'] = $trip_slug;
256 return add_query_arg($params, $page_url);
257 }
258 }
259
260 // Using default dynamic URL
261 $booking_base = SettingsService::getBookingBase();
262 if ($is_plain) {
263 $params['trip'] = $trip_slug;
264
265 return add_query_arg(
266 array_merge(['yatra_page' => $booking_base], $params),
267 home_url('/')
268 );
269 }
270
271 $url = home_url('/' . $booking_base . '/' . $trip_slug);
272
273 if (!empty($params)) {
274 $url = add_query_arg($params, $url);
275 }
276
277 return $url;
278 }
279
280 /**
281 * Normalized Dynamic Pricing display toggles (listing, trip page, availability).
282 *
283 * @return array{show_original_price: bool, show_savings_badge: bool, show_urgency_messages: bool}
284 */
285 if (!function_exists('yatra_get_dynamic_pricing_display_flags')) {
286 function yatra_get_dynamic_pricing_display_flags(): array
287 {
288 $s = apply_filters('yatra_get_dynamic_pricing_display_settings', [
289 'show_original_price' => true,
290 'show_savings_badge' => true,
291 'show_urgency_messages' => false,
292 ]);
293
294 return [
295 'show_original_price' => filter_var($s['show_original_price'] ?? true, FILTER_VALIDATE_BOOLEAN),
296 'show_savings_badge' => filter_var($s['show_savings_badge'] ?? true, FILTER_VALIDATE_BOOLEAN),
297 'show_urgency_messages' => filter_var($s['show_urgency_messages'] ?? false, FILTER_VALIDATE_BOOLEAN),
298 ];
299 }
300 }
301
302 /**
303 * Urgency lines for a trip surface (listing card, sidebar, similar trips). Pro fills via yatra_trip_card_dynamic_pricing_meta.
304 *
305 * @param array<string, mixed> $context base_sale_price, base_original_price, departure_date, spots_remaining, …
306 * @return array<int, string>
307 */
308 if (!function_exists('yatra_trip_card_dynamic_pricing_urgency_lines')) {
309 function yatra_trip_card_dynamic_pricing_urgency_lines(int $trip_id, array $context = []): array
310 {
311 if ($trip_id <= 0) {
312 return [];
313 }
314
315 $flags = yatra_get_dynamic_pricing_display_flags();
316 if (!$flags['show_urgency_messages']) {
317 return [];
318 }
319
320 $meta = apply_filters(
321 'yatra_trip_card_dynamic_pricing_meta',
322 ['urgency_messages' => []],
323 array_merge($context, [
324 'trip_id' => $trip_id,
325 'display' => $flags,
326 ])
327 );
328
329 if (!is_array($meta) || empty($meta['urgency_messages']) || !is_array($meta['urgency_messages'])) {
330 return [];
331 }
332
333 $out = [];
334 foreach ($meta['urgency_messages'] as $line) {
335 $line = sanitize_text_field((string) $line);
336 if ($line !== '') {
337 $out[] = $line;
338 }
339 }
340
341 return array_values(array_unique($out));
342 }
343 }
344
345 /**
346 * Format price with currency
347 *
348 * @param float $amount The amount to format
349 * @param string|null $currency The currency code (optional, uses global setting if not provided)
350 * @param bool $zero_is_unknown When true (default), 0 is shown as "Contact for pricing" (trip/listing).
351 * Set false for checkout, payments, and invoices where 0 is a real amount.
352 * @return string Formatted price
353 */
354 if (!function_exists('yatra_format_price')) {
355 function yatra_format_price(float $amount, ?string $currency = null, bool $zero_is_unknown = true): string
356 {
357 if ($zero_is_unknown && (empty($amount) || $amount == 0)) {
358 return __('Contact for pricing', 'yatra');
359 }
360
361 // Get currency from global settings if not provided
362 if (empty($currency)) {
363 $currency = SettingsService::getCurrency();
364 }
365
366 // Get formatting settings from global settings
367 $currency_position = SettingsService::getCurrencyPosition();
368 // Single source of truth: honors the admin "Number of decimals" field and
369 // stays in sync with the JS price formatter (already clamped to 0–4).
370 $decimal_places = SettingsService::getPriceDecimals();
371 $thousand_separator = SettingsService::getString('thousand_separator', ',');
372 $decimal_separator = SettingsService::getString('decimal_separator', '.');
373
374 // Format the amount with proper separators
375 $formatted_amount = number_format($amount, $decimal_places, $decimal_separator, $thousand_separator);
376
377 // Get currency symbol
378 $currency_symbol = yatra_get_currency_symbol($currency);
379
380 // Placement: Settings UI uses left, right, left_space, right_space; legacy uses before/after.
381 $raw = strtolower(trim((string) $currency_position));
382 if ($raw === 'before') {
383 $pos = 'left_space';
384 } elseif ($raw === 'after') {
385 $pos = 'right_space';
386 } else {
387 $pos = $raw;
388 }
389 $allowed = ['left', 'right', 'left_space', 'right_space'];
390 if (!in_array($pos, $allowed, true)) {
391 $pos = 'left_space';
392 }
393
394 if ($pos === 'right') {
395 return $formatted_amount . $currency_symbol;
396 }
397 if ($pos === 'right_space') {
398 return $formatted_amount . ' ' . $currency_symbol;
399 }
400 if ($pos === 'left') {
401 return $currency_symbol . $formatted_amount;
402 }
403
404 return $currency_symbol . ' ' . $formatted_amount;
405 }
406 }
407
408 /**
409 * Get currency symbol from currency code
410 *
411 * @param string $currency_code The currency code (e.g., 'USD', 'EUR', 'NPR')
412 * @return string The currency symbol or code
413 */
414 if (!function_exists('yatra_get_currency_symbol')) {
415 function yatra_get_currency_symbol(string $currency_code): string
416 {
417 $symbols = [
418 'USD' => '$',
419 'EUR' => '€',
420 'GBP' => '£',
421 'JPY' => '¥',
422 'CNY' => '¥',
423 'INR' => '₹',
424 'NPR' => 'Rs',
425 'AUD' => 'A$',
426 'CAD' => 'C$',
427 'CHF' => 'CHF',
428 'NZD' => 'NZ$',
429 'SGD' => 'S$',
430 'HKD' => 'HK$',
431 'KRW' => '₩',
432 'THB' => '฿',
433 'MYR' => 'RM',
434 'PHP' => '₱',
435 'IDR' => 'Rp',
436 'VND' => '₫',
437 'BRL' => 'R$',
438 'MXN' => 'MX$',
439 'RUB' => '₽',
440 'ZAR' => 'R',
441 'AED' => 'د.إ',
442 'SAR' => '﷼',
443 'TRY' => '₺',
444 'SEK' => 'kr',
445 'NOK' => 'kr',
446 'DKK' => 'kr',
447 'PLN' => 'zł',
448 'CZK' => 'Kč',
449 'HUF' => 'Ft',
450 'ILS' => '₪',
451 'TWD' => 'NT$',
452 'PKR' => '₨',
453 'BDT' => '৳',
454 'LKR' => 'Rs',
455 'EGP' => 'E£',
456 'NGN' => '₦',
457 'KES' => 'KSh',
458 // Ghanaian cedi – use plain symbol without the GH prefix
459 'GHS' => '₵',
460 'GHC' => '₵',
461 'ARS' => 'AR$',
462 'CLP' => 'CL$',
463 'COP' => 'CO$',
464 'PEN' => 'S/',
465 ];
466
467 return $symbols[strtoupper($currency_code)] ?? $currency_code;
468 }
469 }
470
471 /**
472 * Format duration (days/nights)
473 *
474 * @param int $days Number of days
475 * @param int|null $nights Number of nights (optional)
476 * @return string Formatted duration
477 */
478 if (!function_exists('yatra_format_duration')) {
479 function yatra_format_duration(int $days, ?int $nights = null): string
480 {
481 if ($days > 0 && $nights !== null && $nights > 0) {
482 /* translators: 1: number of days, 2: number of nights. */
483 return sprintf(__('%1$d days / %2$d nights', 'yatra'), $days, $nights);
484 }
485 if ($days > 0) {
486 return sprintf(
487 /* translators: %d: number of days. */
488 _n('%d day', '%d days', $days, 'yatra'),
489 $days
490 );
491 }
492 return __('Flexible', 'yatra');
493 }
494 }
495
496 /**
497 * Render SVG icon
498 *
499 * @param string $icon_name Icon name
500 * @param string $class Optional CSS class
501 * @return string SVG markup
502 */
503 if (!function_exists('yatra_svg_icon')) {
504 function yatra_svg_icon(string $icon_name, string $class = ''): string
505 {
506 static $icons = null;
507
508 // Load icons from JSON file once
509 if ($icons === null) {
510 $icons_file = dirname(__FILE__) . '/icons.json';
511 if (file_exists($icons_file)) {
512 $icons_data = json_decode(file_get_contents($icons_file), true);
513 $icons = [];
514
515 // Convert JSON data to PHP array
516 foreach ($icons_data as $name => $data) {
517 if (isset($data['svg'])) {
518 $icons[$name] = (string) $data['svg'];
519 }
520 }
521 } else {
522 $icons = [];
523 }
524 }
525
526 $svg = $icons[$icon_name] ?? '';
527
528 if ($svg === '' || !is_string($svg)) {
529 return '';
530 }
531
532 if ($class !== '') {
533 $class_attr = esc_attr($class);
534
535 if (preg_match('/<svg[^>]*\sclass="([^"]*)"/i', $svg, $m)) {
536 $existing = trim((string) ($m[1] ?? ''));
537 $merged = trim($existing . ' ' . $class_attr);
538 $svg = preg_replace('/(<svg[^>]*\sclass=")([^"]*)(")/i', '$1' . $merged . '$3', $svg, 1);
539 } else {
540 $svg = preg_replace('/<svg\b/i', '<svg class="' . $class_attr . '"', $svg, 1);
541 }
542 }
543
544 return (string) $svg;
545 }
546 }
547
548 /**
549 * Allowed Font Awesome Free icon name (maps to fa-{name} class).
550 */
551 if (!function_exists('yatra_sanitize_fa_icon_slug')) {
552 function yatra_sanitize_fa_icon_slug(string $name): string
553 {
554 $n = strtolower(trim($name));
555 if ($n === '' || strlen($n) > 64) {
556 return '';
557 }
558 if (!preg_match('/^[a-z0-9-]+$/', $n)) {
559 return '';
560 }
561
562 return $n;
563 }
564 }
565
566 /**
567 * Normalize icon picker payload before storing (REST / services).
568 *
569 * @param array<string, mixed> $icon
570 * @return array{type: string, value: string|int, provider?: string}
571 */
572 if (!function_exists('yatra_normalize_icon_picker_for_storage')) {
573 function yatra_normalize_icon_picker_for_storage(array $icon): array
574 {
575 $type = isset($icon['type']) && $icon['type'] === 'image' ? 'image' : 'icon';
576 $value = $icon['value'] ?? '';
577 if ($type === 'image') {
578 return [
579 'type' => 'image',
580 'value' => is_numeric($value) ? (int) $value : sanitize_text_field((string) $value),
581 ];
582 }
583 $provider = isset($icon['provider']) ? sanitize_key((string) $icon['provider']) : 'yatra';
584 if (!in_array($provider, ['yatra', 'fa-solid', 'fa-regular'], true)) {
585 $provider = 'yatra';
586 }
587
588 return [
589 'type' => 'icon',
590 'value' => sanitize_text_field((string) $value),
591 'provider' => $provider,
592 ];
593 }
594 }
595
596 /**
597 * Markup for a stored icon picker value (Yatra SVG registry, Font Awesome, or image).
598 *
599 * @param array<string, mixed>|string|null $picker Serialized JSON string, array, or null.
600 * @return string Safe HTML (empty string if nothing renderable).
601 */
602 if (!function_exists('yatra_stored_picker_icon_markup')) {
603 function yatra_stored_picker_icon_markup($picker, string $default_yatra_slug = 'mountain', string $class = ''): string
604 {
605 $class = trim($class);
606 $class_attr = $class !== '' ? ' ' . esc_attr($class) : '';
607
608 if ($picker === null || $picker === '') {
609 return function_exists('yatra_svg_icon') ? yatra_svg_icon($default_yatra_slug, $class) : '';
610 }
611 if (is_string($picker) && strpos($picker, '{') === 0) {
612 $picker = json_decode($picker, true);
613 }
614 if (!is_array($picker) || !isset($picker['type'])) {
615 if (is_string($picker)) {
616 $slug = trim($picker);
617
618 return $slug !== '' && function_exists('yatra_svg_icon')
619 ? yatra_svg_icon($slug, $class)
620 : yatra_svg_icon($default_yatra_slug, $class);
621 }
622
623 return function_exists('yatra_svg_icon') ? yatra_svg_icon($default_yatra_slug, $class) : '';
624 }
625
626 if ($picker['type'] === 'image' && !empty($picker['value'])) {
627 $image_url = is_numeric($picker['value'])
628 ? wp_get_attachment_url((int) $picker['value'])
629 : (string) $picker['value'];
630 if ($image_url) {
631 $style = 'width:24px;height:24px;object-fit:cover;border-radius:4px;';
632
633 return '<img src="' . esc_url($image_url) . '" alt="" class="' . esc_attr(trim('yatra-picker-img-icon ' . $class)) . '" style="' . esc_attr($style) . '" loading="lazy" decoding="async" />';
634 }
635
636 return function_exists('yatra_svg_icon') ? yatra_svg_icon('image', $class) : '';
637 }
638
639 if ($picker['type'] === 'icon' && !empty($picker['value'])) {
640 $provider = isset($picker['provider']) ? sanitize_key((string) $picker['provider']) : 'yatra';
641 if ($provider === 'fa-solid' || $provider === 'fa-regular') {
642 $slug = yatra_sanitize_fa_icon_slug((string) $picker['value']);
643 if ($slug === '') {
644 return function_exists('yatra_svg_icon') ? yatra_svg_icon($default_yatra_slug, $class) : '';
645 }
646 $fa_prefix = $provider === 'fa-regular' ? 'fa-regular' : 'fa-solid';
647
648 return '<i class="' . esc_attr($fa_prefix . ' fa-' . $slug . $class_attr) . '" aria-hidden="true"></i>';
649 }
650
651 return function_exists('yatra_svg_icon')
652 ? yatra_svg_icon((string) $picker['value'], $class)
653 : '';
654 }
655
656 return function_exists('yatra_svg_icon') ? yatra_svg_icon($default_yatra_slug, $class) : '';
657 }
658 }
659
660 /**
661 * Translated display label for trip meal_plan stored slug (matches admin Trip Builder options).
662 *
663 * @param string|null $slug Raw value from DB (e.g. half_board, "Half Board").
664 */
665 if (!function_exists('yatra_meal_plan_label')) {
666 function yatra_meal_plan_label(?string $slug): string
667 {
668 if ($slug === null || $slug === '') {
669 return '';
670 }
671 $s = strtolower(trim(preg_replace('/[\s\-]+/', '_', $slug), " \t\n\r\0\x0B_-"));
672 switch ($s) {
673 case 'breakfast':
674 return __('Breakfast Only', 'yatra');
675 case 'half_board':
676 return __('Half Board (Breakfast + Dinner)', 'yatra');
677 case 'full_board':
678 return __('Full Board (All Meals)', 'yatra');
679 case 'all_inclusive':
680 return __('All Inclusive', 'yatra');
681 case 'none':
682 return __('No Meals Included', 'yatra');
683 default:
684 return ucwords(str_replace('_', ' ', $s));
685 }
686 }
687 }
688
689 /**
690 * Translated itinerary entry item type label for frontend (matches admin item type names).
691 */
692 if (!function_exists('yatra_itinerary_item_type_label')) {
693 function yatra_itinerary_item_type_label(string $type): string
694 {
695 $t = trim($type);
696 switch ($t) {
697 case 'Meal':
698 return __('Meal', 'yatra');
699 case 'Activity':
700 return __('Activity', 'yatra');
701 case 'Accommodation':
702 return __('Accommodation', 'yatra');
703 case 'Transportation':
704 return __('Transportation', 'yatra');
705 case 'Rest':
706 return __('Rest', 'yatra');
707 default:
708 return $t;
709 }
710 }
711 }
712
713 /**
714 * Extract SVG icon slug from a stored icon field (same shape as admin / archive cards).
715 *
716 * @param mixed $icon Raw value from DB (serialized array with type/value, URL, attachment id, or legacy slug string).
717 */
718 function yatra_icon_slug_from_stored_field($icon): string
719 {
720 if ($icon === null || $icon === '') {
721 return '';
722 }
723
724 $icon = maybe_unserialize($icon);
725
726 if (is_array($icon)) {
727 $type = $icon['type'] ?? $icon[0] ?? '';
728 $value = $icon['value'] ?? $icon[1] ?? '';
729 if ($type === 'icon' && !empty($value) && is_string($value)) {
730 $provider = isset($icon['provider']) ? sanitize_key((string) $icon['provider']) : 'yatra';
731 if ($provider === 'fa-solid' || $provider === 'fa-regular') {
732 return '';
733 }
734
735 return $value;
736 }
737
738 return '';
739 }
740
741 if (is_string($icon)) {
742 if (filter_var($icon, FILTER_VALIDATE_URL)) {
743 return '';
744 }
745 $slug = trim($icon);
746
747 return $slug !== '' ? $slug : '';
748 }
749
750 return '';
751 }
752
753 /**
754 * SVG markup for archive listing CTAs: use admin icon when present and valid in icons.json; else default slug.
755 *
756 * @param string $resolved_icon_slug From the listing loop (same source as card hero icon when type is "icon").
757 * @param string $default_slug icons.json key when no admin icon.
758 */
759 function yatra_archive_listing_cta_icon_markup(string $resolved_icon_slug, string $default_slug, string $class = 'yatra-btn-icon'): string
760 {
761 $slug = trim($resolved_icon_slug);
762 if ($slug !== '' && function_exists('yatra_svg_icon')) {
763 $out = yatra_svg_icon($slug, $class);
764 if ($out !== '') {
765 return $out;
766 }
767 }
768
769 $fallback = trim($default_slug);
770 if ($fallback !== '' && function_exists('yatra_svg_icon')) {
771 return yatra_svg_icon($fallback, $class);
772 }
773
774 return '';
775 }
776
777 /**
778 * Icon slug for trip listing card "View Details" — category, then destination, then difficulty (backend order).
779 *
780 * @param array<int, object|array<string, mixed>> $categories Trip categories from getCategories()
781 * @param array<int, object|array<string, mixed>> $destinations Trip destinations from getDestinations()
782 * @param array<string, mixed> $difficulty From Trip::getDifficulty()
783 */
784 function yatra_trip_listing_card_cta_icon_slug(array $categories, array $destinations, array $difficulty): string
785 {
786 foreach ($categories as $row) {
787 if (empty($row)) {
788 continue;
789 }
790 $raw = is_object($row) ? ($row->icon ?? null) : ($row['icon'] ?? null);
791 $slug = yatra_icon_slug_from_stored_field($raw);
792 if ($slug !== '') {
793 return $slug;
794 }
795 }
796
797 foreach ($destinations as $row) {
798 if (empty($row)) {
799 continue;
800 }
801 $raw = is_object($row) ? ($row->icon ?? null) : ($row['icon'] ?? null);
802 $slug = yatra_icon_slug_from_stored_field($raw);
803 if ($slug !== '') {
804 return $slug;
805 }
806 }
807
808 if (!empty($difficulty['icon']) && is_string($difficulty['icon'])) {
809 $try = trim($difficulty['icon']);
810 if ($try !== '') {
811 return $try;
812 }
813 }
814
815 return '';
816 }
817
818 /**
819 * Get booking base URL slug
820 *
821 * @return string The booking base slug
822 */
823 function yatra_get_booking_base(): string
824 {
825 // Check if using custom booking page
826 if (SettingsService::useCustomBookingPage()) {
827 $booking_page_id = SettingsService::getBookingPageId();
828 if ($booking_page_id > 0) {
829 $page = get_post($booking_page_id);
830 if ($page) {
831 return $page->post_name;
832 }
833 }
834 }
835
836 return SettingsService::getBookingBase();
837 }
838
839 /**
840 * Check if the current page is a booking page
841 *
842 * @return bool
843 */
844 function yatra_is_booking_page(): bool
845 {
846 global $wp_query;
847
848 // Check for custom booking page
849 if (SettingsService::useCustomBookingPage()) {
850 $booking_page_id = SettingsService::getBookingPageId();
851 if ($booking_page_id > 0 && is_page($booking_page_id)) {
852 return true;
853 }
854 }
855
856 $booking_base = SettingsService::getBookingBase();
857 if (!empty($wp_query->get('yatra_page')) && (string) $wp_query->get('yatra_page') === $booking_base) {
858 return true;
859 }
860
861 // Check for dynamic booking URL
862 return !empty($wp_query->get('yatra_booking_trip_slug'));
863 }
864
865 /**
866 * Get the global trip object
867 *
868 * Similar to WordPress get_post(), this function returns the current trip object
869 * when on a single trip page.
870 *
871 * @return object|null The trip object or null if not on a trip page
872 */
873 function yatra_get_trip(): ?object
874 {
875 global $trip;
876 return $trip ?? null;
877 }
878
879 /**
880 * Check if we're on a single trip page
881 *
882 * @return bool True if on a single trip page
883 */
884 function yatra_is_single_trip(): bool
885 {
886
887 global $wp_query;
888 return !empty($wp_query->get('yatra_trip_id'));
889 }
890
891 /**
892 * Get a trip field value with default fallback
893 *
894 * @param string $field The field name
895 * @param mixed $default Default value if field is empty
896 * @return mixed The field value or default
897 */
898 function yatra_get_trip_field(string $field, $default = '')
899 {
900 global $trip;
901
902 if (!$trip || !isset($trip->$field)) {
903 return $default;
904 }
905
906 return $trip->$field ?: $default;
907 }
908
909 /**
910 * Echo a trip field value with escaping
911 *
912 * @param string $field The field name
913 * @param string $escape Escape function: 'html', 'attr', 'url', 'js', 'none'
914 * @param mixed $default Default value if field is empty
915 */
916 function yatra_trip_field(string $field, string $escape = 'html', $default = ''): void
917 {
918 $value = yatra_get_trip_field($field, $default);
919
920 switch ($escape) {
921 case 'html':
922 echo esc_html($value);
923 break;
924 case 'attr':
925 echo esc_attr($value);
926 break;
927 case 'url':
928 echo esc_url($value);
929 break;
930 case 'js':
931 echo esc_js($value);
932 break;
933 case 'none':
934 case 'kses':
935 echo wp_kses_post($value);
936 break;
937 default:
938 echo esc_html($value);
939 }
940 }
941
942 /**
943 * ============================================
944 * BRAND / WHITE LABEL HELPERS (THIN WRAPPERS)
945 * ============================================
946 *
947 * The free plugin owns the function NAMES (so callers in plugin row meta,
948 * admin menu, PDF templates, etc. work without conditional `function_exists`
949 * checks), but every override lives in Yatra Pro's White Label module.
950 *
951 * Each helper here just applies a filter; Pro's WhiteLabel module registers
952 * filter callbacks when the module is enabled AND an Agency-tier license is
953 * active. Without Pro, every filter no-ops and these return the defaults —
954 * which is the correct behavior for a free-only install.
955 *
956 * Option storage, REST endpoints, sanitization, plugin-list rebranding,
957 * brand-color CSS injection, and dependency-link rewriting all live in
958 * yatra-pro/app/Modules/WhiteLabel/ — NOT here.
959 */
960
961 /**
962 * Public URL for the Yatra brand icon (admin menu + React sidebar).
963 * Defaults to the bundled `yatra-icon.png`; Pro overrides via the
964 * `yatra_brand_icon_url` filter when a White Label logo is configured.
965 */
966 function yatra_get_brand_icon_url(): string
967 {
968 $default = '';
969 if (defined('YATRA_PLUGIN_PATH') && defined('YATRA_PLUGIN_URL')) {
970 $candidates = [
971 'assets/images/yatra-icon.png',
972 'assets/images/yara-icon.png',
973 ];
974 foreach ($candidates as $relative) {
975 $file = YATRA_PLUGIN_PATH . $relative;
976 if (!is_readable($file)) {
977 continue;
978 }
979 $default = add_query_arg(
980 'ver',
981 (string) filemtime($file),
982 YATRA_PLUGIN_URL . $relative
983 );
984 break;
985 }
986 }
987
988 return (string) apply_filters('yatra_brand_icon_url', $default);
989 }
990
991 /**
992 * Whether the Agency White Label module is active and may override branding.
993 * Pro returns true via the `yatra_white_label_active` filter when its
994 * WhiteLabel module is enabled AND the license tier is Agency.
995 */
996 function yatra_is_white_label_active(): bool
997 {
998 return (bool) apply_filters('yatra_white_label_active', false);
999 }
1000
1001 /**
1002 * Read a single white-label setting with a default fallback. Backed by a
1003 * filter so option access stays in Pro.
1004 *
1005 * @param mixed $default
1006 * @return mixed
1007 */
1008 function yatra_get_white_label_setting(string $key, $default = '')
1009 {
1010 return apply_filters('yatra_white_label_setting', $default, $key);
1011 }
1012
1013 /**
1014 * @return array<string, mixed>
1015 */
1016 function yatra_get_white_label_settings(): array
1017 {
1018 $value = apply_filters('yatra_white_label_settings', []);
1019 return is_array($value) ? $value : [];
1020 }
1021
1022 /**
1023 * Branding for generated PDFs (invoice, voucher, itinerary).
1024 *
1025 * Free ships an unbranded default — the header keeps whatever colour the
1026 * document already used and no logo is shown — so nothing changes for a site
1027 * without Yatra Pro. The White Label module hooks these filters to supply the
1028 * operator's own logo and colour, exactly as it already does for
1029 * `yatra_brand_icon_url` and friends.
1030 *
1031 * Kept as filters rather than reading White Label options directly so free never
1032 * depends on Pro, and so a site can brand its PDFs from a theme or snippet
1033 * without the module at all.
1034 *
1035 * @param string $defaultHeaderColor The document's existing header colour, so
1036 * each PDF keeps its own look when unbranded.
1037 * @return array{logo_url: string, header_color: string}
1038 */
1039 function yatra_get_pdf_branding(string $defaultHeaderColor): array
1040 {
1041 $logo = (string) apply_filters('yatra_pdf_branding_logo_url', '');
1042 $color = (string) apply_filters('yatra_pdf_branding_header_color', $defaultHeaderColor);
1043
1044 // Only accept a well-formed hex colour; anything else falls back to the
1045 // document default rather than emitting broken CSS into the PDF.
1046 if (!preg_match('/^#[0-9a-fA-F]{3}(?:[0-9a-fA-F]{3})?$/', $color)) {
1047 $color = $defaultHeaderColor;
1048 }
1049
1050 $logo = esc_url_raw(trim($logo));
1051
1052 return [
1053 'logo_url' => $logo,
1054 'header_color' => $color,
1055 ];
1056 }
1057
1058 /**
1059 * Are partial payments possible on this site at all?
1060 *
1061 * True when deposits or partial payments are switched on globally. Used to
1062 * decide whether part-payment specific features (such as the separate
1063 * "part payment received" email template) are relevant — there is no point
1064 * showing them to an operator who only ever takes payment in full.
1065 */
1066 function yatra_partial_payments_enabled(): bool
1067 {
1068 $enabled = \Yatra\Services\SettingsService::isEnabled('partial_payment')
1069 || \Yatra\Services\SettingsService::isEnabled('enable_deposit')
1070 || \Yatra\Services\SettingsService::isEnabled('deposit_required');
1071
1072 return (bool) apply_filters('yatra_partial_payments_enabled', $enabled);
1073 }
1074
1075 /**
1076 * Branded plugin name shown in admin menu, plugin list, and PDFs.
1077 */
1078 function yatra_get_brand_name(): string
1079 {
1080 return (string) apply_filters('yatra_brand_name', 'Yatra');
1081 }
1082
1083 /**
1084 * Branded company/author name (replaces "MantraBrain").
1085 */
1086 function yatra_get_brand_company(): string
1087 {
1088 return (string) apply_filters('yatra_brand_company', 'MantraBrain');
1089 }
1090
1091 /**
1092 * Public website URL for the branded product.
1093 */
1094 function yatra_get_brand_website_url(): string
1095 {
1096 $url = (string) apply_filters('yatra_brand_website_url', 'https://wpyatra.com/');
1097 return $url !== '' ? esc_url_raw($url) : 'https://wpyatra.com/';
1098 }
1099
1100 /**
1101 * Support URL surfaced in admin notices and the plugin row.
1102 */
1103 function yatra_get_brand_support_url(): string
1104 {
1105 $url = (string) apply_filters(
1106 'yatra_brand_support_url',
1107 'https://wordpress.org/support/plugin/yatra/reviews/?filter=5'
1108 );
1109 return $url !== '' ? esc_url_raw($url) : 'https://wordpress.org/support/plugin/yatra/reviews/?filter=5';
1110 }
1111
1112
1113 /**
1114 * ============================================
1115 * BOOKING SESSION MANAGEMENT
1116 * ============================================
1117 */
1118
1119 /**
1120 * Start WordPress session if not already started
1121 */
1122 function yatra_start_session(): void
1123 {
1124 // Start output buffering to prevent accidental output from breaking sessions
1125 if (!ob_get_level()) {
1126 ob_start();
1127 }
1128
1129 if (session_status() === PHP_SESSION_NONE && !headers_sent()) {
1130 // Set session cookie parameters for better compatibility
1131 if (PHP_VERSION_ID >= 70300) {
1132 session_set_cookie_params([
1133 'lifetime' => 0,
1134 'path' => defined('COOKIEPATH') ? COOKIEPATH : '/',
1135 'domain' => defined('COOKIE_DOMAIN') ? COOKIE_DOMAIN : '',
1136 'secure' => is_ssl(),
1137 'httponly' => true,
1138 'samesite' => 'Lax'
1139 ]);
1140 }
1141 session_start();
1142 }
1143 }
1144
1145 /**
1146 * Set booking session data
1147 *
1148 * @param array $data Booking data to store
1149 */
1150 function yatra_set_booking_session(array $data): void
1151 {
1152 yatra_start_session();
1153
1154 // Clear any existing remaining payment session to avoid conflicts
1155 unset($_SESSION['yatra_remaining']);
1156
1157 $session_data = array_merge(
1158 $_SESSION['yatra_booking'] ?? [],
1159 $data,
1160 ['timestamp' => time()]
1161 );
1162
1163 $_SESSION['yatra_booking'] = $session_data;
1164
1165 // ALWAYS store in transient as backup (not just for REST API)
1166 // This ensures data persists across all request types
1167 // Generate or reuse booking token
1168 $booking_token = $_SESSION['yatra_booking_token'] ?? 'yatra_booking_' . wp_generate_password(32, false);
1169 $_SESSION['yatra_booking_token'] = $booking_token;
1170 $session_data['booking_token'] = $booking_token;
1171
1172 // Store in transient (expires in 30 minutes)
1173 try {
1174 $transient_set = set_transient($booking_token, $session_data, 1800);
1175 } catch (Exception $e) {
1176 // Continue without transient - session fallback will be used
1177 }
1178
1179 }
1180
1181 /**
1182 * Get booking session data
1183 *
1184 * @param string|null $key Specific key to retrieve, or null for all data
1185 * @param mixed $default Default value if key not found
1186 * @return mixed
1187 */
1188 function yatra_get_booking_session(?string $key = null, $default = null)
1189 {
1190 yatra_start_session();
1191
1192 $booking_data = $_SESSION['yatra_booking'] ?? [];
1193
1194 // If session is empty, try to restore from transient (REST API → page load transition)
1195 if (empty($booking_data) || empty($booking_data['trip_id'])) {
1196 // Check for booking token in URL or session
1197 $booking_token = $_GET['booking_token'] ?? $_SESSION['yatra_booking_token'] ?? null;
1198
1199 if ($booking_token) {
1200 try {
1201 $transient_data = get_transient($booking_token);
1202
1203 if ($transient_data && is_array($transient_data) && !empty($transient_data['trip_id'])) {
1204 // Validate transient data integrity
1205 if (isset($transient_data['timestamp']) && (time() - $transient_data['timestamp']) < 1800) {
1206 $booking_data = $transient_data;
1207 // Restore to session
1208 $_SESSION['yatra_booking'] = $booking_data;
1209 $_SESSION['yatra_booking_token'] = $booking_token;
1210 }
1211 }
1212 } catch (Exception $e) {
1213 // Continue without transient data
1214 }
1215 }
1216 }
1217
1218 // Check if session is expired (30 minutes)
1219 if (!empty($booking_data['timestamp'])) {
1220 $session_age = time() - $booking_data['timestamp'];
1221 if ($session_age > 1800) { // 30 minutes
1222 yatra_clear_booking_session();
1223 return $key ? $default : [];
1224 }
1225 }
1226
1227 if ($key === null) {
1228 return $booking_data;
1229 }
1230
1231 return $booking_data[$key] ?? $default;
1232 }
1233
1234 /**
1235 * Clear booking session data (PHP session, booking token, and REST backup transient).
1236 *
1237 * Without removing the token and transient, yatra_get_booking_session() can repopulate
1238 * checkout data from the transient on the next request after a completed booking.
1239 */
1240 function yatra_clear_booking_session(): void
1241 {
1242 yatra_start_session();
1243
1244 $token = $_SESSION['yatra_booking_token'] ?? null;
1245 if (is_string($token) && $token !== '') {
1246 delete_transient($token);
1247 }
1248
1249 unset($_SESSION['yatra_booking'], $_SESSION['yatra_booking_token']);
1250 }
1251
1252 /**
1253 * Check if booking session exists and is valid
1254 *
1255 * @return bool
1256 */
1257 function yatra_has_booking_session(): bool
1258 {
1259 $booking_data = yatra_get_booking_session();
1260 return !empty($booking_data) && !empty($booking_data['trip_id']);
1261 }
1262
1263 /**
1264 * Fire {@see 'yatra_booking_confirmed'} when a booking reaches `confirmed` from a non-confirmed status.
1265 *
1266 * Core always fired `yatra_booking_status_changed`; Pro modules (Trip Consent, Google Calendar) listen
1267 * on this dedicated action. Call this after any code path that sets a booking to `confirmed` without
1268 * going through {@see \Yatra\Services\BookingService::updateStatus()}.
1269 *
1270 * @param int $bookingId Booking ID.
1271 * @param string $previousStatus Booking status in the database immediately before confirming.
1272 */
1273 function yatra_trigger_booking_confirmed(int $bookingId, string $previousStatus): void
1274 {
1275 if ($bookingId < 1 || $previousStatus === 'confirmed') {
1276 return;
1277 }
1278
1279 $repo = new \Yatra\Repositories\BookingRepository();
1280 $booking = $repo->findWithTrip($bookingId);
1281
1282 if (!$booking || ($booking->status ?? '') !== 'confirmed') {
1283 return;
1284 }
1285
1286 /**
1287 * Booking reached confirmed status (was not confirmed before this transition).
1288 *
1289 * @param int $bookingId Booking ID.
1290 * @param object $booking Row from {@see \Yatra\Repositories\BookingRepository::findWithTrip()}.
1291 */
1292 do_action('yatra_booking_confirmed', $bookingId, $booking);
1293 }
1294
1295 /**
1296 * Decide whether a successful payment should auto-confirm the booking.
1297 *
1298 * A booking auto-confirms on payment only when the operator has enabled
1299 * "Auto-Confirm Bookings", OR the booking is now fully paid. A deposit /
1300 * partial payment must NOT confirm the booking while auto-confirm is off — the
1301 * operator confirms it manually. Previously the synchronous-gateway, Stripe and
1302 * PayPal completion paths force-confirmed on any payment, so deposit bookings
1303 * were confirmed immediately regardless of the setting.
1304 *
1305 * @param bool $fullyPaid Whether the booking's balance is now zero.
1306 * @param int $bookingId Booking ID (passed to the filter for context).
1307 * @return bool True to set the booking to `confirmed`.
1308 */
1309 function yatra_should_confirm_booking_on_payment(bool $fullyPaid, int $bookingId = 0): bool
1310 {
1311 $autoConfirm = (bool) \Yatra\Services\SettingsService::isEnabled('auto_confirm_bookings');
1312 $shouldConfirm = $autoConfirm || $fullyPaid;
1313
1314 /**
1315 * Filter whether a completed payment auto-confirms the booking.
1316 *
1317 * @param bool $shouldConfirm Default: auto-confirm setting is on OR fully paid.
1318 * @param bool $fullyPaid Whether the balance is now zero.
1319 * @param int $bookingId Booking ID.
1320 * @param bool $autoConfirm The `auto_confirm_bookings` setting value.
1321 */
1322 return (bool) apply_filters('yatra_confirm_booking_on_payment', $shouldConfirm, $fullyPaid, $bookingId, $autoConfirm);
1323 }
1324
1325 /**
1326 * ============================================
1327 * REMAINING PAYMENT SESSION MANAGEMENT
1328 * ============================================
1329 */
1330
1331 /**
1332 * Set remaining payment session data
1333 *
1334 * @param array $data Remaining payment data to store
1335 */
1336 function yatra_set_remaining_session(array $data): void
1337 {
1338 yatra_start_session();
1339
1340 // Clear checkout session fully (including token + transient) before remaining-payment flow
1341 yatra_clear_booking_session();
1342
1343 $_SESSION['yatra_remaining'] = array_merge(
1344 $data,
1345 ['timestamp' => time()]
1346 );
1347
1348 // Ensure session data is written to storage immediately
1349 if (session_status() === PHP_SESSION_ACTIVE) {
1350 session_write_close();
1351 }
1352 }
1353
1354 /**
1355 * Get remaining payment session data
1356 *
1357 * @param string|null $key Specific key to retrieve, or null for all data
1358 * @param mixed $default Default value if key not found
1359 * @return mixed
1360 */
1361 function yatra_get_remaining_session(?string $key = null, $default = null)
1362 {
1363 yatra_start_session();
1364
1365 $remaining_data = $_SESSION['yatra_remaining'] ?? [];
1366
1367 // Check if session is expired (30 minutes)
1368 if (!empty($remaining_data['timestamp'])) {
1369 $session_age = time() - $remaining_data['timestamp'];
1370 if ($session_age > 1800) { // 30 minutes
1371 yatra_clear_remaining_session();
1372 return $key ? $default : [];
1373 }
1374 }
1375
1376 if ($key === null) {
1377 return $remaining_data;
1378 }
1379
1380 return $remaining_data[$key] ?? $default;
1381 }
1382
1383 /**
1384 * Clear remaining payment session data
1385 */
1386 function yatra_clear_remaining_session(): void
1387 {
1388 yatra_start_session();
1389 unset($_SESSION['yatra_remaining']);
1390 }
1391
1392 /**
1393 * Check if remaining payment session exists and is valid
1394 *
1395 * @return bool
1396 */
1397 function yatra_has_remaining_session(): bool
1398 {
1399 $remaining_data = yatra_get_remaining_session();
1400 return !empty($remaining_data) && !empty($remaining_data['booking_id']);
1401 }
1402
1403 /**
1404 * Get the active checkout session type
1405 *
1406 * @return string|null 'remaining' if remaining session exists, 'booking' if booking session exists, null if neither
1407 */
1408 function yatra_get_checkout_session_type(): ?string
1409 {
1410 if (yatra_has_remaining_session()) {
1411 return 'remaining';
1412 }
1413
1414 if (yatra_has_booking_session()) {
1415 return 'booking';
1416 }
1417
1418 return null;
1419 }
1420
1421 /**
1422 * Get the active checkout session data (remaining or booking)
1423 *
1424 * @return array Session data with 'type' key indicating session type
1425 */
1426 function yatra_get_active_checkout_session(): array
1427 {
1428 if (yatra_has_remaining_session()) {
1429 $data = yatra_get_remaining_session();
1430 $data['session_type'] = 'remaining';
1431 return $data;
1432 }
1433
1434 if (yatra_has_booking_session()) {
1435 $data = yatra_get_booking_session();
1436 $data['session_type'] = 'booking';
1437 return $data;
1438 }
1439
1440 return [];
1441 }
1442
1443 /**
1444 * Get booking/checkout URL
1445 *
1446 * Logic:
1447 * 1. If custom booking page is set → return that page's URL
1448 * 2. Otherwise → return dynamic URL using booking_base from settings (e.g., /bookings/)
1449 *
1450 * @return string Booking URL
1451 */
1452 function yatra_get_checkout_url(): string
1453 {
1454 $permalink_structure = get_option('permalink_structure');
1455 $is_plain = empty($permalink_structure);
1456
1457 // Check if custom booking page is set via SettingsService
1458 if (SettingsService::useCustomBookingPage()) {
1459 $page_id = SettingsService::getBookingPageId();
1460 if ($page_id > 0) {
1461 return get_permalink($page_id);
1462 }
1463 }
1464
1465 // Default dynamic URL using booking base from settings
1466 $base = SettingsService::getBookingBase();
1467 if ($is_plain) {
1468 return add_query_arg(['yatra_page' => $base], home_url('/'));
1469 }
1470
1471 return home_url('/' . $base . '/');
1472 }
1473
1474 /**
1475 * Front-end URL for booking confirmation for a given reference.
1476 *
1477 * Booking confirmation is pageless: Yatra serves it via rewrite rules and query vars,
1478 * not a WordPress page permalink. Pretty URLs use /{booking_base}/confirmation/{reference}/.
1479 * Plain permalinks use ?yatra_booking_confirmation={reference}.
1480 *
1481 * To use a real WordPress page as the base (advanced), filter {@see 'yatra_booking_confirmation_base_url'}.
1482 * Legacy /booking-confirmation/{reference}/ remains registered in rewrites for old links.
1483 *
1484 * @param string $reference Booking reference segment (may be empty for base URL only).
1485 * @return string Full URL.
1486 */
1487 function yatra_get_booking_confirmation_url(string $reference = ''): string
1488 {
1489 $reference = (string) $reference;
1490 $permalink_structure = get_option('permalink_structure');
1491 $is_plain = empty($permalink_structure);
1492
1493 if ($is_plain) {
1494 if ($reference === '') {
1495 $url = home_url('/');
1496 } else {
1497 $url = add_query_arg('yatra_booking_confirmation', $reference, home_url('/'));
1498 }
1499 } else {
1500 $booking_base = trim((string) SettingsService::getBookingBase(), '/');
1501 if ($booking_base === '') {
1502 $booking_base = 'book';
1503 }
1504 $confirmSeg = trim((string) SettingsService::getPermalinkBases()['booking_flow_confirmation_segment'], '/');
1505 if ($confirmSeg === '') {
1506 $confirmSeg = 'confirmation';
1507 }
1508 $virtual_base = home_url('/' . $booking_base . '/' . $confirmSeg . '/');
1509
1510 /**
1511 * Override the base URL for booking confirmation (before the reference path segment).
1512 * Return a non-empty string to use a custom base (e.g. get_permalink( $page_id )).
1513 * Default null keeps the pageless virtual URL from Settings → booking base.
1514 *
1515 * @param string|null $base_url Custom base, or null to use virtual URL.
1516 * @param string $reference Booking reference (may be empty).
1517 */
1518 $base_url = apply_filters('yatra_booking_confirmation_base_url', null, $reference);
1519 if (!is_string($base_url) || $base_url === '') {
1520 $base_url = $virtual_base;
1521 }
1522
1523 if ($reference === '') {
1524 $url = trailingslashit($base_url);
1525 } else {
1526 $url = trailingslashit($base_url) . $reference . '/';
1527 }
1528 }
1529
1530 /**
1531 * Filter the booking confirmation URL.
1532 *
1533 * @param string $url Built URL.
1534 * @param string $reference Booking reference (may be empty).
1535 */
1536 return (string) apply_filters('yatra_booking_confirmation_url', $url, $reference);
1537 }
1538
1539 /**
1540 * Front-end URL to verify a customer email (checkout registration / account).
1541 *
1542 * Pretty permalinks: /yatra-verify-email/{token}/ (rewrite + query var).
1543 * Plain permalinks: ?yatra_verify_email={token} on the home URL (same as {@see \Yatra\Core\Routing\PermalinkCanonical}).
1544 *
1545 * @param string $secure_token URL-safe token (base64-derived; only [A-Za-z0-9_-] used in the path/query).
1546 */
1547 function yatra_get_email_verification_url(string $secure_token): string
1548 {
1549 $t = preg_replace('/[^a-zA-Z0-9_-]/', '', (string) $secure_token) ?? '';
1550 if ($t === '') {
1551 return home_url('/');
1552 }
1553
1554 $permalink_structure = get_option('permalink_structure');
1555 $is_plain = empty($permalink_structure);
1556
1557 if ($is_plain) {
1558 $url = add_query_arg('yatra_verify_email', $t, home_url('/'));
1559 } else {
1560 $prefix = SettingsService::getPermalinkBases()['email_verification_prefix'];
1561 $url = trailingslashit(home_url('/' . $prefix . '/' . $t . '/'));
1562 }
1563
1564 /**
1565 * Filter the customer email verification URL.
1566 *
1567 * @param string $url Full verification URL.
1568 * @param string $token Sanitized token segment.
1569 */
1570 return (string) apply_filters('yatra_email_verification_url', $url, $t);
1571 }
1572
1573 /**
1574 * ============================================
1575 * ARCHIVE LISTING (plain permalinks pagination)
1576 * ============================================
1577 */
1578
1579 /**
1580 * Items per page from WordPress Reading settings ("Blog pages show at most").
1581 * Used for Yatra front-end listings (trips, taxonomies, activity/destination/category archives).
1582 *
1583 * @return int At least 1.
1584 */
1585 function yatra_get_posts_per_page(): int
1586 {
1587 $n = absint((int) get_option('posts_per_page', 10));
1588
1589 return (int) apply_filters('yatra_posts_per_page', max(1, $n));
1590 }
1591
1592 /**
1593 * Current page number for Yatra archive templates (activity, destination, trip category).
1594 * Handles plain URLs where WordPress may use {@see 'paged'} or {@see 'page'} on the front page.
1595 */
1596 function yatra_get_archive_listing_paged(): int
1597 {
1598 if (isset($_GET['paged']) && $_GET['paged'] !== '') {
1599 return max(1, absint(wp_unslash($_GET['paged'])));
1600 }
1601
1602 if (!empty($_GET['yatra_page']) && isset($_GET['page']) && $_GET['page'] !== '') {
1603 return max(1, absint(wp_unslash($_GET['page'])));
1604 }
1605
1606 $p = (int) get_query_var('paged');
1607 if ($p > 0) {
1608 return max(1, $p);
1609 }
1610
1611 $p = (int) get_query_var('page');
1612
1613 return max(1, $p);
1614 }
1615
1616 /**
1617 * Result summary for destination / activity / trip-category browse pages (parity with trip grid header).
1618 *
1619 * @param string $items_label Plural noun, e.g. translated "destinations".
1620 */
1621 function yatra_archive_browse_results_line(int $start, int $end, int $total, int $page, int $pages, string $items_label): string
1622 {
1623 if ($total <= 0) {
1624 return '';
1625 }
1626
1627 return sprintf(
1628 /* translators: 1–2: range, 3: total, 4: item type, 5–6: pagination */
1629 __('Showing %1$d–%2$d of %3$d %4$s (page %5$d of %6$d)', 'yatra'),
1630 $start,
1631 $end,
1632 $total,
1633 $items_label,
1634 $page,
1635 $pages
1636 );
1637 }
1638
1639 /**
1640 * Request path (leading slash, no query string) for same-page links. Strips /page/N/ pagination segments.
1641 */
1642 function yatra_get_current_request_path_for_query_urls(): string
1643 {
1644 $request_uri = isset($_SERVER['REQUEST_URI']) ? (string) wp_unslash($_SERVER['REQUEST_URI']) : '/';
1645 $base_path = strtok($request_uri, '?') ?: '/';
1646 $base_path = rtrim((string) $base_path, '/');
1647 $base_path = preg_replace('#/page/[0-9]+#', '', $base_path);
1648 $base_path = rtrim($base_path, '/');
1649
1650 if ($base_path === '') {
1651 return '/';
1652 }
1653
1654 return $base_path[0] === '/' ? $base_path : '/' . $base_path;
1655 }
1656
1657 /**
1658 * Full URL for the same archive request with a different page (preserves yatra_page and other args).
1659 * Uses the current request path so /destination/, /activity/, /trip-category/ stay on the same listing.
1660 */
1661 function yatra_build_archive_listing_url(int $page_num): string
1662 {
1663 $params = !empty($_GET) && is_array($_GET) ? wp_unslash($_GET) : [];
1664
1665 $qvYatra = (string) get_query_var('yatra_page');
1666 if ($qvYatra !== '' && (!isset($params['yatra_page']) || $params['yatra_page'] === '')) {
1667 $params['yatra_page'] = $qvYatra;
1668 }
1669
1670 if (!empty($params['yatra_page']) || isset($params['yatra_trip'])) {
1671 unset($params['page']);
1672 }
1673
1674 if ($page_num > 1) {
1675 $params['paged'] = (string) $page_num;
1676 } else {
1677 unset($params['paged'], $params['page']);
1678 }
1679
1680 $path = yatra_get_current_request_path_for_query_urls();
1681 $query = http_build_query($params);
1682
1683 return esc_url($path . ($query !== '' ? '?' . $query : ''));
1684 }
1685
1686 /**
1687 * Same request path with a different paged query arg (strips an existing /page/N/ segment first).
1688 * For taxonomy trip lists and other templates not rooted at home_url('/').
1689 */
1690 function yatra_build_current_request_paged_url(int $page_num): string
1691 {
1692 $page_num = max(1, $page_num);
1693 $params = !empty($_GET) && is_array($_GET) ? wp_unslash($_GET) : [];
1694
1695 if ($page_num > 1) {
1696 $params['paged'] = (string) $page_num;
1697 } else {
1698 unset($params['paged'], $params['page']);
1699 }
1700
1701 $path = yatra_get_current_request_path_for_query_urls();
1702 $query = http_build_query($params);
1703
1704 return esc_url($path . ($query !== '' ? '?' . $query : ''));
1705 }
1706
1707 /**
1708 * Same request path with trip sort (TripRepository / TripListingService). Resets pagination.
1709 *
1710 * @param string $sort Allowed: '' (recommended), most_popular, price_low, price_high, rating_high, duration_short, duration_long.
1711 */
1712 function yatra_build_current_request_sort_url(string $sort): string
1713 {
1714 $allowed = ['', 'most_popular', 'price_low', 'price_high', 'rating_high', 'duration_short', 'duration_long'];
1715 if (!in_array($sort, $allowed, true)) {
1716 $sort = '';
1717 }
1718
1719 $params = !empty($_GET) && is_array($_GET) ? wp_unslash($_GET) : [];
1720 unset($params['paged'], $params['page']);
1721 if ($sort !== '') {
1722 $params['sort'] = $sort;
1723 } else {
1724 unset($params['sort']);
1725 }
1726
1727 $path = yatra_get_current_request_path_for_query_urls();
1728 $query = http_build_query($params);
1729
1730 return esc_url($path . ($query !== '' ? '?' . $query : ''));
1731 }
1732
1733 /**
1734 * Compare two archive listing rows (activity, destination, or category) by sort key.
1735 */
1736 function yatra_compare_archive_listing_row_pair(object $a, object $b, string $sort): int
1737 {
1738 $nameA = isset($a->name) ? strtolower((string) $a->name) : '';
1739 $nameB = isset($b->name) ? strtolower((string) $b->name) : '';
1740 $tripsA = isset($a->trips_count) ? (int) $a->trips_count : 0;
1741 $tripsB = isset($b->trips_count) ? (int) $b->trips_count : 0;
1742 $ratingA = isset($a->avg_rating) ? (float) $a->avg_rating : 0.0;
1743 $ratingB = isset($b->avg_rating) ? (float) $b->avg_rating : 0.0;
1744
1745 switch ($sort) {
1746 case 'trips_desc':
1747 return $tripsB <=> $tripsA;
1748 case 'trips_asc':
1749 return $tripsA <=> $tripsB;
1750 case 'name_asc':
1751 return $nameA <=> $nameB;
1752 case 'name_desc':
1753 return $nameB <=> $nameA;
1754 case 'rating_desc':
1755 default:
1756 $cmp = $ratingB <=> $ratingA;
1757 if (0 === $cmp) {
1758 return $tripsB <=> $tripsA;
1759 }
1760
1761 return $cmp;
1762 }
1763 }
1764
1765 /**
1766 * Invokable comparator for {@see yatra_sort_archive_listing_stats_rows()}.
1767 *
1768 * @internal
1769 */
1770 final class Yatra_Archive_Listing_Stats_Comparator
1771 {
1772 /** @var string */
1773 private $sort;
1774
1775 public function __construct(string $sort)
1776 {
1777 $this->sort = $sort;
1778 }
1779
1780 /**
1781 * @param object $a
1782 * @param object $b
1783 */
1784 public function __invoke($a, $b): int
1785 {
1786 return yatra_compare_archive_listing_row_pair($a, $b, $this->sort);
1787 }
1788 }
1789
1790 /**
1791 * Sort archive listing rows in place (stats objects from repository).
1792 */
1793 function yatra_sort_archive_listing_stats_rows(array &$items, string $sort): void
1794 {
1795 if (empty($items)) {
1796 return;
1797 }
1798
1799 usort($items, new Yatra_Archive_Listing_Stats_Comparator($sort));
1800 }
1801
1802 /**
1803 * Sort dropdown URL: same archive, page reset to 1, yatra_sort applied (preserves yatra_page etc.).
1804 */
1805 function yatra_build_archive_listing_sort_url(string $yatra_sort): string
1806 {
1807 $params = !empty($_GET) && is_array($_GET) ? wp_unslash($_GET) : [];
1808 unset($params['paged'], $params['page']);
1809 if (!empty($params['yatra_page']) || isset($params['yatra_trip'])) {
1810 unset($params['page']);
1811 }
1812 $params['yatra_sort'] = $yatra_sort;
1813
1814 $path = yatra_get_current_request_path_for_query_urls();
1815 $query = http_build_query($params);
1816
1817 return esc_url($path . ($query !== '' ? '?' . $query : ''));
1818 }
1819
1820 /**
1821 * ============================================
1822 * PERMALINK HELPERS
1823 * ============================================
1824 */
1825
1826 /**
1827 * Get destination permalink
1828 *
1829 * @param object|int $destination Destination object with slug property, or destination ID
1830 * @return string Destination permalink URL
1831 */
1832 function yatra_get_destination_permalink($destination): string
1833 {
1834 $original = $destination;
1835
1836 if (is_numeric($destination)) {
1837 global $wpdb;
1838 $table = ClassificationsTable::getTableName();
1839 $destination = $wpdb->get_row($wpdb->prepare(
1840 "SELECT slug FROM {$table} WHERE id = %d AND type = %s",
1841 (int) $destination,
1842 ClassificationTypes::DESTINATION
1843 ));
1844 }
1845
1846 $slug = is_object($destination) ? ($destination->slug ?? '') : '';
1847
1848 if (empty($slug)) {
1849 return '';
1850 }
1851
1852 $base = SettingsService::getDestinationBase();
1853 $permalink_structure = get_option('permalink_structure');
1854 $is_plain = empty($permalink_structure);
1855
1856 if ($is_plain) {
1857 $key = preg_replace('/[^a-z0-9_-]/i', '', $base) ?: 'destination';
1858
1859 $url = add_query_arg([$key => $slug], home_url('/'));
1860 } else {
1861 $url = home_url('/' . $base . '/' . $slug . '/');
1862 }
1863
1864 /** @var string $url Override full destination URL or path (plain/pretty handled above). Third arg: slug. */
1865 return (string) apply_filters('yatra_destination_permalink', $url, $original, $slug);
1866 }
1867
1868 /**
1869 * Get activity permalink
1870 *
1871 * @param object|int $activity Activity object with slug property, or activity ID
1872 * @return string Activity permalink URL
1873 */
1874 function yatra_get_activity_permalink($activity): string
1875 {
1876 $original = $activity;
1877
1878 if (is_numeric($activity)) {
1879 global $wpdb;
1880 $table = ClassificationsTable::getTableName();
1881 $activity = $wpdb->get_row($wpdb->prepare(
1882 "SELECT slug FROM {$table} WHERE id = %d AND type = %s",
1883 (int) $activity,
1884 ClassificationTypes::ACTIVITY
1885 ));
1886 }
1887
1888 $slug = is_object($activity) ? ($activity->slug ?? '') : '';
1889
1890 if (empty($slug)) {
1891 return '';
1892 }
1893
1894 $base = SettingsService::getActivityBase();
1895 $permalink_structure = get_option('permalink_structure');
1896 $is_plain = empty($permalink_structure);
1897
1898 if ($is_plain) {
1899 $key = preg_replace('/[^a-z0-9_-]/i', '', $base) ?: 'activity';
1900
1901 $url = add_query_arg([$key => $slug], home_url('/'));
1902 } else {
1903 $url = home_url('/' . $base . '/' . $slug . '/');
1904 }
1905
1906 /** @var string $url Override full activity URL. Third arg: slug. */
1907 return (string) apply_filters('yatra_activity_permalink', $url, $original, $slug);
1908 }
1909
1910 /**
1911 * Get trip category permalink
1912 *
1913 * @param object|int $category Category object with slug property, or category ID
1914 * @return string Category permalink URL
1915 */
1916 function yatra_get_category_permalink($category): string
1917 {
1918 $original = $category;
1919
1920 if (is_numeric($category)) {
1921 global $wpdb;
1922 $table = ClassificationsTable::getTableName();
1923 $category = $wpdb->get_row($wpdb->prepare(
1924 "SELECT slug FROM {$table} WHERE id = %d AND type = %s",
1925 (int) $category,
1926 ClassificationTypes::CATEGORY
1927 ));
1928 }
1929
1930 $slug = is_object($category) ? ($category->slug ?? '') : '';
1931
1932 if (empty($slug)) {
1933 return '';
1934 }
1935
1936 $base = SettingsService::getTripCategoryBase();
1937 $permalink_structure = get_option('permalink_structure');
1938 $is_plain = empty($permalink_structure);
1939
1940 if ($is_plain) {
1941 $key = preg_replace('/[^a-z0-9_-]/i', '', $base) ?: 'trip-category';
1942
1943 $url = add_query_arg([$key => $slug], home_url('/'));
1944 } else {
1945 $url = home_url('/' . $base . '/' . $slug . '/');
1946 }
1947
1948 /** @var string $url Override full trip-category URL. Third arg: slug. */
1949 return (string) apply_filters('yatra_category_permalink', $url, $original, $slug);
1950 }
1951
1952 /**
1953 * Get trip permalink
1954 *
1955 * @param object|int $trip Trip object with slug property, or trip ID
1956 * @return string Trip permalink URL
1957 */
1958 function yatra_get_trip_permalink($trip): string
1959 {
1960 $original = $trip;
1961
1962 if (is_numeric($trip)) {
1963 global $wpdb;
1964 $table = TripsTable::getTableName();
1965 $trip = $wpdb->get_row($wpdb->prepare(
1966 "SELECT slug FROM {$table} WHERE id = %d",
1967 (int) $trip
1968 ));
1969 }
1970
1971 $slug = is_object($trip) ? ($trip->slug ?? '') : '';
1972
1973 if (empty($slug)) {
1974 return '';
1975 }
1976
1977 $base = SettingsService::getTripBase();
1978 $permalink_structure = get_option('permalink_structure');
1979 $is_plain = empty($permalink_structure);
1980
1981 if ($is_plain) {
1982 $key = preg_replace('/[^a-z0-9_-]/i', '', $base) ?: 'trip';
1983
1984 $url = add_query_arg([$key => $slug], home_url('/'));
1985 } else {
1986 $url = home_url('/' . $base . '/' . $slug . '/');
1987 }
1988
1989 /** @var string $url Override full trip URL. Third arg: slug. */
1990 return (string) apply_filters('yatra_trip_permalink', $url, $original, $slug);
1991 }
1992
1993 /**
1994 * Canonical URL for the trip archive / filter listing (respects Settings trip base).
1995 * Plain permalinks use ?yatra_page={base}; pretty permalinks use /{base}/.
1996 */
1997 function yatra_get_trip_listing_url(): string
1998 {
1999 $base = SettingsService::getTripBase();
2000 $base = preg_replace('/[^a-zA-Z0-9_-]/', '', (string) $base) ?: 'trip';
2001 $permalink_structure = (string) get_option('permalink_structure', '');
2002
2003 if ($permalink_structure === '') {
2004 $url = esc_url(add_query_arg('yatra_page', $base, home_url('/')));
2005 } else {
2006 $url = trailingslashit(home_url('/' . $base . '/'));
2007 }
2008
2009 return (string) apply_filters('yatra_trip_listing_url', $url, $base);
2010 }
2011
2012 /**
2013 * Canonical URL for browse-all taxonomy listings (destinations, activities, trip categories).
2014 * Plain permalinks use ?yatra_page={base}; pretty permalinks use /{base}/.
2015 *
2016 * @param string $listing_type One of: destination, activity, category
2017 */
2018 function yatra_get_taxonomy_listing_url(string $listing_type): string
2019 {
2020 $map = [
2021 'destination' => SettingsService::getDestinationBase(),
2022 'activity' => SettingsService::getActivityBase(),
2023 'category' => SettingsService::getTripCategoryBase(),
2024 ];
2025 $base = $map[$listing_type] ?? '';
2026 $base = preg_replace('/[^a-zA-Z0-9_-]/', '', (string) $base) ?: 'destination';
2027 $permalink_structure = (string) get_option('permalink_structure', '');
2028
2029 if ($permalink_structure === '') {
2030 $url = esc_url(add_query_arg('yatra_page', $base, home_url('/')));
2031 } else {
2032 $url = trailingslashit(home_url('/' . $base . '/'));
2033 }
2034
2035 return (string) apply_filters('yatra_taxonomy_listing_url', $url, $listing_type, $base);
2036 }
2037
2038 /**
2039 * Decode trips.price_types for listing-card logic (DB may store JSON string or array).
2040 *
2041 * @return array<int, array<string, mixed>>
2042 */
2043 function yatra_trip_listing_decode_price_types(object $trip): array
2044 {
2045 $pts = $trip->price_types ?? null;
2046 if (is_string($pts) && $pts !== '') {
2047 $decoded = json_decode($pts, true);
2048 $pts = is_array($decoded) ? $decoded : [];
2049 } elseif (!is_array($pts)) {
2050 $pts = [];
2051 }
2052 if ($pts === [] && method_exists($trip, 'getPriceTypes')) {
2053 $got = $trip->getPriceTypes();
2054 $pts = is_array($got) ? $got : [];
2055 }
2056
2057 return $pts;
2058 }
2059
2060 /**
2061 * Lowercase keys for traveler tier labels (used to strip mis-tagged classifications).
2062 *
2063 * @return array<string, true>
2064 */
2065 function yatra_trip_listing_traveler_tier_label_keys(object $trip): array
2066 {
2067 if (($trip->pricing_type ?? '') !== 'traveler_based') {
2068 return [];
2069 }
2070 $keys = [];
2071 foreach (yatra_trip_listing_decode_price_types($trip) as $pt) {
2072 if (!is_array($pt)) {
2073 continue;
2074 }
2075 foreach (['label', 'category_label', 'title'] as $k) {
2076 if (!empty($pt[$k]) && is_string($pt[$k])) {
2077 $t = strtolower(trim($pt[$k]));
2078 if ($t !== '') {
2079 $keys[$t] = true;
2080 }
2081 break;
2082 }
2083 }
2084 }
2085
2086 return $keys;
2087 }
2088
2089 /**
2090 * Ordered unique labels for the listing card “Traveler types” row.
2091 *
2092 * @return list<string>
2093 */
2094 function yatra_trip_listing_traveler_type_labels_for_card(object $trip): array
2095 {
2096 if (($trip->pricing_type ?? '') !== 'traveler_based') {
2097 return [];
2098 }
2099 $labels = [];
2100 $seen = [];
2101 foreach (yatra_trip_listing_decode_price_types($trip) as $pt) {
2102 if (!is_array($pt)) {
2103 continue;
2104 }
2105 foreach (['label', 'category_label', 'title'] as $k) {
2106 if (!empty($pt[$k]) && is_string($pt[$k])) {
2107 $lab = trim($pt[$k]);
2108 if ($lab === '') {
2109 break;
2110 }
2111 $lk = strtolower($lab);
2112 if (!isset($seen[$lk])) {
2113 $seen[$lk] = true;
2114 $labels[] = $lab;
2115 }
2116 break;
2117 }
2118 }
2119 }
2120
2121 return $labels;
2122 }
2123
2124 /**
2125 * Format start → end for listing cards; avoids repeating the same country when both
2126 * strings are "City, Country".
2127 */
2128 function yatra_format_trip_listing_route_line(string $start, string $end): string
2129 {
2130 $start = trim($start);
2131 $end = trim($end);
2132 if ($start === '') {
2133 return $end;
2134 }
2135 if ($end === '') {
2136 return $start;
2137 }
2138 if (strcasecmp($start, $end) === 0) {
2139 return $start;
2140 }
2141 if (strpos($start, ',') !== false && strpos($end, ',') !== false) {
2142 $s_parts = array_map('trim', explode(',', $start, 2));
2143 $e_parts = array_map('trim', explode(',', $end, 2));
2144 if (count($s_parts) === 2 && count($e_parts) === 2
2145 && strcasecmp($s_parts[1], $e_parts[1]) === 0) {
2146 return $s_parts[0] . ' → ' . $e_parts[0] . ', ' . $s_parts[1];
2147 }
2148 }
2149
2150 return $start . ' → ' . $end;
2151 }
2152
2153 /**
2154 * Human label for trip_type column (listing card meta).
2155 */
2156 function yatra_trip_listing_trip_type_label(?string $trip_type): string
2157 {
2158 $t = (string) $trip_type;
2159 $map = [
2160 'single_day' => __('Single day', 'yatra'),
2161 'multi_day' => __('Multi-day', 'yatra'),
2162 'flexible' => __('Flexible', 'yatra'),
2163 ];
2164
2165 return $map[$t] ?? '';
2166 }
2167
2168 /**
2169 * Rating block for listing cards: prefers SQL aggregates (average_rating, review_count)
2170 * when the hydrated reviews array is empty.
2171 *
2172 * @param array{has_rating: bool, average_rating: float, review_count: int, formatted_rating: string} $from_reviews
2173 * @return array{has_rating: bool, average_rating: float, review_count: int, formatted_rating: string}
2174 */
2175 function yatra_trip_listing_card_rating_data(object $trip, array $from_reviews): array
2176 {
2177 $has = !empty($from_reviews['has_rating']);
2178 $avg = (float) ($from_reviews['average_rating'] ?? 0);
2179 $cnt = (int) ($from_reviews['review_count'] ?? 0);
2180 $fmt = (string) ($from_reviews['formatted_rating'] ?? '0.0');
2181
2182 if ($cnt === 0 || !$has || $avg <= 0) {
2183 $q_avg = isset($trip->average_rating) ? (float) $trip->average_rating : null;
2184 $q_cnt = isset($trip->review_count) ? (int) $trip->review_count : null;
2185 if (($q_cnt === null || $q_cnt === 0) && isset($trip->reviews_count)) {
2186 $q_cnt = (int) $trip->reviews_count;
2187 }
2188 if ($q_cnt !== null && $q_cnt > 0 && $q_avg !== null && $q_avg > 0) {
2189 $avg = round($q_avg, 1);
2190 $cnt = $q_cnt;
2191 $fmt = number_format($avg, 1);
2192 $has = true;
2193 }
2194 }
2195
2196 return [
2197 'has_rating' => $has && $avg > 0 && $cnt > 0,
2198 'average_rating' => $avg,
2199 'review_count' => $cnt,
2200 'formatted_rating' => $fmt,
2201 ];
2202 }
2203
2204 /**
2205 * Avoid repeating the same classification label in the destination, activity, and category
2206 * rows on listing cards (traveler tier labels wrongly linked as classifications, or same
2207 * term attached in multiple roles).
2208 *
2209 * @param array<int, object> $destinations
2210 * @param array<int, object> $activities
2211 * @param array<int, object> $categories
2212 * @return array{0: array<int, object>, 1: array<int, object>, 2: array<int, object>}
2213 */
2214 function yatra_trip_listing_filter_classification_duplicates(array $destinations, array $activities, array $categories, object $trip): array
2215 {
2216 $tier_keys = yatra_trip_listing_traveler_tier_label_keys($trip);
2217
2218 $strip_tiers = static function (array $items) use ($tier_keys): array {
2219 if ($tier_keys === []) {
2220 return $items;
2221 }
2222
2223 return array_values(array_filter($items, static function ($item) use ($tier_keys) {
2224 $n = strtolower(trim((string) ($item->name ?? '')));
2225
2226 return $n === '' || !isset($tier_keys[$n]);
2227 }));
2228 };
2229
2230 $destinations = $strip_tiers($destinations);
2231 $activities = $strip_tiers($activities);
2232 $categories = $strip_tiers($categories);
2233
2234 $seen = [];
2235 $dedupe = static function (array $items) use (&$seen): array {
2236 $out = [];
2237 foreach ($items as $item) {
2238 $n = strtolower(trim((string) ($item->name ?? '')));
2239 if ($n === '') {
2240 $out[] = $item;
2241 continue;
2242 }
2243 if (isset($seen[$n])) {
2244 continue;
2245 }
2246 $seen[$n] = true;
2247 $out[] = $item;
2248 }
2249
2250 return $out;
2251 };
2252
2253 $destinations = $dedupe($destinations);
2254 $activities = $dedupe($activities);
2255 $categories = $dedupe($categories);
2256
2257 return [$destinations, $activities, $categories];
2258 }
2259
2260 /**
2261 * Check if we're on a trip listing page
2262 *
2263 * @return bool True if on a trip listing page
2264 */
2265 function yatra_is_trip_listing(): bool
2266 {
2267 global $yatra_trip_list;
2268
2269 // Check for trip list context (base trip listing page)
2270 if (!empty($yatra_trip_list)) {
2271 return true;
2272 }
2273
2274 // Check if we're on the main trips listing page
2275 $trip_base = SettingsService::getTripBase();
2276 $request_uri = $_SERVER['REQUEST_URI'] ?? '';
2277 $parsed_url = parse_url($request_uri, PHP_URL_PATH);
2278
2279 if ($parsed_url && strpos($parsed_url, '/' . $trip_base) === 0) {
2280 $path_parts = array_values(array_filter(explode('/', trim($parsed_url, '/'))));
2281 if ($path_parts === [] || ($path_parts[0] ?? '') !== $trip_base) {
2282 return false;
2283 }
2284 // /trip/ or /trip/page/2/ (WordPress paged archives)
2285 if (count($path_parts) === 1) {
2286 return true;
2287 }
2288 if (count($path_parts) === 3 && ($path_parts[1] ?? '') === 'page' && ctype_digit((string) ($path_parts[2] ?? ''))) {
2289 return true;
2290 }
2291 }
2292
2293 return false;
2294 }
2295
2296 /**
2297 * Check if we're on a taxonomy page (destination, activity, category)
2298 *
2299 * @return bool True if on a taxonomy page
2300 */
2301 function yatra_is_taxonomy_page(): bool
2302 {
2303 global $yatra_taxonomy_data;
2304 return !empty($yatra_taxonomy_data);
2305 }
2306
2307 /**
2308 * Check if we're on an activity listing page
2309 *
2310 * @return bool True if on an activity listing page
2311 */
2312 function yatra_is_activity_listing(): bool
2313 {
2314 return isset($_GET['yatra_page_type']) && $_GET['yatra_page_type'] === 'activities';
2315 }
2316
2317 /**
2318 * Check if we're on a destination listing page
2319 *
2320 * @return bool True if on a destination listing page
2321 */
2322 function yatra_is_destination_listing(): bool
2323 {
2324 return isset($_GET['yatra_page_type']) && $_GET['yatra_page_type'] === 'destinations';
2325 }
2326
2327 /**
2328 * Check if we're on an account page
2329 *
2330 * @return bool True if on an account page
2331 */
2332 function yatra_is_account_page(): bool
2333 {
2334 if (!empty($GLOBALS['yatra_loading_react_account_page'])) {
2335 return true;
2336 }
2337
2338 if ((string) get_query_var('yatra_account_page') !== '') {
2339 return true;
2340 }
2341
2342 global $post;
2343 if ($post && function_exists('has_shortcode') && isset($post->post_content)
2344 && has_shortcode((string) $post->post_content, 'yatra_my_account')) {
2345 return true;
2346 }
2347
2348 if (!$post) {
2349 return false;
2350 }
2351
2352 $accountPageId = get_option('yatra_my_account_page');
2353 return $accountPageId && (int) $post->ID === (int) $accountPageId;
2354 }
2355
2356 /**
2357 * Get difficulty level permalink
2358 *
2359 * @param object|int $difficulty Difficulty object with slug property, or difficulty ID
2360 * @return string Difficulty permalink URL
2361 */
2362 function yatra_get_difficulty_permalink($difficulty): string
2363 {
2364 if (is_numeric($difficulty)) {
2365 global $wpdb;
2366 $table = ClassificationsTable::getTableName();
2367 $difficulty = $wpdb->get_row($wpdb->prepare(
2368 "SELECT slug FROM {$table} WHERE id = %d AND type = %s",
2369 (int) $difficulty,
2370 ClassificationTypes::DIFFICULTY
2371 ));
2372 }
2373
2374 $slug = is_object($difficulty) ? ($difficulty->slug ?? '') : '';
2375
2376 if (empty($slug)) {
2377 return '';
2378 }
2379
2380 $base = SettingsService::getString('difficulty_base', 'difficulty');
2381
2382 return home_url('/' . $base . '/' . $slug . '/');
2383 }
2384
2385 /**
2386 * Load a template file with theme override support
2387 *
2388 * This function allows themes to override plugin templates by placing them in:
2389 * theme/yatra/template-name.php
2390 *
2391 * If no theme override exists, loads from plugin templates directory.
2392 *
2393 * @param string $template_name Template file name (without .php extension)
2394 * @param array $args Arguments to extract and make available in template
2395 * @param string $template_path Template path within plugin (default: 'templates/')
2396 * @param array $data Alternative data array (won't be extracted, available as $data)
2397 * @return void
2398 */
2399 function yatra_get_template(string $template_name, array $args = [], string $template_path = 'templates/', array $data = []): void
2400 {
2401 $template_name = ltrim($template_name, '/');
2402
2403 // Check if theme has override
2404 $theme_template = locate_template([
2405 'yatra/' . $template_name . '.php',
2406 'yatra/' . $template_name
2407 ]);
2408
2409 if ($theme_template) {
2410 // Load from theme
2411 $template_file = $theme_template;
2412 } else {
2413 // Load from plugin
2414 $template_file = YATRA_PLUGIN_PATH . ltrim($template_path, '/') . '/' . $template_name . '.php';
2415 }
2416
2417 // Extract arguments to make them available as individual variables
2418 if (!empty($args)) {
2419 extract($args);
2420 }
2421
2422 // Make data available as $data array (not extracted)
2423 if (!empty($data)) {
2424 $data = $data;
2425 }
2426
2427 // Include the template
2428 if (file_exists($template_file)) {
2429 include $template_file;
2430 }
2431 }
2432
2433 /**
2434 * Enqueue single trip scripts and styles
2435 *
2436 * @return void
2437 */
2438 function yatra_enqueue_single_trip_scripts(): void
2439 {
2440 // Only enqueue on single trip pages
2441 if (!is_single() || get_post_type() !== 'trip') {
2442 return;
2443 }
2444
2445 // Enqueue the single trip JavaScript
2446 wp_enqueue_script(
2447 'yatra-single-trip',
2448 YATRA_PLUGIN_URL . 'assets/js/single-trip.js',
2449 ['jquery', 'yatra-trip'],
2450 YATRA_VERSION,
2451 true
2452 );
2453
2454 // Localize script data
2455 global $trip;
2456 if ($trip) {
2457 wp_localize_script(
2458 'yatra-single-trip',
2459 'yatraSingleTripData',
2460 [
2461 'tripId' => (int) $trip->id,
2462 'basePrice' => (float) ($trip->base_price ?? 0),
2463 'currencySymbol' => yatra_get_currency_symbol(\Yatra\Services\SettingsService::getCurrency()),
2464 'apiUrls' => [
2465 'groupDiscounts' => rest_url('yatra/v1/discounts/group-discounts')
2466 ]
2467 ]
2468 );
2469 }
2470 }
2471
2472 /**
2473 * Calculate base price for single trip display using CalculationService
2474 *
2475 * @param object $trip Trip object
2476 * @return array Pricing data including base_price, has_availability, has_traveler_pricing, pricing_type
2477 */
2478 function yatra_single_trip_calculate_base_price($trip) {
2479 // Check if availability dates exist (PRIORITY)
2480 $has_availability = !empty($trip->availability_dates) && is_array($trip->availability_dates) && count($trip->availability_dates) > 0;
2481
2482 // Determine pricing type from trip settings
2483 $pricing_type = $trip->pricing_type ?? 'regular';
2484 $has_traveler_pricing = ($pricing_type === 'traveler_based' && !empty($trip->price_types));
2485
2486 // Use CalculationService for consistent pricing
2487 $calculationService = new \Yatra\Services\CalculationService();
2488
2489 // Determine base price using CalculationService logic
2490 $trip_price = 0;
2491
2492 if ($has_availability) {
2493 // Page-load pricing priority (traveler-based):
2494 // - If a default category is marked at trip-level, use that as the base price.
2495 // - Otherwise fall back to lowest price across availability (legacy behavior).
2496 $default_trip_price = 0.0;
2497 if ($has_traveler_pricing && !empty($trip->price_types) && is_array($trip->price_types)) {
2498 $default_price_type = null;
2499 foreach ($trip->price_types as $pt) {
2500 if (is_array($pt)) {
2501 $pt = (object) $pt;
2502 }
2503 if (!empty($pt->is_default)) {
2504 $default_price_type = $pt;
2505 break;
2506 }
2507 }
2508 if ($default_price_type) {
2509 $default_trip_price = (float) ($default_price_type->effective_price
2510 ?? $default_price_type->discounted_price
2511 ?? $default_price_type->original_price
2512 ?? 0);
2513 }
2514 }
2515
2516 if ($default_trip_price > 0) {
2517 $trip_price = $default_trip_price;
2518 } else {
2519 // Get the lowest price from availability dates
2520 $min_price = PHP_FLOAT_MAX;
2521 foreach ($trip->availability_dates as $avail) {
2522 $avail_price = $avail->effective_price ?? $avail->original_price ?? 0;
2523 if ($avail_price > 0 && $avail_price < $min_price) {
2524 $min_price = $avail_price;
2525 }
2526
2527 // Also check price_types within availability if traveler-based
2528 if (!empty($avail->price_types) && is_array($avail->price_types)) {
2529 foreach ($avail->price_types as $pt) {
2530 $pt = (object)$pt;
2531 $pt_price = (float)($pt->effective_price ?? $pt->discounted_price ?? $pt->original_price ?? 0);
2532 if ($pt_price > 0 && $pt_price < $min_price) {
2533 $min_price = $pt_price;
2534 }
2535 }
2536 }
2537 }
2538
2539 // If no price found from availability, check traveler-based pricing
2540 if ($min_price >= PHP_FLOAT_MAX && $has_traveler_pricing) {
2541 foreach ($trip->price_types as $pt) {
2542 $pt = is_array($pt) ? (object) $pt : $pt;
2543 $pt_price = (float)($pt->effective_price ?? $pt->discounted_price ?? $pt->original_price ?? 0);
2544 if ($pt_price > 0 && $pt_price < $min_price) {
2545 $min_price = $pt_price;
2546 }
2547 }
2548 }
2549
2550 $trip_price = ($min_price < PHP_FLOAT_MAX) ? $min_price : ($trip->sale_price ?: $trip->original_price);
2551 }
2552 } elseif ($has_traveler_pricing) {
2553 // Get default or first traveler category price
2554 $default_price_type = null;
2555 foreach ($trip->price_types as $pt) {
2556 if (!empty($pt->is_default)) {
2557 $default_price_type = $pt;
2558 break;
2559 }
2560 }
2561 if (!$default_price_type && !empty($trip->price_types)) {
2562 $default_price_type = $trip->price_types[0];
2563 }
2564
2565 // Get the price from the price type - check multiple possible fields
2566 if ($default_price_type) {
2567 $trip_price = 0;
2568 // Try effective_price first, then discounted_price, then original_price
2569 if (!empty($default_price_type->effective_price) && $default_price_type->effective_price > 0) {
2570 $trip_price = (float)$default_price_type->effective_price;
2571 } elseif (!empty($default_price_type->discounted_price) && $default_price_type->discounted_price > 0) {
2572 $trip_price = (float)$default_price_type->discounted_price;
2573 } elseif (!empty($default_price_type->original_price) && $default_price_type->original_price > 0) {
2574 $trip_price = (float)$default_price_type->original_price;
2575 } elseif (!empty($default_price_type->sale_price) && $default_price_type->sale_price > 0) {
2576 $trip_price = (float)$default_price_type->sale_price;
2577 }
2578
2579 // If still no price, try to get the minimum from all price types
2580 if ($trip_price <= 0) {
2581 foreach ($trip->price_types as $pt) {
2582 $pt_price = (float)($pt->effective_price ?? $pt->discounted_price ?? $pt->original_price ?? 0);
2583 if ($pt_price > 0 && ($trip_price <= 0 || $pt_price < $trip_price)) {
2584 $trip_price = $pt_price;
2585 }
2586 }
2587 }
2588 } else {
2589 $trip_price = $trip->sale_price ?: $trip->original_price;
2590 }
2591 } else {
2592 // Regular pricing
2593 $trip_price = $trip->sale_price > 0 ? $trip->sale_price : $trip->original_price;
2594 }
2595
2596 // Apply CalculationService filter for dynamic pricing (pro plugins)
2597 $base_price = apply_filters('yatra_calculate_base_amount', $trip_price, [
2598 'trip_price' => $trip_price,
2599 'travelers_count' => 1,
2600 'traveler_counts' => ['default' => 1],
2601 'pricing_type' => $pricing_type,
2602 'price_types' => $trip->price_types ?? [],
2603 'trip_id' => $trip->id ?? 0
2604 ]);
2605
2606 return [
2607 'base_price' => $base_price,
2608 'has_availability' => $has_availability,
2609 'has_traveler_pricing' => $has_traveler_pricing,
2610 'pricing_type' => $pricing_type
2611 ];
2612 }
2613
2614 /**
2615 * Get group discounts data for single trip
2616 *
2617 * @param int $trip_id Trip ID
2618 * @return array Group discounts data including has_group_discounts and group_discounts_data
2619 */
2620 function yatra_single_trip_get_group_discounts($trip_id) {
2621 $has_group_discounts = false;
2622 $group_discounts_data = [];
2623 $trip_id = (int) $trip_id;
2624
2625 if ($trip_id <= 0) {
2626 return [
2627 'has_group_discounts' => false,
2628 'group_discounts_data' => [],
2629 ];
2630 }
2631
2632 try {
2633 // Direct controller path avoids rest_do_request / loopback issues on single-trip templates.
2634 if (class_exists(\Yatra\Controllers\DiscountController::class)) {
2635 $ctrl = new \Yatra\Controllers\DiscountController();
2636 $payload = $ctrl->getPublicGroupDiscountDiscoverabilityForTrip($trip_id);
2637 $discounts = isset($payload['discounts']) && is_array($payload['discounts']) ? $payload['discounts'] : [];
2638 if (!empty($payload['has_group_discounts']) && $discounts !== []) {
2639 return [
2640 'has_group_discounts' => true,
2641 'group_discounts_data' => $discounts,
2642 ];
2643 }
2644 }
2645
2646 $row = null;
2647
2648 // Fallback: internal REST then HTTP (e.g. if controller unavailable).
2649 if (class_exists('\WP_REST_Request') && function_exists('rest_do_request')) {
2650 $request = new \WP_REST_Request('GET', '/yatra/v1/discounts/group-discounts');
2651 $request->set_param('trip_ids', [$trip_id]);
2652 $rest_response = rest_do_request($request);
2653 if ($rest_response instanceof \WP_REST_Response && $rest_response->get_status() === 200) {
2654 $row = yatra_single_trip_parse_group_discounts_payload($rest_response->get_data(), $trip_id);
2655 }
2656 }
2657
2658 if (!is_array($row)) {
2659 $api_url = add_query_arg(
2660 ['trip_ids' => [$trip_id]],
2661 rest_url('yatra/v1/discounts/group-discounts')
2662 );
2663 $response = wp_remote_get($api_url, [
2664 'timeout' => 6,
2665 'headers' => [
2666 'Accept' => 'application/json',
2667 ],
2668 ]);
2669
2670 if (!is_wp_error($response) && wp_remote_retrieve_response_code($response) === 200) {
2671 $data = json_decode(wp_remote_retrieve_body($response), true);
2672 $row = yatra_single_trip_parse_group_discounts_payload($data, $trip_id);
2673 }
2674 }
2675
2676 if (is_array($row) && !empty($row['has_group_discounts']) && !empty($row['discounts']) && is_array($row['discounts'])) {
2677 $has_group_discounts = true;
2678 $group_discounts_data = $row['discounts'];
2679 }
2680 } catch (Exception $e) {
2681 $has_group_discounts = false;
2682 }
2683
2684 return [
2685 'has_group_discounts' => $has_group_discounts,
2686 'group_discounts_data' => $group_discounts_data,
2687 ];
2688 }
2689
2690 /**
2691 * Extract the per-trip object from a group-discounts REST payload (handles optional wrappers).
2692 *
2693 * @param mixed $data
2694 * @return array<string, mixed>|null
2695 */
2696 function yatra_single_trip_parse_group_discounts_payload($data, int $trip_id): ?array {
2697 if (!is_array($data)) {
2698 return null;
2699 }
2700 if (isset($data['data']) && is_array($data['data'])) {
2701 $data = $data['data'];
2702 }
2703 $keyStr = (string) $trip_id;
2704 $row = $data[$trip_id] ?? $data[$keyStr] ?? null;
2705
2706 return is_array($row) ? $row : null;
2707 }
2708
2709 /**
2710 * Payload for single-trip booking UI JS (sidebar date/traveler pricing + group tiers).
2711 * Kept in yatraTripData instead of large HTML data-* attributes on .yatra-booking-card.
2712 *
2713 * @param object $trip Trip model
2714 * @return array{pricingType: string, sidebarAvailability: array<int, array<string, mixed>>, sidebarGroupDiscounts: array<int, array<string, mixed>>}
2715 */
2716 function yatra_single_trip_get_client_booking_payload($trip): array {
2717 $empty = [
2718 'pricingType' => 'regular',
2719 'sidebarAvailability' => [],
2720 'sidebarGroupDiscounts' => [],
2721 ];
2722
2723 if (!is_object($trip) || empty($trip->id)) {
2724 return $empty;
2725 }
2726
2727 $pricing_data = function_exists('yatra_single_trip_calculate_base_price')
2728 ? yatra_single_trip_calculate_base_price($trip)
2729 : ['has_availability' => false, 'pricing_type' => $trip->pricing_type ?? 'regular'];
2730
2731 $pricing_type = (string) ($pricing_data['pricing_type'] ?? ($trip->pricing_type ?? 'regular'));
2732 $has_availability = !empty($pricing_data['has_availability']);
2733
2734 $availability = [];
2735 if ($has_availability && method_exists($trip, 'getAvailabilityDates')) {
2736 foreach ($trip->getAvailabilityDates() as $avail) {
2737 if (!is_object($avail)) {
2738 continue;
2739 }
2740 $price_types_raw = !empty($avail->price_types) && is_array($avail->price_types) ? $avail->price_types : [];
2741 $price_types = [];
2742 foreach ($price_types_raw as $pt) {
2743 if (is_object($pt)) {
2744 $decoded = json_decode(wp_json_encode($pt), true);
2745 $price_types[] = is_array($decoded) ? $decoded : [];
2746 } elseif (is_array($pt)) {
2747 $price_types[] = $pt;
2748 }
2749 }
2750
2751 $availability[] = [
2752 'id' => (int) ($avail->id ?? 0),
2753 'date' => $avail->departure_date ?? '',
2754 'departure_date' => $avail->departure_date ?? '',
2755 'return_date' => (isset($avail->return_date) && $avail->return_date !== '')
2756 ? $avail->return_date
2757 : (isset($avail->arrival_date) ? $avail->arrival_date : null),
2758 'price' => $avail->effective_price ?? $avail->original_price ?? 0,
2759 'original_price' => $avail->original_price ?? 0,
2760 'discounted_price' => $avail->discounted_price ?? null,
2761 'seats_available' => $avail->seats_available ?? 0,
2762 'seats_total' => $avail->seats_total ?? 0,
2763 'status' => $avail->status ?? '',
2764 'is_limited' => (bool) ($avail->is_limited ?? false),
2765 'is_sold_out' => (bool) ($avail->is_sold_out ?? false),
2766 'pricing_type' => $price_types !== [] ? 'traveler_based' : $pricing_type,
2767 'price_types' => $price_types,
2768 ];
2769 }
2770 }
2771
2772 $sidebar_group_discounts = [];
2773 if (function_exists('yatra_single_trip_get_group_discounts')) {
2774 $gd = yatra_single_trip_get_group_discounts((int) $trip->id);
2775 $cards = isset($gd['group_discounts_data']) && is_array($gd['group_discounts_data'])
2776 ? $gd['group_discounts_data']
2777 : [];
2778 $sidebar_group_discounts = apply_filters('yatra_advanced_discount_enabled', false) ? $cards : [];
2779 $sidebar_group_discounts = array_values(array_map(static function ($row) {
2780 if (is_object($row)) {
2781 $decoded = json_decode(wp_json_encode($row), true);
2782
2783 return is_array($decoded) ? $decoded : [];
2784 }
2785
2786 return $row;
2787 }, $sidebar_group_discounts));
2788 }
2789
2790 return [
2791 'pricingType' => $pricing_type,
2792 'sidebarAvailability' => $availability,
2793 'sidebarGroupDiscounts' => $sidebar_group_discounts,
2794 ];
2795 }
2796
2797 // Hook into WordPress enqueue system
2798 add_action('wp_enqueue_scripts', 'yatra_enqueue_single_trip_scripts');
2799
2800 // Yatra page type detection functions
2801 if (!function_exists('yatra_is_trip_page')) {
2802 function yatra_is_trip_page() {
2803 global $trip;
2804 return isset($trip) && !empty($trip);
2805 }
2806 }
2807
2808 if (!function_exists('yatra_is_destination_page')) {
2809 function yatra_is_destination_page() {
2810 global $destination, $yatra_taxonomy_data;
2811
2812 // Check direct global first
2813 if (isset($destination) && !empty($destination)) {
2814 return true;
2815 }
2816
2817 // Check taxonomy data
2818 if (isset($yatra_taxonomy_data) && !empty($yatra_taxonomy_data) && $yatra_taxonomy_data->type === 'destination') {
2819 return true;
2820 }
2821
2822 return false;
2823 }
2824 }
2825
2826 if (!function_exists('yatra_is_activity_page')) {
2827 function yatra_is_activity_page() {
2828 global $activity, $yatra_taxonomy_data;
2829
2830 // Check direct global first
2831 if (isset($activity) && !empty($activity)) {
2832 return true;
2833 }
2834
2835 // Check taxonomy data
2836 if (isset($yatra_taxonomy_data) && !empty($yatra_taxonomy_data) && $yatra_taxonomy_data->type === 'activity') {
2837 return true;
2838 }
2839
2840 return false;
2841 }
2842 }
2843
2844 if (!function_exists('yatra_is_category_page')) {
2845 function yatra_is_category_page() {
2846 global $category, $yatra_taxonomy_data;
2847
2848 // Check direct global first
2849 if (isset($category) && !empty($category)) {
2850 return true;
2851 }
2852
2853 // Check taxonomy data
2854 if (isset($yatra_taxonomy_data) && !empty($yatra_taxonomy_data) && $yatra_taxonomy_data->type === 'category') {
2855 return true;
2856 }
2857
2858 return false;
2859 }
2860 }
2861
2862 if (!function_exists('yatra_is_trip_archive_page')) {
2863 function yatra_is_trip_archive_page() {
2864 $current_url = $_SERVER['REQUEST_URI'] ?? '';
2865 $current_path = parse_url($current_url, PHP_URL_PATH) ?? '';
2866 $trip_base = \Yatra\Services\SettingsService::getTripBase();
2867
2868 // Check for both /trip/ and /trip patterns
2869 $pattern1 = '/' . $trip_base . '/';
2870 $pattern2 = '/' . $trip_base;
2871
2872 return (strpos($current_path, $pattern1) !== false || $current_path === $pattern2) && !yatra_is_trip_page();
2873 }
2874 }
2875
2876 // Yatra only has trip archive pages - no destination/activity/category archive pages
2877
2878 if (!function_exists('yatra_is_listing_page')) {
2879 function yatra_is_listing_page() {
2880 $current_url = $_SERVER['REQUEST_URI'] ?? '';
2881 $current_path = parse_url($current_url, PHP_URL_PATH) ?? '';
2882 return strpos($current_path, '/listing-') !== false;
2883 }
2884 }
2885
2886 if (!function_exists('yatra_is_yatra_page')) {
2887 function yatra_is_yatra_page() {
2888 return yatra_is_trip_page() ||
2889 yatra_is_destination_page() ||
2890 yatra_is_activity_page() ||
2891 yatra_is_category_page() ||
2892 yatra_is_trip_archive_page() ||
2893 yatra_is_listing_page();
2894 }
2895 }
2896
2897 if ( ! function_exists( 'yatra_get_header' ) ) {
2898
2899 function yatra_get_header( $header_name = null ) {
2900 global $wp_version;
2901
2902 // When the template is being rendered as the body of the yatra/page-content
2903 // server block inside a block-template canvas, the canvas already emits the
2904 // doctype/html/head/body and the site header template part. Re-emitting them
2905 // here would nest <html>/<body> and duplicate the header — so we no-op.
2906 if (
2907 class_exists( '\\Yatra\\Core\\Template\\FseTemplates' )
2908 && \Yatra\Core\Template\FseTemplates::isRenderingInsideCanvas()
2909 ) {
2910 return;
2911 }
2912
2913 if (
2914 version_compare( $wp_version, '5.9', '>=' ) &&
2915 function_exists( 'wp_is_block_theme' ) &&
2916 wp_is_block_theme()
2917 ) {
2918 /*
2919 * Full-site editing themes often omit add_theme_support( 'title-tag' ); the document title is
2920 * injected via template canvas using _block_template_render_title_tag (unconditional). Yatra
2921 * renders this minimal head instead of canvas, so _wp_render_title_tag would no-op and the
2922 * page would have no <title>. Mirror canvas: print title here and drop duplicate core hooks.
2923 */
2924 remove_action( 'wp_head', '_wp_render_title_tag', 1 );
2925 remove_action( 'wp_head', '_block_template_render_title_tag', 1 );
2926 ?>
2927 <!doctype html>
2928 <html <?php language_attributes(); ?>>
2929 <head>
2930 <meta charset="<?php bloginfo( 'charset' ); ?>">
2931 <title><?php echo esc_html( wp_get_document_title() ); ?></title>
2932 <?php wp_head(); ?>
2933 </head>
2934
2935 <body <?php body_class(); ?>>
2936 <?php wp_body_open(); ?>
2937 <div class="wp-site-blocks">
2938 <header class="wp-block-template-part site-header">
2939 <?php block_header_area(); ?>
2940 </header>
2941 <?php
2942 } else {
2943 get_header( $header_name );
2944 }
2945 }
2946 }
2947
2948 if ( ! function_exists( 'yatra_block_support_styles' ) ) {
2949 function yatra_block_support_styles() {
2950 // Bail early if function does not exists.
2951 if ( ! function_exists( 'wp_style_engine_get_stylesheet_from_context' ) ) {
2952 return;
2953 }
2954
2955 $core_styles_keys = array( 'block-supports' );
2956
2957 $compiled_core_stylesheet = '';
2958
2959 foreach ( $core_styles_keys as $style_key ) {
2960 $compiled_core_stylesheet .= wp_style_engine_get_stylesheet_from_context( $style_key, array() );
2961 }
2962
2963 if ( empty( $compiled_core_stylesheet ) ) {
2964 return;
2965 }
2966
2967 wp_register_style( 'yatra-block-supports', false );
2968 wp_enqueue_style( 'yatra-block-supports' );
2969 wp_add_inline_style( 'yatra-block-supports', $compiled_core_stylesheet );
2970 }
2971 }
2972
2973 if ( ! function_exists( 'yatra_get_footer' ) ) {
2974
2975 function yatra_get_footer( $footer_name = null ) {
2976 global $wp_version;
2977
2978 // Mirror of yatra_get_header(): when rendered inside the FSE canvas via
2979 // the yatra/page-content block, the canvas already emits the footer
2980 // template part and closes <body>/<html>. No-op here to avoid duplicates.
2981 if (
2982 class_exists( '\\Yatra\\Core\\Template\\FseTemplates' )
2983 && \Yatra\Core\Template\FseTemplates::isRenderingInsideCanvas()
2984 ) {
2985 return;
2986 }
2987
2988 if (
2989 version_compare( $wp_version, '5.9', '>=' ) &&
2990 function_exists( 'wp_is_block_theme' ) &&
2991 wp_is_block_theme()
2992 ) {
2993 ?>
2994 <footer class="wp-block-template-part site-footer">
2995 <?php block_footer_area(); ?>
2996 </footer>
2997 </div>
2998 <?php yatra_block_support_styles(); ?>
2999 <?php wp_footer(); ?>
3000 </body>
3001 </html>
3002 <?php
3003 } else {
3004 get_footer( $footer_name );
3005 }
3006 }
3007 }
3008
3009 /**
3010 * Render tab icon (supports both SVG icons and images)
3011 *
3012 * @param mixed $icon_data Icon data (string, array, or object)
3013 * @param string $default_icon Default icon name
3014 * @param string $css_class CSS class for the icon
3015 * @param string $label Label for alt text
3016 * @return void Echoes the icon HTML
3017 */
3018 if (!function_exists('yatra_render_tab_icon')) {
3019 function yatra_render_tab_icon($icon_data, $default_icon = 'book', $css_class = '', $label = '') {
3020 if (empty($icon_data)) {
3021 echo function_exists('yatra_svg_icon') ? yatra_svg_icon($default_icon, $css_class) : '';
3022
3023 return;
3024 }
3025 if (is_string($icon_data) && strpos($icon_data, '{') === 0) {
3026 $icon_data = json_decode($icon_data, true);
3027 }
3028 if (is_object($icon_data)) {
3029 $icon_data = (array) $icon_data;
3030 }
3031 if (is_array($icon_data) && isset($icon_data['type']) && $icon_data['type'] === 'image' && !empty($icon_data['value'])) {
3032 $image_url = is_numeric($icon_data['value'])
3033 ? wp_get_attachment_url((int) $icon_data['value'])
3034 : $icon_data['value'];
3035 if ($image_url) {
3036 $size_style = strpos($css_class, 'sticky-nav') !== false ? 'width: 18px; height: 18px;' : 'width: 24px; height: 24px;';
3037 echo '<img src="' . esc_url($image_url) . '" alt="' . esc_attr($label) . '" class="' . esc_attr($css_class) . '" style="' . esc_attr($size_style) . ' object-fit: cover; border-radius: 4px;">';
3038
3039 return;
3040 }
3041 }
3042 // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped -- markup built from sanitized picker / SVG registry
3043 echo yatra_stored_picker_icon_markup($icon_data, $default_icon, $css_class);
3044 }
3045 }
3046
3047 if (!function_exists('yatra_listing_sidebar_filter_visible_cap')) {
3048 /**
3049 * How many sidebar checkbox rows to show before "Show more" on the trip listing.
3050 *
3051 * Filter: {@see 'yatra_listing_sidebar_filter_visible_count'} — default 8, clamped 3–40.
3052 *
3053 * @return int
3054 */
3055 function yatra_listing_sidebar_filter_visible_cap(): int
3056 {
3057 $n = (int) apply_filters('yatra_listing_sidebar_filter_visible_count', 8);
3058
3059 return max(3, min(40, $n));
3060 }
3061 }
3062
3063 if (!function_exists('yatra_wishlist_enabled')) {
3064 /**
3065 * Whether wishlist UI and REST should be active (Yatra Pro + setting).
3066 */
3067 function yatra_wishlist_enabled(): bool
3068 {
3069 return \Yatra\Services\SettingsService::wishlistEnabled();
3070 }
3071 }
3072
3073 if (!function_exists('yatra_usage_track_event')) {
3074 /**
3075 * Record an anonymous product telemetry event (requires opt-in).
3076 *
3077 * @param string $event Event key (sanitized).
3078 * @param int $delta Counter increment.
3079 */
3080 function yatra_usage_track_event(string $event, int $delta = 1): void
3081 {
3082 if (!class_exists(\Yatra\Services\StatsUsage::class)) {
3083 return;
3084 }
3085 \Yatra\Services\StatsUsage::instance()->record_event($event, $delta);
3086 }
3087 }
3088