<?php

namespace App\Http\Controllers;

use App\Models\User;
use App\Models\UserFlight;
use App\Http\Resources\UserFlightResource;
use Illuminate\Support\Facades\DB;
use Inertia\Inertia;

class FlightProfileController extends Controller
{
    public function profileData(string $username, string $view, ?int $selectedFlightId = null) : array {
        $user = User::whereRaw(DB::raw('LOWER(name) = ?'), [strtolower($username)])->firstOrFail();

        $flights = UserFlight::where('user_id', $user->id)
            ->with([
                'departureAirport.region.country',
                'departureAirport.region.continent',
                'arrivalAirport.region.country',
                'arrivalAirport.region.continent',
                'airline.country',
                'aircraft',
                'seatType',
                'flightReason',
                'flightClass',
                'crewType'
            ])
            ->orderBy('departure_date', 'desc')
            ->get();

        return [
            'user' => $user,
            'canEdit' => auth()->check() && auth()->id() === $user->id,
            'flights' => UserFlightResource::collection($flights)->resolve(),
            'initialView' => $view,
            'selectedFlightId' => $selectedFlightId,
        ];
    }

    public function departureBoard(string $username, ?UserFlight $flight = null){
        $profileData = $this->profileData($username, 'board', $flight?->id);
        return Inertia::render('UserProfile', $profileData);
    }

    public function map(string $username){
        $profileData = $this->profileData($username, 'map');
        return Inertia::render('UserProfile', $profileData);
    }

    public function boardingPasses(string $username){
        $profileData = $this->profileData($username, 'passes');
        return Inertia::render('UserProfile', $profileData);
    }

    public function view(string $username)
    {
        return $this->departureBoard($username);
    }
}
