<?php

namespace App\Services;

use App\Models\Service;
use Carbon\Carbon;

class AppointmentSlotService
{
    public function calculateServiceSlots(string $date, string $startTime, array $serviceItems): array
    {
        $current = Carbon::parse($date . ' ' . $startTime);
        $slots = [];
        foreach ($serviceItems as $item) {
            $service = isset($item['service']) ? $item['service'] : Service::find($item['service_id'] ?? 0);
            if (!$service) {
                continue;
            }
            $duration = (int) ($item['duration_minutes'] ?? $service->duration_minutes);
            $buffer = (int) ($item['buffer_minutes'] ?? $service->buffer_minutes);
            $slotStart = $current->format('H:i');
            $current->addMinutes($duration + $buffer);
            $slotEnd = $current->format('H:i');
            $slots[] = [
                'service_id' => $service->id,
                'assigned_staff_id' => $item['assigned_staff_id'] ?? null,
                'price' => $item['price'] ?? $service->price,
                'duration_minutes' => $duration,
                'start_time' => $slotStart,
                'end_time' => $slotEnd,
            ];
        }
        return $slots;
    }

    public function calculateEndTime(string $startTime, array $serviceItems): string
    {
        $slots = $this->calculateServiceSlots(date('Y-m-d'), $startTime, $serviceItems);
        return $slots ? end($slots)['end_time'] : $startTime;
    }
}
