<?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.
     */
    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;
            }
        }
    }
}
