trip-planner/backend/app/Infrastructure/Http/Controllers/API/CalendarSlot/CalendarSlotController.php

81 lines
2.7 KiB
PHP
Raw Normal View History

2025-09-28 13:31:43 +02:00
<?php
namespace App\Infrastructure\Http\Controllers\API\CalendarSlot;
use App\Domain\CalendarSlot\Policies\CalendarSlotPolicy;
2025-09-28 13:31:43 +02:00
use App\Infrastructure\Http\Controllers\Controller;
use App\Models\CalendarSlot;
use App\Models\Trip;
use App\Models\PlannedItem;
use Illuminate\Http\Request;
use Illuminate\Http\JsonResponse;
class CalendarSlotController extends Controller
{
public function __construct(
private CalendarSlotPolicy $policy
) {}
2025-09-28 13:31:43 +02:00
public function index(Trip $trip): JsonResponse
{
if (!$this->policy->viewAny(auth()->user(), $trip)) {
2025-09-30 08:29:17 +02:00
return response()->json(['message' => 'Forbidden'], 403);
}
2025-09-28 13:31:43 +02:00
$calendarSlots = $trip->calendarSlots()
->with(['plannedItems.plannableItem'])
->orderBy('slot_date')
->orderBy('datetime_start')
2025-09-28 13:31:43 +02:00
->get();
2025-09-30 08:29:17 +02:00
return response()->json(['data' => $calendarSlots]);
2025-09-28 13:31:43 +02:00
}
public function update(Request $request, CalendarSlot $calendarSlot): JsonResponse
{
if (!$this->policy->update(auth()->user(), $calendarSlot)) {
2025-09-30 08:29:17 +02:00
return response()->json(['message' => 'Forbidden'], 403);
}
2025-09-28 13:31:43 +02:00
$validated = $request->validate([
'name' => 'sometimes|required|string|max:255',
]);
$calendarSlot->update($validated);
2025-09-30 08:29:17 +02:00
return response()->json(['data' => $calendarSlot]);
2025-09-28 13:31:43 +02:00
}
public function reorder(Request $request, CalendarSlot $calendarSlot): JsonResponse
{
if (!$this->policy->reorder(auth()->user(), $calendarSlot)) {
return response()->json(['message' => 'Forbidden'], 403);
}
2025-09-28 13:31:43 +02:00
$validated = $request->validate([
'items' => 'required|array',
'items.*.plannable_item_id' => 'required|exists:plannable_items,id',
'items.*.sort_order' => 'required|integer',
]);
// Validate all plannable items belong to the same trip
$trip = $calendarSlot->trip;
$validPlannableItemIds = $trip->plannableItems()->pluck('id')->toArray();
2025-09-28 13:31:43 +02:00
foreach ($validated['items'] as $item) {
if (!in_array($item['plannable_item_id'], $validPlannableItemIds)) {
return response()->json(['message' => 'Invalid plannable item for this trip'], 422);
}
2025-09-28 13:31:43 +02:00
}
// Update sort orders in transaction
\DB::transaction(function () use ($validated, $calendarSlot) {
foreach ($validated['items'] as $item) {
PlannedItem::where('calendar_slot_id', $calendarSlot->id)
->where('plannable_item_id', $item['plannable_item_id'])
->update(['sort_order' => $item['sort_order']]);
}
});
2025-09-28 13:31:43 +02:00
return response()->json(['message' => 'Items reordered successfully']);
}
}