66 lines
2 KiB
PHP
66 lines
2 KiB
PHP
|
|
<?php
|
||
|
|
|
||
|
|
namespace App\Domain\Trip\Services;
|
||
|
|
|
||
|
|
use App\Models\Trip;
|
||
|
|
use App\Models\CalendarSlot;
|
||
|
|
use Carbon\Carbon;
|
||
|
|
use Illuminate\Support\Collection;
|
||
|
|
|
||
|
|
class CalendarSlotService
|
||
|
|
{
|
||
|
|
public function createOrUpdateSlotsForTrip(Trip $trip): Collection
|
||
|
|
{
|
||
|
|
if (!$trip->start_date || !$trip->end_date) {
|
||
|
|
return collect();
|
||
|
|
}
|
||
|
|
|
||
|
|
$existingSlots = $trip->calendarSlots;
|
||
|
|
$existingSlotsMap = $existingSlots->keyBy('slot_date');
|
||
|
|
|
||
|
|
$startDate = Carbon::parse($trip->start_date);
|
||
|
|
$endDate = Carbon::parse($trip->end_date);
|
||
|
|
|
||
|
|
$newSlots = collect();
|
||
|
|
$currentDate = $startDate->copy();
|
||
|
|
$dayNumber = 1;
|
||
|
|
|
||
|
|
while ($currentDate->lte($endDate)) {
|
||
|
|
$slotDate = $currentDate->toDateString();
|
||
|
|
|
||
|
|
if (!$existingSlotsMap->has($slotDate)) {
|
||
|
|
$slot = CalendarSlot::create([
|
||
|
|
'trip_id' => $trip->id,
|
||
|
|
'name' => 'Day ' . $dayNumber,
|
||
|
|
'slot_date' => $slotDate,
|
||
|
|
'datetime_start' => $currentDate->copy()->startOfDay(),
|
||
|
|
'datetime_end' => $currentDate->copy()->endOfDay(),
|
||
|
|
'slot_order' => $dayNumber,
|
||
|
|
]);
|
||
|
|
$newSlots->push($slot);
|
||
|
|
} else {
|
||
|
|
$existingSlot = $existingSlotsMap->get($slotDate);
|
||
|
|
$existingSlot->update([
|
||
|
|
'slot_order' => $dayNumber,
|
||
|
|
'datetime_start' => $currentDate->copy()->startOfDay(),
|
||
|
|
'datetime_end' => $currentDate->copy()->endOfDay(),
|
||
|
|
]);
|
||
|
|
$newSlots->push($existingSlot);
|
||
|
|
}
|
||
|
|
|
||
|
|
$currentDate->addDay();
|
||
|
|
$dayNumber++;
|
||
|
|
}
|
||
|
|
|
||
|
|
$trip->calendarSlots()
|
||
|
|
->whereNotIn('slot_date', $newSlots->pluck('slot_date'))
|
||
|
|
->delete();
|
||
|
|
|
||
|
|
return $newSlots;
|
||
|
|
}
|
||
|
|
|
||
|
|
public function deleteSlotsForTrip(Trip $trip): void
|
||
|
|
{
|
||
|
|
$trip->calendarSlots()->delete();
|
||
|
|
}
|
||
|
|
}
|