PluginProbe
Yatra – Travel Booking & Tour Operator Software / 3.0.7
Yatra – Travel Booking & Tour Operator Software v3.0.7
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 2.0.10 All 83 releases
yatra / includes / helpers.php

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

3,005 lines 95.3 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' => '',
448 'CZK' => '',
449 'HUF' => 'Ft',
450 'ILS' => '',
451 'TWD' => 'NT$',
452 'PKR' => '',
453 'BDT' => '',
454 'LKR' => 'Rs',
455 'EGP' => '',
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 * Branded plugin name shown in admin menu, plugin list, and PDFs.
1024 */
1025 function yatra_get_brand_name(): string
1026 {
1027 return (string) apply_filters('yatra_brand_name', 'Yatra');
1028 }
1029
1030 /**
1031 * Branded company/author name (replaces "MantraBrain").
1032 */
1033 function yatra_get_brand_company(): string
1034 {
1035 return (string) apply_filters('yatra_brand_company', 'MantraBrain');
1036 }
1037
1038 /**
1039 * Public website URL for the branded product.
1040 */
1041 function yatra_get_brand_website_url(): string
1042 {
1043 $url = (string) apply_filters('yatra_brand_website_url', 'https://wpyatra.com/');
1044 return $url !== '' ? esc_url_raw($url) : 'https://wpyatra.com/';
1045 }
1046
1047 /**
1048 * Support URL surfaced in admin notices and the plugin row.
1049 */
1050 function yatra_get_brand_support_url(): string
1051 {
1052 $url = (string) apply_filters(
1053 'yatra_brand_support_url',
1054 'https://wordpress.org/support/plugin/yatra/reviews/?filter=5'
1055 );
1056 return $url !== '' ? esc_url_raw($url) : 'https://wordpress.org/support/plugin/yatra/reviews/?filter=5';
1057 }
1058
1059
1060 /**
1061 * ============================================
1062 * BOOKING SESSION MANAGEMENT
1063 * ============================================
1064 */
1065
1066 /**
1067 * Start WordPress session if not already started
1068 */
1069 function yatra_start_session(): void
1070 {
1071 // Start output buffering to prevent accidental output from breaking sessions
1072 if (!ob_get_level()) {
1073 ob_start();
1074 }
1075
1076 if (session_status() === PHP_SESSION_NONE && !headers_sent()) {
1077 // Set session cookie parameters for better compatibility
1078 if (PHP_VERSION_ID >= 70300) {
1079 session_set_cookie_params([
1080 'lifetime' => 0,
1081 'path' => defined('COOKIEPATH') ? COOKIEPATH : '/',
1082 'domain' => defined('COOKIE_DOMAIN') ? COOKIE_DOMAIN : '',
1083 'secure' => is_ssl(),
1084 'httponly' => true,
1085 'samesite' => 'Lax'
1086 ]);
1087 }
1088 session_start();
1089 }
1090 }
1091
1092 /**
1093 * Set booking session data
1094 *
1095 * @param array $data Booking data to store
1096 */
1097 function yatra_set_booking_session(array $data): void
1098 {
1099 yatra_start_session();
1100
1101 // Clear any existing remaining payment session to avoid conflicts
1102 unset($_SESSION['yatra_remaining']);
1103
1104 $session_data = array_merge(
1105 $_SESSION['yatra_booking'] ?? [],
1106 $data,
1107 ['timestamp' => time()]
1108 );
1109
1110 $_SESSION['yatra_booking'] = $session_data;
1111
1112 // ALWAYS store in transient as backup (not just for REST API)
1113 // This ensures data persists across all request types
1114 // Generate or reuse booking token
1115 $booking_token = $_SESSION['yatra_booking_token'] ?? 'yatra_booking_' . wp_generate_password(32, false);
1116 $_SESSION['yatra_booking_token'] = $booking_token;
1117 $session_data['booking_token'] = $booking_token;
1118
1119 // Store in transient (expires in 30 minutes)
1120 try {
1121 $transient_set = set_transient($booking_token, $session_data, 1800);
1122 } catch (Exception $e) {
1123 // Continue without transient - session fallback will be used
1124 }
1125
1126 }
1127
1128 /**
1129 * Get booking session data
1130 *
1131 * @param string|null $key Specific key to retrieve, or null for all data
1132 * @param mixed $default Default value if key not found
1133 * @return mixed
1134 */
1135 function yatra_get_booking_session(?string $key = null, $default = null)
1136 {
1137 yatra_start_session();
1138
1139 $booking_data = $_SESSION['yatra_booking'] ?? [];
1140
1141 // If session is empty, try to restore from transient (REST API → page load transition)
1142 if (empty($booking_data) || empty($booking_data['trip_id'])) {
1143 // Check for booking token in URL or session
1144 $booking_token = $_GET['booking_token'] ?? $_SESSION['yatra_booking_token'] ?? null;
1145
1146 if ($booking_token) {
1147 try {
1148 $transient_data = get_transient($booking_token);
1149
1150 if ($transient_data && is_array($transient_data) && !empty($transient_data['trip_id'])) {
1151 // Validate transient data integrity
1152 if (isset($transient_data['timestamp']) && (time() - $transient_data['timestamp']) < 1800) {
1153 $booking_data = $transient_data;
1154 // Restore to session
1155 $_SESSION['yatra_booking'] = $booking_data;
1156 $_SESSION['yatra_booking_token'] = $booking_token;
1157 }
1158 }
1159 } catch (Exception $e) {
1160 // Continue without transient data
1161 }
1162 }
1163 }
1164
1165 // Check if session is expired (30 minutes)
1166 if (!empty($booking_data['timestamp'])) {
1167 $session_age = time() - $booking_data['timestamp'];
1168 if ($session_age > 1800) { // 30 minutes
1169 yatra_clear_booking_session();
1170 return $key ? $default : [];
1171 }
1172 }
1173
1174 if ($key === null) {
1175 return $booking_data;
1176 }
1177
1178 return $booking_data[$key] ?? $default;
1179 }
1180
1181 /**
1182 * Clear booking session data (PHP session, booking token, and REST backup transient).
1183 *
1184 * Without removing the token and transient, yatra_get_booking_session() can repopulate
1185 * checkout data from the transient on the next request after a completed booking.
1186 */
1187 function yatra_clear_booking_session(): void
1188 {
1189 yatra_start_session();
1190
1191 $token = $_SESSION['yatra_booking_token'] ?? null;
1192 if (is_string($token) && $token !== '') {
1193 delete_transient($token);
1194 }
1195
1196 unset($_SESSION['yatra_booking'], $_SESSION['yatra_booking_token']);
1197 }
1198
1199 /**
1200 * Check if booking session exists and is valid
1201 *
1202 * @return bool
1203 */
1204 function yatra_has_booking_session(): bool
1205 {
1206 $booking_data = yatra_get_booking_session();
1207 return !empty($booking_data) && !empty($booking_data['trip_id']);
1208 }
1209
1210 /**
1211 * Fire {@see 'yatra_booking_confirmed'} when a booking reaches `confirmed` from a non-confirmed status.
1212 *
1213 * Core always fired `yatra_booking_status_changed`; Pro modules (Trip Consent, Google Calendar) listen
1214 * on this dedicated action. Call this after any code path that sets a booking to `confirmed` without
1215 * going through {@see \Yatra\Services\BookingService::updateStatus()}.
1216 *
1217 * @param int $bookingId Booking ID.
1218 * @param string $previousStatus Booking status in the database immediately before confirming.
1219 */
1220 function yatra_trigger_booking_confirmed(int $bookingId, string $previousStatus): void
1221 {
1222 if ($bookingId < 1 || $previousStatus === 'confirmed') {
1223 return;
1224 }
1225
1226 $repo = new \Yatra\Repositories\BookingRepository();
1227 $booking = $repo->findWithTrip($bookingId);
1228
1229 if (!$booking || ($booking->status ?? '') !== 'confirmed') {
1230 return;
1231 }
1232
1233 /**
1234 * Booking reached confirmed status (was not confirmed before this transition).
1235 *
1236 * @param int $bookingId Booking ID.
1237 * @param object $booking Row from {@see \Yatra\Repositories\BookingRepository::findWithTrip()}.
1238 */
1239 do_action('yatra_booking_confirmed', $bookingId, $booking);
1240 }
1241
1242 /**
1243 * ============================================
1244 * REMAINING PAYMENT SESSION MANAGEMENT
1245 * ============================================
1246 */
1247
1248 /**
1249 * Set remaining payment session data
1250 *
1251 * @param array $data Remaining payment data to store
1252 */
1253 function yatra_set_remaining_session(array $data): void
1254 {
1255 yatra_start_session();
1256
1257 // Clear checkout session fully (including token + transient) before remaining-payment flow
1258 yatra_clear_booking_session();
1259
1260 $_SESSION['yatra_remaining'] = array_merge(
1261 $data,
1262 ['timestamp' => time()]
1263 );
1264
1265 // Ensure session data is written to storage immediately
1266 if (session_status() === PHP_SESSION_ACTIVE) {
1267 session_write_close();
1268 }
1269 }
1270
1271 /**
1272 * Get remaining payment session data
1273 *
1274 * @param string|null $key Specific key to retrieve, or null for all data
1275 * @param mixed $default Default value if key not found
1276 * @return mixed
1277 */
1278 function yatra_get_remaining_session(?string $key = null, $default = null)
1279 {
1280 yatra_start_session();
1281
1282 $remaining_data = $_SESSION['yatra_remaining'] ?? [];
1283
1284 // Check if session is expired (30 minutes)
1285 if (!empty($remaining_data['timestamp'])) {
1286 $session_age = time() - $remaining_data['timestamp'];
1287 if ($session_age > 1800) { // 30 minutes
1288 yatra_clear_remaining_session();
1289 return $key ? $default : [];
1290 }
1291 }
1292
1293 if ($key === null) {
1294 return $remaining_data;
1295 }
1296
1297 return $remaining_data[$key] ?? $default;
1298 }
1299
1300 /**
1301 * Clear remaining payment session data
1302 */
1303 function yatra_clear_remaining_session(): void
1304 {
1305 yatra_start_session();
1306 unset($_SESSION['yatra_remaining']);
1307 }
1308
1309 /**
1310 * Check if remaining payment session exists and is valid
1311 *
1312 * @return bool
1313 */
1314 function yatra_has_remaining_session(): bool
1315 {
1316 $remaining_data = yatra_get_remaining_session();
1317 return !empty($remaining_data) && !empty($remaining_data['booking_id']);
1318 }
1319
1320 /**
1321 * Get the active checkout session type
1322 *
1323 * @return string|null 'remaining' if remaining session exists, 'booking' if booking session exists, null if neither
1324 */
1325 function yatra_get_checkout_session_type(): ?string
1326 {
1327 if (yatra_has_remaining_session()) {
1328 return 'remaining';
1329 }
1330
1331 if (yatra_has_booking_session()) {
1332 return 'booking';
1333 }
1334
1335 return null;
1336 }
1337
1338 /**
1339 * Get the active checkout session data (remaining or booking)
1340 *
1341 * @return array Session data with 'type' key indicating session type
1342 */
1343 function yatra_get_active_checkout_session(): array
1344 {
1345 if (yatra_has_remaining_session()) {
1346 $data = yatra_get_remaining_session();
1347 $data['session_type'] = 'remaining';
1348 return $data;
1349 }
1350
1351 if (yatra_has_booking_session()) {
1352 $data = yatra_get_booking_session();
1353 $data['session_type'] = 'booking';
1354 return $data;
1355 }
1356
1357 return [];
1358 }
1359
1360 /**
1361 * Get booking/checkout URL
1362 *
1363 * Logic:
1364 * 1. If custom booking page is set → return that page's URL
1365 * 2. Otherwise → return dynamic URL using booking_base from settings (e.g., /bookings/)
1366 *
1367 * @return string Booking URL
1368 */
1369 function yatra_get_checkout_url(): string
1370 {
1371 $permalink_structure = get_option('permalink_structure');
1372 $is_plain = empty($permalink_structure);
1373
1374 // Check if custom booking page is set via SettingsService
1375 if (SettingsService::useCustomBookingPage()) {
1376 $page_id = SettingsService::getBookingPageId();
1377 if ($page_id > 0) {
1378 return get_permalink($page_id);
1379 }
1380 }
1381
1382 // Default dynamic URL using booking base from settings
1383 $base = SettingsService::getBookingBase();
1384 if ($is_plain) {
1385 return add_query_arg(['yatra_page' => $base], home_url('/'));
1386 }
1387
1388 return home_url('/' . $base . '/');
1389 }
1390
1391 /**
1392 * Front-end URL for booking confirmation for a given reference.
1393 *
1394 * Booking confirmation is pageless: Yatra serves it via rewrite rules and query vars,
1395 * not a WordPress page permalink. Pretty URLs use /{booking_base}/confirmation/{reference}/.
1396 * Plain permalinks use ?yatra_booking_confirmation={reference}.
1397 *
1398 * To use a real WordPress page as the base (advanced), filter {@see 'yatra_booking_confirmation_base_url'}.
1399 * Legacy /booking-confirmation/{reference}/ remains registered in rewrites for old links.
1400 *
1401 * @param string $reference Booking reference segment (may be empty for base URL only).
1402 * @return string Full URL.
1403 */
1404 function yatra_get_booking_confirmation_url(string $reference = ''): string
1405 {
1406 $reference = (string) $reference;
1407 $permalink_structure = get_option('permalink_structure');
1408 $is_plain = empty($permalink_structure);
1409
1410 if ($is_plain) {
1411 if ($reference === '') {
1412 $url = home_url('/');
1413 } else {
1414 $url = add_query_arg('yatra_booking_confirmation', $reference, home_url('/'));
1415 }
1416 } else {
1417 $booking_base = trim((string) SettingsService::getBookingBase(), '/');
1418 if ($booking_base === '') {
1419 $booking_base = 'book';
1420 }
1421 $confirmSeg = trim((string) SettingsService::getPermalinkBases()['booking_flow_confirmation_segment'], '/');
1422 if ($confirmSeg === '') {
1423 $confirmSeg = 'confirmation';
1424 }
1425 $virtual_base = home_url('/' . $booking_base . '/' . $confirmSeg . '/');
1426
1427 /**
1428 * Override the base URL for booking confirmation (before the reference path segment).
1429 * Return a non-empty string to use a custom base (e.g. get_permalink( $page_id )).
1430 * Default null keeps the pageless virtual URL from Settings → booking base.
1431 *
1432 * @param string|null $base_url Custom base, or null to use virtual URL.
1433 * @param string $reference Booking reference (may be empty).
1434 */
1435 $base_url = apply_filters('yatra_booking_confirmation_base_url', null, $reference);
1436 if (!is_string($base_url) || $base_url === '') {
1437 $base_url = $virtual_base;
1438 }
1439
1440 if ($reference === '') {
1441 $url = trailingslashit($base_url);
1442 } else {
1443 $url = trailingslashit($base_url) . $reference . '/';
1444 }
1445 }
1446
1447 /**
1448 * Filter the booking confirmation URL.
1449 *
1450 * @param string $url Built URL.
1451 * @param string $reference Booking reference (may be empty).
1452 */
1453 return (string) apply_filters('yatra_booking_confirmation_url', $url, $reference);
1454 }
1455
1456 /**
1457 * Front-end URL to verify a customer email (checkout registration / account).
1458 *
1459 * Pretty permalinks: /yatra-verify-email/{token}/ (rewrite + query var).
1460 * Plain permalinks: ?yatra_verify_email={token} on the home URL (same as {@see \Yatra\Core\Routing\PermalinkCanonical}).
1461 *
1462 * @param string $secure_token URL-safe token (base64-derived; only [A-Za-z0-9_-] used in the path/query).
1463 */
1464 function yatra_get_email_verification_url(string $secure_token): string
1465 {
1466 $t = preg_replace('/[^a-zA-Z0-9_-]/', '', (string) $secure_token) ?? '';
1467 if ($t === '') {
1468 return home_url('/');
1469 }
1470
1471 $permalink_structure = get_option('permalink_structure');
1472 $is_plain = empty($permalink_structure);
1473
1474 if ($is_plain) {
1475 $url = add_query_arg('yatra_verify_email', $t, home_url('/'));
1476 } else {
1477 $prefix = SettingsService::getPermalinkBases()['email_verification_prefix'];
1478 $url = trailingslashit(home_url('/' . $prefix . '/' . $t . '/'));
1479 }
1480
1481 /**
1482 * Filter the customer email verification URL.
1483 *
1484 * @param string $url Full verification URL.
1485 * @param string $token Sanitized token segment.
1486 */
1487 return (string) apply_filters('yatra_email_verification_url', $url, $t);
1488 }
1489
1490 /**
1491 * ============================================
1492 * ARCHIVE LISTING (plain permalinks pagination)
1493 * ============================================
1494 */
1495
1496 /**
1497 * Items per page from WordPress Reading settings ("Blog pages show at most").
1498 * Used for Yatra front-end listings (trips, taxonomies, activity/destination/category archives).
1499 *
1500 * @return int At least 1.
1501 */
1502 function yatra_get_posts_per_page(): int
1503 {
1504 $n = absint((int) get_option('posts_per_page', 10));
1505
1506 return (int) apply_filters('yatra_posts_per_page', max(1, $n));
1507 }
1508
1509 /**
1510 * Current page number for Yatra archive templates (activity, destination, trip category).
1511 * Handles plain URLs where WordPress may use {@see 'paged'} or {@see 'page'} on the front page.
1512 */
1513 function yatra_get_archive_listing_paged(): int
1514 {
1515 if (isset($_GET['paged']) && $_GET['paged'] !== '') {
1516 return max(1, absint(wp_unslash($_GET['paged'])));
1517 }
1518
1519 if (!empty($_GET['yatra_page']) && isset($_GET['page']) && $_GET['page'] !== '') {
1520 return max(1, absint(wp_unslash($_GET['page'])));
1521 }
1522
1523 $p = (int) get_query_var('paged');
1524 if ($p > 0) {
1525 return max(1, $p);
1526 }
1527
1528 $p = (int) get_query_var('page');
1529
1530 return max(1, $p);
1531 }
1532
1533 /**
1534 * Result summary for destination / activity / trip-category browse pages (parity with trip grid header).
1535 *
1536 * @param string $items_label Plural noun, e.g. translated "destinations".
1537 */
1538 function yatra_archive_browse_results_line(int $start, int $end, int $total, int $page, int $pages, string $items_label): string
1539 {
1540 if ($total <= 0) {
1541 return '';
1542 }
1543
1544 return sprintf(
1545 /* translators: 1–2: range, 3: total, 4: item type, 5–6: pagination */
1546 __('Showing %1$d–%2$d of %3$d %4$s (page %5$d of %6$d)', 'yatra'),
1547 $start,
1548 $end,
1549 $total,
1550 $items_label,
1551 $page,
1552 $pages
1553 );
1554 }
1555
1556 /**
1557 * Request path (leading slash, no query string) for same-page links. Strips /page/N/ pagination segments.
1558 */
1559 function yatra_get_current_request_path_for_query_urls(): string
1560 {
1561 $request_uri = isset($_SERVER['REQUEST_URI']) ? (string) wp_unslash($_SERVER['REQUEST_URI']) : '/';
1562 $base_path = strtok($request_uri, '?') ?: '/';
1563 $base_path = rtrim((string) $base_path, '/');
1564 $base_path = preg_replace('#/page/[0-9]+#', '', $base_path);
1565 $base_path = rtrim($base_path, '/');
1566
1567 if ($base_path === '') {
1568 return '/';
1569 }
1570
1571 return $base_path[0] === '/' ? $base_path : '/' . $base_path;
1572 }
1573
1574 /**
1575 * Full URL for the same archive request with a different page (preserves yatra_page and other args).
1576 * Uses the current request path so /destination/, /activity/, /trip-category/ stay on the same listing.
1577 */
1578 function yatra_build_archive_listing_url(int $page_num): string
1579 {
1580 $params = !empty($_GET) && is_array($_GET) ? wp_unslash($_GET) : [];
1581
1582 $qvYatra = (string) get_query_var('yatra_page');
1583 if ($qvYatra !== '' && (!isset($params['yatra_page']) || $params['yatra_page'] === '')) {
1584 $params['yatra_page'] = $qvYatra;
1585 }
1586
1587 if (!empty($params['yatra_page']) || isset($params['yatra_trip'])) {
1588 unset($params['page']);
1589 }
1590
1591 if ($page_num > 1) {
1592 $params['paged'] = (string) $page_num;
1593 } else {
1594 unset($params['paged'], $params['page']);
1595 }
1596
1597 $path = yatra_get_current_request_path_for_query_urls();
1598 $query = http_build_query($params);
1599
1600 return esc_url($path . ($query !== '' ? '?' . $query : ''));
1601 }
1602
1603 /**
1604 * Same request path with a different paged query arg (strips an existing /page/N/ segment first).
1605 * For taxonomy trip lists and other templates not rooted at home_url('/').
1606 */
1607 function yatra_build_current_request_paged_url(int $page_num): string
1608 {
1609 $page_num = max(1, $page_num);
1610 $params = !empty($_GET) && is_array($_GET) ? wp_unslash($_GET) : [];
1611
1612 if ($page_num > 1) {
1613 $params['paged'] = (string) $page_num;
1614 } else {
1615 unset($params['paged'], $params['page']);
1616 }
1617
1618 $path = yatra_get_current_request_path_for_query_urls();
1619 $query = http_build_query($params);
1620
1621 return esc_url($path . ($query !== '' ? '?' . $query : ''));
1622 }
1623
1624 /**
1625 * Same request path with trip sort (TripRepository / TripListingService). Resets pagination.
1626 *
1627 * @param string $sort Allowed: '' (recommended), most_popular, price_low, price_high, rating_high, duration_short, duration_long.
1628 */
1629 function yatra_build_current_request_sort_url(string $sort): string
1630 {
1631 $allowed = ['', 'most_popular', 'price_low', 'price_high', 'rating_high', 'duration_short', 'duration_long'];
1632 if (!in_array($sort, $allowed, true)) {
1633 $sort = '';
1634 }
1635
1636 $params = !empty($_GET) && is_array($_GET) ? wp_unslash($_GET) : [];
1637 unset($params['paged'], $params['page']);
1638 if ($sort !== '') {
1639 $params['sort'] = $sort;
1640 } else {
1641 unset($params['sort']);
1642 }
1643
1644 $path = yatra_get_current_request_path_for_query_urls();
1645 $query = http_build_query($params);
1646
1647 return esc_url($path . ($query !== '' ? '?' . $query : ''));
1648 }
1649
1650 /**
1651 * Compare two archive listing rows (activity, destination, or category) by sort key.
1652 */
1653 function yatra_compare_archive_listing_row_pair(object $a, object $b, string $sort): int
1654 {
1655 $nameA = isset($a->name) ? strtolower((string) $a->name) : '';
1656 $nameB = isset($b->name) ? strtolower((string) $b->name) : '';
1657 $tripsA = isset($a->trips_count) ? (int) $a->trips_count : 0;
1658 $tripsB = isset($b->trips_count) ? (int) $b->trips_count : 0;
1659 $ratingA = isset($a->avg_rating) ? (float) $a->avg_rating : 0.0;
1660 $ratingB = isset($b->avg_rating) ? (float) $b->avg_rating : 0.0;
1661
1662 switch ($sort) {
1663 case 'trips_desc':
1664 return $tripsB <=> $tripsA;
1665 case 'trips_asc':
1666 return $tripsA <=> $tripsB;
1667 case 'name_asc':
1668 return $nameA <=> $nameB;
1669 case 'name_desc':
1670 return $nameB <=> $nameA;
1671 case 'rating_desc':
1672 default:
1673 $cmp = $ratingB <=> $ratingA;
1674 if (0 === $cmp) {
1675 return $tripsB <=> $tripsA;
1676 }
1677
1678 return $cmp;
1679 }
1680 }
1681
1682 /**
1683 * Invokable comparator for {@see yatra_sort_archive_listing_stats_rows()}.
1684 *
1685 * @internal
1686 */
1687 final class Yatra_Archive_Listing_Stats_Comparator
1688 {
1689 /** @var string */
1690 private $sort;
1691
1692 public function __construct(string $sort)
1693 {
1694 $this->sort = $sort;
1695 }
1696
1697 /**
1698 * @param object $a
1699 * @param object $b
1700 */
1701 public function __invoke($a, $b): int
1702 {
1703 return yatra_compare_archive_listing_row_pair($a, $b, $this->sort);
1704 }
1705 }
1706
1707 /**
1708 * Sort archive listing rows in place (stats objects from repository).
1709 */
1710 function yatra_sort_archive_listing_stats_rows(array &$items, string $sort): void
1711 {
1712 if (empty($items)) {
1713 return;
1714 }
1715
1716 usort($items, new Yatra_Archive_Listing_Stats_Comparator($sort));
1717 }
1718
1719 /**
1720 * Sort dropdown URL: same archive, page reset to 1, yatra_sort applied (preserves yatra_page etc.).
1721 */
1722 function yatra_build_archive_listing_sort_url(string $yatra_sort): string
1723 {
1724 $params = !empty($_GET) && is_array($_GET) ? wp_unslash($_GET) : [];
1725 unset($params['paged'], $params['page']);
1726 if (!empty($params['yatra_page']) || isset($params['yatra_trip'])) {
1727 unset($params['page']);
1728 }
1729 $params['yatra_sort'] = $yatra_sort;
1730
1731 $path = yatra_get_current_request_path_for_query_urls();
1732 $query = http_build_query($params);
1733
1734 return esc_url($path . ($query !== '' ? '?' . $query : ''));
1735 }
1736
1737 /**
1738 * ============================================
1739 * PERMALINK HELPERS
1740 * ============================================
1741 */
1742
1743 /**
1744 * Get destination permalink
1745 *
1746 * @param object|int $destination Destination object with slug property, or destination ID
1747 * @return string Destination permalink URL
1748 */
1749 function yatra_get_destination_permalink($destination): string
1750 {
1751 $original = $destination;
1752
1753 if (is_numeric($destination)) {
1754 global $wpdb;
1755 $table = ClassificationsTable::getTableName();
1756 $destination = $wpdb->get_row($wpdb->prepare(
1757 "SELECT slug FROM {$table} WHERE id = %d AND type = %s",
1758 (int) $destination,
1759 ClassificationTypes::DESTINATION
1760 ));
1761 }
1762
1763 $slug = is_object($destination) ? ($destination->slug ?? '') : '';
1764
1765 if (empty($slug)) {
1766 return '';
1767 }
1768
1769 $base = SettingsService::getDestinationBase();
1770 $permalink_structure = get_option('permalink_structure');
1771 $is_plain = empty($permalink_structure);
1772
1773 if ($is_plain) {
1774 $key = preg_replace('/[^a-z0-9_-]/i', '', $base) ?: 'destination';
1775
1776 $url = add_query_arg([$key => $slug], home_url('/'));
1777 } else {
1778 $url = home_url('/' . $base . '/' . $slug . '/');
1779 }
1780
1781 /** @var string $url Override full destination URL or path (plain/pretty handled above). Third arg: slug. */
1782 return (string) apply_filters('yatra_destination_permalink', $url, $original, $slug);
1783 }
1784
1785 /**
1786 * Get activity permalink
1787 *
1788 * @param object|int $activity Activity object with slug property, or activity ID
1789 * @return string Activity permalink URL
1790 */
1791 function yatra_get_activity_permalink($activity): string
1792 {
1793 $original = $activity;
1794
1795 if (is_numeric($activity)) {
1796 global $wpdb;
1797 $table = ClassificationsTable::getTableName();
1798 $activity = $wpdb->get_row($wpdb->prepare(
1799 "SELECT slug FROM {$table} WHERE id = %d AND type = %s",
1800 (int) $activity,
1801 ClassificationTypes::ACTIVITY
1802 ));
1803 }
1804
1805 $slug = is_object($activity) ? ($activity->slug ?? '') : '';
1806
1807 if (empty($slug)) {
1808 return '';
1809 }
1810
1811 $base = SettingsService::getActivityBase();
1812 $permalink_structure = get_option('permalink_structure');
1813 $is_plain = empty($permalink_structure);
1814
1815 if ($is_plain) {
1816 $key = preg_replace('/[^a-z0-9_-]/i', '', $base) ?: 'activity';
1817
1818 $url = add_query_arg([$key => $slug], home_url('/'));
1819 } else {
1820 $url = home_url('/' . $base . '/' . $slug . '/');
1821 }
1822
1823 /** @var string $url Override full activity URL. Third arg: slug. */
1824 return (string) apply_filters('yatra_activity_permalink', $url, $original, $slug);
1825 }
1826
1827 /**
1828 * Get trip category permalink
1829 *
1830 * @param object|int $category Category object with slug property, or category ID
1831 * @return string Category permalink URL
1832 */
1833 function yatra_get_category_permalink($category): string
1834 {
1835 $original = $category;
1836
1837 if (is_numeric($category)) {
1838 global $wpdb;
1839 $table = ClassificationsTable::getTableName();
1840 $category = $wpdb->get_row($wpdb->prepare(
1841 "SELECT slug FROM {$table} WHERE id = %d AND type = %s",
1842 (int) $category,
1843 ClassificationTypes::CATEGORY
1844 ));
1845 }
1846
1847 $slug = is_object($category) ? ($category->slug ?? '') : '';
1848
1849 if (empty($slug)) {
1850 return '';
1851 }
1852
1853 $base = SettingsService::getTripCategoryBase();
1854 $permalink_structure = get_option('permalink_structure');
1855 $is_plain = empty($permalink_structure);
1856
1857 if ($is_plain) {
1858 $key = preg_replace('/[^a-z0-9_-]/i', '', $base) ?: 'trip-category';
1859
1860 $url = add_query_arg([$key => $slug], home_url('/'));
1861 } else {
1862 $url = home_url('/' . $base . '/' . $slug . '/');
1863 }
1864
1865 /** @var string $url Override full trip-category URL. Third arg: slug. */
1866 return (string) apply_filters('yatra_category_permalink', $url, $original, $slug);
1867 }
1868
1869 /**
1870 * Get trip permalink
1871 *
1872 * @param object|int $trip Trip object with slug property, or trip ID
1873 * @return string Trip permalink URL
1874 */
1875 function yatra_get_trip_permalink($trip): string
1876 {
1877 $original = $trip;
1878
1879 if (is_numeric($trip)) {
1880 global $wpdb;
1881 $table = TripsTable::getTableName();
1882 $trip = $wpdb->get_row($wpdb->prepare(
1883 "SELECT slug FROM {$table} WHERE id = %d",
1884 (int) $trip
1885 ));
1886 }
1887
1888 $slug = is_object($trip) ? ($trip->slug ?? '') : '';
1889
1890 if (empty($slug)) {
1891 return '';
1892 }
1893
1894 $base = SettingsService::getTripBase();
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) ?: 'trip';
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 trip URL. Third arg: slug. */
1907 return (string) apply_filters('yatra_trip_permalink', $url, $original, $slug);
1908 }
1909
1910 /**
1911 * Canonical URL for the trip archive / filter listing (respects Settings trip base).
1912 * Plain permalinks use ?yatra_page={base}; pretty permalinks use /{base}/.
1913 */
1914 function yatra_get_trip_listing_url(): string
1915 {
1916 $base = SettingsService::getTripBase();
1917 $base = preg_replace('/[^a-zA-Z0-9_-]/', '', (string) $base) ?: 'trip';
1918 $permalink_structure = (string) get_option('permalink_structure', '');
1919
1920 if ($permalink_structure === '') {
1921 $url = esc_url(add_query_arg('yatra_page', $base, home_url('/')));
1922 } else {
1923 $url = trailingslashit(home_url('/' . $base . '/'));
1924 }
1925
1926 return (string) apply_filters('yatra_trip_listing_url', $url, $base);
1927 }
1928
1929 /**
1930 * Canonical URL for browse-all taxonomy listings (destinations, activities, trip categories).
1931 * Plain permalinks use ?yatra_page={base}; pretty permalinks use /{base}/.
1932 *
1933 * @param string $listing_type One of: destination, activity, category
1934 */
1935 function yatra_get_taxonomy_listing_url(string $listing_type): string
1936 {
1937 $map = [
1938 'destination' => SettingsService::getDestinationBase(),
1939 'activity' => SettingsService::getActivityBase(),
1940 'category' => SettingsService::getTripCategoryBase(),
1941 ];
1942 $base = $map[$listing_type] ?? '';
1943 $base = preg_replace('/[^a-zA-Z0-9_-]/', '', (string) $base) ?: 'destination';
1944 $permalink_structure = (string) get_option('permalink_structure', '');
1945
1946 if ($permalink_structure === '') {
1947 $url = esc_url(add_query_arg('yatra_page', $base, home_url('/')));
1948 } else {
1949 $url = trailingslashit(home_url('/' . $base . '/'));
1950 }
1951
1952 return (string) apply_filters('yatra_taxonomy_listing_url', $url, $listing_type, $base);
1953 }
1954
1955 /**
1956 * Decode trips.price_types for listing-card logic (DB may store JSON string or array).
1957 *
1958 * @return array<int, array<string, mixed>>
1959 */
1960 function yatra_trip_listing_decode_price_types(object $trip): array
1961 {
1962 $pts = $trip->price_types ?? null;
1963 if (is_string($pts) && $pts !== '') {
1964 $decoded = json_decode($pts, true);
1965 $pts = is_array($decoded) ? $decoded : [];
1966 } elseif (!is_array($pts)) {
1967 $pts = [];
1968 }
1969 if ($pts === [] && method_exists($trip, 'getPriceTypes')) {
1970 $got = $trip->getPriceTypes();
1971 $pts = is_array($got) ? $got : [];
1972 }
1973
1974 return $pts;
1975 }
1976
1977 /**
1978 * Lowercase keys for traveler tier labels (used to strip mis-tagged classifications).
1979 *
1980 * @return array<string, true>
1981 */
1982 function yatra_trip_listing_traveler_tier_label_keys(object $trip): array
1983 {
1984 if (($trip->pricing_type ?? '') !== 'traveler_based') {
1985 return [];
1986 }
1987 $keys = [];
1988 foreach (yatra_trip_listing_decode_price_types($trip) as $pt) {
1989 if (!is_array($pt)) {
1990 continue;
1991 }
1992 foreach (['label', 'category_label', 'title'] as $k) {
1993 if (!empty($pt[$k]) && is_string($pt[$k])) {
1994 $t = strtolower(trim($pt[$k]));
1995 if ($t !== '') {
1996 $keys[$t] = true;
1997 }
1998 break;
1999 }
2000 }
2001 }
2002
2003 return $keys;
2004 }
2005
2006 /**
2007 * Ordered unique labels for the listing card “Traveler types” row.
2008 *
2009 * @return list<string>
2010 */
2011 function yatra_trip_listing_traveler_type_labels_for_card(object $trip): array
2012 {
2013 if (($trip->pricing_type ?? '') !== 'traveler_based') {
2014 return [];
2015 }
2016 $labels = [];
2017 $seen = [];
2018 foreach (yatra_trip_listing_decode_price_types($trip) as $pt) {
2019 if (!is_array($pt)) {
2020 continue;
2021 }
2022 foreach (['label', 'category_label', 'title'] as $k) {
2023 if (!empty($pt[$k]) && is_string($pt[$k])) {
2024 $lab = trim($pt[$k]);
2025 if ($lab === '') {
2026 break;
2027 }
2028 $lk = strtolower($lab);
2029 if (!isset($seen[$lk])) {
2030 $seen[$lk] = true;
2031 $labels[] = $lab;
2032 }
2033 break;
2034 }
2035 }
2036 }
2037
2038 return $labels;
2039 }
2040
2041 /**
2042 * Format start → end for listing cards; avoids repeating the same country when both
2043 * strings are "City, Country".
2044 */
2045 function yatra_format_trip_listing_route_line(string $start, string $end): string
2046 {
2047 $start = trim($start);
2048 $end = trim($end);
2049 if ($start === '') {
2050 return $end;
2051 }
2052 if ($end === '') {
2053 return $start;
2054 }
2055 if (strcasecmp($start, $end) === 0) {
2056 return $start;
2057 }
2058 if (strpos($start, ',') !== false && strpos($end, ',') !== false) {
2059 $s_parts = array_map('trim', explode(',', $start, 2));
2060 $e_parts = array_map('trim', explode(',', $end, 2));
2061 if (count($s_parts) === 2 && count($e_parts) === 2
2062 && strcasecmp($s_parts[1], $e_parts[1]) === 0) {
2063 return $s_parts[0] . '' . $e_parts[0] . ', ' . $s_parts[1];
2064 }
2065 }
2066
2067 return $start . '' . $end;
2068 }
2069
2070 /**
2071 * Human label for trip_type column (listing card meta).
2072 */
2073 function yatra_trip_listing_trip_type_label(?string $trip_type): string
2074 {
2075 $t = (string) $trip_type;
2076 $map = [
2077 'single_day' => __('Single day', 'yatra'),
2078 'multi_day' => __('Multi-day', 'yatra'),
2079 'flexible' => __('Flexible', 'yatra'),
2080 ];
2081
2082 return $map[$t] ?? '';
2083 }
2084
2085 /**
2086 * Rating block for listing cards: prefers SQL aggregates (average_rating, review_count)
2087 * when the hydrated reviews array is empty.
2088 *
2089 * @param array{has_rating: bool, average_rating: float, review_count: int, formatted_rating: string} $from_reviews
2090 * @return array{has_rating: bool, average_rating: float, review_count: int, formatted_rating: string}
2091 */
2092 function yatra_trip_listing_card_rating_data(object $trip, array $from_reviews): array
2093 {
2094 $has = !empty($from_reviews['has_rating']);
2095 $avg = (float) ($from_reviews['average_rating'] ?? 0);
2096 $cnt = (int) ($from_reviews['review_count'] ?? 0);
2097 $fmt = (string) ($from_reviews['formatted_rating'] ?? '0.0');
2098
2099 if ($cnt === 0 || !$has || $avg <= 0) {
2100 $q_avg = isset($trip->average_rating) ? (float) $trip->average_rating : null;
2101 $q_cnt = isset($trip->review_count) ? (int) $trip->review_count : null;
2102 if (($q_cnt === null || $q_cnt === 0) && isset($trip->reviews_count)) {
2103 $q_cnt = (int) $trip->reviews_count;
2104 }
2105 if ($q_cnt !== null && $q_cnt > 0 && $q_avg !== null && $q_avg > 0) {
2106 $avg = round($q_avg, 1);
2107 $cnt = $q_cnt;
2108 $fmt = number_format($avg, 1);
2109 $has = true;
2110 }
2111 }
2112
2113 return [
2114 'has_rating' => $has && $avg > 0 && $cnt > 0,
2115 'average_rating' => $avg,
2116 'review_count' => $cnt,
2117 'formatted_rating' => $fmt,
2118 ];
2119 }
2120
2121 /**
2122 * Avoid repeating the same classification label in the destination, activity, and category
2123 * rows on listing cards (traveler tier labels wrongly linked as classifications, or same
2124 * term attached in multiple roles).
2125 *
2126 * @param array<int, object> $destinations
2127 * @param array<int, object> $activities
2128 * @param array<int, object> $categories
2129 * @return array{0: array<int, object>, 1: array<int, object>, 2: array<int, object>}
2130 */
2131 function yatra_trip_listing_filter_classification_duplicates(array $destinations, array $activities, array $categories, object $trip): array
2132 {
2133 $tier_keys = yatra_trip_listing_traveler_tier_label_keys($trip);
2134
2135 $strip_tiers = static function (array $items) use ($tier_keys): array {
2136 if ($tier_keys === []) {
2137 return $items;
2138 }
2139
2140 return array_values(array_filter($items, static function ($item) use ($tier_keys) {
2141 $n = strtolower(trim((string) ($item->name ?? '')));
2142
2143 return $n === '' || !isset($tier_keys[$n]);
2144 }));
2145 };
2146
2147 $destinations = $strip_tiers($destinations);
2148 $activities = $strip_tiers($activities);
2149 $categories = $strip_tiers($categories);
2150
2151 $seen = [];
2152 $dedupe = static function (array $items) use (&$seen): array {
2153 $out = [];
2154 foreach ($items as $item) {
2155 $n = strtolower(trim((string) ($item->name ?? '')));
2156 if ($n === '') {
2157 $out[] = $item;
2158 continue;
2159 }
2160 if (isset($seen[$n])) {
2161 continue;
2162 }
2163 $seen[$n] = true;
2164 $out[] = $item;
2165 }
2166
2167 return $out;
2168 };
2169
2170 $destinations = $dedupe($destinations);
2171 $activities = $dedupe($activities);
2172 $categories = $dedupe($categories);
2173
2174 return [$destinations, $activities, $categories];
2175 }
2176
2177 /**
2178 * Check if we're on a trip listing page
2179 *
2180 * @return bool True if on a trip listing page
2181 */
2182 function yatra_is_trip_listing(): bool
2183 {
2184 global $yatra_trip_list;
2185
2186 // Check for trip list context (base trip listing page)
2187 if (!empty($yatra_trip_list)) {
2188 return true;
2189 }
2190
2191 // Check if we're on the main trips listing page
2192 $trip_base = SettingsService::getTripBase();
2193 $request_uri = $_SERVER['REQUEST_URI'] ?? '';
2194 $parsed_url = parse_url($request_uri, PHP_URL_PATH);
2195
2196 if ($parsed_url && strpos($parsed_url, '/' . $trip_base) === 0) {
2197 $path_parts = array_values(array_filter(explode('/', trim($parsed_url, '/'))));
2198 if ($path_parts === [] || ($path_parts[0] ?? '') !== $trip_base) {
2199 return false;
2200 }
2201 // /trip/ or /trip/page/2/ (WordPress paged archives)
2202 if (count($path_parts) === 1) {
2203 return true;
2204 }
2205 if (count($path_parts) === 3 && ($path_parts[1] ?? '') === 'page' && ctype_digit((string) ($path_parts[2] ?? ''))) {
2206 return true;
2207 }
2208 }
2209
2210 return false;
2211 }
2212
2213 /**
2214 * Check if we're on a taxonomy page (destination, activity, category)
2215 *
2216 * @return bool True if on a taxonomy page
2217 */
2218 function yatra_is_taxonomy_page(): bool
2219 {
2220 global $yatra_taxonomy_data;
2221 return !empty($yatra_taxonomy_data);
2222 }
2223
2224 /**
2225 * Check if we're on an activity listing page
2226 *
2227 * @return bool True if on an activity listing page
2228 */
2229 function yatra_is_activity_listing(): bool
2230 {
2231 return isset($_GET['yatra_page_type']) && $_GET['yatra_page_type'] === 'activities';
2232 }
2233
2234 /**
2235 * Check if we're on a destination listing page
2236 *
2237 * @return bool True if on a destination listing page
2238 */
2239 function yatra_is_destination_listing(): bool
2240 {
2241 return isset($_GET['yatra_page_type']) && $_GET['yatra_page_type'] === 'destinations';
2242 }
2243
2244 /**
2245 * Check if we're on an account page
2246 *
2247 * @return bool True if on an account page
2248 */
2249 function yatra_is_account_page(): bool
2250 {
2251 if (!empty($GLOBALS['yatra_loading_react_account_page'])) {
2252 return true;
2253 }
2254
2255 if ((string) get_query_var('yatra_account_page') !== '') {
2256 return true;
2257 }
2258
2259 global $post;
2260 if ($post && function_exists('has_shortcode') && isset($post->post_content)
2261 && has_shortcode((string) $post->post_content, 'yatra_my_account')) {
2262 return true;
2263 }
2264
2265 if (!$post) {
2266 return false;
2267 }
2268
2269 $accountPageId = get_option('yatra_my_account_page');
2270 return $accountPageId && (int) $post->ID === (int) $accountPageId;
2271 }
2272
2273 /**
2274 * Get difficulty level permalink
2275 *
2276 * @param object|int $difficulty Difficulty object with slug property, or difficulty ID
2277 * @return string Difficulty permalink URL
2278 */
2279 function yatra_get_difficulty_permalink($difficulty): string
2280 {
2281 if (is_numeric($difficulty)) {
2282 global $wpdb;
2283 $table = ClassificationsTable::getTableName();
2284 $difficulty = $wpdb->get_row($wpdb->prepare(
2285 "SELECT slug FROM {$table} WHERE id = %d AND type = %s",
2286 (int) $difficulty,
2287 ClassificationTypes::DIFFICULTY
2288 ));
2289 }
2290
2291 $slug = is_object($difficulty) ? ($difficulty->slug ?? '') : '';
2292
2293 if (empty($slug)) {
2294 return '';
2295 }
2296
2297 $base = SettingsService::getString('difficulty_base', 'difficulty');
2298
2299 return home_url('/' . $base . '/' . $slug . '/');
2300 }
2301
2302 /**
2303 * Load a template file with theme override support
2304 *
2305 * This function allows themes to override plugin templates by placing them in:
2306 * theme/yatra/template-name.php
2307 *
2308 * If no theme override exists, loads from plugin templates directory.
2309 *
2310 * @param string $template_name Template file name (without .php extension)
2311 * @param array $args Arguments to extract and make available in template
2312 * @param string $template_path Template path within plugin (default: 'templates/')
2313 * @param array $data Alternative data array (won't be extracted, available as $data)
2314 * @return void
2315 */
2316 function yatra_get_template(string $template_name, array $args = [], string $template_path = 'templates/', array $data = []): void
2317 {
2318 $template_name = ltrim($template_name, '/');
2319
2320 // Check if theme has override
2321 $theme_template = locate_template([
2322 'yatra/' . $template_name . '.php',
2323 'yatra/' . $template_name
2324 ]);
2325
2326 if ($theme_template) {
2327 // Load from theme
2328 $template_file = $theme_template;
2329 } else {
2330 // Load from plugin
2331 $template_file = YATRA_PLUGIN_PATH . ltrim($template_path, '/') . '/' . $template_name . '.php';
2332 }
2333
2334 // Extract arguments to make them available as individual variables
2335 if (!empty($args)) {
2336 extract($args);
2337 }
2338
2339 // Make data available as $data array (not extracted)
2340 if (!empty($data)) {
2341 $data = $data;
2342 }
2343
2344 // Include the template
2345 if (file_exists($template_file)) {
2346 include $template_file;
2347 }
2348 }
2349
2350 /**
2351 * Enqueue single trip scripts and styles
2352 *
2353 * @return void
2354 */
2355 function yatra_enqueue_single_trip_scripts(): void
2356 {
2357 // Only enqueue on single trip pages
2358 if (!is_single() || get_post_type() !== 'trip') {
2359 return;
2360 }
2361
2362 // Enqueue the single trip JavaScript
2363 wp_enqueue_script(
2364 'yatra-single-trip',
2365 YATRA_PLUGIN_URL . 'assets/js/single-trip.js',
2366 ['jquery', 'yatra-trip'],
2367 YATRA_VERSION,
2368 true
2369 );
2370
2371 // Localize script data
2372 global $trip;
2373 if ($trip) {
2374 wp_localize_script(
2375 'yatra-single-trip',
2376 'yatraSingleTripData',
2377 [
2378 'tripId' => (int) $trip->id,
2379 'basePrice' => (float) ($trip->base_price ?? 0),
2380 'currencySymbol' => yatra_get_currency_symbol(\Yatra\Services\SettingsService::getCurrency()),
2381 'apiUrls' => [
2382 'groupDiscounts' => rest_url('yatra/v1/discounts/group-discounts')
2383 ]
2384 ]
2385 );
2386 }
2387 }
2388
2389 /**
2390 * Calculate base price for single trip display using CalculationService
2391 *
2392 * @param object $trip Trip object
2393 * @return array Pricing data including base_price, has_availability, has_traveler_pricing, pricing_type
2394 */
2395 function yatra_single_trip_calculate_base_price($trip) {
2396 // Check if availability dates exist (PRIORITY)
2397 $has_availability = !empty($trip->availability_dates) && is_array($trip->availability_dates) && count($trip->availability_dates) > 0;
2398
2399 // Determine pricing type from trip settings
2400 $pricing_type = $trip->pricing_type ?? 'regular';
2401 $has_traveler_pricing = ($pricing_type === 'traveler_based' && !empty($trip->price_types));
2402
2403 // Use CalculationService for consistent pricing
2404 $calculationService = new \Yatra\Services\CalculationService();
2405
2406 // Determine base price using CalculationService logic
2407 $trip_price = 0;
2408
2409 if ($has_availability) {
2410 // Page-load pricing priority (traveler-based):
2411 // - If a default category is marked at trip-level, use that as the base price.
2412 // - Otherwise fall back to lowest price across availability (legacy behavior).
2413 $default_trip_price = 0.0;
2414 if ($has_traveler_pricing && !empty($trip->price_types) && is_array($trip->price_types)) {
2415 $default_price_type = null;
2416 foreach ($trip->price_types as $pt) {
2417 if (is_array($pt)) {
2418 $pt = (object) $pt;
2419 }
2420 if (!empty($pt->is_default)) {
2421 $default_price_type = $pt;
2422 break;
2423 }
2424 }
2425 if ($default_price_type) {
2426 $default_trip_price = (float) ($default_price_type->effective_price
2427 ?? $default_price_type->discounted_price
2428 ?? $default_price_type->original_price
2429 ?? 0);
2430 }
2431 }
2432
2433 if ($default_trip_price > 0) {
2434 $trip_price = $default_trip_price;
2435 } else {
2436 // Get the lowest price from availability dates
2437 $min_price = PHP_FLOAT_MAX;
2438 foreach ($trip->availability_dates as $avail) {
2439 $avail_price = $avail->effective_price ?? $avail->original_price ?? 0;
2440 if ($avail_price > 0 && $avail_price < $min_price) {
2441 $min_price = $avail_price;
2442 }
2443
2444 // Also check price_types within availability if traveler-based
2445 if (!empty($avail->price_types) && is_array($avail->price_types)) {
2446 foreach ($avail->price_types as $pt) {
2447 $pt = (object)$pt;
2448 $pt_price = (float)($pt->effective_price ?? $pt->discounted_price ?? $pt->original_price ?? 0);
2449 if ($pt_price > 0 && $pt_price < $min_price) {
2450 $min_price = $pt_price;
2451 }
2452 }
2453 }
2454 }
2455
2456 // If no price found from availability, check traveler-based pricing
2457 if ($min_price >= PHP_FLOAT_MAX && $has_traveler_pricing) {
2458 foreach ($trip->price_types as $pt) {
2459 $pt = is_array($pt) ? (object) $pt : $pt;
2460 $pt_price = (float)($pt->effective_price ?? $pt->discounted_price ?? $pt->original_price ?? 0);
2461 if ($pt_price > 0 && $pt_price < $min_price) {
2462 $min_price = $pt_price;
2463 }
2464 }
2465 }
2466
2467 $trip_price = ($min_price < PHP_FLOAT_MAX) ? $min_price : ($trip->sale_price ?: $trip->original_price);
2468 }
2469 } elseif ($has_traveler_pricing) {
2470 // Get default or first traveler category price
2471 $default_price_type = null;
2472 foreach ($trip->price_types as $pt) {
2473 if (!empty($pt->is_default)) {
2474 $default_price_type = $pt;
2475 break;
2476 }
2477 }
2478 if (!$default_price_type && !empty($trip->price_types)) {
2479 $default_price_type = $trip->price_types[0];
2480 }
2481
2482 // Get the price from the price type - check multiple possible fields
2483 if ($default_price_type) {
2484 $trip_price = 0;
2485 // Try effective_price first, then discounted_price, then original_price
2486 if (!empty($default_price_type->effective_price) && $default_price_type->effective_price > 0) {
2487 $trip_price = (float)$default_price_type->effective_price;
2488 } elseif (!empty($default_price_type->discounted_price) && $default_price_type->discounted_price > 0) {
2489 $trip_price = (float)$default_price_type->discounted_price;
2490 } elseif (!empty($default_price_type->original_price) && $default_price_type->original_price > 0) {
2491 $trip_price = (float)$default_price_type->original_price;
2492 } elseif (!empty($default_price_type->sale_price) && $default_price_type->sale_price > 0) {
2493 $trip_price = (float)$default_price_type->sale_price;
2494 }
2495
2496 // If still no price, try to get the minimum from all price types
2497 if ($trip_price <= 0) {
2498 foreach ($trip->price_types as $pt) {
2499 $pt_price = (float)($pt->effective_price ?? $pt->discounted_price ?? $pt->original_price ?? 0);
2500 if ($pt_price > 0 && ($trip_price <= 0 || $pt_price < $trip_price)) {
2501 $trip_price = $pt_price;
2502 }
2503 }
2504 }
2505 } else {
2506 $trip_price = $trip->sale_price ?: $trip->original_price;
2507 }
2508 } else {
2509 // Regular pricing
2510 $trip_price = $trip->sale_price > 0 ? $trip->sale_price : $trip->original_price;
2511 }
2512
2513 // Apply CalculationService filter for dynamic pricing (pro plugins)
2514 $base_price = apply_filters('yatra_calculate_base_amount', $trip_price, [
2515 'trip_price' => $trip_price,
2516 'travelers_count' => 1,
2517 'traveler_counts' => ['default' => 1],
2518 'pricing_type' => $pricing_type,
2519 'price_types' => $trip->price_types ?? [],
2520 'trip_id' => $trip->id ?? 0
2521 ]);
2522
2523 return [
2524 'base_price' => $base_price,
2525 'has_availability' => $has_availability,
2526 'has_traveler_pricing' => $has_traveler_pricing,
2527 'pricing_type' => $pricing_type
2528 ];
2529 }
2530
2531 /**
2532 * Get group discounts data for single trip
2533 *
2534 * @param int $trip_id Trip ID
2535 * @return array Group discounts data including has_group_discounts and group_discounts_data
2536 */
2537 function yatra_single_trip_get_group_discounts($trip_id) {
2538 $has_group_discounts = false;
2539 $group_discounts_data = [];
2540 $trip_id = (int) $trip_id;
2541
2542 if ($trip_id <= 0) {
2543 return [
2544 'has_group_discounts' => false,
2545 'group_discounts_data' => [],
2546 ];
2547 }
2548
2549 try {
2550 // Direct controller path avoids rest_do_request / loopback issues on single-trip templates.
2551 if (class_exists(\Yatra\Controllers\DiscountController::class)) {
2552 $ctrl = new \Yatra\Controllers\DiscountController();
2553 $payload = $ctrl->getPublicGroupDiscountDiscoverabilityForTrip($trip_id);
2554 $discounts = isset($payload['discounts']) && is_array($payload['discounts']) ? $payload['discounts'] : [];
2555 if (!empty($payload['has_group_discounts']) && $discounts !== []) {
2556 return [
2557 'has_group_discounts' => true,
2558 'group_discounts_data' => $discounts,
2559 ];
2560 }
2561 }
2562
2563 $row = null;
2564
2565 // Fallback: internal REST then HTTP (e.g. if controller unavailable).
2566 if (class_exists('\WP_REST_Request') && function_exists('rest_do_request')) {
2567 $request = new \WP_REST_Request('GET', '/yatra/v1/discounts/group-discounts');
2568 $request->set_param('trip_ids', [$trip_id]);
2569 $rest_response = rest_do_request($request);
2570 if ($rest_response instanceof \WP_REST_Response && $rest_response->get_status() === 200) {
2571 $row = yatra_single_trip_parse_group_discounts_payload($rest_response->get_data(), $trip_id);
2572 }
2573 }
2574
2575 if (!is_array($row)) {
2576 $api_url = add_query_arg(
2577 ['trip_ids' => [$trip_id]],
2578 rest_url('yatra/v1/discounts/group-discounts')
2579 );
2580 $response = wp_remote_get($api_url, [
2581 'timeout' => 6,
2582 'headers' => [
2583 'Accept' => 'application/json',
2584 ],
2585 ]);
2586
2587 if (!is_wp_error($response) && wp_remote_retrieve_response_code($response) === 200) {
2588 $data = json_decode(wp_remote_retrieve_body($response), true);
2589 $row = yatra_single_trip_parse_group_discounts_payload($data, $trip_id);
2590 }
2591 }
2592
2593 if (is_array($row) && !empty($row['has_group_discounts']) && !empty($row['discounts']) && is_array($row['discounts'])) {
2594 $has_group_discounts = true;
2595 $group_discounts_data = $row['discounts'];
2596 }
2597 } catch (Exception $e) {
2598 $has_group_discounts = false;
2599 }
2600
2601 return [
2602 'has_group_discounts' => $has_group_discounts,
2603 'group_discounts_data' => $group_discounts_data,
2604 ];
2605 }
2606
2607 /**
2608 * Extract the per-trip object from a group-discounts REST payload (handles optional wrappers).
2609 *
2610 * @param mixed $data
2611 * @return array<string, mixed>|null
2612 */
2613 function yatra_single_trip_parse_group_discounts_payload($data, int $trip_id): ?array {
2614 if (!is_array($data)) {
2615 return null;
2616 }
2617 if (isset($data['data']) && is_array($data['data'])) {
2618 $data = $data['data'];
2619 }
2620 $keyStr = (string) $trip_id;
2621 $row = $data[$trip_id] ?? $data[$keyStr] ?? null;
2622
2623 return is_array($row) ? $row : null;
2624 }
2625
2626 /**
2627 * Payload for single-trip booking UI JS (sidebar date/traveler pricing + group tiers).
2628 * Kept in yatraTripData instead of large HTML data-* attributes on .yatra-booking-card.
2629 *
2630 * @param object $trip Trip model
2631 * @return array{pricingType: string, sidebarAvailability: array<int, array<string, mixed>>, sidebarGroupDiscounts: array<int, array<string, mixed>>}
2632 */
2633 function yatra_single_trip_get_client_booking_payload($trip): array {
2634 $empty = [
2635 'pricingType' => 'regular',
2636 'sidebarAvailability' => [],
2637 'sidebarGroupDiscounts' => [],
2638 ];
2639
2640 if (!is_object($trip) || empty($trip->id)) {
2641 return $empty;
2642 }
2643
2644 $pricing_data = function_exists('yatra_single_trip_calculate_base_price')
2645 ? yatra_single_trip_calculate_base_price($trip)
2646 : ['has_availability' => false, 'pricing_type' => $trip->pricing_type ?? 'regular'];
2647
2648 $pricing_type = (string) ($pricing_data['pricing_type'] ?? ($trip->pricing_type ?? 'regular'));
2649 $has_availability = !empty($pricing_data['has_availability']);
2650
2651 $availability = [];
2652 if ($has_availability && method_exists($trip, 'getAvailabilityDates')) {
2653 foreach ($trip->getAvailabilityDates() as $avail) {
2654 if (!is_object($avail)) {
2655 continue;
2656 }
2657 $price_types_raw = !empty($avail->price_types) && is_array($avail->price_types) ? $avail->price_types : [];
2658 $price_types = [];
2659 foreach ($price_types_raw as $pt) {
2660 if (is_object($pt)) {
2661 $decoded = json_decode(wp_json_encode($pt), true);
2662 $price_types[] = is_array($decoded) ? $decoded : [];
2663 } elseif (is_array($pt)) {
2664 $price_types[] = $pt;
2665 }
2666 }
2667
2668 $availability[] = [
2669 'id' => (int) ($avail->id ?? 0),
2670 'date' => $avail->departure_date ?? '',
2671 'departure_date' => $avail->departure_date ?? '',
2672 'return_date' => (isset($avail->return_date) && $avail->return_date !== '')
2673 ? $avail->return_date
2674 : (isset($avail->arrival_date) ? $avail->arrival_date : null),
2675 'price' => $avail->effective_price ?? $avail->original_price ?? 0,
2676 'original_price' => $avail->original_price ?? 0,
2677 'discounted_price' => $avail->discounted_price ?? null,
2678 'seats_available' => $avail->seats_available ?? 0,
2679 'seats_total' => $avail->seats_total ?? 0,
2680 'status' => $avail->status ?? '',
2681 'is_limited' => (bool) ($avail->is_limited ?? false),
2682 'is_sold_out' => (bool) ($avail->is_sold_out ?? false),
2683 'pricing_type' => $price_types !== [] ? 'traveler_based' : $pricing_type,
2684 'price_types' => $price_types,
2685 ];
2686 }
2687 }
2688
2689 $sidebar_group_discounts = [];
2690 if (function_exists('yatra_single_trip_get_group_discounts')) {
2691 $gd = yatra_single_trip_get_group_discounts((int) $trip->id);
2692 $cards = isset($gd['group_discounts_data']) && is_array($gd['group_discounts_data'])
2693 ? $gd['group_discounts_data']
2694 : [];
2695 $sidebar_group_discounts = apply_filters('yatra_advanced_discount_enabled', false) ? $cards : [];
2696 $sidebar_group_discounts = array_values(array_map(static function ($row) {
2697 if (is_object($row)) {
2698 $decoded = json_decode(wp_json_encode($row), true);
2699
2700 return is_array($decoded) ? $decoded : [];
2701 }
2702
2703 return $row;
2704 }, $sidebar_group_discounts));
2705 }
2706
2707 return [
2708 'pricingType' => $pricing_type,
2709 'sidebarAvailability' => $availability,
2710 'sidebarGroupDiscounts' => $sidebar_group_discounts,
2711 ];
2712 }
2713
2714 // Hook into WordPress enqueue system
2715 add_action('wp_enqueue_scripts', 'yatra_enqueue_single_trip_scripts');
2716
2717 // Yatra page type detection functions
2718 if (!function_exists('yatra_is_trip_page')) {
2719 function yatra_is_trip_page() {
2720 global $trip;
2721 return isset($trip) && !empty($trip);
2722 }
2723 }
2724
2725 if (!function_exists('yatra_is_destination_page')) {
2726 function yatra_is_destination_page() {
2727 global $destination, $yatra_taxonomy_data;
2728
2729 // Check direct global first
2730 if (isset($destination) && !empty($destination)) {
2731 return true;
2732 }
2733
2734 // Check taxonomy data
2735 if (isset($yatra_taxonomy_data) && !empty($yatra_taxonomy_data) && $yatra_taxonomy_data->type === 'destination') {
2736 return true;
2737 }
2738
2739 return false;
2740 }
2741 }
2742
2743 if (!function_exists('yatra_is_activity_page')) {
2744 function yatra_is_activity_page() {
2745 global $activity, $yatra_taxonomy_data;
2746
2747 // Check direct global first
2748 if (isset($activity) && !empty($activity)) {
2749 return true;
2750 }
2751
2752 // Check taxonomy data
2753 if (isset($yatra_taxonomy_data) && !empty($yatra_taxonomy_data) && $yatra_taxonomy_data->type === 'activity') {
2754 return true;
2755 }
2756
2757 return false;
2758 }
2759 }
2760
2761 if (!function_exists('yatra_is_category_page')) {
2762 function yatra_is_category_page() {
2763 global $category, $yatra_taxonomy_data;
2764
2765 // Check direct global first
2766 if (isset($category) && !empty($category)) {
2767 return true;
2768 }
2769
2770 // Check taxonomy data
2771 if (isset($yatra_taxonomy_data) && !empty($yatra_taxonomy_data) && $yatra_taxonomy_data->type === 'category') {
2772 return true;
2773 }
2774
2775 return false;
2776 }
2777 }
2778
2779 if (!function_exists('yatra_is_trip_archive_page')) {
2780 function yatra_is_trip_archive_page() {
2781 $current_url = $_SERVER['REQUEST_URI'] ?? '';
2782 $current_path = parse_url($current_url, PHP_URL_PATH) ?? '';
2783 $trip_base = \Yatra\Services\SettingsService::getTripBase();
2784
2785 // Check for both /trip/ and /trip patterns
2786 $pattern1 = '/' . $trip_base . '/';
2787 $pattern2 = '/' . $trip_base;
2788
2789 return (strpos($current_path, $pattern1) !== false || $current_path === $pattern2) && !yatra_is_trip_page();
2790 }
2791 }
2792
2793 // Yatra only has trip archive pages - no destination/activity/category archive pages
2794
2795 if (!function_exists('yatra_is_listing_page')) {
2796 function yatra_is_listing_page() {
2797 $current_url = $_SERVER['REQUEST_URI'] ?? '';
2798 $current_path = parse_url($current_url, PHP_URL_PATH) ?? '';
2799 return strpos($current_path, '/listing-') !== false;
2800 }
2801 }
2802
2803 if (!function_exists('yatra_is_yatra_page')) {
2804 function yatra_is_yatra_page() {
2805 return yatra_is_trip_page() ||
2806 yatra_is_destination_page() ||
2807 yatra_is_activity_page() ||
2808 yatra_is_category_page() ||
2809 yatra_is_trip_archive_page() ||
2810 yatra_is_listing_page();
2811 }
2812 }
2813
2814 if ( ! function_exists( 'yatra_get_header' ) ) {
2815
2816 function yatra_get_header( $header_name = null ) {
2817 global $wp_version;
2818
2819 // When the template is being rendered as the body of the yatra/page-content
2820 // server block inside a block-template canvas, the canvas already emits the
2821 // doctype/html/head/body and the site header template part. Re-emitting them
2822 // here would nest <html>/<body> and duplicate the header — so we no-op.
2823 if (
2824 class_exists( '\\Yatra\\Core\\Template\\FseTemplates' )
2825 && \Yatra\Core\Template\FseTemplates::isRenderingInsideCanvas()
2826 ) {
2827 return;
2828 }
2829
2830 if (
2831 version_compare( $wp_version, '5.9', '>=' ) &&
2832 function_exists( 'wp_is_block_theme' ) &&
2833 wp_is_block_theme()
2834 ) {
2835 /*
2836 * Full-site editing themes often omit add_theme_support( 'title-tag' ); the document title is
2837 * injected via template canvas using _block_template_render_title_tag (unconditional). Yatra
2838 * renders this minimal head instead of canvas, so _wp_render_title_tag would no-op and the
2839 * page would have no <title>. Mirror canvas: print title here and drop duplicate core hooks.
2840 */
2841 remove_action( 'wp_head', '_wp_render_title_tag', 1 );
2842 remove_action( 'wp_head', '_block_template_render_title_tag', 1 );
2843 ?>
2844 <!doctype html>
2845 <html <?php language_attributes(); ?>>
2846 <head>
2847 <meta charset="<?php bloginfo( 'charset' ); ?>">
2848 <title><?php echo esc_html( wp_get_document_title() ); ?></title>
2849 <?php wp_head(); ?>
2850 </head>
2851
2852 <body <?php body_class(); ?>>
2853 <?php wp_body_open(); ?>
2854 <div class="wp-site-blocks">
2855 <header class="wp-block-template-part site-header">
2856 <?php block_header_area(); ?>
2857 </header>
2858 <?php
2859 } else {
2860 get_header( $header_name );
2861 }
2862 }
2863 }
2864
2865 if ( ! function_exists( 'yatra_block_support_styles' ) ) {
2866 function yatra_block_support_styles() {
2867 // Bail early if function does not exists.
2868 if ( ! function_exists( 'wp_style_engine_get_stylesheet_from_context' ) ) {
2869 return;
2870 }
2871
2872 $core_styles_keys = array( 'block-supports' );
2873
2874 $compiled_core_stylesheet = '';
2875
2876 foreach ( $core_styles_keys as $style_key ) {
2877 $compiled_core_stylesheet .= wp_style_engine_get_stylesheet_from_context( $style_key, array() );
2878 }
2879
2880 if ( empty( $compiled_core_stylesheet ) ) {
2881 return;
2882 }
2883
2884 wp_register_style( 'yatra-block-supports', false );
2885 wp_enqueue_style( 'yatra-block-supports' );
2886 wp_add_inline_style( 'yatra-block-supports', $compiled_core_stylesheet );
2887 }
2888 }
2889
2890 if ( ! function_exists( 'yatra_get_footer' ) ) {
2891
2892 function yatra_get_footer( $footer_name = null ) {
2893 global $wp_version;
2894
2895 // Mirror of yatra_get_header(): when rendered inside the FSE canvas via
2896 // the yatra/page-content block, the canvas already emits the footer
2897 // template part and closes <body>/<html>. No-op here to avoid duplicates.
2898 if (
2899 class_exists( '\\Yatra\\Core\\Template\\FseTemplates' )
2900 && \Yatra\Core\Template\FseTemplates::isRenderingInsideCanvas()
2901 ) {
2902 return;
2903 }
2904
2905 if (
2906 version_compare( $wp_version, '5.9', '>=' ) &&
2907 function_exists( 'wp_is_block_theme' ) &&
2908 wp_is_block_theme()
2909 ) {
2910 ?>
2911 <footer class="wp-block-template-part site-footer">
2912 <?php block_footer_area(); ?>
2913 </footer>
2914 </div>
2915 <?php yatra_block_support_styles(); ?>
2916 <?php wp_footer(); ?>
2917 </body>
2918 </html>
2919 <?php
2920 } else {
2921 get_footer( $footer_name );
2922 }
2923 }
2924 }
2925
2926 /**
2927 * Render tab icon (supports both SVG icons and images)
2928 *
2929 * @param mixed $icon_data Icon data (string, array, or object)
2930 * @param string $default_icon Default icon name
2931 * @param string $css_class CSS class for the icon
2932 * @param string $label Label for alt text
2933 * @return void Echoes the icon HTML
2934 */
2935 if (!function_exists('yatra_render_tab_icon')) {
2936 function yatra_render_tab_icon($icon_data, $default_icon = 'book', $css_class = '', $label = '') {
2937 if (empty($icon_data)) {
2938 echo function_exists('yatra_svg_icon') ? yatra_svg_icon($default_icon, $css_class) : '';
2939
2940 return;
2941 }
2942 if (is_string($icon_data) && strpos($icon_data, '{') === 0) {
2943 $icon_data = json_decode($icon_data, true);
2944 }
2945 if (is_object($icon_data)) {
2946 $icon_data = (array) $icon_data;
2947 }
2948 if (is_array($icon_data) && isset($icon_data['type']) && $icon_data['type'] === 'image' && !empty($icon_data['value'])) {
2949 $image_url = is_numeric($icon_data['value'])
2950 ? wp_get_attachment_url((int) $icon_data['value'])
2951 : $icon_data['value'];
2952 if ($image_url) {
2953 $size_style = strpos($css_class, 'sticky-nav') !== false ? 'width: 18px; height: 18px;' : 'width: 24px; height: 24px;';
2954 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;">';
2955
2956 return;
2957 }
2958 }
2959 // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped -- markup built from sanitized picker / SVG registry
2960 echo yatra_stored_picker_icon_markup($icon_data, $default_icon, $css_class);
2961 }
2962 }
2963
2964 if (!function_exists('yatra_listing_sidebar_filter_visible_cap')) {
2965 /**
2966 * How many sidebar checkbox rows to show before "Show more" on the trip listing.
2967 *
2968 * Filter: {@see 'yatra_listing_sidebar_filter_visible_count'} — default 8, clamped 3–40.
2969 *
2970 * @return int
2971 */
2972 function yatra_listing_sidebar_filter_visible_cap(): int
2973 {
2974 $n = (int) apply_filters('yatra_listing_sidebar_filter_visible_count', 8);
2975
2976 return max(3, min(40, $n));
2977 }
2978 }
2979
2980 if (!function_exists('yatra_wishlist_enabled')) {
2981 /**
2982 * Whether wishlist UI and REST should be active (Yatra Pro + setting).
2983 */
2984 function yatra_wishlist_enabled(): bool
2985 {
2986 return \Yatra\Services\SettingsService::wishlistEnabled();
2987 }
2988 }
2989
2990 if (!function_exists('yatra_usage_track_event')) {
2991 /**
2992 * Record an anonymous product telemetry event (requires opt-in).
2993 *
2994 * @param string $event Event key (sanitized).
2995 * @param int $delta Counter increment.
2996 */
2997 function yatra_usage_track_event(string $event, int $delta = 1): void
2998 {
2999 if (!class_exists(\Yatra\Services\StatsUsage::class)) {
3000 return;
3001 }
3002 \Yatra\Services\StatsUsage::instance()->record_event($event, $delta);
3003 }
3004 }
3005