PluginProbe
Yatra – Travel Booking & Tour Operator Software / 3.0.15
Yatra – Travel Booking & Tour Operator Software v3.0.15
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.15, at includes/helpers.php

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