<?php

namespace App\Http\Resources;

use App\Models\UserFlight;
use Carbon\Carbon;
use Illuminate\Http\Resources\Json\JsonResource;

/** @mixin UserFlight */
class UserFlightResource extends JsonResource
{
    public function toArray($request): array
    {
        $departureTz = $this->departureAirport->timezone;
        $arrivalTz   = $this->arrivalAirport->timezone;
        $duration = $this->departure_date->diffInMinutes($this->arrival_date);
        $hours   = intdiv($duration, 60);
        $minutes = $duration % 60;
        $durationDisplay = $hours . 'h ' . str_pad($minutes, 2, '0', STR_PAD_LEFT) . 'm';

        $departureLocal = $this->departure_date->copy()->setTimezone($departureTz);
        $arrivalLocal   = $this->arrival_date?->copy()->setTimezone($arrivalTz);

        $distance = $this->calculateGreatCircleDistance();

        $dayDifference = (int) abs(Carbon::parse($arrivalLocal->toDateString())
            ->diffInDays(Carbon::parse($departureLocal->toDateString())));


        return [
            ...$this->resource->toArray(),
            'departure_date_display' => $departureLocal->format('j M Y'),
            'departure_time_display' => $departureLocal->format('g:iA'),
            'arrival_date_display'   => $arrivalLocal?->format('j M Y'),
            'arrival_time_display'   => $arrivalLocal?->format('g:iA'),
            'arrival_day_difference' => $dayDifference,
            'duration' => $duration,
            'duration_display' => $durationDisplay,
            'distance' => $distance,
        ];
    }
}
