<?php

namespace App\Observers;

use Mtc\Crm\Traits\RetrievesCustomerId;
use Mtc\VehicleReservations\Reservation;

class ReservationObserver
{
    use RetrievesCustomerId;

    public function saving(Reservation $reservation)
    {
        if ($reservation->isDirty('ingested_at') && empty($reservation->getOriginal('ingested_at'))) {
            $reservation->customer_id = $this->getCustomerId($reservation->email, $this->getDetails($reservation));
        }
    }

    private function getDetails(Reservation $reservation): array
    {
        $details = [];
        $name = explode(' ', $reservation->name);
        $details['phone_number'] = $reservation->contact_number;
        $details['first_name'] = array_shift($name);
        if (!empty($name)) {
            $details['last_name'] = implode(' ', $name);
        }

        return $details;
    }
}
