<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\HasMany;
use Illuminate\Database\Eloquent\SoftDeletes;

/**
 * @property mixed replies
 */
class WorkDay extends Model
{
    //use soft delete
    use SoftDeletes;

    protected $fillable = [
        'day',
        'start_time',
        'end_time',
    ];

    //
    public function getTimeSlotsAttribute()
    {

        // Create DateTime objects for the start and end times
        $startTime= $this->start_time;
        $endTime= $this->end_time;

        $startTime= date('Y-m-d').' '. $startTime;
        $endTime= date('Y-m-d').' '. $endTime;
        $start = new \DateTime($startTime);
        $end = new \DateTime($endTime);
        // If the end time is earlier in the day than the start time,
        // assume the end time is on the next day
        if ($end < $start) {
            $end->modify('+1 day');
        }
        // dd($start, $end);
        // Add one hour to end time to include it in the period
        // $end->modify('+1 hour');

        // Create a DateInterval of 1 hour
        $periodInMinutes= 60*settings('pickup_hours');
        $interval = new \DateInterval('PT'.$periodInMinutes.'M');

        // Create a DatePeriod to iterate over each hour between start and end
        $period = new \DatePeriod($start, $interval, $end);
        // Initialize an array to hold the times and end times
        $times = [];
        $fullTimes = [];
        $startTimes = [];
        $endTimes = [];

        // Loop through the DatePeriod and add each period to the array
        foreach ($period as $time) {
            $times[] = $time->format('H:i');
            $fullTimes[] = $time->format('Y-m-d H:i');
            $startTimes[] = $time->format('g:i A');

            // Create a new DateTime object for each time and add 30 minutes
            $endTimeObj = clone $time;  // Clone to avoid modifying the original object
            $endTimeObj->add(new \DateInterval('PT'.$periodInMinutes.'M'));
            $endTimes[] = $endTimeObj->format('g:i A');
        }
        return [$startTimes, $endTimes, $times, $fullTimes];
    }

}
