<?php

namespace Database\Seeders;

use Illuminate\Database\Console\Seeds\WithoutModelEvents;
use Illuminate\Database\Seeder;
use App\Models\Equipment;
use App\Models\TimeSlot;
use Carbon\Carbon;

class TimeSlotSeeder extends Seeder
{
    /**
     * Run the database seeds.
     */
    public function run(): void
    {
        $equipment = Equipment::active()->get();
        
        // Generate time slots for the next 30 days
        $startDate = now()->startOfDay();
        $endDate = now()->addDays(30)->endOfDay();
        
        foreach ($equipment as $item) {
            $currentDate = $startDate->copy();
            
            while ($currentDate <= $endDate) {
                $this->generateTimeSlotsForDate($item, $currentDate);
                $currentDate->addDay();
            }
        }
        
        $this->command->info('Time slots generated successfully!');
    }
    
    /**
     * Generate time slots for a specific equipment and date.
     */
    private function generateTimeSlotsForDate(Equipment $equipment, Carbon $date): void
    {
        $startTime = Carbon::parse($equipment->start_time);
        $endTime = Carbon::parse($equipment->end_time);
        $slotDuration = $equipment->slot_duration;
        
        $currentTime = $startTime->copy();
        
        while ($currentTime < $endTime) {
            $slotEndTime = $currentTime->copy()->addMinutes($slotDuration);
            
            // Check if this slot is already reserved
            $existingReservation = $equipment->reservations()
                ->where('reservation_date', $date->toDateString())
                ->where('start_time', $currentTime->format('H:i'))
                ->where('status', 'confirmed')
                ->first();
            
            $status = $existingReservation ? 'reserved' : 'available';
            $reservationId = $existingReservation ? $existingReservation->id : null;
            
            TimeSlot::updateOrCreate(
                [
                    'equipment_id' => $equipment->id,
                    'slot_date' => $date->toDateString(),
                    'start_time' => $currentTime->format('H:i'),
                ],
                [
                    'end_time' => $slotEndTime->format('H:i'),
                    'status' => $status,
                    'reservation_id' => $reservationId,
                ]
            );
            
            $currentTime->addMinutes($slotDuration);
        }
    }
}
