<?php

namespace App\Libraries;

/**
 * Display helpers when trips and subtrips are joined (subtrips.* overwrites trips.*).
 */
class TripDisplaySupport
{
    /**
     * SQL fragment: keep parent trip distance/hours before subtrips.* clobbers trips.distance.
     */
    public static function parentMetricsSelectFragment(): string
    {
        return 'trips.distance AS trip_distance, trips.journey_hour AS trip_journey_hour';
    }

    /**
     * Use subtrip distance/hours when set; otherwise fall back to parent trip row.
     */
    /**
     * Label shown for boarding/dropping points on the website and API.
     * Stand name is the primary identifier; detail is optional extra notes.
     */
    public static function resolvePickdropPlaceLabel($row): string
    {
        $standName = trim((string) ($row->stand_name ?? $row->name ?? ''));
        $detail    = trim((string) ($row->detail ?? ''));

        if ($standName !== '') {
            return $standName;
        }

        return $detail;
    }

    public static function applyParentTripDistanceAndHours(object $row): void
    {
        $distance = trim((string) ($row->distance ?? ''));
        if ($distance === '' || $distance === '0') {
            $parentDistance = trim((string) ($row->trip_distance ?? ''));
            if ($parentDistance !== '' && $parentDistance !== '0') {
                $row->distance = $parentDistance;
            }
        }

        $hours = trim((string) ($row->journey_hour ?? ''));
        if ($hours === '' || $hours === '0') {
            $parentHours = trim((string) ($row->trip_journey_hour ?? ''));
            if ($parentHours !== '' && $parentHours !== '0') {
                $row->journey_hour = $parentHours;
            }
        }
    }
}
