m2geval / php /laravel-zap_function_bench.jsonl
Tswatery's picture
Add files using upload-large-folder tool
25b3e24 verified
{"repo_name": "laravel-zap", "file_name": "/laravel-zap/src/Models/SchedulePeriod.php", "inference_info": {"prefix_code": "<?php\n\nnamespace Zap\\Models;\n\nuse Carbon\\Carbon;\nuse Illuminate\\Database\\Eloquent\\Model;\nuse Illuminate\\Database\\Eloquent\\Relations\\BelongsTo;\n\n/**\n * @property int $id\n * @property int $schedule_id\n * @property Carbon $date\n * @property Carbon|null $start_time\n * @property Carbon|null $end_time\n * @property bool $is_available\n * @property array|null $metadata\n * @property Carbon|null $created_at\n * @property Carbon|null $updated_at\n * @property-read Schedule $schedule\n * @property-read int $duration_minutes\n * @property-read Carbon $start_date_time\n * @property-read Carbon $end_date_time\n */\nclass SchedulePeriod extends Model\n{\n /**\n * The attributes that are mass assignable.\n */\n protected $fillable = [\n 'schedule_id',\n 'date',\n 'start_time',\n 'end_time',\n 'is_available',\n 'metadata',\n ];\n\n /**\n * The attributes that should be cast.\n */\n protected $casts = [\n 'date' => 'date',\n 'start_time' => 'string',\n 'end_time' => 'string',\n 'is_available' => 'boolean',\n 'metadata' => 'array',\n ];\n\n /**\n * Get the schedule that owns the period.\n */\n public function schedule(): BelongsTo\n {\n return $this->belongsTo(Schedule::class);\n }\n\n /**\n * Get the duration in minutes.\n */\n ", "suffix_code": "\n\n /**\n * Get the full start datetime.\n */\n public function getStartDateTimeAttribute(): Carbon\n {\n return Carbon::parse($this->date->format('Y-m-d').' '.$this->start_time);\n }\n\n /**\n * Get the full end datetime.\n */\n public function getEndDateTimeAttribute(): Carbon\n {\n return Carbon::parse($this->date->format('Y-m-d').' '.$this->end_time);\n }\n\n /**\n * Check if this period overlaps with another period.\n */\n public function overlapsWith(SchedulePeriod $other): bool\n {\n // Must be on the same date\n if (! $this->date->eq($other->date)) {\n return false;\n }\n\n return $this->start_time < $other->end_time && $this->end_time > $other->start_time;\n }\n\n /**\n * Check if this period is currently active (happening now).\n */\n public function isActiveNow(): bool\n {\n $now = Carbon::now();\n $startDateTime = $this->start_date_time;\n $endDateTime = $this->end_date_time;\n\n return $now->between($startDateTime, $endDateTime);\n }\n\n /**\n * Scope a query to only include available periods.\n */\n public function scopeAvailable(\\Illuminate\\Database\\Eloquent\\Builder $query): \\Illuminate\\Database\\Eloquent\\Builder\n {\n return $query->where('is_available', true);\n }\n\n /**\n * Scope a query to only include periods for a specific date.\n */\n public function scopeForDate(\\Illuminate\\Database\\Eloquent\\Builder $query, string $date): \\Illuminate\\Database\\Eloquent\\Builder\n {\n return $query->where('date', $date);\n }\n\n /**\n * Scope a query to only include periods within a time range.\n */\n public function scopeForTimeRange(\\Illuminate\\Database\\Eloquent\\Builder $query, string $startTime, string $endTime): \\Illuminate\\Database\\Eloquent\\Builder\n {\n return $query->where('start_time', '>=', $startTime)\n ->where('end_time', '<=', $endTime);\n }\n\n /**\n * Scope a query to find overlapping periods.\n */\n public function scopeOverlapping(\\Illuminate\\Database\\Eloquent\\Builder $query, string $date, string $startTime, string $endTime): \\Illuminate\\Database\\Eloquent\\Builder\n {\n return $query->whereDate('date', $date)\n ->where('start_time', '<', $endTime)\n ->where('end_time', '>', $startTime);\n }\n\n /**\n * Convert the period to a human-readable string.\n */\n public function __toString(): string\n {\n return sprintf(\n '%s from %s to %s',\n $this->date->format('Y-m-d'),\n $this->start_time,\n $this->end_time\n );\n }\n}\n", "middle_code": "public function getDurationMinutesAttribute(): int\n {\n if (! $this->start_time || ! $this->end_time) {\n return 0;\n }\n $baseDate = '2024-01-01'; \n $start = Carbon::parse($baseDate.' '.$this->start_time);\n $end = Carbon::parse($baseDate.' '.$this->end_time);\n return (int) $start->diffInMinutes($end);\n }", "code_description": null, "fill_type": "FUNCTION_TYPE", "language_type": "php", "sub_task_type": null}, "context_code": [["/laravel-zap/src/Models/Schedule.php", "<?php\n\nnamespace Zap\\Models;\n\nuse Carbon\\Carbon;\nuse Illuminate\\Database\\Eloquent\\Builder;\nuse Illuminate\\Database\\Eloquent\\Collection;\nuse Illuminate\\Database\\Eloquent\\Model;\nuse Illuminate\\Database\\Eloquent\\Relations\\HasMany;\nuse Illuminate\\Database\\Eloquent\\Relations\\MorphTo;\nuse Zap\\Enums\\ScheduleTypes;\n\n/**\n * @property int $id\n * @property string $name\n * @property string|null $description\n * @property string $schedulable_type\n * @property int $schedulable_id\n * @property ScheduleTypes $schedule_type\n * @property Carbon $start_date\n * @property Carbon|null $end_date\n * @property bool $is_recurring\n * @property string|null $frequency\n * @property array|null $frequency_config\n * @property array|null $metadata\n * @property bool $is_active\n * @property Carbon|null $created_at\n * @property Carbon|null $updated_at\n * @property Carbon|null $deleted_at\n * @property-read \\Illuminate\\Database\\Eloquent\\Collection<int, SchedulePeriod> $periods\n * @property-read Model $schedulable\n * @property-read int $total_duration\n */\nclass Schedule extends Model\n{\n /**\n * The attributes that are mass assignable.\n */\n protected $fillable = [\n 'schedulable_type',\n 'schedulable_id',\n 'name',\n 'description',\n 'schedule_type',\n 'start_date',\n 'end_date',\n 'is_recurring',\n 'frequency',\n 'frequency_config',\n 'metadata',\n 'is_active',\n ];\n\n /**\n * The attributes that should be cast.\n */\n protected $casts = [\n 'schedule_type' => ScheduleTypes::class,\n 'start_date' => 'date',\n 'end_date' => 'date',\n 'is_recurring' => 'boolean',\n 'frequency_config' => 'array',\n 'metadata' => 'array',\n 'is_active' => 'boolean',\n ];\n\n /**\n * The attributes that should be guarded.\n */\n protected $guarded = [];\n\n /**\n * Get the parent schedulable model.\n */\n public function schedulable(): MorphTo\n {\n return $this->morphTo();\n }\n\n /**\n * Get the schedule periods.\n *\n * @return HasMany<SchedulePeriod, $this>\n */\n public function periods(): HasMany\n {\n return $this->hasMany(SchedulePeriod::class);\n }\n\n /**\n * Create a new Eloquent query builder for the model.\n */\n public function newEloquentBuilder($query): Builder\n {\n return new Builder($query);\n }\n\n /**\n * Create a new Eloquent Collection instance.\n *\n * @param array<int, static> $models\n * @return \\Illuminate\\Database\\Eloquent\\Collection<int, static>\n */\n public function newCollection(array $models = []): Collection\n {\n return new Collection($models);\n }\n\n /**\n * Scope a query to only include active schedules.\n */\n public function scopeActive(Builder $query): void\n {\n $query->where('is_active', true);\n }\n\n /**\n * Scope a query to only include recurring schedules.\n */\n public function scopeRecurring(Builder $query): void\n {\n $query->where('is_recurring', true);\n }\n\n /**\n * Scope a query to only include schedules of a specific type.\n */\n public function scopeOfType(Builder $query, string $type): void\n {\n $query->where('schedule_type', $type);\n }\n\n /**\n * Scope a query to only include availability schedules.\n */\n public function scopeAvailability(Builder $query): void\n {\n $query->where('schedule_type', ScheduleTypes::AVAILABILITY);\n }\n\n /**\n * Scope a query to only include appointment schedules.\n */\n public function scopeAppointments(Builder $query): void\n {\n $query->where('schedule_type', ScheduleTypes::APPOINTMENT);\n }\n\n /**\n * Scope a query to only include blocked schedules.\n */\n public function scopeBlocked(Builder $query): void\n {\n $query->where('schedule_type', ScheduleTypes::BLOCKED);\n }\n\n /**\n * Scope a query to only include schedules for a specific date.\n */\n public function scopeForDate(Builder $query, string $date): void\n {\n $checkDate = \\Carbon\\Carbon::parse($date);\n\n $query->where('start_date', '<=', $checkDate)\n ->where(function ($q) use ($checkDate) {\n $q->whereNull('end_date')\n ->orWhere('end_date', '>=', $checkDate);\n });\n }\n\n /**\n * Scope a query to only include schedules within a date range.\n */\n public function scopeForDateRange(Builder $query, string $startDate, string $endDate): void\n {\n $query->where(function ($q) use ($startDate, $endDate) {\n $q->whereBetween('start_date', [$startDate, $endDate])\n ->orWhereBetween('end_date', [$startDate, $endDate])\n ->orWhere(function ($q2) use ($startDate, $endDate) {\n $q2->where('start_date', '<=', $startDate)\n ->where('end_date', '>=', $endDate);\n });\n });\n }\n\n /**\n * Check if this schedule overlaps with another schedule.\n */\n public function overlapsWith(Schedule $other): bool\n {\n // Basic date range overlap check\n if ($this->end_date && $other->end_date) {\n return $this->start_date <= $other->end_date && $this->end_date >= $other->start_date;\n }\n\n // Handle open-ended schedules\n if (! $this->end_date && ! $other->end_date) {\n return $this->start_date <= $other->start_date;\n }\n\n if (! $this->end_date) {\n return $this->start_date <= ($other->end_date ?? $other->start_date);\n }\n\n if (! $other->end_date) {\n return $this->end_date >= $other->start_date;\n }\n\n return false;\n }\n\n /**\n * Get the total duration of all periods in minutes.\n */\n public function getTotalDurationAttribute(): int\n {\n return $this->periods->sum('duration_minutes');\n }\n\n /**\n * Check if the schedule is currently active.\n */\n public function isActiveOn(string $date): bool\n {\n if (! $this->is_active) {\n return false;\n }\n\n $checkDate = \\Carbon\\Carbon::parse($date);\n $startDate = $this->start_date;\n $endDate = $this->end_date;\n\n return $checkDate->greaterThanOrEqualTo($startDate) &&\n ($endDate === null || $checkDate->lessThanOrEqualTo($endDate));\n }\n\n /**\n * Check if this schedule is of availability type.\n */\n public function isAvailability(): bool\n {\n return $this->schedule_type->is(ScheduleTypes::AVAILABILITY);\n }\n\n /**\n * Check if this schedule is of appointment type.\n */\n public function isAppointment(): bool\n {\n return $this->schedule_type->is(ScheduleTypes::APPOINTMENT);\n }\n\n /**\n * Check if this schedule is of blocked type.\n */\n public function isBlocked(): bool\n {\n return $this->schedule_type->is(ScheduleTypes::BLOCKED);\n }\n\n /**\n * Check if this schedule is of custom type.\n */\n public function isCustom(): bool\n {\n return $this->schedule_type->is(ScheduleTypes::CUSTOM);\n }\n\n /**\n * Check if this schedule should prevent overlaps (appointments and blocked schedules).\n */\n public function preventsOverlaps(): bool\n {\n return $this->schedule_type->preventsOverlaps();\n }\n\n /**\n * Check if this schedule allows overlaps (availability schedules).\n */\n public function allowsOverlaps(): bool\n {\n return $this->schedule_type->allowsOverlaps();\n }\n}\n"], ["/laravel-zap/src/Models/Concerns/HasSchedules.php", "<?php\n\nnamespace Zap\\Models\\Concerns;\n\nuse Illuminate\\Database\\Eloquent\\Relations\\MorphMany;\nuse Zap\\Builders\\ScheduleBuilder;\nuse Zap\\Enums\\ScheduleTypes;\nuse Zap\\Models\\Schedule;\nuse Zap\\Services\\ConflictDetectionService;\n\n/**\n * Trait HasSchedules\n *\n * This trait provides scheduling capabilities to any Eloquent model.\n * Use this trait in models that need to be schedulable.\n *\n * @mixin \\Illuminate\\Database\\Eloquent\\Model\n */\ntrait HasSchedules\n{\n /**\n * Get all schedules for this model.\n *\n * @return MorphMany<Schedule, $this>\n */\n public function schedules(): MorphMany\n {\n return $this->morphMany(Schedule::class, 'schedulable');\n }\n\n /**\n * Get only active schedules.\n *\n * @return MorphMany<Schedule, $this>\n */\n public function activeSchedules(): MorphMany\n {\n return $this->schedules()->active();\n }\n\n /**\n * Get availability schedules.\n *\n * @return MorphMany<Schedule, $this>\n */\n public function availabilitySchedules(): MorphMany\n {\n return $this->schedules()->availability();\n }\n\n /**\n * Get appointment schedules.\n *\n * @return MorphMany<Schedule, $this>\n */\n public function appointmentSchedules(): MorphMany\n {\n return $this->schedules()->appointments();\n }\n\n /**\n * Get blocked schedules.\n *\n * @return MorphMany<Schedule, $this>\n */\n public function blockedSchedules(): MorphMany\n {\n return $this->schedules()->blocked();\n }\n\n /**\n * Get schedules for a specific date.\n *\n * @return MorphMany<Schedule, $this>\n */\n public function schedulesForDate(string $date): MorphMany\n {\n return $this->schedules()->forDate($date);\n }\n\n /**\n * Get schedules within a date range.\n *\n * @return MorphMany<Schedule, $this>\n */\n public function schedulesForDateRange(string $startDate, string $endDate): MorphMany\n {\n return $this->schedules()->forDateRange($startDate, $endDate);\n }\n\n /**\n * Get recurring schedules.\n *\n * @return MorphMany<Schedule, $this>\n */\n public function recurringSchedules(): MorphMany\n {\n return $this->schedules()->recurring();\n }\n\n /**\n * Get schedules of a specific type.\n *\n * @return MorphMany<Schedule, $this>\n */\n public function schedulesOfType(string $type): MorphMany\n {\n return $this->schedules()->ofType($type);\n }\n\n /**\n * Create a new schedule builder for this model.\n */\n public function createSchedule(): ScheduleBuilder\n {\n return (new ScheduleBuilder)->for($this);\n }\n\n /**\n * Check if this model has any schedule conflicts with the given schedule.\n */\n public function hasScheduleConflict(Schedule $schedule): bool\n {\n return app(ConflictDetectionService::class)->hasConflicts($schedule);\n }\n\n /**\n * Find all schedules that conflict with the given schedule.\n */\n public function findScheduleConflicts(Schedule $schedule): array\n {\n return app(ConflictDetectionService::class)->findConflicts($schedule);\n }\n\n /**\n * Check if this model is available during a specific time period.\n */\n public function isAvailableAt(string $date, string $startTime, string $endTime): bool\n {\n // Get all active schedules for this model on this date\n $schedules = \\Zap\\Models\\Schedule::where('schedulable_type', get_class($this))\n ->where('schedulable_id', $this->getKey())\n ->active()\n ->forDate($date)\n ->with('periods')\n ->get();\n\n foreach ($schedules as $schedule) {\n $shouldBlock = $schedule->schedule_type === null\n || $schedule->schedule_type->is(ScheduleTypes::CUSTOM)\n || $schedule->preventsOverlaps();\n\n if ($shouldBlock && $this->scheduleBlocksTime($schedule, $date, $startTime, $endTime)) {\n return false;\n }\n }\n\n return true;\n }\n\n /**\n * Check if a specific schedule blocks the given time period.\n */\n protected function scheduleBlocksTime(\\Zap\\Models\\Schedule $schedule, string $date, string $startTime, string $endTime): bool\n {\n if (! $schedule->isActiveOn($date)) {\n return false;\n }\n\n if ($schedule->is_recurring) {\n return $this->recurringScheduleBlocksTime($schedule, $date, $startTime, $endTime);\n }\n\n // For non-recurring schedules, check stored periods\n return $schedule->periods()->overlapping($date, $startTime, $endTime)->exists();\n }\n\n /**\n * Check if a recurring schedule blocks the given time period.\n */\n protected function recurringScheduleBlocksTime(\\Zap\\Models\\Schedule $schedule, string $date, string $startTime, string $endTime): bool\n {\n $checkDate = \\Carbon\\Carbon::parse($date);\n\n // Check if this date should have a recurring instance\n if (! $this->shouldCreateRecurringInstance($schedule, $checkDate)) {\n return false;\n }\n\n // Get the base periods and check if any would overlap on this date\n $basePeriods = $schedule->periods;\n\n foreach ($basePeriods as $basePeriod) {\n if ($this->timePeriodsOverlap($basePeriod->start_time, $basePeriod->end_time, $startTime, $endTime)) {\n return true;\n }\n }\n\n return false;\n }\n\n /**\n * Check if a recurring instance should be created for the given date.\n */\n protected function shouldCreateRecurringInstance(\\Zap\\Models\\Schedule $schedule, \\Carbon\\Carbon $date): bool\n {\n $frequency = $schedule->frequency;\n $config = $schedule->frequency_config ?? [];\n\n switch ($frequency) {\n case 'daily':\n return true;\n\n case 'weekly':\n $allowedDays = $config['days'] ?? ['monday'];\n $allowedDayNumbers = array_map(function ($day) {\n return match (strtolower($day)) {\n 'sunday' => 0,\n 'monday' => 1,\n 'tuesday' => 2,\n 'wednesday' => 3,\n 'thursday' => 4,\n 'friday' => 5,\n 'saturday' => 6,\n default => 1, // Default to Monday\n };\n }, $allowedDays);\n\n return in_array($date->dayOfWeek, $allowedDayNumbers);\n\n case 'monthly':\n $dayOfMonth = $config['day_of_month'] ?? $schedule->start_date->day;\n\n return $date->day === $dayOfMonth;\n\n default:\n return false;\n }\n }\n\n /**\n * Check if two time periods overlap.\n */\n protected function timePeriodsOverlap(string $start1, string $end1, string $start2, string $end2): bool\n {\n return $start1 < $end2 && $end1 > $start2;\n }\n\n /**\n * Get available time slots for a specific date.\n */\n public function getAvailableSlots(\n string $date,\n string $dayStart = '09:00',\n string $dayEnd = '17:00',\n int $slotDuration = 60\n ): array {\n // Validate inputs to prevent infinite loops\n if ($slotDuration <= 0) {\n return [];\n }\n\n $slots = [];\n $currentTime = \\Carbon\\Carbon::parse($date.' '.$dayStart);\n $endTime = \\Carbon\\Carbon::parse($date.' '.$dayEnd);\n\n // If end time is before or equal to start time, return empty array\n if ($endTime->lessThanOrEqualTo($currentTime)) {\n return [];\n }\n\n // Safety counter to prevent infinite loops (max 1440 minutes in a day / min slot duration)\n $maxIterations = 1440;\n $iterations = 0;\n\n while ($currentTime->lessThan($endTime) && $iterations < $maxIterations) {\n $slotEnd = $currentTime->copy()->addMinutes($slotDuration);\n\n if ($slotEnd->lessThanOrEqualTo($endTime)) {\n $isAvailable = $this->isAvailableAt(\n $date,\n $currentTime->format('H:i'),\n $slotEnd->format('H:i')\n );\n\n $slots[] = [\n 'start_time' => $currentTime->format('H:i'),\n 'end_time' => $slotEnd->format('H:i'),\n 'is_available' => $isAvailable,\n ];\n }\n\n $currentTime->addMinutes($slotDuration);\n $iterations++;\n }\n\n return $slots;\n }\n\n /**\n * Get the next available time slot.\n */\n public function getNextAvailableSlot(\n ?string $afterDate = null,\n int $duration = 60,\n string $dayStart = '09:00',\n string $dayEnd = '17:00'\n ): ?array {\n // Validate inputs\n if ($duration <= 0) {\n return null;\n }\n\n $startDate = $afterDate ?? now()->format('Y-m-d');\n $checkDate = \\Carbon\\Carbon::parse($startDate);\n\n // Check up to 30 days in the future\n for ($i = 0; $i < 30; $i++) {\n $dateString = $checkDate->format('Y-m-d');\n $slots = $this->getAvailableSlots($dateString, $dayStart, $dayEnd, $duration);\n\n foreach ($slots as $slot) {\n if ($slot['is_available']) {\n return array_merge($slot, ['date' => $dateString]);\n }\n }\n\n $checkDate->addDay();\n }\n\n return null;\n }\n\n /**\n * Count total scheduled time for a date range.\n */\n public function getTotalScheduledTime(string $startDate, string $endDate): int\n {\n return $this->schedules()\n ->active()\n ->forDateRange($startDate, $endDate)\n ->with('periods')\n ->get()\n ->sum(function ($schedule) {\n return $schedule->periods->sum('duration_minutes');\n });\n }\n\n /**\n * Check if the model has any schedules.\n */\n public function hasSchedules(): bool\n {\n return $this->schedules()->exists();\n }\n\n /**\n * Check if the model has any active schedules.\n */\n public function hasActiveSchedules(): bool\n {\n return $this->activeSchedules()->exists();\n }\n}\n"], ["/laravel-zap/src/Services/ConflictDetectionService.php", "<?php\n\nnamespace Zap\\Services;\n\nuse Illuminate\\Database\\Eloquent\\Model;\nuse Illuminate\\Support\\Collection;\nuse Zap\\Enums\\ScheduleTypes;\nuse Zap\\Models\\Schedule;\nuse Zap\\Models\\SchedulePeriod;\n\nclass ConflictDetectionService\n{\n /**\n * Check if a schedule has conflicts with existing schedules.\n */\n public function hasConflicts(Schedule $schedule): bool\n {\n return ! empty($this->findConflicts($schedule));\n }\n\n /**\n * Find all schedules that conflict with the given schedule.\n */\n public function findConflicts(Schedule $schedule): array\n {\n if (! config('zap.conflict_detection.enabled', true)) {\n return [];\n }\n\n $conflicts = [];\n $bufferMinutes = config('zap.conflict_detection.buffer_minutes', 0);\n\n // Get all other active schedules for the same schedulable\n $otherSchedules = $this->getOtherSchedules($schedule);\n\n foreach ($otherSchedules as $otherSchedule) {\n // Check conflicts based on schedule types and rules\n $shouldCheckConflict = $this->shouldCheckConflict($schedule, $otherSchedule);\n\n if ($shouldCheckConflict && $this->schedulesOverlap($schedule, $otherSchedule, $bufferMinutes)) {\n $conflicts[] = $otherSchedule;\n }\n }\n\n return $conflicts;\n }\n\n /**\n * Determine if two schedules should be checked for conflicts.\n */\n protected function shouldCheckConflict(Schedule $schedule1, Schedule $schedule2): bool\n {\n // Availability schedules never conflict with anything (they allow overlaps)\n if ($schedule1->schedule_type->is(ScheduleTypes::AVAILABILITY) ||\n $schedule2->schedule_type->is(ScheduleTypes::AVAILABILITY)) {\n return false;\n }\n\n // Check if no_overlap rule is enabled and applies to these schedule types\n $noOverlapConfig = config('zap.default_rules.no_overlap', []);\n if (! ($noOverlapConfig['enabled'] ?? true)) {\n return false;\n }\n\n $appliesTo = $noOverlapConfig['applies_to'] ?? [ScheduleTypes::APPOINTMENT->value, ScheduleTypes::BLOCKED->value];\n $schedule1ShouldCheck = in_array($schedule1->schedule_type->value, $appliesTo);\n $schedule2ShouldCheck = in_array($schedule2->schedule_type->value, $appliesTo);\n\n // Both schedules must be of types that should be checked for conflicts\n return $schedule1ShouldCheck && $schedule2ShouldCheck;\n }\n\n /**\n * Check if a schedulable has conflicts with a given schedule.\n */\n public function hasSchedulableConflicts(Model $schedulable, Schedule $schedule): bool\n {\n $conflicts = $this->findSchedulableConflicts($schedulable, $schedule);\n\n return ! empty($conflicts);\n }\n\n /**\n * Find conflicts for a schedulable with a given schedule.\n */\n public function findSchedulableConflicts(Model $schedulable, Schedule $schedule): array\n {\n // Create a temporary schedule for conflict checking\n $tempSchedule = new Schedule([\n 'schedulable_type' => get_class($schedulable),\n 'schedulable_id' => $schedulable->getKey(),\n 'start_date' => $schedule->start_date,\n 'end_date' => $schedule->end_date,\n 'is_active' => true,\n ]);\n\n // Copy periods if they exist\n if ($schedule->relationLoaded('periods')) {\n $tempSchedule->setRelation('periods', $schedule->periods);\n }\n\n return $this->findConflicts($tempSchedule);\n }\n\n /**\n * Check if two schedules overlap.\n */\n public function schedulesOverlap(\n Schedule $schedule1,\n Schedule $schedule2,\n int $bufferMinutes = 0\n ): bool {\n // First check date range overlap\n if (! $this->dateRangesOverlap($schedule1, $schedule2)) {\n return false;\n }\n\n // Then check period-level conflicts\n return $this->periodsOverlap($schedule1, $schedule2, $bufferMinutes);\n }\n\n /**\n * Check if two schedules have overlapping date ranges.\n */\n protected function dateRangesOverlap(Schedule $schedule1, Schedule $schedule2): bool\n {\n $start1 = $schedule1->start_date;\n $end1 = $schedule1->end_date ?? \\Carbon\\Carbon::parse('2099-12-31');\n $start2 = $schedule2->start_date;\n $end2 = $schedule2->end_date ?? \\Carbon\\Carbon::parse('2099-12-31');\n\n return $start1 <= $end2 && $end1 >= $start2;\n }\n\n /**\n * Check if periods from two schedules overlap.\n */\n protected function periodsOverlap(\n Schedule $schedule1,\n Schedule $schedule2,\n int $bufferMinutes = 0\n ): bool {\n $periods1 = $this->getSchedulePeriods($schedule1);\n $periods2 = $this->getSchedulePeriods($schedule2);\n\n foreach ($periods1 as $period1) {\n foreach ($periods2 as $period2) {\n if ($this->periodPairOverlaps($period1, $period2, $bufferMinutes)) {\n return true;\n }\n }\n }\n\n return false;\n }\n\n /**\n * Check if two specific periods overlap.\n */\n protected function periodPairOverlaps(\n SchedulePeriod $period1,\n SchedulePeriod $period2,\n int $bufferMinutes = 0\n ): bool {\n // Must be on the same date\n if (! $period1->date->eq($period2->date)) {\n return false;\n }\n\n $start1 = $this->parseTime($period1->start_time);\n $end1 = $this->parseTime($period1->end_time);\n $start2 = $this->parseTime($period2->start_time);\n $end2 = $this->parseTime($period2->end_time);\n\n // Apply buffer\n if ($bufferMinutes > 0) {\n $start1->subMinutes($bufferMinutes);\n $end1->addMinutes($bufferMinutes);\n }\n\n return $start1 < $end2 && $end1 > $start2;\n }\n\n /**\n * Get periods for a schedule, handling recurring schedules.\n */\n protected function getSchedulePeriods(Schedule $schedule): Collection\n {\n $periods = $schedule->relationLoaded('periods')\n ? $schedule->periods\n : $schedule->periods()->get();\n\n // If this is a recurring schedule, we need to generate recurring instances\n if ($schedule->is_recurring) {\n return $this->generateRecurringPeriods($schedule, $periods);\n }\n\n return $periods;\n }\n\n /**\n * Generate recurring periods for a recurring schedule within a reasonable range.\n */\n protected function generateRecurringPeriods(Schedule $schedule, Collection $basePeriods): Collection\n {\n if (! $schedule->is_recurring || $basePeriods->isEmpty()) {\n return $basePeriods;\n }\n\n $allPeriods = collect();\n\n // Generate recurring instances for the next year to cover reasonable conflicts\n $startDate = $schedule->start_date;\n $endDate = $schedule->end_date ?? $startDate->copy()->addYear();\n\n // Limit the range to avoid infinite generation\n $maxEndDate = $startDate->copy()->addYear();\n if ($endDate->gt($maxEndDate)) {\n $endDate = $maxEndDate;\n }\n\n $current = $startDate->copy();\n\n while ($current->lte($endDate)) {\n // Check if this date should have a recurring instance\n if ($this->shouldCreateRecurringInstance($schedule, $current)) {\n // Generate periods for this recurring date\n foreach ($basePeriods as $basePeriod) {\n $recurringPeriod = new \\Zap\\Models\\SchedulePeriod([\n 'schedule_id' => $schedule->id,\n 'date' => $current->toDateString(),\n 'start_time' => $basePeriod->start_time,\n 'end_time' => $basePeriod->end_time,\n 'is_available' => $basePeriod->is_available,\n 'metadata' => $basePeriod->metadata,\n ]);\n\n $allPeriods->push($recurringPeriod);\n }\n }\n\n $current = $this->getNextRecurrence($schedule, $current);\n\n if ($current->gt($endDate)) {\n break;\n }\n }\n\n return $allPeriods;\n }\n\n /**\n * Check if a recurring instance should be created for the given date.\n */\n protected function shouldCreateRecurringInstance(Schedule $schedule, \\Carbon\\Carbon $date): bool\n {\n $frequency = $schedule->frequency;\n $config = $schedule->frequency_config ?? [];\n\n switch ($frequency) {\n case 'daily':\n return true;\n\n case 'weekly':\n $allowedDays = $config['days'] ?? ['monday'];\n $allowedDayNumbers = array_map(function ($day) {\n return match (strtolower($day)) {\n 'sunday' => 0,\n 'monday' => 1,\n 'tuesday' => 2,\n 'wednesday' => 3,\n 'thursday' => 4,\n 'friday' => 5,\n 'saturday' => 6,\n default => 1, // Default to Monday\n };\n }, $allowedDays);\n\n return in_array($date->dayOfWeek, $allowedDayNumbers);\n\n case 'monthly':\n $dayOfMonth = $config['day_of_month'] ?? $schedule->start_date->day;\n\n return $date->day === $dayOfMonth;\n\n default:\n return false;\n }\n }\n\n /**\n * Get the next recurrence date for a recurring schedule.\n */\n protected function getNextRecurrence(Schedule $schedule, \\Carbon\\Carbon $current): \\Carbon\\Carbon\n {\n $frequency = $schedule->frequency;\n $config = $schedule->frequency_config ?? [];\n\n switch ($frequency) {\n case 'daily':\n return $current->copy()->addDay();\n\n case 'weekly':\n $allowedDays = $config['days'] ?? ['monday'];\n\n return $this->getNextWeeklyOccurrence($current, $allowedDays);\n\n case 'monthly':\n $dayOfMonth = $config['day_of_month'] ?? $current->day;\n\n return $current->copy()->addMonth()->day($dayOfMonth);\n\n default:\n return $current->copy()->addDay();\n }\n }\n\n /**\n * Get the next weekly occurrence for the given days.\n */\n protected function getNextWeeklyOccurrence(\\Carbon\\Carbon $current, array $allowedDays): \\Carbon\\Carbon\n {\n $next = $current->copy()->addDay();\n\n // Convert day names to numbers (0 = Sunday, 1 = Monday, etc.)\n $allowedDayNumbers = array_map(function ($day) {\n return match (strtolower($day)) {\n 'sunday' => 0,\n 'monday' => 1,\n 'tuesday' => 2,\n 'wednesday' => 3,\n 'thursday' => 4,\n 'friday' => 5,\n 'saturday' => 6,\n default => 1, // Default to Monday\n };\n }, $allowedDays);\n\n // Find the next allowed day\n while (! in_array($next->dayOfWeek, $allowedDayNumbers)) {\n $next->addDay();\n\n // Prevent infinite loop\n if ($next->diffInDays($current) > 7) {\n break;\n }\n }\n\n return $next;\n }\n\n /**\n * Get other active schedules for the same schedulable.\n */\n protected function getOtherSchedules(Schedule $schedule): Collection\n {\n return Schedule::where('schedulable_type', $schedule->schedulable_type)\n ->where('schedulable_id', $schedule->schedulable_id)\n ->where('id', '!=', $schedule->id)\n ->active()\n ->with('periods')\n ->get();\n }\n\n /**\n * Parse a time string to Carbon instance.\n */\n protected function parseTime(string $time): \\Carbon\\Carbon\n {\n $baseDate = '2024-01-01'; // Use a consistent base date for time parsing\n\n return \\Carbon\\Carbon::parse($baseDate.' '.$time);\n }\n\n /**\n * Get conflicts for a specific time period.\n */\n public function findPeriodConflicts(\n Model $schedulable,\n string $date,\n string $startTime,\n string $endTime\n ): Collection {\n return Schedule::where('schedulable_type', get_class($schedulable))\n ->where('schedulable_id', $schedulable->getKey())\n ->active()\n ->forDate($date)\n ->whereHas('periods', function ($query) use ($date, $startTime, $endTime) {\n $query->whereDate('date', $date)\n ->where('start_time', '<', $endTime)\n ->where('end_time', '>', $startTime);\n })\n ->with('periods')\n ->get();\n }\n\n /**\n * Check if a specific time slot is available.\n */\n public function isTimeSlotAvailable(\n Model $schedulable,\n string $date,\n string $startTime,\n string $endTime\n ): bool {\n return $this->findPeriodConflicts($schedulable, $date, $startTime, $endTime)->isEmpty();\n }\n}\n"], ["/laravel-zap/src/Services/ValidationService.php", "<?php\n\nnamespace Zap\\Services;\n\nuse Illuminate\\Database\\Eloquent\\Model;\nuse Zap\\Exceptions\\InvalidScheduleException;\n\nclass ValidationService\n{\n /**\n * Validate a schedule before creation.\n */\n public function validate(\n Model $schedulable,\n array $attributes,\n array $periods,\n array $rules = []\n ): void {\n $errors = [];\n\n // Basic validation\n $basicErrors = $this->validateBasicAttributes($attributes);\n if (! empty($basicErrors)) {\n $errors = array_merge($errors, $basicErrors);\n }\n\n // Period validation\n $periodErrors = $this->validatePeriods($periods);\n if (! empty($periodErrors)) {\n $errors = array_merge($errors, $periodErrors);\n }\n\n // Business rules validation\n $ruleErrors = $this->validateRules($rules, $schedulable, $attributes, $periods);\n if (! empty($ruleErrors)) {\n $errors = array_merge($errors, $ruleErrors);\n }\n\n if (! empty($errors)) {\n $message = $this->buildValidationErrorMessage($errors);\n throw (new InvalidScheduleException($message))->setErrors($errors);\n }\n }\n\n /**\n * Validate basic schedule attributes.\n */\n protected function validateBasicAttributes(array $attributes): array\n {\n $errors = [];\n\n // Start date is required\n if (empty($attributes['start_date'])) {\n $errors['start_date'] = 'A start date is required for the schedule';\n }\n\n // End date must be after start date if provided\n if (! empty($attributes['end_date']) && ! empty($attributes['start_date'])) {\n $startDate = \\Carbon\\Carbon::parse($attributes['start_date']);\n $endDate = \\Carbon\\Carbon::parse($attributes['end_date']);\n\n if ($endDate->lte($startDate)) {\n $errors['end_date'] = 'The end date must be after the start date';\n }\n }\n\n // Check date range limits\n if (! empty($attributes['start_date']) && ! empty($attributes['end_date'])) {\n $startDate = \\Carbon\\Carbon::parse($attributes['start_date']);\n $endDate = \\Carbon\\Carbon::parse($attributes['end_date']);\n $maxRange = config('zap.validation.max_date_range', 365);\n\n if ($endDate->diffInDays($startDate) > $maxRange) {\n $errors['end_date'] = \"The schedule duration cannot exceed {$maxRange} days\";\n }\n }\n\n // Require future dates if configured\n if (config('zap.validation.require_future_dates', true)) {\n if (! empty($attributes['start_date'])) {\n $startDate = \\Carbon\\Carbon::parse($attributes['start_date']);\n if ($startDate->lt(now()->startOfDay())) {\n $errors['start_date'] = 'The schedule cannot be created in the past. Please choose a future date';\n }\n }\n }\n\n return $errors;\n }\n\n /**\n * Validate schedule periods.\n */\n protected function validatePeriods(array $periods): array\n {\n $errors = [];\n\n if (empty($periods)) {\n $errors['periods'] = 'At least one time period must be defined for the schedule';\n\n return $errors;\n }\n\n $maxPeriods = config('zap.validation.max_periods_per_schedule', 50);\n if (count($periods) > $maxPeriods) {\n $errors['periods'] = \"Too many time periods. A schedule cannot have more than {$maxPeriods} periods\";\n }\n\n foreach ($periods as $index => $period) {\n $periodErrors = $this->validateSinglePeriod($period, $index);\n if (! empty($periodErrors)) {\n $errors = array_merge($errors, $periodErrors);\n }\n }\n\n // Check for overlapping periods if not allowed\n if (! config('zap.validation.allow_overlapping_periods', false)) {\n $overlapErrors = $this->checkPeriodOverlaps($periods);\n if (! empty($overlapErrors)) {\n $errors = array_merge($errors, $overlapErrors);\n }\n }\n\n return $errors;\n }\n\n /**\n * Validate a single period.\n */\n protected function validateSinglePeriod(array $period, int $index): array\n {\n $errors = [];\n $prefix = \"periods.{$index}\";\n\n // Required fields\n if (empty($period['start_time'])) {\n $errors[\"{$prefix}.start_time\"] = 'A start time is required for this period';\n }\n\n if (empty($period['end_time'])) {\n $errors[\"{$prefix}.end_time\"] = 'An end time is required for this period';\n }\n\n // Time format validation\n if (! empty($period['start_time']) && ! $this->isValidTimeFormat($period['start_time'])) {\n $errors[\"{$prefix}.start_time\"] = \"Invalid start time format '{$period['start_time']}'. Please use HH:MM format (e.g., 09:30)\";\n }\n\n if (! empty($period['end_time']) && ! $this->isValidTimeFormat($period['end_time'])) {\n $errors[\"{$prefix}.end_time\"] = \"Invalid end time format '{$period['end_time']}'. Please use HH:MM format (e.g., 17:30)\";\n }\n\n // End time must be after start time\n if (! empty($period['start_time']) && ! empty($period['end_time'])) {\n $baseDate = '2024-01-01'; // Use a consistent base date for time parsing\n $start = \\Carbon\\Carbon::parse($baseDate.' '.$period['start_time']);\n $end = \\Carbon\\Carbon::parse($baseDate.' '.$period['end_time']);\n\n if ($end->lte($start)) {\n $errors[\"{$prefix}.end_time\"] = \"End time ({$period['end_time']}) must be after start time ({$period['start_time']})\";\n }\n\n // Duration validation\n $duration = $start->diffInMinutes($end);\n $minDuration = config('zap.validation.min_period_duration', 15);\n $maxDuration = config('zap.validation.max_period_duration', 480);\n\n if ($duration < $minDuration) {\n $errors[\"{$prefix}.duration\"] = \"Period is too short ({$duration} minutes). Minimum duration is {$minDuration} minutes\";\n }\n\n if ($duration > $maxDuration) {\n $errors[\"{$prefix}.duration\"] = \"Period is too long ({$duration} minutes). Maximum duration is {$maxDuration} minutes\";\n }\n }\n\n return $errors;\n }\n\n /**\n * Check for overlapping periods within the same schedule.\n */\n protected function checkPeriodOverlaps(array $periods): array\n {\n $errors = [];\n\n for ($i = 0; $i < count($periods); $i++) {\n for ($j = $i + 1; $j < count($periods); $j++) {\n $period1 = $periods[$i];\n $period2 = $periods[$j];\n\n // Only check periods on the same date\n $date1 = $period1['date'] ?? null;\n $date2 = $period2['date'] ?? null;\n\n // If both periods have dates and they're different, skip\n if ($date1 && $date2 && $date1 !== $date2) {\n continue;\n }\n\n // If one has a date and the other doesn't, skip (they're on different days)\n if (($date1 && ! $date2) || (! $date1 && $date2)) {\n continue;\n }\n\n if ($this->periodsOverlap($period1, $period2)) {\n $time1 = \"{$period1['start_time']}-{$period1['end_time']}\";\n $time2 = \"{$period2['start_time']}-{$period2['end_time']}\";\n $errors[\"periods.{$i}.overlap\"] = \"Period {$i} ({$time1}) overlaps with period {$j} ({$time2})\";\n }\n }\n }\n\n return $errors;\n }\n\n /**\n * Check if two periods overlap.\n */\n protected function periodsOverlap(array $period1, array $period2): bool\n {\n if (empty($period1['start_time']) || empty($period1['end_time']) ||\n empty($period2['start_time']) || empty($period2['end_time'])) {\n return false;\n }\n\n $baseDate = '2024-01-01'; // Use a consistent base date for time parsing\n $start1 = \\Carbon\\Carbon::parse($baseDate.' '.$period1['start_time']);\n $end1 = \\Carbon\\Carbon::parse($baseDate.' '.$period1['end_time']);\n $start2 = \\Carbon\\Carbon::parse($baseDate.' '.$period2['start_time']);\n $end2 = \\Carbon\\Carbon::parse($baseDate.' '.$period2['end_time']);\n\n return $start1 < $end2 && $end1 > $start2;\n }\n\n /**\n * Validate schedule rules.\n */\n protected function validateRules(array $rules, Model $schedulable, array $attributes, array $periods): array\n {\n $errors = [];\n\n // Validate explicitly provided rules (these are always enabled unless explicitly disabled)\n foreach ($rules as $ruleName => $ruleConfig) {\n if (! $this->isExplicitRuleEnabled($ruleName, $ruleConfig)) {\n continue;\n }\n\n $ruleErrors = $this->validateRule($ruleName, $ruleConfig, $schedulable, $attributes, $periods);\n if (! empty($ruleErrors)) {\n $errors = array_merge($errors, $ruleErrors);\n }\n }\n\n // Add enabled default rules that weren't explicitly provided\n $defaultRules = config('zap.default_rules', []);\n foreach ($defaultRules as $ruleName => $defaultConfig) {\n // Skip if rule was explicitly provided\n if (isset($rules[$ruleName])) {\n continue;\n }\n\n // Check if default rule is enabled\n if (! $this->isDefaultRuleEnabled($ruleName, $defaultConfig)) {\n continue;\n }\n\n $ruleErrors = $this->validateRule($ruleName, $defaultConfig, $schedulable, $attributes, $periods);\n if (! empty($ruleErrors)) {\n $errors = array_merge($errors, $ruleErrors);\n }\n }\n\n // Automatically add no_overlap rule for appointment and blocked schedules if enabled\n $scheduleType = $attributes['schedule_type'] ?? \\Zap\\Enums\\ScheduleTypes::CUSTOM;\n $noOverlapConfig = config('zap.default_rules.no_overlap', []);\n $shouldApplyNoOverlap = $this->shouldApplyNoOverlapRule($scheduleType, $noOverlapConfig, $rules);\n\n if ($shouldApplyNoOverlap) {\n $ruleErrors = $this->validateNoOverlap($noOverlapConfig, $schedulable, $attributes, $periods);\n $errors = array_merge($errors, $ruleErrors);\n }\n\n return $errors;\n }\n\n /**\n * Validate a specific rule.\n */\n protected function validateRule(\n string $ruleName,\n $ruleConfig,\n Model $schedulable,\n array $attributes,\n array $periods\n ): array {\n switch ($ruleName) {\n case 'working_hours':\n return $this->validateWorkingHours($ruleConfig, $periods);\n\n case 'max_duration':\n return $this->validateMaxDuration($ruleConfig, $periods);\n\n case 'no_weekends':\n return $this->validateNoWeekends($ruleConfig, $attributes, $periods);\n\n case 'no_overlap':\n return $this->validateNoOverlap($ruleConfig, $schedulable, $attributes, $periods);\n\n default:\n return [];\n }\n }\n\n /**\n * Merge provided rules with default rules from configuration.\n */\n protected function mergeWithDefaultRules(array $rules): array\n {\n $defaultRules = config('zap.default_rules', []);\n\n // Start with default rules\n $mergedRules = $defaultRules;\n\n // Override with provided rules\n foreach ($rules as $ruleName => $ruleConfig) {\n $mergedRules[$ruleName] = $ruleConfig;\n }\n\n return $mergedRules;\n }\n\n /**\n * Check if an explicitly provided rule is enabled.\n */\n protected function isExplicitRuleEnabled(string $ruleName, $ruleConfig): bool\n {\n // If rule config is just a boolean, use it directly\n if (is_bool($ruleConfig)) {\n return $ruleConfig;\n }\n\n // If rule config is an array, check for 'enabled' key\n if (is_array($ruleConfig)) {\n // If the rule has explicit enabled/disabled setting, use it\n if (isset($ruleConfig['enabled'])) {\n return $ruleConfig['enabled'];\n }\n\n // If the rule config is empty (like from builder methods), check global config\n if (empty($ruleConfig)) {\n $defaultConfig = config(\"zap.default_rules.{$ruleName}\", []);\n\n return $this->isDefaultRuleEnabled($ruleName, $defaultConfig);\n }\n\n // For explicit rules with config (like workingHoursOnly(), maxDuration()),\n // they should be enabled since they were explicitly requested\n return true;\n }\n\n // For other types (explicit rule config provided), consider the rule enabled\n return $ruleConfig !== null;\n }\n\n /**\n * Check if a default rule is enabled.\n */\n protected function isDefaultRuleEnabled(string $ruleName, $ruleConfig): bool\n {\n // If rule config is just a boolean, use it directly\n if (is_bool($ruleConfig)) {\n return $ruleConfig;\n }\n\n // If rule config is an array, check for 'enabled' key\n if (is_array($ruleConfig)) {\n return $ruleConfig['enabled'] ?? true;\n }\n\n // For other types, consider the rule enabled if config is provided\n return $ruleConfig !== null;\n }\n\n /**\n * Check if a rule is enabled (legacy method - kept for compatibility).\n */\n protected function isRuleEnabled(string $ruleName, $ruleConfig): bool\n {\n return $this->isExplicitRuleEnabled($ruleName, $ruleConfig);\n }\n\n /**\n * Determine if no_overlap rule should be applied.\n */\n protected function shouldApplyNoOverlapRule(\\Zap\\Enums\\ScheduleTypes $scheduleType, array $noOverlapConfig, array $providedRules): bool\n {\n // If no_overlap rule was explicitly provided, don't auto-apply\n if (isset($providedRules['no_overlap'])) {\n return false;\n }\n\n // Check if no_overlap rule is enabled in config\n if (! ($noOverlapConfig['enabled'] ?? false)) {\n return false;\n }\n\n // Check if this schedule type should get the no_overlap rule\n $appliesTo = $noOverlapConfig['applies_to'] ?? [];\n\n return in_array($scheduleType, $appliesTo);\n }\n\n /**\n * Validate working hours rule.\n */\n protected function validateWorkingHours($config, array $periods): array\n {\n if (! is_array($config)) {\n return [];\n }\n\n // Support both old and new configuration key formats\n $startTime = $config['start_time'] ?? $config['start'] ?? null;\n $endTime = $config['end_time'] ?? $config['end'] ?? null;\n\n if (empty($startTime) || empty($endTime)) {\n return [];\n }\n\n $errors = [];\n $baseDate = '2024-01-01'; // Use a consistent base date for time parsing\n $workStart = \\Carbon\\Carbon::parse($baseDate.' '.$startTime);\n $workEnd = \\Carbon\\Carbon::parse($baseDate.' '.$endTime);\n\n foreach ($periods as $index => $period) {\n if (empty($period['start_time']) || empty($period['end_time'])) {\n continue;\n }\n\n $periodStart = \\Carbon\\Carbon::parse($baseDate.' '.$period['start_time']);\n $periodEnd = \\Carbon\\Carbon::parse($baseDate.' '.$period['end_time']);\n\n if ($periodStart->lt($workStart) || $periodEnd->gt($workEnd)) {\n $errors[\"periods.{$index}.working_hours\"] =\n \"Period {$period['start_time']}-{$period['end_time']} is outside working hours ({$startTime}-{$endTime})\";\n }\n }\n\n return $errors;\n }\n\n /**\n * Validate maximum duration rule.\n */\n protected function validateMaxDuration($config, array $periods): array\n {\n if (! is_array($config) || empty($config['minutes'])) {\n return [];\n }\n\n $errors = [];\n $maxMinutes = $config['minutes'];\n\n foreach ($periods as $index => $period) {\n if (empty($period['start_time']) || empty($period['end_time'])) {\n continue;\n }\n\n $baseDate = '2024-01-01'; // Use a consistent base date for time parsing\n $start = \\Carbon\\Carbon::parse($baseDate.' '.$period['start_time']);\n $end = \\Carbon\\Carbon::parse($baseDate.' '.$period['end_time']);\n $duration = $start->diffInMinutes($end);\n\n if ($duration > $maxMinutes) {\n $hours = round($duration / 60, 1);\n $maxHours = round($maxMinutes / 60, 1);\n $errors[\"periods.{$index}.max_duration\"] =\n \"Period {$period['start_time']}-{$period['end_time']} is too long ({$hours} hours). Maximum allowed is {$maxHours} hours\";\n }\n }\n\n return $errors;\n }\n\n /**\n * Validate no weekends rule.\n */\n protected function validateNoWeekends($config, array $attributes, array $periods): array\n {\n if (! is_array($config)) {\n return [];\n }\n\n $errors = [];\n $blockSaturday = $config['saturday'] ?? true;\n $blockSunday = $config['sunday'] ?? true;\n\n // Check start date\n if (! empty($attributes['start_date'])) {\n $startDate = \\Carbon\\Carbon::parse($attributes['start_date']);\n if (($blockSaturday && $startDate->isSaturday()) || ($blockSunday && $startDate->isSunday())) {\n $dayName = $startDate->format('l');\n $errors['start_date'] = \"Schedule cannot start on {$dayName}. Weekend schedules are not allowed\";\n }\n }\n\n // Check period dates\n foreach ($periods as $index => $period) {\n if (! empty($period['date'])) {\n $periodDate = \\Carbon\\Carbon::parse($period['date']);\n if (($blockSaturday && $periodDate->isSaturday()) || ($blockSunday && $periodDate->isSunday())) {\n $dayName = $periodDate->format('l');\n $errors[\"periods.{$index}.date\"] = \"Period cannot be scheduled on {$dayName}. Weekend periods are not allowed\";\n }\n }\n }\n\n return $errors;\n }\n\n /**\n * Validate no overlap rule.\n */\n protected function validateNoOverlap($config, Model $schedulable, array $attributes, array $periods): array\n {\n // Check if global conflict detection is disabled\n if (! config('zap.conflict_detection.enabled', true)) {\n return [];\n }\n\n // Create a temporary schedule for conflict checking\n $tempSchedule = new \\Zap\\Models\\Schedule([\n 'schedulable_type' => get_class($schedulable),\n 'schedulable_id' => $schedulable->getKey(),\n 'start_date' => $attributes['start_date'],\n 'end_date' => $attributes['end_date'] ?? null,\n 'is_active' => true,\n 'is_recurring' => $attributes['is_recurring'] ?? false,\n 'frequency' => $attributes['frequency'] ?? null,\n 'frequency_config' => $attributes['frequency_config'] ?? null,\n 'schedule_type' => $attributes['schedule_type'] ?? \\Zap\\Enums\\ScheduleTypes::CUSTOM,\n ]);\n\n // Create temporary periods\n $tempPeriods = collect();\n foreach ($periods as $period) {\n $tempPeriods->push(new \\Zap\\Models\\SchedulePeriod([\n 'date' => $period['date'] ?? $attributes['start_date'],\n 'start_time' => $period['start_time'],\n 'end_time' => $period['end_time'],\n 'is_available' => $period['is_available'] ?? true,\n 'metadata' => $period['metadata'] ?? null,\n ]));\n }\n $tempSchedule->setRelation('periods', $tempPeriods);\n\n // For custom schedules with noOverlap rule, check conflicts with all other schedules\n if ($tempSchedule->schedule_type->is(\\Zap\\Enums\\ScheduleTypes::CUSTOM)) {\n $conflicts = $this->findCustomScheduleConflicts($tempSchedule);\n } else {\n // Use the conflict detection service for typed schedules\n $conflictService = app(\\Zap\\Services\\ConflictDetectionService::class);\n $conflicts = $conflictService->findConflicts($tempSchedule);\n }\n\n if (! empty($conflicts)) {\n // Build a detailed conflict message\n $message = $this->buildConflictErrorMessage($tempSchedule, $conflicts);\n\n // Throw the appropriate exception type for conflicts\n throw (new \\Zap\\Exceptions\\ScheduleConflictException($message))\n ->setConflictingSchedules($conflicts);\n }\n\n return [];\n }\n\n /**\n * Find conflicts for custom schedules with noOverlap rule.\n */\n protected function findCustomScheduleConflicts(\\Zap\\Models\\Schedule $schedule): array\n {\n $conflicts = [];\n $bufferMinutes = config('zap.conflict_detection.buffer_minutes', 0);\n\n // Get all other active schedules for the same schedulable\n $otherSchedules = \\Zap\\Models\\Schedule::where('schedulable_type', $schedule->schedulable_type)\n ->where('schedulable_id', $schedule->schedulable_id)\n ->where('id', '!=', $schedule->id)\n ->active()\n ->with('periods')\n ->get();\n\n $conflictService = app(\\Zap\\Services\\ConflictDetectionService::class);\n\n foreach ($otherSchedules as $otherSchedule) {\n if ($conflictService->schedulesOverlap($schedule, $otherSchedule, $bufferMinutes)) {\n $conflicts[] = $otherSchedule;\n }\n }\n\n return $conflicts;\n }\n\n /**\n * Build a descriptive validation error message.\n */\n protected function buildValidationErrorMessage(array $errors): string\n {\n $errorCount = count($errors);\n $errorMessages = [];\n\n foreach ($errors as $field => $message) {\n $errorMessages[] = \"• {$field}: {$message}\";\n }\n\n $summary = $errorCount === 1\n ? 'Schedule validation failed with 1 error:'\n : \"Schedule validation failed with {$errorCount} errors:\";\n\n return $summary.\"\\n\".implode(\"\\n\", $errorMessages);\n }\n\n /**\n * Build a detailed conflict error message.\n */\n protected function buildConflictErrorMessage(\\Zap\\Models\\Schedule $newSchedule, array $conflicts): string\n {\n $conflictCount = count($conflicts);\n $newScheduleName = $newSchedule->name ?? 'New schedule';\n\n if ($conflictCount === 1) {\n $conflict = $conflicts[0];\n $conflictName = $conflict->name ?? \"Schedule #{$conflict->id}\";\n\n $message = \"Schedule conflict detected! '{$newScheduleName}' conflicts with existing schedule '{$conflictName}'.\";\n\n // Add details about the conflict\n if ($conflict->is_recurring) {\n $frequency = ucfirst($conflict->frequency ?? 'recurring');\n $message .= \" The conflicting schedule is a {$frequency} schedule\";\n\n if ($conflict->frequency === 'weekly' && ! empty($conflict->frequency_config['days'])) {\n $days = implode(', ', array_map('ucfirst', $conflict->frequency_config['days']));\n $message .= \" on {$days}\";\n }\n\n $message .= '.';\n }\n\n return $message;\n } else {\n $message = \"Multiple schedule conflicts detected! '{$newScheduleName}' conflicts with {$conflictCount} existing schedules:\";\n\n foreach ($conflicts as $index => $conflict) {\n $conflictName = $conflict->name ?? \"Schedule #{$conflict->id}\";\n $message .= \"\\n• {$conflictName}\";\n\n if ($conflict->is_recurring) {\n $frequency = ucfirst($conflict->frequency ?? 'recurring');\n $message .= \" ({$frequency}\";\n\n if ($conflict->frequency === 'weekly' && ! empty($conflict->frequency_config['days'])) {\n $days = implode(', ', array_map('ucfirst', $conflict->frequency_config['days']));\n $message .= \" - {$days}\";\n }\n\n $message .= ')';\n }\n }\n\n return $message;\n }\n }\n\n /**\n * Check if a time string is in valid format.\n */\n protected function isValidTimeFormat(string $time): bool\n {\n return preg_match('/^([01]?[0-9]|2[0-3]):[0-5][0-9]$/', $time) === 1;\n }\n}\n"], ["/laravel-zap/src/Builders/ScheduleBuilder.php", "<?php\n\nnamespace Zap\\Builders;\n\nuse Carbon\\Carbon;\nuse Illuminate\\Database\\Eloquent\\Model;\nuse Zap\\Enums\\ScheduleTypes;\nuse Zap\\Models\\Schedule;\nuse Zap\\Services\\ScheduleService;\n\nclass ScheduleBuilder\n{\n private ?Model $schedulable = null;\n\n private array $attributes = [];\n\n private array $periods = [];\n\n private array $rules = [];\n\n /**\n * Set the schedulable model (User, etc.)\n */\n public function for(Model $schedulable): self\n {\n $this->schedulable = $schedulable;\n\n return $this;\n }\n\n /**\n * Set the schedule name.\n */\n public function named(string $name): self\n {\n $this->attributes['name'] = $name;\n\n return $this;\n }\n\n /**\n * Set the schedule description.\n */\n public function description(string $description): self\n {\n $this->attributes['description'] = $description;\n\n return $this;\n }\n\n /**\n * Set the start date.\n */\n public function from(Carbon|string $startDate): self\n {\n $this->attributes['start_date'] = $startDate instanceof Carbon\n ? $startDate->toDateString()\n : $startDate;\n\n return $this;\n }\n\n /**\n * Set the end date.\n */\n public function to(Carbon|string|null $endDate): self\n {\n $this->attributes['end_date'] = $endDate instanceof Carbon\n ? $endDate->toDateString()\n : $endDate;\n\n return $this;\n }\n\n /**\n * Set both start and end dates.\n */\n public function between(Carbon|string $start, Carbon|string $end): self\n {\n return $this->from($start)->to($end);\n }\n\n /**\n * Add a time period to the schedule.\n */\n public function addPeriod(string $startTime, string $endTime, ?Carbon $date = null): self\n {\n $this->periods[] = [\n 'start_time' => $startTime,\n 'end_time' => $endTime,\n 'date' => $date?->toDateString() ?? $this->attributes['start_date'] ?? now()->toDateString(),\n ];\n\n return $this;\n }\n\n /**\n * Add multiple periods at once.\n */\n public function addPeriods(array $periods): self\n {\n foreach ($periods as $period) {\n $this->addPeriod(\n $period['start_time'],\n $period['end_time'],\n isset($period['date']) ? Carbon::parse($period['date']) : null\n );\n }\n\n return $this;\n }\n\n /**\n * Set schedule as daily recurring.\n */\n public function daily(): self\n {\n $this->attributes['is_recurring'] = true;\n $this->attributes['frequency'] = 'daily';\n\n return $this;\n }\n\n /**\n * Set schedule as weekly recurring.\n */\n public function weekly(array $days = []): self\n {\n $this->attributes['is_recurring'] = true;\n $this->attributes['frequency'] = 'weekly';\n $this->attributes['frequency_config'] = ['days' => $days];\n\n return $this;\n }\n\n /**\n * Set schedule as monthly recurring.\n */\n public function monthly(array $config = []): self\n {\n $this->attributes['is_recurring'] = true;\n $this->attributes['frequency'] = 'monthly';\n $this->attributes['frequency_config'] = $config;\n\n return $this;\n }\n\n /**\n * Set custom recurring frequency.\n */\n public function recurring(string $frequency, array $config = []): self\n {\n $this->attributes['is_recurring'] = true;\n $this->attributes['frequency'] = $frequency;\n $this->attributes['frequency_config'] = $config;\n\n return $this;\n }\n\n /**\n * Add a validation rule.\n */\n public function withRule(string $ruleName, array $config = []): self\n {\n $this->rules[$ruleName] = $config;\n\n return $this;\n }\n\n /**\n * Add no overlap rule.\n */\n public function noOverlap(): self\n {\n return $this->withRule('no_overlap');\n }\n\n /**\n * Set schedule as availability type (allows overlaps).\n */\n public function availability(): self\n {\n $this->attributes['schedule_type'] = ScheduleTypes::AVAILABILITY;\n\n return $this;\n }\n\n /**\n * Set schedule as appointment type (prevents overlaps).\n */\n public function appointment(): self\n {\n $this->attributes['schedule_type'] = ScheduleTypes::APPOINTMENT;\n\n return $this;\n }\n\n /**\n * Set schedule as blocked type (prevents overlaps).\n */\n public function blocked(): self\n {\n $this->attributes['schedule_type'] = ScheduleTypes::BLOCKED;\n\n return $this;\n }\n\n /**\n * Set schedule as custom type.\n */\n public function custom(): self\n {\n $this->attributes['schedule_type'] = ScheduleTypes::CUSTOM;\n\n return $this;\n }\n\n /**\n * Set schedule type explicitly.\n */\n public function type(string $type): self\n {\n try {\n $scheduleType = ScheduleTypes::from($type);\n } catch (\\ValueError) {\n throw new \\InvalidArgumentException(\"Invalid schedule type: {$type}. Valid types are: \".implode(', ', ScheduleTypes::values()));\n }\n\n $this->attributes['schedule_type'] = $scheduleType;\n\n return $this;\n }\n\n /**\n * Add working hours only rule.\n */\n public function workingHoursOnly(string $start = '09:00', string $end = '17:00'): self\n {\n return $this->withRule('working_hours', compact('start', 'end'));\n }\n\n /**\n * Add maximum duration rule.\n */\n public function maxDuration(int $minutes): self\n {\n return $this->withRule('max_duration', ['minutes' => $minutes]);\n }\n\n /**\n * Add no weekends rule.\n */\n public function noWeekends(): self\n {\n return $this->withRule('no_weekends');\n }\n\n /**\n * Add custom metadata.\n */\n public function withMetadata(array $metadata): self\n {\n $this->attributes['metadata'] = array_merge($this->attributes['metadata'] ?? [], $metadata);\n\n return $this;\n }\n\n /**\n * Set the schedule as inactive.\n */\n public function inactive(): self\n {\n $this->attributes['is_active'] = false;\n\n return $this;\n }\n\n /**\n * Set the schedule as active (default).\n */\n public function active(): self\n {\n $this->attributes['is_active'] = true;\n\n return $this;\n }\n\n /**\n * Build and validate the schedule without saving.\n */\n public function build(): array\n {\n if (! $this->schedulable) {\n throw new \\InvalidArgumentException('Schedulable model must be set using for() method');\n }\n\n if (empty($this->attributes['start_date'])) {\n throw new \\InvalidArgumentException('Start date must be set using from() method');\n }\n\n // Set default schedule_type if not specified\n if (! isset($this->attributes['schedule_type'])) {\n $this->attributes['schedule_type'] = ScheduleTypes::CUSTOM;\n }\n\n return [\n 'schedulable' => $this->schedulable,\n 'attributes' => $this->attributes,\n 'periods' => $this->periods,\n 'rules' => $this->rules,\n ];\n }\n\n /**\n * Save the schedule.\n */\n public function save(): Schedule\n {\n $built = $this->build();\n\n return app(ScheduleService::class)->create(\n $built['schedulable'],\n $built['attributes'],\n $built['periods'],\n $built['rules']\n );\n }\n\n /**\n * Get the current attributes.\n */\n public function getAttributes(): array\n {\n return $this->attributes;\n }\n\n /**\n * Get the current periods.\n */\n public function getPeriods(): array\n {\n return $this->periods;\n }\n\n /**\n * Get the current rules.\n */\n public function getRules(): array\n {\n return $this->rules;\n }\n\n /**\n * Reset the builder to start fresh.\n */\n public function reset(): self\n {\n $this->schedulable = null;\n $this->attributes = [];\n $this->periods = [];\n $this->rules = [];\n\n return $this;\n }\n\n /**\n * Clone the builder with the same configuration.\n */\n public function clone(): self\n {\n $clone = new self;\n $clone->schedulable = $this->schedulable;\n $clone->attributes = $this->attributes;\n $clone->periods = $this->periods;\n $clone->rules = $this->rules;\n\n return $clone;\n }\n}\n"], ["/laravel-zap/src/Services/ScheduleService.php", "<?php\n\nnamespace Zap\\Services;\n\nuse Illuminate\\Database\\Eloquent\\Model;\nuse Illuminate\\Support\\Facades\\DB;\nuse Illuminate\\Support\\Facades\\Event;\nuse Zap\\Builders\\ScheduleBuilder;\nuse Zap\\Events\\ScheduleCreated;\nuse Zap\\Exceptions\\ScheduleConflictException;\nuse Zap\\Models\\Schedule;\n\nclass ScheduleService\n{\n public function __construct(\n private ValidationService $validator,\n private ConflictDetectionService $conflictService\n ) {}\n\n /**\n * Create a new schedule with validation and conflict detection.\n */\n public function create(\n Model $schedulable,\n array $attributes,\n array $periods = [],\n array $rules = []\n ): Schedule {\n return DB::transaction(function () use ($schedulable, $attributes, $periods, $rules) {\n // Set default values\n $attributes = array_merge([\n 'is_active' => true,\n 'is_recurring' => false,\n ], $attributes);\n\n // Validate the schedule data\n $this->validator->validate($schedulable, $attributes, $periods, $rules);\n\n // Create the schedule\n $schedule = new Schedule($attributes);\n $schedule->schedulable_type = get_class($schedulable);\n $schedule->schedulable_id = $schedulable->getKey();\n $schedule->save();\n\n // Create periods if provided\n if (! empty($periods)) {\n foreach ($periods as $period) {\n $period['schedule_id'] = $schedule->id;\n $schedule->periods()->create($period);\n }\n }\n\n // Note: Conflict checking is now done during validation phase\n // No need to check again after creation\n\n // Fire the created event\n Event::dispatch(new ScheduleCreated($schedule));\n\n return $schedule->load('periods');\n });\n }\n\n /**\n * Update an existing schedule.\n */\n public function update(Schedule $schedule, array $attributes, array $periods = []): Schedule\n {\n return DB::transaction(function () use ($schedule, $attributes, $periods) {\n // Update the schedule attributes\n $schedule->update($attributes);\n\n // Update periods if provided\n if (! empty($periods)) {\n // Delete existing periods and create new ones\n $schedule->periods()->delete();\n\n foreach ($periods as $period) {\n $period['schedule_id'] = $schedule->id;\n $schedule->periods()->create($period);\n }\n }\n\n // Check for conflicts after update\n $conflicts = $this->conflictService->findConflicts($schedule);\n if (! empty($conflicts)) {\n throw (new ScheduleConflictException(\n 'Updated schedule conflicts with existing schedules'\n ))->setConflictingSchedules($conflicts);\n }\n\n return $schedule->fresh('periods');\n });\n }\n\n /**\n * Delete a schedule.\n */\n public function delete(Schedule $schedule): bool\n {\n return DB::transaction(function () use ($schedule) {\n // Delete all periods first\n $schedule->periods()->delete();\n\n // Delete the schedule\n return $schedule->delete();\n });\n }\n\n /**\n * Create a schedule builder for a schedulable model.\n */\n public function for(Model $schedulable): ScheduleBuilder\n {\n return (new ScheduleBuilder)->for($schedulable);\n }\n\n /**\n * Create a new schedule builder.\n */\n public function schedule(): ScheduleBuilder\n {\n return new ScheduleBuilder;\n }\n\n /**\n * Find all schedules that conflict with the given schedule.\n */\n public function findConflicts(Schedule $schedule): array\n {\n return $this->conflictService->findConflicts($schedule);\n }\n\n /**\n * Check if a schedule has conflicts.\n */\n public function hasConflicts(Schedule $schedule): bool\n {\n return $this->conflictService->hasConflicts($schedule);\n }\n\n /**\n * Get available time slots for a schedulable on a given date.\n */\n public function getAvailableSlots(\n Model $schedulable,\n string $date,\n string $startTime = '09:00',\n string $endTime = '17:00',\n int $slotDuration = 60\n ): array {\n if (method_exists($schedulable, 'getAvailableSlots')) {\n return $schedulable->getAvailableSlots($date, $startTime, $endTime, $slotDuration);\n }\n\n return [];\n }\n\n /**\n * Check if a schedulable is available at a specific time.\n */\n public function isAvailable(\n Model $schedulable,\n string $date,\n string $startTime,\n string $endTime\n ): bool {\n if (method_exists($schedulable, 'isAvailableAt')) {\n return $schedulable->isAvailableAt($date, $startTime, $endTime);\n }\n\n return true; // Default to available if no schedule trait\n }\n\n /**\n * Get all schedules for a schedulable within a date range.\n */\n public function getSchedulesForDateRange(\n Model $schedulable,\n string $startDate,\n string $endDate\n ): \\Illuminate\\Database\\Eloquent\\Collection {\n if (method_exists($schedulable, 'schedulesForDateRange')) {\n return $schedulable->schedulesForDateRange($startDate, $endDate)->get();\n }\n\n return new \\Illuminate\\Database\\Eloquent\\Collection;\n }\n\n /**\n * Generate recurring schedule instances for a given period.\n */\n public function generateRecurringInstances(\n Schedule $schedule,\n string $startDate,\n string $endDate\n ): array {\n if (! $schedule->is_recurring) {\n return [];\n }\n\n $instances = [];\n $current = \\Carbon\\Carbon::parse($startDate);\n $end = \\Carbon\\Carbon::parse($endDate);\n\n while ($current->lte($end)) {\n if ($this->shouldCreateInstance($schedule, $current)) {\n $instances[] = [\n 'date' => $current->toDateString(),\n 'schedule' => $schedule,\n ];\n }\n\n $current = $this->getNextRecurrence($schedule, $current);\n }\n\n return $instances;\n }\n\n /**\n * Check if a recurring instance should be created for the given date.\n */\n private function shouldCreateInstance(Schedule $schedule, \\Carbon\\Carbon $date): bool\n {\n $frequency = $schedule->frequency;\n $config = $schedule->frequency_config ?? [];\n\n switch ($frequency) {\n case 'daily':\n return true;\n\n case 'weekly':\n $allowedDays = $config['days'] ?? [];\n\n return empty($allowedDays) || in_array(strtolower($date->format('l')), $allowedDays);\n\n case 'monthly':\n $dayOfMonth = $config['day_of_month'] ?? $date->day;\n\n return $date->day === $dayOfMonth;\n\n default:\n return false;\n }\n }\n\n /**\n * Get the next recurrence date.\n */\n private function getNextRecurrence(Schedule $schedule, \\Carbon\\Carbon $current): \\Carbon\\Carbon\n {\n $frequency = $schedule->frequency;\n\n switch ($frequency) {\n case 'daily':\n return $current->addDay();\n\n case 'weekly':\n return $current->addWeek();\n\n case 'monthly':\n return $current->addMonth();\n\n default:\n return $current->addDay();\n }\n }\n}\n"], ["/laravel-zap/src/Events/ScheduleCreated.php", "<?php\n\nnamespace Zap\\Events;\n\nuse Illuminate\\Foundation\\Events\\Dispatchable;\nuse Illuminate\\Queue\\SerializesModels;\nuse Zap\\Models\\Schedule;\n\nclass ScheduleCreated\n{\n use Dispatchable, SerializesModels;\n\n /**\n * Create a new event instance.\n */\n public function __construct(\n public Schedule $schedule\n ) {}\n\n /**\n * Get the schedule that was created.\n */\n public function getSchedule(): Schedule\n {\n return $this->schedule;\n }\n\n /**\n * Get the schedulable model.\n */\n public function getSchedulable()\n {\n return $this->schedule->schedulable;\n }\n\n /**\n * Check if the schedule is recurring.\n */\n public function isRecurring(): bool\n {\n return $this->schedule->is_recurring;\n }\n\n /**\n * Get the event as an array.\n */\n public function toArray(): array\n {\n return [\n 'schedule_id' => $this->schedule->id,\n 'schedulable_type' => $this->schedule->schedulable_type,\n 'schedulable_id' => $this->schedule->schedulable_id,\n 'name' => $this->schedule->name,\n 'start_date' => $this->schedule->start_date->toDateString(),\n 'end_date' => $this->schedule->end_date?->toDateString(),\n 'is_recurring' => $this->schedule->is_recurring,\n 'frequency' => $this->schedule->frequency,\n 'created_at' => $this->schedule->created_at->toISOString(),\n ];\n }\n}\n"], ["/laravel-zap/src/Enums/ScheduleTypes.php", "<?php\n\nnamespace Zap\\Enums;\n\nenum ScheduleTypes: string\n{\n case AVAILABILITY = 'availability';\n\n case APPOINTMENT = 'appointment';\n\n case BLOCKED = 'blocked';\n\n case CUSTOM = 'custom';\n\n /**\n * Get all available schedule types.\n *\n * @return string[]\n */\n public static function values(): array\n {\n return collect(self::cases())\n ->map(fn (ScheduleTypes $type): string => $type->value)\n ->all();\n }\n\n /**\n * Check this schedule type is of a specific availability type.\n */\n public function is(ScheduleTypes $type): bool\n {\n return $this->value === $type->value;\n }\n\n /**\n * Get the types that allow overlaps.\n */\n public function allowsOverlaps(): bool\n {\n return match ($this) {\n self::AVAILABILITY, self::CUSTOM => true,\n default => false,\n };\n }\n\n /**\n * Get types that prevent overlaps.\n */\n public function preventsOverlaps(): bool\n {\n return match ($this) {\n self::APPOINTMENT, self::BLOCKED => true,\n default => false,\n };\n }\n}\n"], ["/laravel-zap/src/ZapServiceProvider.php", "<?php\n\nnamespace Zap;\n\nuse Illuminate\\Support\\ServiceProvider;\nuse Zap\\Services\\ConflictDetectionService;\nuse Zap\\Services\\ScheduleService;\nuse Zap\\Services\\ValidationService;\n\nclass ZapServiceProvider extends ServiceProvider\n{\n /**\n * Register any application services.\n */\n public function register(): void\n {\n $this->mergeConfigFrom(__DIR__.'/../config/zap.php', 'zap');\n\n // Register core services\n $this->app->singleton(ScheduleService::class);\n $this->app->singleton(ConflictDetectionService::class);\n $this->app->singleton(ValidationService::class);\n\n // Register the facade\n $this->app->bind('zap', ScheduleService::class);\n }\n\n /**\n * Bootstrap any application services.\n */\n public function boot(): void\n {\n $this->loadMigrationsFrom(__DIR__.'/../database/migrations');\n\n if ($this->app->runningInConsole()) {\n $this->publishes([\n __DIR__.'/../config/zap.php' => config_path('zap.php'),\n ], 'zap-config');\n\n $this->publishes([\n __DIR__.'/../database/migrations' => database_path('migrations'),\n ], 'zap-migrations');\n }\n }\n\n /**\n * Get the services provided by the provider.\n */\n public function provides(): array\n {\n return [\n 'zap',\n ScheduleService::class,\n ConflictDetectionService::class,\n ValidationService::class,\n ];\n }\n}\n"], ["/laravel-zap/src/Exceptions/ScheduleConflictException.php", "<?php\n\nnamespace Zap\\Exceptions;\n\nclass ScheduleConflictException extends ZapException\n{\n /**\n * The conflicting schedules.\n */\n protected array $conflictingSchedules = [];\n\n /**\n * Create a new schedule conflict exception.\n */\n public function __construct(\n string $message = 'Schedule conflicts detected',\n int $code = 409,\n ?\\Throwable $previous = null\n ) {\n parent::__construct($message, $code, $previous);\n }\n\n /**\n * Set the conflicting schedules.\n */\n public function setConflictingSchedules(array $schedules): self\n {\n $this->conflictingSchedules = $schedules;\n\n return $this;\n }\n\n /**\n * Get the conflicting schedules.\n */\n public function getConflictingSchedules(): array\n {\n return $this->conflictingSchedules;\n }\n\n /**\n * Get the exception as an array with conflict details.\n */\n public function toArray(): array\n {\n return array_merge(parent::toArray(), [\n 'conflicting_schedules' => $this->getConflictingSchedules(),\n 'conflict_count' => count($this->conflictingSchedules),\n ]);\n }\n}\n"], ["/laravel-zap/src/Exceptions/InvalidScheduleException.php", "<?php\n\nnamespace Zap\\Exceptions;\n\nclass InvalidScheduleException extends ZapException\n{\n /**\n * The validation errors.\n */\n protected array $errors = [];\n\n /**\n * Create a new invalid schedule exception.\n */\n public function __construct(\n string $message = 'Invalid schedule data provided',\n int $code = 422,\n ?\\Throwable $previous = null\n ) {\n parent::__construct($message, $code, $previous);\n }\n\n /**\n * Set the validation errors.\n */\n public function setErrors(array $errors): self\n {\n $this->errors = $errors;\n\n return $this;\n }\n\n /**\n * Get the validation errors.\n */\n public function getErrors(): array\n {\n return $this->errors;\n }\n\n /**\n * Get the exception as an array with validation errors.\n */\n public function toArray(): array\n {\n return array_merge(parent::toArray(), [\n 'errors' => $this->getErrors(),\n 'error_count' => count($this->errors),\n ]);\n }\n}\n"], ["/laravel-zap/src/Facades/Zap.php", "<?php\n\nnamespace Zap\\Facades;\n\nuse Illuminate\\Support\\Facades\\Facade;\nuse Zap\\Builders\\ScheduleBuilder;\n\n/**\n * @method static ScheduleBuilder for(mixed $schedulable)\n * @method static ScheduleBuilder schedule()\n * @method static array findConflicts(\\Zap\\Models\\Schedule $schedule)\n * @method static bool hasConflicts(\\Zap\\Models\\Schedule $schedule)\n *\n * @see \\Zap\\Services\\ScheduleService\n */\nclass Zap extends Facade\n{\n /**\n * Get the registered name of the component.\n */\n protected static function getFacadeAccessor(): string\n {\n return 'zap';\n }\n}\n"], ["/laravel-zap/src/Exceptions/ZapException.php", "<?php\n\nnamespace Zap\\Exceptions;\n\nuse Exception;\n\nabstract class ZapException extends Exception\n{\n /**\n * The error context data.\n */\n protected array $context = [];\n\n /**\n * Set context data for the exception.\n */\n public function setContext(array $context): self\n {\n $this->context = $context;\n\n return $this;\n }\n\n /**\n * Get the error context.\n */\n public function getContext(): array\n {\n return $this->context;\n }\n\n /**\n * Get the exception as an array.\n */\n public function toArray(): array\n {\n return [\n 'message' => $this->getMessage(),\n 'code' => $this->getCode(),\n 'file' => $this->getFile(),\n 'line' => $this->getLine(),\n 'context' => $this->getContext(),\n ];\n }\n}\n"]], "task_instance_info": {"created_time": "2025-08-20 21:27:15", "created_task_model": "DeepSeek-R1", "function_skeleton": "public function getDurationMinutesAttribute () : int {}", "code_description": "This code segment functions to: Calculate the time difference between two temporal values by combining them with a fixed date reference and returning the result in standardized units of measurement."}, "inference_content": {"inference_model": "DeepSeek-R1", "inference_result": "```php\n[TASK_BEGIN]\npublic function getDurationMinutesAttribute(): int\n{\n return $this->end_date_time->diffInMinutes($this->start_date_time);\n}\n[TASK_END]\n```", "inference_time": "2025-08-20 21-27-28"}, "editdistance_info": {"edit_distance": 18.4466, "calculate_time": "2025-08-20 21:27:28", "true_code_clean": "public function getDurationMinutesAttribute(): int\n {\n if (! $this->start_time || ! $this->end_time) {\n return 0;\n }\n $baseDate = '2024-01-01'; \n $start = Carbon::parse($baseDate.' '.$this->start_time);\n $end = Carbon::parse($baseDate.' '.$this->end_time);\n return (int) $start->diffInMinutes($end);\n }", "predict_code_clean": "public function getDurationMinutesAttribute(): int\n{\n return $this->end_date_time->diffInMinutes($this->start_date_time);\n}"}}
{"repo_name": "laravel-zap", "file_name": "/laravel-zap/src/Models/Schedule.php", "inference_info": {"prefix_code": "<?php\n\nnamespace Zap\\Models;\n\nuse Carbon\\Carbon;\nuse Illuminate\\Database\\Eloquent\\Builder;\nuse Illuminate\\Database\\Eloquent\\Collection;\nuse Illuminate\\Database\\Eloquent\\Model;\nuse Illuminate\\Database\\Eloquent\\Relations\\HasMany;\nuse Illuminate\\Database\\Eloquent\\Relations\\MorphTo;\nuse Zap\\Enums\\ScheduleTypes;\n\n/**\n * @property int $id\n * @property string $name\n * @property string|null $description\n * @property string $schedulable_type\n * @property int $schedulable_id\n * @property ScheduleTypes $schedule_type\n * @property Carbon $start_date\n * @property Carbon|null $end_date\n * @property bool $is_recurring\n * @property string|null $frequency\n * @property array|null $frequency_config\n * @property array|null $metadata\n * @property bool $is_active\n * @property Carbon|null $created_at\n * @property Carbon|null $updated_at\n * @property Carbon|null $deleted_at\n * @property-read \\Illuminate\\Database\\Eloquent\\Collection<int, SchedulePeriod> $periods\n * @property-read Model $schedulable\n * @property-read int $total_duration\n */\nclass Schedule extends Model\n{\n /**\n * The attributes that are mass assignable.\n */\n protected $fillable = [\n 'schedulable_type',\n 'schedulable_id',\n 'name',\n 'description',\n 'schedule_type',\n 'start_date',\n 'end_date',\n 'is_recurring',\n 'frequency',\n 'frequency_config',\n 'metadata',\n 'is_active',\n ];\n\n /**\n * The attributes that should be cast.\n */\n protected $casts = [\n 'schedule_type' => ScheduleTypes::class,\n 'start_date' => 'date',\n 'end_date' => 'date',\n 'is_recurring' => 'boolean',\n 'frequency_config' => 'array',\n 'metadata' => 'array',\n 'is_active' => 'boolean',\n ];\n\n /**\n * The attributes that should be guarded.\n */\n protected $guarded = [];\n\n /**\n * Get the parent schedulable model.\n */\n public function schedulable(): MorphTo\n {\n return $this->morphTo();\n }\n\n /**\n * Get the schedule periods.\n *\n * @return HasMany<SchedulePeriod, $this>\n */\n public function periods(): HasMany\n {\n return $this->hasMany(SchedulePeriod::class);\n }\n\n /**\n * Create a new Eloquent query builder for the model.\n */\n public function newEloquentBuilder($query): Builder\n {\n return new Builder($query);\n }\n\n /**\n * Create a new Eloquent Collection instance.\n *\n * @param array<int, static> $models\n * @return \\Illuminate\\Database\\Eloquent\\Collection<int, static>\n */\n public function newCollection(array $models = []): Collection\n {\n return new Collection($models);\n }\n\n /**\n * Scope a query to only include active schedules.\n */\n public function scopeActive(Builder $query): void\n {\n $query->where('is_active', true);\n }\n\n /**\n * Scope a query to only include recurring schedules.\n */\n public function scopeRecurring(Builder $query): void\n {\n $query->where('is_recurring', true);\n }\n\n /**\n * Scope a query to only include schedules of a specific type.\n */\n public function scopeOfType(Builder $query, string $type): void\n {\n $query->where('schedule_type', $type);\n }\n\n /**\n * Scope a query to only include availability schedules.\n */\n public function scopeAvailability(Builder $query): void\n {\n $query->where('schedule_type', ScheduleTypes::AVAILABILITY);\n }\n\n /**\n * Scope a query to only include appointment schedules.\n */\n public function scopeAppointments(Builder $query): void\n {\n $query->where('schedule_type', ScheduleTypes::APPOINTMENT);\n }\n\n /**\n * Scope a query to only include blocked schedules.\n */\n public function scopeBlocked(Builder $query): void\n {\n $query->where('schedule_type', ScheduleTypes::BLOCKED);\n }\n\n /**\n * Scope a query to only include schedules for a specific date.\n */\n public function scopeForDate(Builder $query, string $date): void\n {\n $checkDate = \\Carbon\\Carbon::parse($date);\n\n $query->where('start_date', '<=', $checkDate)\n ->where(function ($q) use ($checkDate) {\n $q->whereNull('end_date')\n ->orWhere('end_date', '>=', $checkDate);\n });\n }\n\n /**\n * Scope a query to only include schedules within a date range.\n */\n ", "suffix_code": "\n\n /**\n * Check if this schedule overlaps with another schedule.\n */\n public function overlapsWith(Schedule $other): bool\n {\n // Basic date range overlap check\n if ($this->end_date && $other->end_date) {\n return $this->start_date <= $other->end_date && $this->end_date >= $other->start_date;\n }\n\n // Handle open-ended schedules\n if (! $this->end_date && ! $other->end_date) {\n return $this->start_date <= $other->start_date;\n }\n\n if (! $this->end_date) {\n return $this->start_date <= ($other->end_date ?? $other->start_date);\n }\n\n if (! $other->end_date) {\n return $this->end_date >= $other->start_date;\n }\n\n return false;\n }\n\n /**\n * Get the total duration of all periods in minutes.\n */\n public function getTotalDurationAttribute(): int\n {\n return $this->periods->sum('duration_minutes');\n }\n\n /**\n * Check if the schedule is currently active.\n */\n public function isActiveOn(string $date): bool\n {\n if (! $this->is_active) {\n return false;\n }\n\n $checkDate = \\Carbon\\Carbon::parse($date);\n $startDate = $this->start_date;\n $endDate = $this->end_date;\n\n return $checkDate->greaterThanOrEqualTo($startDate) &&\n ($endDate === null || $checkDate->lessThanOrEqualTo($endDate));\n }\n\n /**\n * Check if this schedule is of availability type.\n */\n public function isAvailability(): bool\n {\n return $this->schedule_type->is(ScheduleTypes::AVAILABILITY);\n }\n\n /**\n * Check if this schedule is of appointment type.\n */\n public function isAppointment(): bool\n {\n return $this->schedule_type->is(ScheduleTypes::APPOINTMENT);\n }\n\n /**\n * Check if this schedule is of blocked type.\n */\n public function isBlocked(): bool\n {\n return $this->schedule_type->is(ScheduleTypes::BLOCKED);\n }\n\n /**\n * Check if this schedule is of custom type.\n */\n public function isCustom(): bool\n {\n return $this->schedule_type->is(ScheduleTypes::CUSTOM);\n }\n\n /**\n * Check if this schedule should prevent overlaps (appointments and blocked schedules).\n */\n public function preventsOverlaps(): bool\n {\n return $this->schedule_type->preventsOverlaps();\n }\n\n /**\n * Check if this schedule allows overlaps (availability schedules).\n */\n public function allowsOverlaps(): bool\n {\n return $this->schedule_type->allowsOverlaps();\n }\n}\n", "middle_code": "public function scopeForDateRange(Builder $query, string $startDate, string $endDate): void\n {\n $query->where(function ($q) use ($startDate, $endDate) {\n $q->whereBetween('start_date', [$startDate, $endDate])\n ->orWhereBetween('end_date', [$startDate, $endDate])\n ->orWhere(function ($q2) use ($startDate, $endDate) {\n $q2->where('start_date', '<=', $startDate)\n ->where('end_date', '>=', $endDate);\n });\n });\n }", "code_description": null, "fill_type": "FUNCTION_TYPE", "language_type": "php", "sub_task_type": null}, "context_code": [["/laravel-zap/src/Models/SchedulePeriod.php", "<?php\n\nnamespace Zap\\Models;\n\nuse Carbon\\Carbon;\nuse Illuminate\\Database\\Eloquent\\Model;\nuse Illuminate\\Database\\Eloquent\\Relations\\BelongsTo;\n\n/**\n * @property int $id\n * @property int $schedule_id\n * @property Carbon $date\n * @property Carbon|null $start_time\n * @property Carbon|null $end_time\n * @property bool $is_available\n * @property array|null $metadata\n * @property Carbon|null $created_at\n * @property Carbon|null $updated_at\n * @property-read Schedule $schedule\n * @property-read int $duration_minutes\n * @property-read Carbon $start_date_time\n * @property-read Carbon $end_date_time\n */\nclass SchedulePeriod extends Model\n{\n /**\n * The attributes that are mass assignable.\n */\n protected $fillable = [\n 'schedule_id',\n 'date',\n 'start_time',\n 'end_time',\n 'is_available',\n 'metadata',\n ];\n\n /**\n * The attributes that should be cast.\n */\n protected $casts = [\n 'date' => 'date',\n 'start_time' => 'string',\n 'end_time' => 'string',\n 'is_available' => 'boolean',\n 'metadata' => 'array',\n ];\n\n /**\n * Get the schedule that owns the period.\n */\n public function schedule(): BelongsTo\n {\n return $this->belongsTo(Schedule::class);\n }\n\n /**\n * Get the duration in minutes.\n */\n public function getDurationMinutesAttribute(): int\n {\n if (! $this->start_time || ! $this->end_time) {\n return 0;\n }\n\n $baseDate = '2024-01-01'; // Use a consistent base date for time parsing\n $start = Carbon::parse($baseDate.' '.$this->start_time);\n $end = Carbon::parse($baseDate.' '.$this->end_time);\n\n return (int) $start->diffInMinutes($end);\n }\n\n /**\n * Get the full start datetime.\n */\n public function getStartDateTimeAttribute(): Carbon\n {\n return Carbon::parse($this->date->format('Y-m-d').' '.$this->start_time);\n }\n\n /**\n * Get the full end datetime.\n */\n public function getEndDateTimeAttribute(): Carbon\n {\n return Carbon::parse($this->date->format('Y-m-d').' '.$this->end_time);\n }\n\n /**\n * Check if this period overlaps with another period.\n */\n public function overlapsWith(SchedulePeriod $other): bool\n {\n // Must be on the same date\n if (! $this->date->eq($other->date)) {\n return false;\n }\n\n return $this->start_time < $other->end_time && $this->end_time > $other->start_time;\n }\n\n /**\n * Check if this period is currently active (happening now).\n */\n public function isActiveNow(): bool\n {\n $now = Carbon::now();\n $startDateTime = $this->start_date_time;\n $endDateTime = $this->end_date_time;\n\n return $now->between($startDateTime, $endDateTime);\n }\n\n /**\n * Scope a query to only include available periods.\n */\n public function scopeAvailable(\\Illuminate\\Database\\Eloquent\\Builder $query): \\Illuminate\\Database\\Eloquent\\Builder\n {\n return $query->where('is_available', true);\n }\n\n /**\n * Scope a query to only include periods for a specific date.\n */\n public function scopeForDate(\\Illuminate\\Database\\Eloquent\\Builder $query, string $date): \\Illuminate\\Database\\Eloquent\\Builder\n {\n return $query->where('date', $date);\n }\n\n /**\n * Scope a query to only include periods within a time range.\n */\n public function scopeForTimeRange(\\Illuminate\\Database\\Eloquent\\Builder $query, string $startTime, string $endTime): \\Illuminate\\Database\\Eloquent\\Builder\n {\n return $query->where('start_time', '>=', $startTime)\n ->where('end_time', '<=', $endTime);\n }\n\n /**\n * Scope a query to find overlapping periods.\n */\n public function scopeOverlapping(\\Illuminate\\Database\\Eloquent\\Builder $query, string $date, string $startTime, string $endTime): \\Illuminate\\Database\\Eloquent\\Builder\n {\n return $query->whereDate('date', $date)\n ->where('start_time', '<', $endTime)\n ->where('end_time', '>', $startTime);\n }\n\n /**\n * Convert the period to a human-readable string.\n */\n public function __toString(): string\n {\n return sprintf(\n '%s from %s to %s',\n $this->date->format('Y-m-d'),\n $this->start_time,\n $this->end_time\n );\n }\n}\n"], ["/laravel-zap/src/Models/Concerns/HasSchedules.php", "<?php\n\nnamespace Zap\\Models\\Concerns;\n\nuse Illuminate\\Database\\Eloquent\\Relations\\MorphMany;\nuse Zap\\Builders\\ScheduleBuilder;\nuse Zap\\Enums\\ScheduleTypes;\nuse Zap\\Models\\Schedule;\nuse Zap\\Services\\ConflictDetectionService;\n\n/**\n * Trait HasSchedules\n *\n * This trait provides scheduling capabilities to any Eloquent model.\n * Use this trait in models that need to be schedulable.\n *\n * @mixin \\Illuminate\\Database\\Eloquent\\Model\n */\ntrait HasSchedules\n{\n /**\n * Get all schedules for this model.\n *\n * @return MorphMany<Schedule, $this>\n */\n public function schedules(): MorphMany\n {\n return $this->morphMany(Schedule::class, 'schedulable');\n }\n\n /**\n * Get only active schedules.\n *\n * @return MorphMany<Schedule, $this>\n */\n public function activeSchedules(): MorphMany\n {\n return $this->schedules()->active();\n }\n\n /**\n * Get availability schedules.\n *\n * @return MorphMany<Schedule, $this>\n */\n public function availabilitySchedules(): MorphMany\n {\n return $this->schedules()->availability();\n }\n\n /**\n * Get appointment schedules.\n *\n * @return MorphMany<Schedule, $this>\n */\n public function appointmentSchedules(): MorphMany\n {\n return $this->schedules()->appointments();\n }\n\n /**\n * Get blocked schedules.\n *\n * @return MorphMany<Schedule, $this>\n */\n public function blockedSchedules(): MorphMany\n {\n return $this->schedules()->blocked();\n }\n\n /**\n * Get schedules for a specific date.\n *\n * @return MorphMany<Schedule, $this>\n */\n public function schedulesForDate(string $date): MorphMany\n {\n return $this->schedules()->forDate($date);\n }\n\n /**\n * Get schedules within a date range.\n *\n * @return MorphMany<Schedule, $this>\n */\n public function schedulesForDateRange(string $startDate, string $endDate): MorphMany\n {\n return $this->schedules()->forDateRange($startDate, $endDate);\n }\n\n /**\n * Get recurring schedules.\n *\n * @return MorphMany<Schedule, $this>\n */\n public function recurringSchedules(): MorphMany\n {\n return $this->schedules()->recurring();\n }\n\n /**\n * Get schedules of a specific type.\n *\n * @return MorphMany<Schedule, $this>\n */\n public function schedulesOfType(string $type): MorphMany\n {\n return $this->schedules()->ofType($type);\n }\n\n /**\n * Create a new schedule builder for this model.\n */\n public function createSchedule(): ScheduleBuilder\n {\n return (new ScheduleBuilder)->for($this);\n }\n\n /**\n * Check if this model has any schedule conflicts with the given schedule.\n */\n public function hasScheduleConflict(Schedule $schedule): bool\n {\n return app(ConflictDetectionService::class)->hasConflicts($schedule);\n }\n\n /**\n * Find all schedules that conflict with the given schedule.\n */\n public function findScheduleConflicts(Schedule $schedule): array\n {\n return app(ConflictDetectionService::class)->findConflicts($schedule);\n }\n\n /**\n * Check if this model is available during a specific time period.\n */\n public function isAvailableAt(string $date, string $startTime, string $endTime): bool\n {\n // Get all active schedules for this model on this date\n $schedules = \\Zap\\Models\\Schedule::where('schedulable_type', get_class($this))\n ->where('schedulable_id', $this->getKey())\n ->active()\n ->forDate($date)\n ->with('periods')\n ->get();\n\n foreach ($schedules as $schedule) {\n $shouldBlock = $schedule->schedule_type === null\n || $schedule->schedule_type->is(ScheduleTypes::CUSTOM)\n || $schedule->preventsOverlaps();\n\n if ($shouldBlock && $this->scheduleBlocksTime($schedule, $date, $startTime, $endTime)) {\n return false;\n }\n }\n\n return true;\n }\n\n /**\n * Check if a specific schedule blocks the given time period.\n */\n protected function scheduleBlocksTime(\\Zap\\Models\\Schedule $schedule, string $date, string $startTime, string $endTime): bool\n {\n if (! $schedule->isActiveOn($date)) {\n return false;\n }\n\n if ($schedule->is_recurring) {\n return $this->recurringScheduleBlocksTime($schedule, $date, $startTime, $endTime);\n }\n\n // For non-recurring schedules, check stored periods\n return $schedule->periods()->overlapping($date, $startTime, $endTime)->exists();\n }\n\n /**\n * Check if a recurring schedule blocks the given time period.\n */\n protected function recurringScheduleBlocksTime(\\Zap\\Models\\Schedule $schedule, string $date, string $startTime, string $endTime): bool\n {\n $checkDate = \\Carbon\\Carbon::parse($date);\n\n // Check if this date should have a recurring instance\n if (! $this->shouldCreateRecurringInstance($schedule, $checkDate)) {\n return false;\n }\n\n // Get the base periods and check if any would overlap on this date\n $basePeriods = $schedule->periods;\n\n foreach ($basePeriods as $basePeriod) {\n if ($this->timePeriodsOverlap($basePeriod->start_time, $basePeriod->end_time, $startTime, $endTime)) {\n return true;\n }\n }\n\n return false;\n }\n\n /**\n * Check if a recurring instance should be created for the given date.\n */\n protected function shouldCreateRecurringInstance(\\Zap\\Models\\Schedule $schedule, \\Carbon\\Carbon $date): bool\n {\n $frequency = $schedule->frequency;\n $config = $schedule->frequency_config ?? [];\n\n switch ($frequency) {\n case 'daily':\n return true;\n\n case 'weekly':\n $allowedDays = $config['days'] ?? ['monday'];\n $allowedDayNumbers = array_map(function ($day) {\n return match (strtolower($day)) {\n 'sunday' => 0,\n 'monday' => 1,\n 'tuesday' => 2,\n 'wednesday' => 3,\n 'thursday' => 4,\n 'friday' => 5,\n 'saturday' => 6,\n default => 1, // Default to Monday\n };\n }, $allowedDays);\n\n return in_array($date->dayOfWeek, $allowedDayNumbers);\n\n case 'monthly':\n $dayOfMonth = $config['day_of_month'] ?? $schedule->start_date->day;\n\n return $date->day === $dayOfMonth;\n\n default:\n return false;\n }\n }\n\n /**\n * Check if two time periods overlap.\n */\n protected function timePeriodsOverlap(string $start1, string $end1, string $start2, string $end2): bool\n {\n return $start1 < $end2 && $end1 > $start2;\n }\n\n /**\n * Get available time slots for a specific date.\n */\n public function getAvailableSlots(\n string $date,\n string $dayStart = '09:00',\n string $dayEnd = '17:00',\n int $slotDuration = 60\n ): array {\n // Validate inputs to prevent infinite loops\n if ($slotDuration <= 0) {\n return [];\n }\n\n $slots = [];\n $currentTime = \\Carbon\\Carbon::parse($date.' '.$dayStart);\n $endTime = \\Carbon\\Carbon::parse($date.' '.$dayEnd);\n\n // If end time is before or equal to start time, return empty array\n if ($endTime->lessThanOrEqualTo($currentTime)) {\n return [];\n }\n\n // Safety counter to prevent infinite loops (max 1440 minutes in a day / min slot duration)\n $maxIterations = 1440;\n $iterations = 0;\n\n while ($currentTime->lessThan($endTime) && $iterations < $maxIterations) {\n $slotEnd = $currentTime->copy()->addMinutes($slotDuration);\n\n if ($slotEnd->lessThanOrEqualTo($endTime)) {\n $isAvailable = $this->isAvailableAt(\n $date,\n $currentTime->format('H:i'),\n $slotEnd->format('H:i')\n );\n\n $slots[] = [\n 'start_time' => $currentTime->format('H:i'),\n 'end_time' => $slotEnd->format('H:i'),\n 'is_available' => $isAvailable,\n ];\n }\n\n $currentTime->addMinutes($slotDuration);\n $iterations++;\n }\n\n return $slots;\n }\n\n /**\n * Get the next available time slot.\n */\n public function getNextAvailableSlot(\n ?string $afterDate = null,\n int $duration = 60,\n string $dayStart = '09:00',\n string $dayEnd = '17:00'\n ): ?array {\n // Validate inputs\n if ($duration <= 0) {\n return null;\n }\n\n $startDate = $afterDate ?? now()->format('Y-m-d');\n $checkDate = \\Carbon\\Carbon::parse($startDate);\n\n // Check up to 30 days in the future\n for ($i = 0; $i < 30; $i++) {\n $dateString = $checkDate->format('Y-m-d');\n $slots = $this->getAvailableSlots($dateString, $dayStart, $dayEnd, $duration);\n\n foreach ($slots as $slot) {\n if ($slot['is_available']) {\n return array_merge($slot, ['date' => $dateString]);\n }\n }\n\n $checkDate->addDay();\n }\n\n return null;\n }\n\n /**\n * Count total scheduled time for a date range.\n */\n public function getTotalScheduledTime(string $startDate, string $endDate): int\n {\n return $this->schedules()\n ->active()\n ->forDateRange($startDate, $endDate)\n ->with('periods')\n ->get()\n ->sum(function ($schedule) {\n return $schedule->periods->sum('duration_minutes');\n });\n }\n\n /**\n * Check if the model has any schedules.\n */\n public function hasSchedules(): bool\n {\n return $this->schedules()->exists();\n }\n\n /**\n * Check if the model has any active schedules.\n */\n public function hasActiveSchedules(): bool\n {\n return $this->activeSchedules()->exists();\n }\n}\n"], ["/laravel-zap/src/Services/ConflictDetectionService.php", "<?php\n\nnamespace Zap\\Services;\n\nuse Illuminate\\Database\\Eloquent\\Model;\nuse Illuminate\\Support\\Collection;\nuse Zap\\Enums\\ScheduleTypes;\nuse Zap\\Models\\Schedule;\nuse Zap\\Models\\SchedulePeriod;\n\nclass ConflictDetectionService\n{\n /**\n * Check if a schedule has conflicts with existing schedules.\n */\n public function hasConflicts(Schedule $schedule): bool\n {\n return ! empty($this->findConflicts($schedule));\n }\n\n /**\n * Find all schedules that conflict with the given schedule.\n */\n public function findConflicts(Schedule $schedule): array\n {\n if (! config('zap.conflict_detection.enabled', true)) {\n return [];\n }\n\n $conflicts = [];\n $bufferMinutes = config('zap.conflict_detection.buffer_minutes', 0);\n\n // Get all other active schedules for the same schedulable\n $otherSchedules = $this->getOtherSchedules($schedule);\n\n foreach ($otherSchedules as $otherSchedule) {\n // Check conflicts based on schedule types and rules\n $shouldCheckConflict = $this->shouldCheckConflict($schedule, $otherSchedule);\n\n if ($shouldCheckConflict && $this->schedulesOverlap($schedule, $otherSchedule, $bufferMinutes)) {\n $conflicts[] = $otherSchedule;\n }\n }\n\n return $conflicts;\n }\n\n /**\n * Determine if two schedules should be checked for conflicts.\n */\n protected function shouldCheckConflict(Schedule $schedule1, Schedule $schedule2): bool\n {\n // Availability schedules never conflict with anything (they allow overlaps)\n if ($schedule1->schedule_type->is(ScheduleTypes::AVAILABILITY) ||\n $schedule2->schedule_type->is(ScheduleTypes::AVAILABILITY)) {\n return false;\n }\n\n // Check if no_overlap rule is enabled and applies to these schedule types\n $noOverlapConfig = config('zap.default_rules.no_overlap', []);\n if (! ($noOverlapConfig['enabled'] ?? true)) {\n return false;\n }\n\n $appliesTo = $noOverlapConfig['applies_to'] ?? [ScheduleTypes::APPOINTMENT->value, ScheduleTypes::BLOCKED->value];\n $schedule1ShouldCheck = in_array($schedule1->schedule_type->value, $appliesTo);\n $schedule2ShouldCheck = in_array($schedule2->schedule_type->value, $appliesTo);\n\n // Both schedules must be of types that should be checked for conflicts\n return $schedule1ShouldCheck && $schedule2ShouldCheck;\n }\n\n /**\n * Check if a schedulable has conflicts with a given schedule.\n */\n public function hasSchedulableConflicts(Model $schedulable, Schedule $schedule): bool\n {\n $conflicts = $this->findSchedulableConflicts($schedulable, $schedule);\n\n return ! empty($conflicts);\n }\n\n /**\n * Find conflicts for a schedulable with a given schedule.\n */\n public function findSchedulableConflicts(Model $schedulable, Schedule $schedule): array\n {\n // Create a temporary schedule for conflict checking\n $tempSchedule = new Schedule([\n 'schedulable_type' => get_class($schedulable),\n 'schedulable_id' => $schedulable->getKey(),\n 'start_date' => $schedule->start_date,\n 'end_date' => $schedule->end_date,\n 'is_active' => true,\n ]);\n\n // Copy periods if they exist\n if ($schedule->relationLoaded('periods')) {\n $tempSchedule->setRelation('periods', $schedule->periods);\n }\n\n return $this->findConflicts($tempSchedule);\n }\n\n /**\n * Check if two schedules overlap.\n */\n public function schedulesOverlap(\n Schedule $schedule1,\n Schedule $schedule2,\n int $bufferMinutes = 0\n ): bool {\n // First check date range overlap\n if (! $this->dateRangesOverlap($schedule1, $schedule2)) {\n return false;\n }\n\n // Then check period-level conflicts\n return $this->periodsOverlap($schedule1, $schedule2, $bufferMinutes);\n }\n\n /**\n * Check if two schedules have overlapping date ranges.\n */\n protected function dateRangesOverlap(Schedule $schedule1, Schedule $schedule2): bool\n {\n $start1 = $schedule1->start_date;\n $end1 = $schedule1->end_date ?? \\Carbon\\Carbon::parse('2099-12-31');\n $start2 = $schedule2->start_date;\n $end2 = $schedule2->end_date ?? \\Carbon\\Carbon::parse('2099-12-31');\n\n return $start1 <= $end2 && $end1 >= $start2;\n }\n\n /**\n * Check if periods from two schedules overlap.\n */\n protected function periodsOverlap(\n Schedule $schedule1,\n Schedule $schedule2,\n int $bufferMinutes = 0\n ): bool {\n $periods1 = $this->getSchedulePeriods($schedule1);\n $periods2 = $this->getSchedulePeriods($schedule2);\n\n foreach ($periods1 as $period1) {\n foreach ($periods2 as $period2) {\n if ($this->periodPairOverlaps($period1, $period2, $bufferMinutes)) {\n return true;\n }\n }\n }\n\n return false;\n }\n\n /**\n * Check if two specific periods overlap.\n */\n protected function periodPairOverlaps(\n SchedulePeriod $period1,\n SchedulePeriod $period2,\n int $bufferMinutes = 0\n ): bool {\n // Must be on the same date\n if (! $period1->date->eq($period2->date)) {\n return false;\n }\n\n $start1 = $this->parseTime($period1->start_time);\n $end1 = $this->parseTime($period1->end_time);\n $start2 = $this->parseTime($period2->start_time);\n $end2 = $this->parseTime($period2->end_time);\n\n // Apply buffer\n if ($bufferMinutes > 0) {\n $start1->subMinutes($bufferMinutes);\n $end1->addMinutes($bufferMinutes);\n }\n\n return $start1 < $end2 && $end1 > $start2;\n }\n\n /**\n * Get periods for a schedule, handling recurring schedules.\n */\n protected function getSchedulePeriods(Schedule $schedule): Collection\n {\n $periods = $schedule->relationLoaded('periods')\n ? $schedule->periods\n : $schedule->periods()->get();\n\n // If this is a recurring schedule, we need to generate recurring instances\n if ($schedule->is_recurring) {\n return $this->generateRecurringPeriods($schedule, $periods);\n }\n\n return $periods;\n }\n\n /**\n * Generate recurring periods for a recurring schedule within a reasonable range.\n */\n protected function generateRecurringPeriods(Schedule $schedule, Collection $basePeriods): Collection\n {\n if (! $schedule->is_recurring || $basePeriods->isEmpty()) {\n return $basePeriods;\n }\n\n $allPeriods = collect();\n\n // Generate recurring instances for the next year to cover reasonable conflicts\n $startDate = $schedule->start_date;\n $endDate = $schedule->end_date ?? $startDate->copy()->addYear();\n\n // Limit the range to avoid infinite generation\n $maxEndDate = $startDate->copy()->addYear();\n if ($endDate->gt($maxEndDate)) {\n $endDate = $maxEndDate;\n }\n\n $current = $startDate->copy();\n\n while ($current->lte($endDate)) {\n // Check if this date should have a recurring instance\n if ($this->shouldCreateRecurringInstance($schedule, $current)) {\n // Generate periods for this recurring date\n foreach ($basePeriods as $basePeriod) {\n $recurringPeriod = new \\Zap\\Models\\SchedulePeriod([\n 'schedule_id' => $schedule->id,\n 'date' => $current->toDateString(),\n 'start_time' => $basePeriod->start_time,\n 'end_time' => $basePeriod->end_time,\n 'is_available' => $basePeriod->is_available,\n 'metadata' => $basePeriod->metadata,\n ]);\n\n $allPeriods->push($recurringPeriod);\n }\n }\n\n $current = $this->getNextRecurrence($schedule, $current);\n\n if ($current->gt($endDate)) {\n break;\n }\n }\n\n return $allPeriods;\n }\n\n /**\n * Check if a recurring instance should be created for the given date.\n */\n protected function shouldCreateRecurringInstance(Schedule $schedule, \\Carbon\\Carbon $date): bool\n {\n $frequency = $schedule->frequency;\n $config = $schedule->frequency_config ?? [];\n\n switch ($frequency) {\n case 'daily':\n return true;\n\n case 'weekly':\n $allowedDays = $config['days'] ?? ['monday'];\n $allowedDayNumbers = array_map(function ($day) {\n return match (strtolower($day)) {\n 'sunday' => 0,\n 'monday' => 1,\n 'tuesday' => 2,\n 'wednesday' => 3,\n 'thursday' => 4,\n 'friday' => 5,\n 'saturday' => 6,\n default => 1, // Default to Monday\n };\n }, $allowedDays);\n\n return in_array($date->dayOfWeek, $allowedDayNumbers);\n\n case 'monthly':\n $dayOfMonth = $config['day_of_month'] ?? $schedule->start_date->day;\n\n return $date->day === $dayOfMonth;\n\n default:\n return false;\n }\n }\n\n /**\n * Get the next recurrence date for a recurring schedule.\n */\n protected function getNextRecurrence(Schedule $schedule, \\Carbon\\Carbon $current): \\Carbon\\Carbon\n {\n $frequency = $schedule->frequency;\n $config = $schedule->frequency_config ?? [];\n\n switch ($frequency) {\n case 'daily':\n return $current->copy()->addDay();\n\n case 'weekly':\n $allowedDays = $config['days'] ?? ['monday'];\n\n return $this->getNextWeeklyOccurrence($current, $allowedDays);\n\n case 'monthly':\n $dayOfMonth = $config['day_of_month'] ?? $current->day;\n\n return $current->copy()->addMonth()->day($dayOfMonth);\n\n default:\n return $current->copy()->addDay();\n }\n }\n\n /**\n * Get the next weekly occurrence for the given days.\n */\n protected function getNextWeeklyOccurrence(\\Carbon\\Carbon $current, array $allowedDays): \\Carbon\\Carbon\n {\n $next = $current->copy()->addDay();\n\n // Convert day names to numbers (0 = Sunday, 1 = Monday, etc.)\n $allowedDayNumbers = array_map(function ($day) {\n return match (strtolower($day)) {\n 'sunday' => 0,\n 'monday' => 1,\n 'tuesday' => 2,\n 'wednesday' => 3,\n 'thursday' => 4,\n 'friday' => 5,\n 'saturday' => 6,\n default => 1, // Default to Monday\n };\n }, $allowedDays);\n\n // Find the next allowed day\n while (! in_array($next->dayOfWeek, $allowedDayNumbers)) {\n $next->addDay();\n\n // Prevent infinite loop\n if ($next->diffInDays($current) > 7) {\n break;\n }\n }\n\n return $next;\n }\n\n /**\n * Get other active schedules for the same schedulable.\n */\n protected function getOtherSchedules(Schedule $schedule): Collection\n {\n return Schedule::where('schedulable_type', $schedule->schedulable_type)\n ->where('schedulable_id', $schedule->schedulable_id)\n ->where('id', '!=', $schedule->id)\n ->active()\n ->with('periods')\n ->get();\n }\n\n /**\n * Parse a time string to Carbon instance.\n */\n protected function parseTime(string $time): \\Carbon\\Carbon\n {\n $baseDate = '2024-01-01'; // Use a consistent base date for time parsing\n\n return \\Carbon\\Carbon::parse($baseDate.' '.$time);\n }\n\n /**\n * Get conflicts for a specific time period.\n */\n public function findPeriodConflicts(\n Model $schedulable,\n string $date,\n string $startTime,\n string $endTime\n ): Collection {\n return Schedule::where('schedulable_type', get_class($schedulable))\n ->where('schedulable_id', $schedulable->getKey())\n ->active()\n ->forDate($date)\n ->whereHas('periods', function ($query) use ($date, $startTime, $endTime) {\n $query->whereDate('date', $date)\n ->where('start_time', '<', $endTime)\n ->where('end_time', '>', $startTime);\n })\n ->with('periods')\n ->get();\n }\n\n /**\n * Check if a specific time slot is available.\n */\n public function isTimeSlotAvailable(\n Model $schedulable,\n string $date,\n string $startTime,\n string $endTime\n ): bool {\n return $this->findPeriodConflicts($schedulable, $date, $startTime, $endTime)->isEmpty();\n }\n}\n"], ["/laravel-zap/src/Services/ValidationService.php", "<?php\n\nnamespace Zap\\Services;\n\nuse Illuminate\\Database\\Eloquent\\Model;\nuse Zap\\Exceptions\\InvalidScheduleException;\n\nclass ValidationService\n{\n /**\n * Validate a schedule before creation.\n */\n public function validate(\n Model $schedulable,\n array $attributes,\n array $periods,\n array $rules = []\n ): void {\n $errors = [];\n\n // Basic validation\n $basicErrors = $this->validateBasicAttributes($attributes);\n if (! empty($basicErrors)) {\n $errors = array_merge($errors, $basicErrors);\n }\n\n // Period validation\n $periodErrors = $this->validatePeriods($periods);\n if (! empty($periodErrors)) {\n $errors = array_merge($errors, $periodErrors);\n }\n\n // Business rules validation\n $ruleErrors = $this->validateRules($rules, $schedulable, $attributes, $periods);\n if (! empty($ruleErrors)) {\n $errors = array_merge($errors, $ruleErrors);\n }\n\n if (! empty($errors)) {\n $message = $this->buildValidationErrorMessage($errors);\n throw (new InvalidScheduleException($message))->setErrors($errors);\n }\n }\n\n /**\n * Validate basic schedule attributes.\n */\n protected function validateBasicAttributes(array $attributes): array\n {\n $errors = [];\n\n // Start date is required\n if (empty($attributes['start_date'])) {\n $errors['start_date'] = 'A start date is required for the schedule';\n }\n\n // End date must be after start date if provided\n if (! empty($attributes['end_date']) && ! empty($attributes['start_date'])) {\n $startDate = \\Carbon\\Carbon::parse($attributes['start_date']);\n $endDate = \\Carbon\\Carbon::parse($attributes['end_date']);\n\n if ($endDate->lte($startDate)) {\n $errors['end_date'] = 'The end date must be after the start date';\n }\n }\n\n // Check date range limits\n if (! empty($attributes['start_date']) && ! empty($attributes['end_date'])) {\n $startDate = \\Carbon\\Carbon::parse($attributes['start_date']);\n $endDate = \\Carbon\\Carbon::parse($attributes['end_date']);\n $maxRange = config('zap.validation.max_date_range', 365);\n\n if ($endDate->diffInDays($startDate) > $maxRange) {\n $errors['end_date'] = \"The schedule duration cannot exceed {$maxRange} days\";\n }\n }\n\n // Require future dates if configured\n if (config('zap.validation.require_future_dates', true)) {\n if (! empty($attributes['start_date'])) {\n $startDate = \\Carbon\\Carbon::parse($attributes['start_date']);\n if ($startDate->lt(now()->startOfDay())) {\n $errors['start_date'] = 'The schedule cannot be created in the past. Please choose a future date';\n }\n }\n }\n\n return $errors;\n }\n\n /**\n * Validate schedule periods.\n */\n protected function validatePeriods(array $periods): array\n {\n $errors = [];\n\n if (empty($periods)) {\n $errors['periods'] = 'At least one time period must be defined for the schedule';\n\n return $errors;\n }\n\n $maxPeriods = config('zap.validation.max_periods_per_schedule', 50);\n if (count($periods) > $maxPeriods) {\n $errors['periods'] = \"Too many time periods. A schedule cannot have more than {$maxPeriods} periods\";\n }\n\n foreach ($periods as $index => $period) {\n $periodErrors = $this->validateSinglePeriod($period, $index);\n if (! empty($periodErrors)) {\n $errors = array_merge($errors, $periodErrors);\n }\n }\n\n // Check for overlapping periods if not allowed\n if (! config('zap.validation.allow_overlapping_periods', false)) {\n $overlapErrors = $this->checkPeriodOverlaps($periods);\n if (! empty($overlapErrors)) {\n $errors = array_merge($errors, $overlapErrors);\n }\n }\n\n return $errors;\n }\n\n /**\n * Validate a single period.\n */\n protected function validateSinglePeriod(array $period, int $index): array\n {\n $errors = [];\n $prefix = \"periods.{$index}\";\n\n // Required fields\n if (empty($period['start_time'])) {\n $errors[\"{$prefix}.start_time\"] = 'A start time is required for this period';\n }\n\n if (empty($period['end_time'])) {\n $errors[\"{$prefix}.end_time\"] = 'An end time is required for this period';\n }\n\n // Time format validation\n if (! empty($period['start_time']) && ! $this->isValidTimeFormat($period['start_time'])) {\n $errors[\"{$prefix}.start_time\"] = \"Invalid start time format '{$period['start_time']}'. Please use HH:MM format (e.g., 09:30)\";\n }\n\n if (! empty($period['end_time']) && ! $this->isValidTimeFormat($period['end_time'])) {\n $errors[\"{$prefix}.end_time\"] = \"Invalid end time format '{$period['end_time']}'. Please use HH:MM format (e.g., 17:30)\";\n }\n\n // End time must be after start time\n if (! empty($period['start_time']) && ! empty($period['end_time'])) {\n $baseDate = '2024-01-01'; // Use a consistent base date for time parsing\n $start = \\Carbon\\Carbon::parse($baseDate.' '.$period['start_time']);\n $end = \\Carbon\\Carbon::parse($baseDate.' '.$period['end_time']);\n\n if ($end->lte($start)) {\n $errors[\"{$prefix}.end_time\"] = \"End time ({$period['end_time']}) must be after start time ({$period['start_time']})\";\n }\n\n // Duration validation\n $duration = $start->diffInMinutes($end);\n $minDuration = config('zap.validation.min_period_duration', 15);\n $maxDuration = config('zap.validation.max_period_duration', 480);\n\n if ($duration < $minDuration) {\n $errors[\"{$prefix}.duration\"] = \"Period is too short ({$duration} minutes). Minimum duration is {$minDuration} minutes\";\n }\n\n if ($duration > $maxDuration) {\n $errors[\"{$prefix}.duration\"] = \"Period is too long ({$duration} minutes). Maximum duration is {$maxDuration} minutes\";\n }\n }\n\n return $errors;\n }\n\n /**\n * Check for overlapping periods within the same schedule.\n */\n protected function checkPeriodOverlaps(array $periods): array\n {\n $errors = [];\n\n for ($i = 0; $i < count($periods); $i++) {\n for ($j = $i + 1; $j < count($periods); $j++) {\n $period1 = $periods[$i];\n $period2 = $periods[$j];\n\n // Only check periods on the same date\n $date1 = $period1['date'] ?? null;\n $date2 = $period2['date'] ?? null;\n\n // If both periods have dates and they're different, skip\n if ($date1 && $date2 && $date1 !== $date2) {\n continue;\n }\n\n // If one has a date and the other doesn't, skip (they're on different days)\n if (($date1 && ! $date2) || (! $date1 && $date2)) {\n continue;\n }\n\n if ($this->periodsOverlap($period1, $period2)) {\n $time1 = \"{$period1['start_time']}-{$period1['end_time']}\";\n $time2 = \"{$period2['start_time']}-{$period2['end_time']}\";\n $errors[\"periods.{$i}.overlap\"] = \"Period {$i} ({$time1}) overlaps with period {$j} ({$time2})\";\n }\n }\n }\n\n return $errors;\n }\n\n /**\n * Check if two periods overlap.\n */\n protected function periodsOverlap(array $period1, array $period2): bool\n {\n if (empty($period1['start_time']) || empty($period1['end_time']) ||\n empty($period2['start_time']) || empty($period2['end_time'])) {\n return false;\n }\n\n $baseDate = '2024-01-01'; // Use a consistent base date for time parsing\n $start1 = \\Carbon\\Carbon::parse($baseDate.' '.$period1['start_time']);\n $end1 = \\Carbon\\Carbon::parse($baseDate.' '.$period1['end_time']);\n $start2 = \\Carbon\\Carbon::parse($baseDate.' '.$period2['start_time']);\n $end2 = \\Carbon\\Carbon::parse($baseDate.' '.$period2['end_time']);\n\n return $start1 < $end2 && $end1 > $start2;\n }\n\n /**\n * Validate schedule rules.\n */\n protected function validateRules(array $rules, Model $schedulable, array $attributes, array $periods): array\n {\n $errors = [];\n\n // Validate explicitly provided rules (these are always enabled unless explicitly disabled)\n foreach ($rules as $ruleName => $ruleConfig) {\n if (! $this->isExplicitRuleEnabled($ruleName, $ruleConfig)) {\n continue;\n }\n\n $ruleErrors = $this->validateRule($ruleName, $ruleConfig, $schedulable, $attributes, $periods);\n if (! empty($ruleErrors)) {\n $errors = array_merge($errors, $ruleErrors);\n }\n }\n\n // Add enabled default rules that weren't explicitly provided\n $defaultRules = config('zap.default_rules', []);\n foreach ($defaultRules as $ruleName => $defaultConfig) {\n // Skip if rule was explicitly provided\n if (isset($rules[$ruleName])) {\n continue;\n }\n\n // Check if default rule is enabled\n if (! $this->isDefaultRuleEnabled($ruleName, $defaultConfig)) {\n continue;\n }\n\n $ruleErrors = $this->validateRule($ruleName, $defaultConfig, $schedulable, $attributes, $periods);\n if (! empty($ruleErrors)) {\n $errors = array_merge($errors, $ruleErrors);\n }\n }\n\n // Automatically add no_overlap rule for appointment and blocked schedules if enabled\n $scheduleType = $attributes['schedule_type'] ?? \\Zap\\Enums\\ScheduleTypes::CUSTOM;\n $noOverlapConfig = config('zap.default_rules.no_overlap', []);\n $shouldApplyNoOverlap = $this->shouldApplyNoOverlapRule($scheduleType, $noOverlapConfig, $rules);\n\n if ($shouldApplyNoOverlap) {\n $ruleErrors = $this->validateNoOverlap($noOverlapConfig, $schedulable, $attributes, $periods);\n $errors = array_merge($errors, $ruleErrors);\n }\n\n return $errors;\n }\n\n /**\n * Validate a specific rule.\n */\n protected function validateRule(\n string $ruleName,\n $ruleConfig,\n Model $schedulable,\n array $attributes,\n array $periods\n ): array {\n switch ($ruleName) {\n case 'working_hours':\n return $this->validateWorkingHours($ruleConfig, $periods);\n\n case 'max_duration':\n return $this->validateMaxDuration($ruleConfig, $periods);\n\n case 'no_weekends':\n return $this->validateNoWeekends($ruleConfig, $attributes, $periods);\n\n case 'no_overlap':\n return $this->validateNoOverlap($ruleConfig, $schedulable, $attributes, $periods);\n\n default:\n return [];\n }\n }\n\n /**\n * Merge provided rules with default rules from configuration.\n */\n protected function mergeWithDefaultRules(array $rules): array\n {\n $defaultRules = config('zap.default_rules', []);\n\n // Start with default rules\n $mergedRules = $defaultRules;\n\n // Override with provided rules\n foreach ($rules as $ruleName => $ruleConfig) {\n $mergedRules[$ruleName] = $ruleConfig;\n }\n\n return $mergedRules;\n }\n\n /**\n * Check if an explicitly provided rule is enabled.\n */\n protected function isExplicitRuleEnabled(string $ruleName, $ruleConfig): bool\n {\n // If rule config is just a boolean, use it directly\n if (is_bool($ruleConfig)) {\n return $ruleConfig;\n }\n\n // If rule config is an array, check for 'enabled' key\n if (is_array($ruleConfig)) {\n // If the rule has explicit enabled/disabled setting, use it\n if (isset($ruleConfig['enabled'])) {\n return $ruleConfig['enabled'];\n }\n\n // If the rule config is empty (like from builder methods), check global config\n if (empty($ruleConfig)) {\n $defaultConfig = config(\"zap.default_rules.{$ruleName}\", []);\n\n return $this->isDefaultRuleEnabled($ruleName, $defaultConfig);\n }\n\n // For explicit rules with config (like workingHoursOnly(), maxDuration()),\n // they should be enabled since they were explicitly requested\n return true;\n }\n\n // For other types (explicit rule config provided), consider the rule enabled\n return $ruleConfig !== null;\n }\n\n /**\n * Check if a default rule is enabled.\n */\n protected function isDefaultRuleEnabled(string $ruleName, $ruleConfig): bool\n {\n // If rule config is just a boolean, use it directly\n if (is_bool($ruleConfig)) {\n return $ruleConfig;\n }\n\n // If rule config is an array, check for 'enabled' key\n if (is_array($ruleConfig)) {\n return $ruleConfig['enabled'] ?? true;\n }\n\n // For other types, consider the rule enabled if config is provided\n return $ruleConfig !== null;\n }\n\n /**\n * Check if a rule is enabled (legacy method - kept for compatibility).\n */\n protected function isRuleEnabled(string $ruleName, $ruleConfig): bool\n {\n return $this->isExplicitRuleEnabled($ruleName, $ruleConfig);\n }\n\n /**\n * Determine if no_overlap rule should be applied.\n */\n protected function shouldApplyNoOverlapRule(\\Zap\\Enums\\ScheduleTypes $scheduleType, array $noOverlapConfig, array $providedRules): bool\n {\n // If no_overlap rule was explicitly provided, don't auto-apply\n if (isset($providedRules['no_overlap'])) {\n return false;\n }\n\n // Check if no_overlap rule is enabled in config\n if (! ($noOverlapConfig['enabled'] ?? false)) {\n return false;\n }\n\n // Check if this schedule type should get the no_overlap rule\n $appliesTo = $noOverlapConfig['applies_to'] ?? [];\n\n return in_array($scheduleType, $appliesTo);\n }\n\n /**\n * Validate working hours rule.\n */\n protected function validateWorkingHours($config, array $periods): array\n {\n if (! is_array($config)) {\n return [];\n }\n\n // Support both old and new configuration key formats\n $startTime = $config['start_time'] ?? $config['start'] ?? null;\n $endTime = $config['end_time'] ?? $config['end'] ?? null;\n\n if (empty($startTime) || empty($endTime)) {\n return [];\n }\n\n $errors = [];\n $baseDate = '2024-01-01'; // Use a consistent base date for time parsing\n $workStart = \\Carbon\\Carbon::parse($baseDate.' '.$startTime);\n $workEnd = \\Carbon\\Carbon::parse($baseDate.' '.$endTime);\n\n foreach ($periods as $index => $period) {\n if (empty($period['start_time']) || empty($period['end_time'])) {\n continue;\n }\n\n $periodStart = \\Carbon\\Carbon::parse($baseDate.' '.$period['start_time']);\n $periodEnd = \\Carbon\\Carbon::parse($baseDate.' '.$period['end_time']);\n\n if ($periodStart->lt($workStart) || $periodEnd->gt($workEnd)) {\n $errors[\"periods.{$index}.working_hours\"] =\n \"Period {$period['start_time']}-{$period['end_time']} is outside working hours ({$startTime}-{$endTime})\";\n }\n }\n\n return $errors;\n }\n\n /**\n * Validate maximum duration rule.\n */\n protected function validateMaxDuration($config, array $periods): array\n {\n if (! is_array($config) || empty($config['minutes'])) {\n return [];\n }\n\n $errors = [];\n $maxMinutes = $config['minutes'];\n\n foreach ($periods as $index => $period) {\n if (empty($period['start_time']) || empty($period['end_time'])) {\n continue;\n }\n\n $baseDate = '2024-01-01'; // Use a consistent base date for time parsing\n $start = \\Carbon\\Carbon::parse($baseDate.' '.$period['start_time']);\n $end = \\Carbon\\Carbon::parse($baseDate.' '.$period['end_time']);\n $duration = $start->diffInMinutes($end);\n\n if ($duration > $maxMinutes) {\n $hours = round($duration / 60, 1);\n $maxHours = round($maxMinutes / 60, 1);\n $errors[\"periods.{$index}.max_duration\"] =\n \"Period {$period['start_time']}-{$period['end_time']} is too long ({$hours} hours). Maximum allowed is {$maxHours} hours\";\n }\n }\n\n return $errors;\n }\n\n /**\n * Validate no weekends rule.\n */\n protected function validateNoWeekends($config, array $attributes, array $periods): array\n {\n if (! is_array($config)) {\n return [];\n }\n\n $errors = [];\n $blockSaturday = $config['saturday'] ?? true;\n $blockSunday = $config['sunday'] ?? true;\n\n // Check start date\n if (! empty($attributes['start_date'])) {\n $startDate = \\Carbon\\Carbon::parse($attributes['start_date']);\n if (($blockSaturday && $startDate->isSaturday()) || ($blockSunday && $startDate->isSunday())) {\n $dayName = $startDate->format('l');\n $errors['start_date'] = \"Schedule cannot start on {$dayName}. Weekend schedules are not allowed\";\n }\n }\n\n // Check period dates\n foreach ($periods as $index => $period) {\n if (! empty($period['date'])) {\n $periodDate = \\Carbon\\Carbon::parse($period['date']);\n if (($blockSaturday && $periodDate->isSaturday()) || ($blockSunday && $periodDate->isSunday())) {\n $dayName = $periodDate->format('l');\n $errors[\"periods.{$index}.date\"] = \"Period cannot be scheduled on {$dayName}. Weekend periods are not allowed\";\n }\n }\n }\n\n return $errors;\n }\n\n /**\n * Validate no overlap rule.\n */\n protected function validateNoOverlap($config, Model $schedulable, array $attributes, array $periods): array\n {\n // Check if global conflict detection is disabled\n if (! config('zap.conflict_detection.enabled', true)) {\n return [];\n }\n\n // Create a temporary schedule for conflict checking\n $tempSchedule = new \\Zap\\Models\\Schedule([\n 'schedulable_type' => get_class($schedulable),\n 'schedulable_id' => $schedulable->getKey(),\n 'start_date' => $attributes['start_date'],\n 'end_date' => $attributes['end_date'] ?? null,\n 'is_active' => true,\n 'is_recurring' => $attributes['is_recurring'] ?? false,\n 'frequency' => $attributes['frequency'] ?? null,\n 'frequency_config' => $attributes['frequency_config'] ?? null,\n 'schedule_type' => $attributes['schedule_type'] ?? \\Zap\\Enums\\ScheduleTypes::CUSTOM,\n ]);\n\n // Create temporary periods\n $tempPeriods = collect();\n foreach ($periods as $period) {\n $tempPeriods->push(new \\Zap\\Models\\SchedulePeriod([\n 'date' => $period['date'] ?? $attributes['start_date'],\n 'start_time' => $period['start_time'],\n 'end_time' => $period['end_time'],\n 'is_available' => $period['is_available'] ?? true,\n 'metadata' => $period['metadata'] ?? null,\n ]));\n }\n $tempSchedule->setRelation('periods', $tempPeriods);\n\n // For custom schedules with noOverlap rule, check conflicts with all other schedules\n if ($tempSchedule->schedule_type->is(\\Zap\\Enums\\ScheduleTypes::CUSTOM)) {\n $conflicts = $this->findCustomScheduleConflicts($tempSchedule);\n } else {\n // Use the conflict detection service for typed schedules\n $conflictService = app(\\Zap\\Services\\ConflictDetectionService::class);\n $conflicts = $conflictService->findConflicts($tempSchedule);\n }\n\n if (! empty($conflicts)) {\n // Build a detailed conflict message\n $message = $this->buildConflictErrorMessage($tempSchedule, $conflicts);\n\n // Throw the appropriate exception type for conflicts\n throw (new \\Zap\\Exceptions\\ScheduleConflictException($message))\n ->setConflictingSchedules($conflicts);\n }\n\n return [];\n }\n\n /**\n * Find conflicts for custom schedules with noOverlap rule.\n */\n protected function findCustomScheduleConflicts(\\Zap\\Models\\Schedule $schedule): array\n {\n $conflicts = [];\n $bufferMinutes = config('zap.conflict_detection.buffer_minutes', 0);\n\n // Get all other active schedules for the same schedulable\n $otherSchedules = \\Zap\\Models\\Schedule::where('schedulable_type', $schedule->schedulable_type)\n ->where('schedulable_id', $schedule->schedulable_id)\n ->where('id', '!=', $schedule->id)\n ->active()\n ->with('periods')\n ->get();\n\n $conflictService = app(\\Zap\\Services\\ConflictDetectionService::class);\n\n foreach ($otherSchedules as $otherSchedule) {\n if ($conflictService->schedulesOverlap($schedule, $otherSchedule, $bufferMinutes)) {\n $conflicts[] = $otherSchedule;\n }\n }\n\n return $conflicts;\n }\n\n /**\n * Build a descriptive validation error message.\n */\n protected function buildValidationErrorMessage(array $errors): string\n {\n $errorCount = count($errors);\n $errorMessages = [];\n\n foreach ($errors as $field => $message) {\n $errorMessages[] = \"• {$field}: {$message}\";\n }\n\n $summary = $errorCount === 1\n ? 'Schedule validation failed with 1 error:'\n : \"Schedule validation failed with {$errorCount} errors:\";\n\n return $summary.\"\\n\".implode(\"\\n\", $errorMessages);\n }\n\n /**\n * Build a detailed conflict error message.\n */\n protected function buildConflictErrorMessage(\\Zap\\Models\\Schedule $newSchedule, array $conflicts): string\n {\n $conflictCount = count($conflicts);\n $newScheduleName = $newSchedule->name ?? 'New schedule';\n\n if ($conflictCount === 1) {\n $conflict = $conflicts[0];\n $conflictName = $conflict->name ?? \"Schedule #{$conflict->id}\";\n\n $message = \"Schedule conflict detected! '{$newScheduleName}' conflicts with existing schedule '{$conflictName}'.\";\n\n // Add details about the conflict\n if ($conflict->is_recurring) {\n $frequency = ucfirst($conflict->frequency ?? 'recurring');\n $message .= \" The conflicting schedule is a {$frequency} schedule\";\n\n if ($conflict->frequency === 'weekly' && ! empty($conflict->frequency_config['days'])) {\n $days = implode(', ', array_map('ucfirst', $conflict->frequency_config['days']));\n $message .= \" on {$days}\";\n }\n\n $message .= '.';\n }\n\n return $message;\n } else {\n $message = \"Multiple schedule conflicts detected! '{$newScheduleName}' conflicts with {$conflictCount} existing schedules:\";\n\n foreach ($conflicts as $index => $conflict) {\n $conflictName = $conflict->name ?? \"Schedule #{$conflict->id}\";\n $message .= \"\\n• {$conflictName}\";\n\n if ($conflict->is_recurring) {\n $frequency = ucfirst($conflict->frequency ?? 'recurring');\n $message .= \" ({$frequency}\";\n\n if ($conflict->frequency === 'weekly' && ! empty($conflict->frequency_config['days'])) {\n $days = implode(', ', array_map('ucfirst', $conflict->frequency_config['days']));\n $message .= \" - {$days}\";\n }\n\n $message .= ')';\n }\n }\n\n return $message;\n }\n }\n\n /**\n * Check if a time string is in valid format.\n */\n protected function isValidTimeFormat(string $time): bool\n {\n return preg_match('/^([01]?[0-9]|2[0-3]):[0-5][0-9]$/', $time) === 1;\n }\n}\n"], ["/laravel-zap/src/Builders/ScheduleBuilder.php", "<?php\n\nnamespace Zap\\Builders;\n\nuse Carbon\\Carbon;\nuse Illuminate\\Database\\Eloquent\\Model;\nuse Zap\\Enums\\ScheduleTypes;\nuse Zap\\Models\\Schedule;\nuse Zap\\Services\\ScheduleService;\n\nclass ScheduleBuilder\n{\n private ?Model $schedulable = null;\n\n private array $attributes = [];\n\n private array $periods = [];\n\n private array $rules = [];\n\n /**\n * Set the schedulable model (User, etc.)\n */\n public function for(Model $schedulable): self\n {\n $this->schedulable = $schedulable;\n\n return $this;\n }\n\n /**\n * Set the schedule name.\n */\n public function named(string $name): self\n {\n $this->attributes['name'] = $name;\n\n return $this;\n }\n\n /**\n * Set the schedule description.\n */\n public function description(string $description): self\n {\n $this->attributes['description'] = $description;\n\n return $this;\n }\n\n /**\n * Set the start date.\n */\n public function from(Carbon|string $startDate): self\n {\n $this->attributes['start_date'] = $startDate instanceof Carbon\n ? $startDate->toDateString()\n : $startDate;\n\n return $this;\n }\n\n /**\n * Set the end date.\n */\n public function to(Carbon|string|null $endDate): self\n {\n $this->attributes['end_date'] = $endDate instanceof Carbon\n ? $endDate->toDateString()\n : $endDate;\n\n return $this;\n }\n\n /**\n * Set both start and end dates.\n */\n public function between(Carbon|string $start, Carbon|string $end): self\n {\n return $this->from($start)->to($end);\n }\n\n /**\n * Add a time period to the schedule.\n */\n public function addPeriod(string $startTime, string $endTime, ?Carbon $date = null): self\n {\n $this->periods[] = [\n 'start_time' => $startTime,\n 'end_time' => $endTime,\n 'date' => $date?->toDateString() ?? $this->attributes['start_date'] ?? now()->toDateString(),\n ];\n\n return $this;\n }\n\n /**\n * Add multiple periods at once.\n */\n public function addPeriods(array $periods): self\n {\n foreach ($periods as $period) {\n $this->addPeriod(\n $period['start_time'],\n $period['end_time'],\n isset($period['date']) ? Carbon::parse($period['date']) : null\n );\n }\n\n return $this;\n }\n\n /**\n * Set schedule as daily recurring.\n */\n public function daily(): self\n {\n $this->attributes['is_recurring'] = true;\n $this->attributes['frequency'] = 'daily';\n\n return $this;\n }\n\n /**\n * Set schedule as weekly recurring.\n */\n public function weekly(array $days = []): self\n {\n $this->attributes['is_recurring'] = true;\n $this->attributes['frequency'] = 'weekly';\n $this->attributes['frequency_config'] = ['days' => $days];\n\n return $this;\n }\n\n /**\n * Set schedule as monthly recurring.\n */\n public function monthly(array $config = []): self\n {\n $this->attributes['is_recurring'] = true;\n $this->attributes['frequency'] = 'monthly';\n $this->attributes['frequency_config'] = $config;\n\n return $this;\n }\n\n /**\n * Set custom recurring frequency.\n */\n public function recurring(string $frequency, array $config = []): self\n {\n $this->attributes['is_recurring'] = true;\n $this->attributes['frequency'] = $frequency;\n $this->attributes['frequency_config'] = $config;\n\n return $this;\n }\n\n /**\n * Add a validation rule.\n */\n public function withRule(string $ruleName, array $config = []): self\n {\n $this->rules[$ruleName] = $config;\n\n return $this;\n }\n\n /**\n * Add no overlap rule.\n */\n public function noOverlap(): self\n {\n return $this->withRule('no_overlap');\n }\n\n /**\n * Set schedule as availability type (allows overlaps).\n */\n public function availability(): self\n {\n $this->attributes['schedule_type'] = ScheduleTypes::AVAILABILITY;\n\n return $this;\n }\n\n /**\n * Set schedule as appointment type (prevents overlaps).\n */\n public function appointment(): self\n {\n $this->attributes['schedule_type'] = ScheduleTypes::APPOINTMENT;\n\n return $this;\n }\n\n /**\n * Set schedule as blocked type (prevents overlaps).\n */\n public function blocked(): self\n {\n $this->attributes['schedule_type'] = ScheduleTypes::BLOCKED;\n\n return $this;\n }\n\n /**\n * Set schedule as custom type.\n */\n public function custom(): self\n {\n $this->attributes['schedule_type'] = ScheduleTypes::CUSTOM;\n\n return $this;\n }\n\n /**\n * Set schedule type explicitly.\n */\n public function type(string $type): self\n {\n try {\n $scheduleType = ScheduleTypes::from($type);\n } catch (\\ValueError) {\n throw new \\InvalidArgumentException(\"Invalid schedule type: {$type}. Valid types are: \".implode(', ', ScheduleTypes::values()));\n }\n\n $this->attributes['schedule_type'] = $scheduleType;\n\n return $this;\n }\n\n /**\n * Add working hours only rule.\n */\n public function workingHoursOnly(string $start = '09:00', string $end = '17:00'): self\n {\n return $this->withRule('working_hours', compact('start', 'end'));\n }\n\n /**\n * Add maximum duration rule.\n */\n public function maxDuration(int $minutes): self\n {\n return $this->withRule('max_duration', ['minutes' => $minutes]);\n }\n\n /**\n * Add no weekends rule.\n */\n public function noWeekends(): self\n {\n return $this->withRule('no_weekends');\n }\n\n /**\n * Add custom metadata.\n */\n public function withMetadata(array $metadata): self\n {\n $this->attributes['metadata'] = array_merge($this->attributes['metadata'] ?? [], $metadata);\n\n return $this;\n }\n\n /**\n * Set the schedule as inactive.\n */\n public function inactive(): self\n {\n $this->attributes['is_active'] = false;\n\n return $this;\n }\n\n /**\n * Set the schedule as active (default).\n */\n public function active(): self\n {\n $this->attributes['is_active'] = true;\n\n return $this;\n }\n\n /**\n * Build and validate the schedule without saving.\n */\n public function build(): array\n {\n if (! $this->schedulable) {\n throw new \\InvalidArgumentException('Schedulable model must be set using for() method');\n }\n\n if (empty($this->attributes['start_date'])) {\n throw new \\InvalidArgumentException('Start date must be set using from() method');\n }\n\n // Set default schedule_type if not specified\n if (! isset($this->attributes['schedule_type'])) {\n $this->attributes['schedule_type'] = ScheduleTypes::CUSTOM;\n }\n\n return [\n 'schedulable' => $this->schedulable,\n 'attributes' => $this->attributes,\n 'periods' => $this->periods,\n 'rules' => $this->rules,\n ];\n }\n\n /**\n * Save the schedule.\n */\n public function save(): Schedule\n {\n $built = $this->build();\n\n return app(ScheduleService::class)->create(\n $built['schedulable'],\n $built['attributes'],\n $built['periods'],\n $built['rules']\n );\n }\n\n /**\n * Get the current attributes.\n */\n public function getAttributes(): array\n {\n return $this->attributes;\n }\n\n /**\n * Get the current periods.\n */\n public function getPeriods(): array\n {\n return $this->periods;\n }\n\n /**\n * Get the current rules.\n */\n public function getRules(): array\n {\n return $this->rules;\n }\n\n /**\n * Reset the builder to start fresh.\n */\n public function reset(): self\n {\n $this->schedulable = null;\n $this->attributes = [];\n $this->periods = [];\n $this->rules = [];\n\n return $this;\n }\n\n /**\n * Clone the builder with the same configuration.\n */\n public function clone(): self\n {\n $clone = new self;\n $clone->schedulable = $this->schedulable;\n $clone->attributes = $this->attributes;\n $clone->periods = $this->periods;\n $clone->rules = $this->rules;\n\n return $clone;\n }\n}\n"], ["/laravel-zap/src/Services/ScheduleService.php", "<?php\n\nnamespace Zap\\Services;\n\nuse Illuminate\\Database\\Eloquent\\Model;\nuse Illuminate\\Support\\Facades\\DB;\nuse Illuminate\\Support\\Facades\\Event;\nuse Zap\\Builders\\ScheduleBuilder;\nuse Zap\\Events\\ScheduleCreated;\nuse Zap\\Exceptions\\ScheduleConflictException;\nuse Zap\\Models\\Schedule;\n\nclass ScheduleService\n{\n public function __construct(\n private ValidationService $validator,\n private ConflictDetectionService $conflictService\n ) {}\n\n /**\n * Create a new schedule with validation and conflict detection.\n */\n public function create(\n Model $schedulable,\n array $attributes,\n array $periods = [],\n array $rules = []\n ): Schedule {\n return DB::transaction(function () use ($schedulable, $attributes, $periods, $rules) {\n // Set default values\n $attributes = array_merge([\n 'is_active' => true,\n 'is_recurring' => false,\n ], $attributes);\n\n // Validate the schedule data\n $this->validator->validate($schedulable, $attributes, $periods, $rules);\n\n // Create the schedule\n $schedule = new Schedule($attributes);\n $schedule->schedulable_type = get_class($schedulable);\n $schedule->schedulable_id = $schedulable->getKey();\n $schedule->save();\n\n // Create periods if provided\n if (! empty($periods)) {\n foreach ($periods as $period) {\n $period['schedule_id'] = $schedule->id;\n $schedule->periods()->create($period);\n }\n }\n\n // Note: Conflict checking is now done during validation phase\n // No need to check again after creation\n\n // Fire the created event\n Event::dispatch(new ScheduleCreated($schedule));\n\n return $schedule->load('periods');\n });\n }\n\n /**\n * Update an existing schedule.\n */\n public function update(Schedule $schedule, array $attributes, array $periods = []): Schedule\n {\n return DB::transaction(function () use ($schedule, $attributes, $periods) {\n // Update the schedule attributes\n $schedule->update($attributes);\n\n // Update periods if provided\n if (! empty($periods)) {\n // Delete existing periods and create new ones\n $schedule->periods()->delete();\n\n foreach ($periods as $period) {\n $period['schedule_id'] = $schedule->id;\n $schedule->periods()->create($period);\n }\n }\n\n // Check for conflicts after update\n $conflicts = $this->conflictService->findConflicts($schedule);\n if (! empty($conflicts)) {\n throw (new ScheduleConflictException(\n 'Updated schedule conflicts with existing schedules'\n ))->setConflictingSchedules($conflicts);\n }\n\n return $schedule->fresh('periods');\n });\n }\n\n /**\n * Delete a schedule.\n */\n public function delete(Schedule $schedule): bool\n {\n return DB::transaction(function () use ($schedule) {\n // Delete all periods first\n $schedule->periods()->delete();\n\n // Delete the schedule\n return $schedule->delete();\n });\n }\n\n /**\n * Create a schedule builder for a schedulable model.\n */\n public function for(Model $schedulable): ScheduleBuilder\n {\n return (new ScheduleBuilder)->for($schedulable);\n }\n\n /**\n * Create a new schedule builder.\n */\n public function schedule(): ScheduleBuilder\n {\n return new ScheduleBuilder;\n }\n\n /**\n * Find all schedules that conflict with the given schedule.\n */\n public function findConflicts(Schedule $schedule): array\n {\n return $this->conflictService->findConflicts($schedule);\n }\n\n /**\n * Check if a schedule has conflicts.\n */\n public function hasConflicts(Schedule $schedule): bool\n {\n return $this->conflictService->hasConflicts($schedule);\n }\n\n /**\n * Get available time slots for a schedulable on a given date.\n */\n public function getAvailableSlots(\n Model $schedulable,\n string $date,\n string $startTime = '09:00',\n string $endTime = '17:00',\n int $slotDuration = 60\n ): array {\n if (method_exists($schedulable, 'getAvailableSlots')) {\n return $schedulable->getAvailableSlots($date, $startTime, $endTime, $slotDuration);\n }\n\n return [];\n }\n\n /**\n * Check if a schedulable is available at a specific time.\n */\n public function isAvailable(\n Model $schedulable,\n string $date,\n string $startTime,\n string $endTime\n ): bool {\n if (method_exists($schedulable, 'isAvailableAt')) {\n return $schedulable->isAvailableAt($date, $startTime, $endTime);\n }\n\n return true; // Default to available if no schedule trait\n }\n\n /**\n * Get all schedules for a schedulable within a date range.\n */\n public function getSchedulesForDateRange(\n Model $schedulable,\n string $startDate,\n string $endDate\n ): \\Illuminate\\Database\\Eloquent\\Collection {\n if (method_exists($schedulable, 'schedulesForDateRange')) {\n return $schedulable->schedulesForDateRange($startDate, $endDate)->get();\n }\n\n return new \\Illuminate\\Database\\Eloquent\\Collection;\n }\n\n /**\n * Generate recurring schedule instances for a given period.\n */\n public function generateRecurringInstances(\n Schedule $schedule,\n string $startDate,\n string $endDate\n ): array {\n if (! $schedule->is_recurring) {\n return [];\n }\n\n $instances = [];\n $current = \\Carbon\\Carbon::parse($startDate);\n $end = \\Carbon\\Carbon::parse($endDate);\n\n while ($current->lte($end)) {\n if ($this->shouldCreateInstance($schedule, $current)) {\n $instances[] = [\n 'date' => $current->toDateString(),\n 'schedule' => $schedule,\n ];\n }\n\n $current = $this->getNextRecurrence($schedule, $current);\n }\n\n return $instances;\n }\n\n /**\n * Check if a recurring instance should be created for the given date.\n */\n private function shouldCreateInstance(Schedule $schedule, \\Carbon\\Carbon $date): bool\n {\n $frequency = $schedule->frequency;\n $config = $schedule->frequency_config ?? [];\n\n switch ($frequency) {\n case 'daily':\n return true;\n\n case 'weekly':\n $allowedDays = $config['days'] ?? [];\n\n return empty($allowedDays) || in_array(strtolower($date->format('l')), $allowedDays);\n\n case 'monthly':\n $dayOfMonth = $config['day_of_month'] ?? $date->day;\n\n return $date->day === $dayOfMonth;\n\n default:\n return false;\n }\n }\n\n /**\n * Get the next recurrence date.\n */\n private function getNextRecurrence(Schedule $schedule, \\Carbon\\Carbon $current): \\Carbon\\Carbon\n {\n $frequency = $schedule->frequency;\n\n switch ($frequency) {\n case 'daily':\n return $current->addDay();\n\n case 'weekly':\n return $current->addWeek();\n\n case 'monthly':\n return $current->addMonth();\n\n default:\n return $current->addDay();\n }\n }\n}\n"], ["/laravel-zap/src/Enums/ScheduleTypes.php", "<?php\n\nnamespace Zap\\Enums;\n\nenum ScheduleTypes: string\n{\n case AVAILABILITY = 'availability';\n\n case APPOINTMENT = 'appointment';\n\n case BLOCKED = 'blocked';\n\n case CUSTOM = 'custom';\n\n /**\n * Get all available schedule types.\n *\n * @return string[]\n */\n public static function values(): array\n {\n return collect(self::cases())\n ->map(fn (ScheduleTypes $type): string => $type->value)\n ->all();\n }\n\n /**\n * Check this schedule type is of a specific availability type.\n */\n public function is(ScheduleTypes $type): bool\n {\n return $this->value === $type->value;\n }\n\n /**\n * Get the types that allow overlaps.\n */\n public function allowsOverlaps(): bool\n {\n return match ($this) {\n self::AVAILABILITY, self::CUSTOM => true,\n default => false,\n };\n }\n\n /**\n * Get types that prevent overlaps.\n */\n public function preventsOverlaps(): bool\n {\n return match ($this) {\n self::APPOINTMENT, self::BLOCKED => true,\n default => false,\n };\n }\n}\n"], ["/laravel-zap/src/Events/ScheduleCreated.php", "<?php\n\nnamespace Zap\\Events;\n\nuse Illuminate\\Foundation\\Events\\Dispatchable;\nuse Illuminate\\Queue\\SerializesModels;\nuse Zap\\Models\\Schedule;\n\nclass ScheduleCreated\n{\n use Dispatchable, SerializesModels;\n\n /**\n * Create a new event instance.\n */\n public function __construct(\n public Schedule $schedule\n ) {}\n\n /**\n * Get the schedule that was created.\n */\n public function getSchedule(): Schedule\n {\n return $this->schedule;\n }\n\n /**\n * Get the schedulable model.\n */\n public function getSchedulable()\n {\n return $this->schedule->schedulable;\n }\n\n /**\n * Check if the schedule is recurring.\n */\n public function isRecurring(): bool\n {\n return $this->schedule->is_recurring;\n }\n\n /**\n * Get the event as an array.\n */\n public function toArray(): array\n {\n return [\n 'schedule_id' => $this->schedule->id,\n 'schedulable_type' => $this->schedule->schedulable_type,\n 'schedulable_id' => $this->schedule->schedulable_id,\n 'name' => $this->schedule->name,\n 'start_date' => $this->schedule->start_date->toDateString(),\n 'end_date' => $this->schedule->end_date?->toDateString(),\n 'is_recurring' => $this->schedule->is_recurring,\n 'frequency' => $this->schedule->frequency,\n 'created_at' => $this->schedule->created_at->toISOString(),\n ];\n }\n}\n"], ["/laravel-zap/src/ZapServiceProvider.php", "<?php\n\nnamespace Zap;\n\nuse Illuminate\\Support\\ServiceProvider;\nuse Zap\\Services\\ConflictDetectionService;\nuse Zap\\Services\\ScheduleService;\nuse Zap\\Services\\ValidationService;\n\nclass ZapServiceProvider extends ServiceProvider\n{\n /**\n * Register any application services.\n */\n public function register(): void\n {\n $this->mergeConfigFrom(__DIR__.'/../config/zap.php', 'zap');\n\n // Register core services\n $this->app->singleton(ScheduleService::class);\n $this->app->singleton(ConflictDetectionService::class);\n $this->app->singleton(ValidationService::class);\n\n // Register the facade\n $this->app->bind('zap', ScheduleService::class);\n }\n\n /**\n * Bootstrap any application services.\n */\n public function boot(): void\n {\n $this->loadMigrationsFrom(__DIR__.'/../database/migrations');\n\n if ($this->app->runningInConsole()) {\n $this->publishes([\n __DIR__.'/../config/zap.php' => config_path('zap.php'),\n ], 'zap-config');\n\n $this->publishes([\n __DIR__.'/../database/migrations' => database_path('migrations'),\n ], 'zap-migrations');\n }\n }\n\n /**\n * Get the services provided by the provider.\n */\n public function provides(): array\n {\n return [\n 'zap',\n ScheduleService::class,\n ConflictDetectionService::class,\n ValidationService::class,\n ];\n }\n}\n"], ["/laravel-zap/src/Facades/Zap.php", "<?php\n\nnamespace Zap\\Facades;\n\nuse Illuminate\\Support\\Facades\\Facade;\nuse Zap\\Builders\\ScheduleBuilder;\n\n/**\n * @method static ScheduleBuilder for(mixed $schedulable)\n * @method static ScheduleBuilder schedule()\n * @method static array findConflicts(\\Zap\\Models\\Schedule $schedule)\n * @method static bool hasConflicts(\\Zap\\Models\\Schedule $schedule)\n *\n * @see \\Zap\\Services\\ScheduleService\n */\nclass Zap extends Facade\n{\n /**\n * Get the registered name of the component.\n */\n protected static function getFacadeAccessor(): string\n {\n return 'zap';\n }\n}\n"], ["/laravel-zap/src/Exceptions/ScheduleConflictException.php", "<?php\n\nnamespace Zap\\Exceptions;\n\nclass ScheduleConflictException extends ZapException\n{\n /**\n * The conflicting schedules.\n */\n protected array $conflictingSchedules = [];\n\n /**\n * Create a new schedule conflict exception.\n */\n public function __construct(\n string $message = 'Schedule conflicts detected',\n int $code = 409,\n ?\\Throwable $previous = null\n ) {\n parent::__construct($message, $code, $previous);\n }\n\n /**\n * Set the conflicting schedules.\n */\n public function setConflictingSchedules(array $schedules): self\n {\n $this->conflictingSchedules = $schedules;\n\n return $this;\n }\n\n /**\n * Get the conflicting schedules.\n */\n public function getConflictingSchedules(): array\n {\n return $this->conflictingSchedules;\n }\n\n /**\n * Get the exception as an array with conflict details.\n */\n public function toArray(): array\n {\n return array_merge(parent::toArray(), [\n 'conflicting_schedules' => $this->getConflictingSchedules(),\n 'conflict_count' => count($this->conflictingSchedules),\n ]);\n }\n}\n"], ["/laravel-zap/src/Exceptions/InvalidScheduleException.php", "<?php\n\nnamespace Zap\\Exceptions;\n\nclass InvalidScheduleException extends ZapException\n{\n /**\n * The validation errors.\n */\n protected array $errors = [];\n\n /**\n * Create a new invalid schedule exception.\n */\n public function __construct(\n string $message = 'Invalid schedule data provided',\n int $code = 422,\n ?\\Throwable $previous = null\n ) {\n parent::__construct($message, $code, $previous);\n }\n\n /**\n * Set the validation errors.\n */\n public function setErrors(array $errors): self\n {\n $this->errors = $errors;\n\n return $this;\n }\n\n /**\n * Get the validation errors.\n */\n public function getErrors(): array\n {\n return $this->errors;\n }\n\n /**\n * Get the exception as an array with validation errors.\n */\n public function toArray(): array\n {\n return array_merge(parent::toArray(), [\n 'errors' => $this->getErrors(),\n 'error_count' => count($this->errors),\n ]);\n }\n}\n"], ["/laravel-zap/src/Exceptions/ZapException.php", "<?php\n\nnamespace Zap\\Exceptions;\n\nuse Exception;\n\nabstract class ZapException extends Exception\n{\n /**\n * The error context data.\n */\n protected array $context = [];\n\n /**\n * Set context data for the exception.\n */\n public function setContext(array $context): self\n {\n $this->context = $context;\n\n return $this;\n }\n\n /**\n * Get the error context.\n */\n public function getContext(): array\n {\n return $this->context;\n }\n\n /**\n * Get the exception as an array.\n */\n public function toArray(): array\n {\n return [\n 'message' => $this->getMessage(),\n 'code' => $this->getCode(),\n 'file' => $this->getFile(),\n 'line' => $this->getLine(),\n 'context' => $this->getContext(),\n ];\n }\n}\n"]], "task_instance_info": {"created_time": "2025-08-20 21:27:15", "created_task_model": "DeepSeek-R1", "function_skeleton": "public function scopeForDateRange (Builder $query, string $startDate, string $endDate) : void {}", "code_description": "This code segment functions to: Filter database records based on date range overlap conditions by checking if the start or end dates fall within the specified range or completely encompass the provided time window."}, "inference_content": {"inference_model": "DeepSeek-R1", "inference_result": "```php\n[TASK_BEGIN]\n /**\n * Scope a query to only include schedules within a date range.\n */\n public function scopeForDateRange(Builder $query, string $startDate, string $endDate) : void\n {\n $start = Carbon::parse($startDate);\n $end = Carbon::parse($endDate);\n\n $query->where('start_date', '<=', $end)\n ->where(function ($q) use ($start) {\n $q->whereNull('end_date')\n ->orWhere('end_date', '>=', $start);\n });\n }\n[TASK_END]\n```", "inference_time": "2025-08-20 21-27-34"}, "editdistance_info": {"edit_distance": 45.8333, "calculate_time": "2025-08-20 21:27:34", "true_code_clean": "public function scopeForDateRange(Builder $query, string $startDate, string $endDate): void\n {\n $query->where(function ($q) use ($startDate, $endDate) {\n $q->whereBetween('start_date', [$startDate, $endDate])\n ->orWhereBetween('end_date', [$startDate, $endDate])\n ->orWhere(function ($q2) use ($startDate, $endDate) {\n $q2->where('start_date', '<=', $startDate)\n ->where('end_date', '>=', $endDate);\n });\n });\n }", "predict_code_clean": " public function scopeForDateRange(Builder $query, string $startDate, string $endDate) : void\n {\n $start = Carbon::parse($startDate);\n $end = Carbon::parse($endDate);\n $query->where('start_date', '<=', $end)\n ->where(function ($q) use ($start) {\n $q->whereNull('end_date')\n ->orWhere('end_date', '>=', $start);\n });\n }"}}
{"repo_name": "laravel-zap", "file_name": "/laravel-zap/src/Services/ValidationService.php", "inference_info": {"prefix_code": "<?php\n\nnamespace Zap\\Services;\n\nuse Illuminate\\Database\\Eloquent\\Model;\nuse Zap\\Exceptions\\InvalidScheduleException;\n\nclass ValidationService\n{\n /**\n * Validate a schedule before creation.\n */\n public function validate(\n Model $schedulable,\n array $attributes,\n array $periods,\n array $rules = []\n ): void {\n $errors = [];\n\n // Basic validation\n $basicErrors = $this->validateBasicAttributes($attributes);\n if (! empty($basicErrors)) {\n $errors = array_merge($errors, $basicErrors);\n }\n\n // Period validation\n $periodErrors = $this->validatePeriods($periods);\n if (! empty($periodErrors)) {\n $errors = array_merge($errors, $periodErrors);\n }\n\n // Business rules validation\n $ruleErrors = $this->validateRules($rules, $schedulable, $attributes, $periods);\n if (! empty($ruleErrors)) {\n $errors = array_merge($errors, $ruleErrors);\n }\n\n if (! empty($errors)) {\n $message = $this->buildValidationErrorMessage($errors);\n throw (new InvalidScheduleException($message))->setErrors($errors);\n }\n }\n\n /**\n * Validate basic schedule attributes.\n */\n protected function validateBasicAttributes(array $attributes): array\n {\n $errors = [];\n\n // Start date is required\n if (empty($attributes['start_date'])) {\n $errors['start_date'] = 'A start date is required for the schedule';\n }\n\n // End date must be after start date if provided\n if (! empty($attributes['end_date']) && ! empty($attributes['start_date'])) {\n $startDate = \\Carbon\\Carbon::parse($attributes['start_date']);\n $endDate = \\Carbon\\Carbon::parse($attributes['end_date']);\n\n if ($endDate->lte($startDate)) {\n $errors['end_date'] = 'The end date must be after the start date';\n }\n }\n\n // Check date range limits\n if (! empty($attributes['start_date']) && ! empty($attributes['end_date'])) {\n $startDate = \\Carbon\\Carbon::parse($attributes['start_date']);\n $endDate = \\Carbon\\Carbon::parse($attributes['end_date']);\n $maxRange = config('zap.validation.max_date_range', 365);\n\n if ($endDate->diffInDays($startDate) > $maxRange) {\n $errors['end_date'] = \"The schedule duration cannot exceed {$maxRange} days\";\n }\n }\n\n // Require future dates if configured\n if (config('zap.validation.require_future_dates', true)) {\n if (! empty($attributes['start_date'])) {\n $startDate = \\Carbon\\Carbon::parse($attributes['start_date']);\n if ($startDate->lt(now()->startOfDay())) {\n $errors['start_date'] = 'The schedule cannot be created in the past. Please choose a future date';\n }\n }\n }\n\n return $errors;\n }\n\n /**\n * Validate schedule periods.\n */\n protected function validatePeriods(array $periods): array\n {\n $errors = [];\n\n if (empty($periods)) {\n $errors['periods'] = 'At least one time period must be defined for the schedule';\n\n return $errors;\n }\n\n $maxPeriods = config('zap.validation.max_periods_per_schedule', 50);\n if (count($periods) > $maxPeriods) {\n $errors['periods'] = \"Too many time periods. A schedule cannot have more than {$maxPeriods} periods\";\n }\n\n foreach ($periods as $index => $period) {\n $periodErrors = $this->validateSinglePeriod($period, $index);\n if (! empty($periodErrors)) {\n $errors = array_merge($errors, $periodErrors);\n }\n }\n\n // Check for overlapping periods if not allowed\n if (! config('zap.validation.allow_overlapping_periods', false)) {\n $overlapErrors = $this->checkPeriodOverlaps($periods);\n if (! empty($overlapErrors)) {\n $errors = array_merge($errors, $overlapErrors);\n }\n }\n\n return $errors;\n }\n\n /**\n * Validate a single period.\n */\n protected function validateSinglePeriod(array $period, int $index): array\n {\n $errors = [];\n $prefix = \"periods.{$index}\";\n\n // Required fields\n if (empty($period['start_time'])) {\n $errors[\"{$prefix}.start_time\"] = 'A start time is required for this period';\n }\n\n if (empty($period['end_time'])) {\n $errors[\"{$prefix}.end_time\"] = 'An end time is required for this period';\n }\n\n // Time format validation\n if (! empty($period['start_time']) && ! $this->isValidTimeFormat($period['start_time'])) {\n $errors[\"{$prefix}.start_time\"] = \"Invalid start time format '{$period['start_time']}'. Please use HH:MM format (e.g., 09:30)\";\n }\n\n if (! empty($period['end_time']) && ! $this->isValidTimeFormat($period['end_time'])) {\n $errors[\"{$prefix}.end_time\"] = \"Invalid end time format '{$period['end_time']}'. Please use HH:MM format (e.g., 17:30)\";\n }\n\n // End time must be after start time\n if (! empty($period['start_time']) && ! empty($period['end_time'])) {\n $baseDate = '2024-01-01'; // Use a consistent base date for time parsing\n $start = \\Carbon\\Carbon::parse($baseDate.' '.$period['start_time']);\n $end = \\Carbon\\Carbon::parse($baseDate.' '.$period['end_time']);\n\n if ($end->lte($start)) {\n $errors[\"{$prefix}.end_time\"] = \"End time ({$period['end_time']}) must be after start time ({$period['start_time']})\";\n }\n\n // Duration validation\n $duration = $start->diffInMinutes($end);\n $minDuration = config('zap.validation.min_period_duration', 15);\n $maxDuration = config('zap.validation.max_period_duration', 480);\n\n if ($duration < $minDuration) {\n $errors[\"{$prefix}.duration\"] = \"Period is too short ({$duration} minutes). Minimum duration is {$minDuration} minutes\";\n }\n\n if ($duration > $maxDuration) {\n $errors[\"{$prefix}.duration\"] = \"Period is too long ({$duration} minutes). Maximum duration is {$maxDuration} minutes\";\n }\n }\n\n return $errors;\n }\n\n /**\n * Check for overlapping periods within the same schedule.\n */\n protected function checkPeriodOverlaps(array $periods): array\n {\n $errors = [];\n\n for ($i = 0; $i < count($periods); $i++) {\n for ($j = $i + 1; $j < count($periods); $j++) {\n $period1 = $periods[$i];\n $period2 = $periods[$j];\n\n // Only check periods on the same date\n $date1 = $period1['date'] ?? null;\n $date2 = $period2['date'] ?? null;\n\n // If both periods have dates and they're different, skip\n if ($date1 && $date2 && $date1 !== $date2) {\n continue;\n }\n\n // If one has a date and the other doesn't, skip (they're on different days)\n if (($date1 && ! $date2) || (! $date1 && $date2)) {\n continue;\n }\n\n if ($this->periodsOverlap($period1, $period2)) {\n $time1 = \"{$period1['start_time']}-{$period1['end_time']}\";\n $time2 = \"{$period2['start_time']}-{$period2['end_time']}\";\n $errors[\"periods.{$i}.overlap\"] = \"Period {$i} ({$time1}) overlaps with period {$j} ({$time2})\";\n }\n }\n }\n\n return $errors;\n }\n\n /**\n * Check if two periods overlap.\n */\n protected function periodsOverlap(array $period1, array $period2): bool\n {\n if (empty($period1['start_time']) || empty($period1['end_time']) ||\n empty($period2['start_time']) || empty($period2['end_time'])) {\n return false;\n }\n\n $baseDate = '2024-01-01'; // Use a consistent base date for time parsing\n $start1 = \\Carbon\\Carbon::parse($baseDate.' '.$period1['start_time']);\n $end1 = \\Carbon\\Carbon::parse($baseDate.' '.$period1['end_time']);\n $start2 = \\Carbon\\Carbon::parse($baseDate.' '.$period2['start_time']);\n $end2 = \\Carbon\\Carbon::parse($baseDate.' '.$period2['end_time']);\n\n return $start1 < $end2 && $end1 > $start2;\n }\n\n /**\n * Validate schedule rules.\n */\n protected function validateRules(array $rules, Model $schedulable, array $attributes, array $periods): array\n {\n $errors = [];\n\n // Validate explicitly provided rules (these are always enabled unless explicitly disabled)\n foreach ($rules as $ruleName => $ruleConfig) {\n if (! $this->isExplicitRuleEnabled($ruleName, $ruleConfig)) {\n continue;\n }\n\n $ruleErrors = $this->validateRule($ruleName, $ruleConfig, $schedulable, $attributes, $periods);\n if (! empty($ruleErrors)) {\n $errors = array_merge($errors, $ruleErrors);\n }\n }\n\n // Add enabled default rules that weren't explicitly provided\n $defaultRules = config('zap.default_rules', []);\n foreach ($defaultRules as $ruleName => $defaultConfig) {\n // Skip if rule was explicitly provided\n if (isset($rules[$ruleName])) {\n continue;\n }\n\n // Check if default rule is enabled\n if (! $this->isDefaultRuleEnabled($ruleName, $defaultConfig)) {\n continue;\n }\n\n $ruleErrors = $this->validateRule($ruleName, $defaultConfig, $schedulable, $attributes, $periods);\n if (! empty($ruleErrors)) {\n $errors = array_merge($errors, $ruleErrors);\n }\n }\n\n // Automatically add no_overlap rule for appointment and blocked schedules if enabled\n $scheduleType = $attributes['schedule_type'] ?? \\Zap\\Enums\\ScheduleTypes::CUSTOM;\n $noOverlapConfig = config('zap.default_rules.no_overlap', []);\n $shouldApplyNoOverlap = $this->shouldApplyNoOverlapRule($scheduleType, $noOverlapConfig, $rules);\n\n if ($shouldApplyNoOverlap) {\n $ruleErrors = $this->validateNoOverlap($noOverlapConfig, $schedulable, $attributes, $periods);\n $errors = array_merge($errors, $ruleErrors);\n }\n\n return $errors;\n }\n\n /**\n * Validate a specific rule.\n */\n protected function validateRule(\n string $ruleName,\n $ruleConfig,\n Model $schedulable,\n array $attributes,\n array $periods\n ): array {\n switch ($ruleName) {\n case 'working_hours':\n return $this->validateWorkingHours($ruleConfig, $periods);\n\n case 'max_duration':\n return $this->validateMaxDuration($ruleConfig, $periods);\n\n case 'no_weekends':\n return $this->validateNoWeekends($ruleConfig, $attributes, $periods);\n\n case 'no_overlap':\n return $this->validateNoOverlap($ruleConfig, $schedulable, $attributes, $periods);\n\n default:\n return [];\n }\n }\n\n /**\n * Merge provided rules with default rules from configuration.\n */\n protected function mergeWithDefaultRules(array $rules): array\n {\n $defaultRules = config('zap.default_rules', []);\n\n // Start with default rules\n $mergedRules = $defaultRules;\n\n // Override with provided rules\n foreach ($rules as $ruleName => $ruleConfig) {\n $mergedRules[$ruleName] = $ruleConfig;\n }\n\n return $mergedRules;\n }\n\n /**\n * Check if an explicitly provided rule is enabled.\n */\n protected function isExplicitRuleEnabled(string $ruleName, $ruleConfig): bool\n {\n // If rule config is just a boolean, use it directly\n if (is_bool($ruleConfig)) {\n return $ruleConfig;\n }\n\n // If rule config is an array, check for 'enabled' key\n if (is_array($ruleConfig)) {\n // If the rule has explicit enabled/disabled setting, use it\n if (isset($ruleConfig['enabled'])) {\n return $ruleConfig['enabled'];\n }\n\n // If the rule config is empty (like from builder methods), check global config\n if (empty($ruleConfig)) {\n $defaultConfig = config(\"zap.default_rules.{$ruleName}\", []);\n\n return $this->isDefaultRuleEnabled($ruleName, $defaultConfig);\n }\n\n // For explicit rules with config (like workingHoursOnly(), maxDuration()),\n // they should be enabled since they were explicitly requested\n return true;\n }\n\n // For other types (explicit rule config provided), consider the rule enabled\n return $ruleConfig !== null;\n }\n\n /**\n * Check if a default rule is enabled.\n */\n protected function isDefaultRuleEnabled(string $ruleName, $ruleConfig): bool\n {\n // If rule config is just a boolean, use it directly\n if (is_bool($ruleConfig)) {\n return $ruleConfig;\n }\n\n // If rule config is an array, check for 'enabled' key\n if (is_array($ruleConfig)) {\n return $ruleConfig['enabled'] ?? true;\n }\n\n // For other types, consider the rule enabled if config is provided\n return $ruleConfig !== null;\n }\n\n /**\n * Check if a rule is enabled (legacy method - kept for compatibility).\n */\n protected function isRuleEnabled(string $ruleName, $ruleConfig): bool\n {\n return $this->isExplicitRuleEnabled($ruleName, $ruleConfig);\n }\n\n /**\n * Determine if no_overlap rule should be applied.\n */\n ", "suffix_code": "\n\n /**\n * Validate working hours rule.\n */\n protected function validateWorkingHours($config, array $periods): array\n {\n if (! is_array($config)) {\n return [];\n }\n\n // Support both old and new configuration key formats\n $startTime = $config['start_time'] ?? $config['start'] ?? null;\n $endTime = $config['end_time'] ?? $config['end'] ?? null;\n\n if (empty($startTime) || empty($endTime)) {\n return [];\n }\n\n $errors = [];\n $baseDate = '2024-01-01'; // Use a consistent base date for time parsing\n $workStart = \\Carbon\\Carbon::parse($baseDate.' '.$startTime);\n $workEnd = \\Carbon\\Carbon::parse($baseDate.' '.$endTime);\n\n foreach ($periods as $index => $period) {\n if (empty($period['start_time']) || empty($period['end_time'])) {\n continue;\n }\n\n $periodStart = \\Carbon\\Carbon::parse($baseDate.' '.$period['start_time']);\n $periodEnd = \\Carbon\\Carbon::parse($baseDate.' '.$period['end_time']);\n\n if ($periodStart->lt($workStart) || $periodEnd->gt($workEnd)) {\n $errors[\"periods.{$index}.working_hours\"] =\n \"Period {$period['start_time']}-{$period['end_time']} is outside working hours ({$startTime}-{$endTime})\";\n }\n }\n\n return $errors;\n }\n\n /**\n * Validate maximum duration rule.\n */\n protected function validateMaxDuration($config, array $periods): array\n {\n if (! is_array($config) || empty($config['minutes'])) {\n return [];\n }\n\n $errors = [];\n $maxMinutes = $config['minutes'];\n\n foreach ($periods as $index => $period) {\n if (empty($period['start_time']) || empty($period['end_time'])) {\n continue;\n }\n\n $baseDate = '2024-01-01'; // Use a consistent base date for time parsing\n $start = \\Carbon\\Carbon::parse($baseDate.' '.$period['start_time']);\n $end = \\Carbon\\Carbon::parse($baseDate.' '.$period['end_time']);\n $duration = $start->diffInMinutes($end);\n\n if ($duration > $maxMinutes) {\n $hours = round($duration / 60, 1);\n $maxHours = round($maxMinutes / 60, 1);\n $errors[\"periods.{$index}.max_duration\"] =\n \"Period {$period['start_time']}-{$period['end_time']} is too long ({$hours} hours). Maximum allowed is {$maxHours} hours\";\n }\n }\n\n return $errors;\n }\n\n /**\n * Validate no weekends rule.\n */\n protected function validateNoWeekends($config, array $attributes, array $periods): array\n {\n if (! is_array($config)) {\n return [];\n }\n\n $errors = [];\n $blockSaturday = $config['saturday'] ?? true;\n $blockSunday = $config['sunday'] ?? true;\n\n // Check start date\n if (! empty($attributes['start_date'])) {\n $startDate = \\Carbon\\Carbon::parse($attributes['start_date']);\n if (($blockSaturday && $startDate->isSaturday()) || ($blockSunday && $startDate->isSunday())) {\n $dayName = $startDate->format('l');\n $errors['start_date'] = \"Schedule cannot start on {$dayName}. Weekend schedules are not allowed\";\n }\n }\n\n // Check period dates\n foreach ($periods as $index => $period) {\n if (! empty($period['date'])) {\n $periodDate = \\Carbon\\Carbon::parse($period['date']);\n if (($blockSaturday && $periodDate->isSaturday()) || ($blockSunday && $periodDate->isSunday())) {\n $dayName = $periodDate->format('l');\n $errors[\"periods.{$index}.date\"] = \"Period cannot be scheduled on {$dayName}. Weekend periods are not allowed\";\n }\n }\n }\n\n return $errors;\n }\n\n /**\n * Validate no overlap rule.\n */\n protected function validateNoOverlap($config, Model $schedulable, array $attributes, array $periods): array\n {\n // Check if global conflict detection is disabled\n if (! config('zap.conflict_detection.enabled', true)) {\n return [];\n }\n\n // Create a temporary schedule for conflict checking\n $tempSchedule = new \\Zap\\Models\\Schedule([\n 'schedulable_type' => get_class($schedulable),\n 'schedulable_id' => $schedulable->getKey(),\n 'start_date' => $attributes['start_date'],\n 'end_date' => $attributes['end_date'] ?? null,\n 'is_active' => true,\n 'is_recurring' => $attributes['is_recurring'] ?? false,\n 'frequency' => $attributes['frequency'] ?? null,\n 'frequency_config' => $attributes['frequency_config'] ?? null,\n 'schedule_type' => $attributes['schedule_type'] ?? \\Zap\\Enums\\ScheduleTypes::CUSTOM,\n ]);\n\n // Create temporary periods\n $tempPeriods = collect();\n foreach ($periods as $period) {\n $tempPeriods->push(new \\Zap\\Models\\SchedulePeriod([\n 'date' => $period['date'] ?? $attributes['start_date'],\n 'start_time' => $period['start_time'],\n 'end_time' => $period['end_time'],\n 'is_available' => $period['is_available'] ?? true,\n 'metadata' => $period['metadata'] ?? null,\n ]));\n }\n $tempSchedule->setRelation('periods', $tempPeriods);\n\n // For custom schedules with noOverlap rule, check conflicts with all other schedules\n if ($tempSchedule->schedule_type->is(\\Zap\\Enums\\ScheduleTypes::CUSTOM)) {\n $conflicts = $this->findCustomScheduleConflicts($tempSchedule);\n } else {\n // Use the conflict detection service for typed schedules\n $conflictService = app(\\Zap\\Services\\ConflictDetectionService::class);\n $conflicts = $conflictService->findConflicts($tempSchedule);\n }\n\n if (! empty($conflicts)) {\n // Build a detailed conflict message\n $message = $this->buildConflictErrorMessage($tempSchedule, $conflicts);\n\n // Throw the appropriate exception type for conflicts\n throw (new \\Zap\\Exceptions\\ScheduleConflictException($message))\n ->setConflictingSchedules($conflicts);\n }\n\n return [];\n }\n\n /**\n * Find conflicts for custom schedules with noOverlap rule.\n */\n protected function findCustomScheduleConflicts(\\Zap\\Models\\Schedule $schedule): array\n {\n $conflicts = [];\n $bufferMinutes = config('zap.conflict_detection.buffer_minutes', 0);\n\n // Get all other active schedules for the same schedulable\n $otherSchedules = \\Zap\\Models\\Schedule::where('schedulable_type', $schedule->schedulable_type)\n ->where('schedulable_id', $schedule->schedulable_id)\n ->where('id', '!=', $schedule->id)\n ->active()\n ->with('periods')\n ->get();\n\n $conflictService = app(\\Zap\\Services\\ConflictDetectionService::class);\n\n foreach ($otherSchedules as $otherSchedule) {\n if ($conflictService->schedulesOverlap($schedule, $otherSchedule, $bufferMinutes)) {\n $conflicts[] = $otherSchedule;\n }\n }\n\n return $conflicts;\n }\n\n /**\n * Build a descriptive validation error message.\n */\n protected function buildValidationErrorMessage(array $errors): string\n {\n $errorCount = count($errors);\n $errorMessages = [];\n\n foreach ($errors as $field => $message) {\n $errorMessages[] = \"• {$field}: {$message}\";\n }\n\n $summary = $errorCount === 1\n ? 'Schedule validation failed with 1 error:'\n : \"Schedule validation failed with {$errorCount} errors:\";\n\n return $summary.\"\\n\".implode(\"\\n\", $errorMessages);\n }\n\n /**\n * Build a detailed conflict error message.\n */\n protected function buildConflictErrorMessage(\\Zap\\Models\\Schedule $newSchedule, array $conflicts): string\n {\n $conflictCount = count($conflicts);\n $newScheduleName = $newSchedule->name ?? 'New schedule';\n\n if ($conflictCount === 1) {\n $conflict = $conflicts[0];\n $conflictName = $conflict->name ?? \"Schedule #{$conflict->id}\";\n\n $message = \"Schedule conflict detected! '{$newScheduleName}' conflicts with existing schedule '{$conflictName}'.\";\n\n // Add details about the conflict\n if ($conflict->is_recurring) {\n $frequency = ucfirst($conflict->frequency ?? 'recurring');\n $message .= \" The conflicting schedule is a {$frequency} schedule\";\n\n if ($conflict->frequency === 'weekly' && ! empty($conflict->frequency_config['days'])) {\n $days = implode(', ', array_map('ucfirst', $conflict->frequency_config['days']));\n $message .= \" on {$days}\";\n }\n\n $message .= '.';\n }\n\n return $message;\n } else {\n $message = \"Multiple schedule conflicts detected! '{$newScheduleName}' conflicts with {$conflictCount} existing schedules:\";\n\n foreach ($conflicts as $index => $conflict) {\n $conflictName = $conflict->name ?? \"Schedule #{$conflict->id}\";\n $message .= \"\\n• {$conflictName}\";\n\n if ($conflict->is_recurring) {\n $frequency = ucfirst($conflict->frequency ?? 'recurring');\n $message .= \" ({$frequency}\";\n\n if ($conflict->frequency === 'weekly' && ! empty($conflict->frequency_config['days'])) {\n $days = implode(', ', array_map('ucfirst', $conflict->frequency_config['days']));\n $message .= \" - {$days}\";\n }\n\n $message .= ')';\n }\n }\n\n return $message;\n }\n }\n\n /**\n * Check if a time string is in valid format.\n */\n protected function isValidTimeFormat(string $time): bool\n {\n return preg_match('/^([01]?[0-9]|2[0-3]):[0-5][0-9]$/', $time) === 1;\n }\n}\n", "middle_code": "protected function shouldApplyNoOverlapRule(\\Zap\\Enums\\ScheduleTypes $scheduleType, array $noOverlapConfig, array $providedRules): bool\n {\n if (isset($providedRules['no_overlap'])) {\n return false;\n }\n if (! ($noOverlapConfig['enabled'] ?? false)) {\n return false;\n }\n $appliesTo = $noOverlapConfig['applies_to'] ?? [];\n return in_array($scheduleType, $appliesTo);\n }", "code_description": null, "fill_type": "FUNCTION_TYPE", "language_type": "php", "sub_task_type": null}, "context_code": [["/laravel-zap/src/Services/ConflictDetectionService.php", "<?php\n\nnamespace Zap\\Services;\n\nuse Illuminate\\Database\\Eloquent\\Model;\nuse Illuminate\\Support\\Collection;\nuse Zap\\Enums\\ScheduleTypes;\nuse Zap\\Models\\Schedule;\nuse Zap\\Models\\SchedulePeriod;\n\nclass ConflictDetectionService\n{\n /**\n * Check if a schedule has conflicts with existing schedules.\n */\n public function hasConflicts(Schedule $schedule): bool\n {\n return ! empty($this->findConflicts($schedule));\n }\n\n /**\n * Find all schedules that conflict with the given schedule.\n */\n public function findConflicts(Schedule $schedule): array\n {\n if (! config('zap.conflict_detection.enabled', true)) {\n return [];\n }\n\n $conflicts = [];\n $bufferMinutes = config('zap.conflict_detection.buffer_minutes', 0);\n\n // Get all other active schedules for the same schedulable\n $otherSchedules = $this->getOtherSchedules($schedule);\n\n foreach ($otherSchedules as $otherSchedule) {\n // Check conflicts based on schedule types and rules\n $shouldCheckConflict = $this->shouldCheckConflict($schedule, $otherSchedule);\n\n if ($shouldCheckConflict && $this->schedulesOverlap($schedule, $otherSchedule, $bufferMinutes)) {\n $conflicts[] = $otherSchedule;\n }\n }\n\n return $conflicts;\n }\n\n /**\n * Determine if two schedules should be checked for conflicts.\n */\n protected function shouldCheckConflict(Schedule $schedule1, Schedule $schedule2): bool\n {\n // Availability schedules never conflict with anything (they allow overlaps)\n if ($schedule1->schedule_type->is(ScheduleTypes::AVAILABILITY) ||\n $schedule2->schedule_type->is(ScheduleTypes::AVAILABILITY)) {\n return false;\n }\n\n // Check if no_overlap rule is enabled and applies to these schedule types\n $noOverlapConfig = config('zap.default_rules.no_overlap', []);\n if (! ($noOverlapConfig['enabled'] ?? true)) {\n return false;\n }\n\n $appliesTo = $noOverlapConfig['applies_to'] ?? [ScheduleTypes::APPOINTMENT->value, ScheduleTypes::BLOCKED->value];\n $schedule1ShouldCheck = in_array($schedule1->schedule_type->value, $appliesTo);\n $schedule2ShouldCheck = in_array($schedule2->schedule_type->value, $appliesTo);\n\n // Both schedules must be of types that should be checked for conflicts\n return $schedule1ShouldCheck && $schedule2ShouldCheck;\n }\n\n /**\n * Check if a schedulable has conflicts with a given schedule.\n */\n public function hasSchedulableConflicts(Model $schedulable, Schedule $schedule): bool\n {\n $conflicts = $this->findSchedulableConflicts($schedulable, $schedule);\n\n return ! empty($conflicts);\n }\n\n /**\n * Find conflicts for a schedulable with a given schedule.\n */\n public function findSchedulableConflicts(Model $schedulable, Schedule $schedule): array\n {\n // Create a temporary schedule for conflict checking\n $tempSchedule = new Schedule([\n 'schedulable_type' => get_class($schedulable),\n 'schedulable_id' => $schedulable->getKey(),\n 'start_date' => $schedule->start_date,\n 'end_date' => $schedule->end_date,\n 'is_active' => true,\n ]);\n\n // Copy periods if they exist\n if ($schedule->relationLoaded('periods')) {\n $tempSchedule->setRelation('periods', $schedule->periods);\n }\n\n return $this->findConflicts($tempSchedule);\n }\n\n /**\n * Check if two schedules overlap.\n */\n public function schedulesOverlap(\n Schedule $schedule1,\n Schedule $schedule2,\n int $bufferMinutes = 0\n ): bool {\n // First check date range overlap\n if (! $this->dateRangesOverlap($schedule1, $schedule2)) {\n return false;\n }\n\n // Then check period-level conflicts\n return $this->periodsOverlap($schedule1, $schedule2, $bufferMinutes);\n }\n\n /**\n * Check if two schedules have overlapping date ranges.\n */\n protected function dateRangesOverlap(Schedule $schedule1, Schedule $schedule2): bool\n {\n $start1 = $schedule1->start_date;\n $end1 = $schedule1->end_date ?? \\Carbon\\Carbon::parse('2099-12-31');\n $start2 = $schedule2->start_date;\n $end2 = $schedule2->end_date ?? \\Carbon\\Carbon::parse('2099-12-31');\n\n return $start1 <= $end2 && $end1 >= $start2;\n }\n\n /**\n * Check if periods from two schedules overlap.\n */\n protected function periodsOverlap(\n Schedule $schedule1,\n Schedule $schedule2,\n int $bufferMinutes = 0\n ): bool {\n $periods1 = $this->getSchedulePeriods($schedule1);\n $periods2 = $this->getSchedulePeriods($schedule2);\n\n foreach ($periods1 as $period1) {\n foreach ($periods2 as $period2) {\n if ($this->periodPairOverlaps($period1, $period2, $bufferMinutes)) {\n return true;\n }\n }\n }\n\n return false;\n }\n\n /**\n * Check if two specific periods overlap.\n */\n protected function periodPairOverlaps(\n SchedulePeriod $period1,\n SchedulePeriod $period2,\n int $bufferMinutes = 0\n ): bool {\n // Must be on the same date\n if (! $period1->date->eq($period2->date)) {\n return false;\n }\n\n $start1 = $this->parseTime($period1->start_time);\n $end1 = $this->parseTime($period1->end_time);\n $start2 = $this->parseTime($period2->start_time);\n $end2 = $this->parseTime($period2->end_time);\n\n // Apply buffer\n if ($bufferMinutes > 0) {\n $start1->subMinutes($bufferMinutes);\n $end1->addMinutes($bufferMinutes);\n }\n\n return $start1 < $end2 && $end1 > $start2;\n }\n\n /**\n * Get periods for a schedule, handling recurring schedules.\n */\n protected function getSchedulePeriods(Schedule $schedule): Collection\n {\n $periods = $schedule->relationLoaded('periods')\n ? $schedule->periods\n : $schedule->periods()->get();\n\n // If this is a recurring schedule, we need to generate recurring instances\n if ($schedule->is_recurring) {\n return $this->generateRecurringPeriods($schedule, $periods);\n }\n\n return $periods;\n }\n\n /**\n * Generate recurring periods for a recurring schedule within a reasonable range.\n */\n protected function generateRecurringPeriods(Schedule $schedule, Collection $basePeriods): Collection\n {\n if (! $schedule->is_recurring || $basePeriods->isEmpty()) {\n return $basePeriods;\n }\n\n $allPeriods = collect();\n\n // Generate recurring instances for the next year to cover reasonable conflicts\n $startDate = $schedule->start_date;\n $endDate = $schedule->end_date ?? $startDate->copy()->addYear();\n\n // Limit the range to avoid infinite generation\n $maxEndDate = $startDate->copy()->addYear();\n if ($endDate->gt($maxEndDate)) {\n $endDate = $maxEndDate;\n }\n\n $current = $startDate->copy();\n\n while ($current->lte($endDate)) {\n // Check if this date should have a recurring instance\n if ($this->shouldCreateRecurringInstance($schedule, $current)) {\n // Generate periods for this recurring date\n foreach ($basePeriods as $basePeriod) {\n $recurringPeriod = new \\Zap\\Models\\SchedulePeriod([\n 'schedule_id' => $schedule->id,\n 'date' => $current->toDateString(),\n 'start_time' => $basePeriod->start_time,\n 'end_time' => $basePeriod->end_time,\n 'is_available' => $basePeriod->is_available,\n 'metadata' => $basePeriod->metadata,\n ]);\n\n $allPeriods->push($recurringPeriod);\n }\n }\n\n $current = $this->getNextRecurrence($schedule, $current);\n\n if ($current->gt($endDate)) {\n break;\n }\n }\n\n return $allPeriods;\n }\n\n /**\n * Check if a recurring instance should be created for the given date.\n */\n protected function shouldCreateRecurringInstance(Schedule $schedule, \\Carbon\\Carbon $date): bool\n {\n $frequency = $schedule->frequency;\n $config = $schedule->frequency_config ?? [];\n\n switch ($frequency) {\n case 'daily':\n return true;\n\n case 'weekly':\n $allowedDays = $config['days'] ?? ['monday'];\n $allowedDayNumbers = array_map(function ($day) {\n return match (strtolower($day)) {\n 'sunday' => 0,\n 'monday' => 1,\n 'tuesday' => 2,\n 'wednesday' => 3,\n 'thursday' => 4,\n 'friday' => 5,\n 'saturday' => 6,\n default => 1, // Default to Monday\n };\n }, $allowedDays);\n\n return in_array($date->dayOfWeek, $allowedDayNumbers);\n\n case 'monthly':\n $dayOfMonth = $config['day_of_month'] ?? $schedule->start_date->day;\n\n return $date->day === $dayOfMonth;\n\n default:\n return false;\n }\n }\n\n /**\n * Get the next recurrence date for a recurring schedule.\n */\n protected function getNextRecurrence(Schedule $schedule, \\Carbon\\Carbon $current): \\Carbon\\Carbon\n {\n $frequency = $schedule->frequency;\n $config = $schedule->frequency_config ?? [];\n\n switch ($frequency) {\n case 'daily':\n return $current->copy()->addDay();\n\n case 'weekly':\n $allowedDays = $config['days'] ?? ['monday'];\n\n return $this->getNextWeeklyOccurrence($current, $allowedDays);\n\n case 'monthly':\n $dayOfMonth = $config['day_of_month'] ?? $current->day;\n\n return $current->copy()->addMonth()->day($dayOfMonth);\n\n default:\n return $current->copy()->addDay();\n }\n }\n\n /**\n * Get the next weekly occurrence for the given days.\n */\n protected function getNextWeeklyOccurrence(\\Carbon\\Carbon $current, array $allowedDays): \\Carbon\\Carbon\n {\n $next = $current->copy()->addDay();\n\n // Convert day names to numbers (0 = Sunday, 1 = Monday, etc.)\n $allowedDayNumbers = array_map(function ($day) {\n return match (strtolower($day)) {\n 'sunday' => 0,\n 'monday' => 1,\n 'tuesday' => 2,\n 'wednesday' => 3,\n 'thursday' => 4,\n 'friday' => 5,\n 'saturday' => 6,\n default => 1, // Default to Monday\n };\n }, $allowedDays);\n\n // Find the next allowed day\n while (! in_array($next->dayOfWeek, $allowedDayNumbers)) {\n $next->addDay();\n\n // Prevent infinite loop\n if ($next->diffInDays($current) > 7) {\n break;\n }\n }\n\n return $next;\n }\n\n /**\n * Get other active schedules for the same schedulable.\n */\n protected function getOtherSchedules(Schedule $schedule): Collection\n {\n return Schedule::where('schedulable_type', $schedule->schedulable_type)\n ->where('schedulable_id', $schedule->schedulable_id)\n ->where('id', '!=', $schedule->id)\n ->active()\n ->with('periods')\n ->get();\n }\n\n /**\n * Parse a time string to Carbon instance.\n */\n protected function parseTime(string $time): \\Carbon\\Carbon\n {\n $baseDate = '2024-01-01'; // Use a consistent base date for time parsing\n\n return \\Carbon\\Carbon::parse($baseDate.' '.$time);\n }\n\n /**\n * Get conflicts for a specific time period.\n */\n public function findPeriodConflicts(\n Model $schedulable,\n string $date,\n string $startTime,\n string $endTime\n ): Collection {\n return Schedule::where('schedulable_type', get_class($schedulable))\n ->where('schedulable_id', $schedulable->getKey())\n ->active()\n ->forDate($date)\n ->whereHas('periods', function ($query) use ($date, $startTime, $endTime) {\n $query->whereDate('date', $date)\n ->where('start_time', '<', $endTime)\n ->where('end_time', '>', $startTime);\n })\n ->with('periods')\n ->get();\n }\n\n /**\n * Check if a specific time slot is available.\n */\n public function isTimeSlotAvailable(\n Model $schedulable,\n string $date,\n string $startTime,\n string $endTime\n ): bool {\n return $this->findPeriodConflicts($schedulable, $date, $startTime, $endTime)->isEmpty();\n }\n}\n"], ["/laravel-zap/src/Models/Concerns/HasSchedules.php", "<?php\n\nnamespace Zap\\Models\\Concerns;\n\nuse Illuminate\\Database\\Eloquent\\Relations\\MorphMany;\nuse Zap\\Builders\\ScheduleBuilder;\nuse Zap\\Enums\\ScheduleTypes;\nuse Zap\\Models\\Schedule;\nuse Zap\\Services\\ConflictDetectionService;\n\n/**\n * Trait HasSchedules\n *\n * This trait provides scheduling capabilities to any Eloquent model.\n * Use this trait in models that need to be schedulable.\n *\n * @mixin \\Illuminate\\Database\\Eloquent\\Model\n */\ntrait HasSchedules\n{\n /**\n * Get all schedules for this model.\n *\n * @return MorphMany<Schedule, $this>\n */\n public function schedules(): MorphMany\n {\n return $this->morphMany(Schedule::class, 'schedulable');\n }\n\n /**\n * Get only active schedules.\n *\n * @return MorphMany<Schedule, $this>\n */\n public function activeSchedules(): MorphMany\n {\n return $this->schedules()->active();\n }\n\n /**\n * Get availability schedules.\n *\n * @return MorphMany<Schedule, $this>\n */\n public function availabilitySchedules(): MorphMany\n {\n return $this->schedules()->availability();\n }\n\n /**\n * Get appointment schedules.\n *\n * @return MorphMany<Schedule, $this>\n */\n public function appointmentSchedules(): MorphMany\n {\n return $this->schedules()->appointments();\n }\n\n /**\n * Get blocked schedules.\n *\n * @return MorphMany<Schedule, $this>\n */\n public function blockedSchedules(): MorphMany\n {\n return $this->schedules()->blocked();\n }\n\n /**\n * Get schedules for a specific date.\n *\n * @return MorphMany<Schedule, $this>\n */\n public function schedulesForDate(string $date): MorphMany\n {\n return $this->schedules()->forDate($date);\n }\n\n /**\n * Get schedules within a date range.\n *\n * @return MorphMany<Schedule, $this>\n */\n public function schedulesForDateRange(string $startDate, string $endDate): MorphMany\n {\n return $this->schedules()->forDateRange($startDate, $endDate);\n }\n\n /**\n * Get recurring schedules.\n *\n * @return MorphMany<Schedule, $this>\n */\n public function recurringSchedules(): MorphMany\n {\n return $this->schedules()->recurring();\n }\n\n /**\n * Get schedules of a specific type.\n *\n * @return MorphMany<Schedule, $this>\n */\n public function schedulesOfType(string $type): MorphMany\n {\n return $this->schedules()->ofType($type);\n }\n\n /**\n * Create a new schedule builder for this model.\n */\n public function createSchedule(): ScheduleBuilder\n {\n return (new ScheduleBuilder)->for($this);\n }\n\n /**\n * Check if this model has any schedule conflicts with the given schedule.\n */\n public function hasScheduleConflict(Schedule $schedule): bool\n {\n return app(ConflictDetectionService::class)->hasConflicts($schedule);\n }\n\n /**\n * Find all schedules that conflict with the given schedule.\n */\n public function findScheduleConflicts(Schedule $schedule): array\n {\n return app(ConflictDetectionService::class)->findConflicts($schedule);\n }\n\n /**\n * Check if this model is available during a specific time period.\n */\n public function isAvailableAt(string $date, string $startTime, string $endTime): bool\n {\n // Get all active schedules for this model on this date\n $schedules = \\Zap\\Models\\Schedule::where('schedulable_type', get_class($this))\n ->where('schedulable_id', $this->getKey())\n ->active()\n ->forDate($date)\n ->with('periods')\n ->get();\n\n foreach ($schedules as $schedule) {\n $shouldBlock = $schedule->schedule_type === null\n || $schedule->schedule_type->is(ScheduleTypes::CUSTOM)\n || $schedule->preventsOverlaps();\n\n if ($shouldBlock && $this->scheduleBlocksTime($schedule, $date, $startTime, $endTime)) {\n return false;\n }\n }\n\n return true;\n }\n\n /**\n * Check if a specific schedule blocks the given time period.\n */\n protected function scheduleBlocksTime(\\Zap\\Models\\Schedule $schedule, string $date, string $startTime, string $endTime): bool\n {\n if (! $schedule->isActiveOn($date)) {\n return false;\n }\n\n if ($schedule->is_recurring) {\n return $this->recurringScheduleBlocksTime($schedule, $date, $startTime, $endTime);\n }\n\n // For non-recurring schedules, check stored periods\n return $schedule->periods()->overlapping($date, $startTime, $endTime)->exists();\n }\n\n /**\n * Check if a recurring schedule blocks the given time period.\n */\n protected function recurringScheduleBlocksTime(\\Zap\\Models\\Schedule $schedule, string $date, string $startTime, string $endTime): bool\n {\n $checkDate = \\Carbon\\Carbon::parse($date);\n\n // Check if this date should have a recurring instance\n if (! $this->shouldCreateRecurringInstance($schedule, $checkDate)) {\n return false;\n }\n\n // Get the base periods and check if any would overlap on this date\n $basePeriods = $schedule->periods;\n\n foreach ($basePeriods as $basePeriod) {\n if ($this->timePeriodsOverlap($basePeriod->start_time, $basePeriod->end_time, $startTime, $endTime)) {\n return true;\n }\n }\n\n return false;\n }\n\n /**\n * Check if a recurring instance should be created for the given date.\n */\n protected function shouldCreateRecurringInstance(\\Zap\\Models\\Schedule $schedule, \\Carbon\\Carbon $date): bool\n {\n $frequency = $schedule->frequency;\n $config = $schedule->frequency_config ?? [];\n\n switch ($frequency) {\n case 'daily':\n return true;\n\n case 'weekly':\n $allowedDays = $config['days'] ?? ['monday'];\n $allowedDayNumbers = array_map(function ($day) {\n return match (strtolower($day)) {\n 'sunday' => 0,\n 'monday' => 1,\n 'tuesday' => 2,\n 'wednesday' => 3,\n 'thursday' => 4,\n 'friday' => 5,\n 'saturday' => 6,\n default => 1, // Default to Monday\n };\n }, $allowedDays);\n\n return in_array($date->dayOfWeek, $allowedDayNumbers);\n\n case 'monthly':\n $dayOfMonth = $config['day_of_month'] ?? $schedule->start_date->day;\n\n return $date->day === $dayOfMonth;\n\n default:\n return false;\n }\n }\n\n /**\n * Check if two time periods overlap.\n */\n protected function timePeriodsOverlap(string $start1, string $end1, string $start2, string $end2): bool\n {\n return $start1 < $end2 && $end1 > $start2;\n }\n\n /**\n * Get available time slots for a specific date.\n */\n public function getAvailableSlots(\n string $date,\n string $dayStart = '09:00',\n string $dayEnd = '17:00',\n int $slotDuration = 60\n ): array {\n // Validate inputs to prevent infinite loops\n if ($slotDuration <= 0) {\n return [];\n }\n\n $slots = [];\n $currentTime = \\Carbon\\Carbon::parse($date.' '.$dayStart);\n $endTime = \\Carbon\\Carbon::parse($date.' '.$dayEnd);\n\n // If end time is before or equal to start time, return empty array\n if ($endTime->lessThanOrEqualTo($currentTime)) {\n return [];\n }\n\n // Safety counter to prevent infinite loops (max 1440 minutes in a day / min slot duration)\n $maxIterations = 1440;\n $iterations = 0;\n\n while ($currentTime->lessThan($endTime) && $iterations < $maxIterations) {\n $slotEnd = $currentTime->copy()->addMinutes($slotDuration);\n\n if ($slotEnd->lessThanOrEqualTo($endTime)) {\n $isAvailable = $this->isAvailableAt(\n $date,\n $currentTime->format('H:i'),\n $slotEnd->format('H:i')\n );\n\n $slots[] = [\n 'start_time' => $currentTime->format('H:i'),\n 'end_time' => $slotEnd->format('H:i'),\n 'is_available' => $isAvailable,\n ];\n }\n\n $currentTime->addMinutes($slotDuration);\n $iterations++;\n }\n\n return $slots;\n }\n\n /**\n * Get the next available time slot.\n */\n public function getNextAvailableSlot(\n ?string $afterDate = null,\n int $duration = 60,\n string $dayStart = '09:00',\n string $dayEnd = '17:00'\n ): ?array {\n // Validate inputs\n if ($duration <= 0) {\n return null;\n }\n\n $startDate = $afterDate ?? now()->format('Y-m-d');\n $checkDate = \\Carbon\\Carbon::parse($startDate);\n\n // Check up to 30 days in the future\n for ($i = 0; $i < 30; $i++) {\n $dateString = $checkDate->format('Y-m-d');\n $slots = $this->getAvailableSlots($dateString, $dayStart, $dayEnd, $duration);\n\n foreach ($slots as $slot) {\n if ($slot['is_available']) {\n return array_merge($slot, ['date' => $dateString]);\n }\n }\n\n $checkDate->addDay();\n }\n\n return null;\n }\n\n /**\n * Count total scheduled time for a date range.\n */\n public function getTotalScheduledTime(string $startDate, string $endDate): int\n {\n return $this->schedules()\n ->active()\n ->forDateRange($startDate, $endDate)\n ->with('periods')\n ->get()\n ->sum(function ($schedule) {\n return $schedule->periods->sum('duration_minutes');\n });\n }\n\n /**\n * Check if the model has any schedules.\n */\n public function hasSchedules(): bool\n {\n return $this->schedules()->exists();\n }\n\n /**\n * Check if the model has any active schedules.\n */\n public function hasActiveSchedules(): bool\n {\n return $this->activeSchedules()->exists();\n }\n}\n"], ["/laravel-zap/src/Builders/ScheduleBuilder.php", "<?php\n\nnamespace Zap\\Builders;\n\nuse Carbon\\Carbon;\nuse Illuminate\\Database\\Eloquent\\Model;\nuse Zap\\Enums\\ScheduleTypes;\nuse Zap\\Models\\Schedule;\nuse Zap\\Services\\ScheduleService;\n\nclass ScheduleBuilder\n{\n private ?Model $schedulable = null;\n\n private array $attributes = [];\n\n private array $periods = [];\n\n private array $rules = [];\n\n /**\n * Set the schedulable model (User, etc.)\n */\n public function for(Model $schedulable): self\n {\n $this->schedulable = $schedulable;\n\n return $this;\n }\n\n /**\n * Set the schedule name.\n */\n public function named(string $name): self\n {\n $this->attributes['name'] = $name;\n\n return $this;\n }\n\n /**\n * Set the schedule description.\n */\n public function description(string $description): self\n {\n $this->attributes['description'] = $description;\n\n return $this;\n }\n\n /**\n * Set the start date.\n */\n public function from(Carbon|string $startDate): self\n {\n $this->attributes['start_date'] = $startDate instanceof Carbon\n ? $startDate->toDateString()\n : $startDate;\n\n return $this;\n }\n\n /**\n * Set the end date.\n */\n public function to(Carbon|string|null $endDate): self\n {\n $this->attributes['end_date'] = $endDate instanceof Carbon\n ? $endDate->toDateString()\n : $endDate;\n\n return $this;\n }\n\n /**\n * Set both start and end dates.\n */\n public function between(Carbon|string $start, Carbon|string $end): self\n {\n return $this->from($start)->to($end);\n }\n\n /**\n * Add a time period to the schedule.\n */\n public function addPeriod(string $startTime, string $endTime, ?Carbon $date = null): self\n {\n $this->periods[] = [\n 'start_time' => $startTime,\n 'end_time' => $endTime,\n 'date' => $date?->toDateString() ?? $this->attributes['start_date'] ?? now()->toDateString(),\n ];\n\n return $this;\n }\n\n /**\n * Add multiple periods at once.\n */\n public function addPeriods(array $periods): self\n {\n foreach ($periods as $period) {\n $this->addPeriod(\n $period['start_time'],\n $period['end_time'],\n isset($period['date']) ? Carbon::parse($period['date']) : null\n );\n }\n\n return $this;\n }\n\n /**\n * Set schedule as daily recurring.\n */\n public function daily(): self\n {\n $this->attributes['is_recurring'] = true;\n $this->attributes['frequency'] = 'daily';\n\n return $this;\n }\n\n /**\n * Set schedule as weekly recurring.\n */\n public function weekly(array $days = []): self\n {\n $this->attributes['is_recurring'] = true;\n $this->attributes['frequency'] = 'weekly';\n $this->attributes['frequency_config'] = ['days' => $days];\n\n return $this;\n }\n\n /**\n * Set schedule as monthly recurring.\n */\n public function monthly(array $config = []): self\n {\n $this->attributes['is_recurring'] = true;\n $this->attributes['frequency'] = 'monthly';\n $this->attributes['frequency_config'] = $config;\n\n return $this;\n }\n\n /**\n * Set custom recurring frequency.\n */\n public function recurring(string $frequency, array $config = []): self\n {\n $this->attributes['is_recurring'] = true;\n $this->attributes['frequency'] = $frequency;\n $this->attributes['frequency_config'] = $config;\n\n return $this;\n }\n\n /**\n * Add a validation rule.\n */\n public function withRule(string $ruleName, array $config = []): self\n {\n $this->rules[$ruleName] = $config;\n\n return $this;\n }\n\n /**\n * Add no overlap rule.\n */\n public function noOverlap(): self\n {\n return $this->withRule('no_overlap');\n }\n\n /**\n * Set schedule as availability type (allows overlaps).\n */\n public function availability(): self\n {\n $this->attributes['schedule_type'] = ScheduleTypes::AVAILABILITY;\n\n return $this;\n }\n\n /**\n * Set schedule as appointment type (prevents overlaps).\n */\n public function appointment(): self\n {\n $this->attributes['schedule_type'] = ScheduleTypes::APPOINTMENT;\n\n return $this;\n }\n\n /**\n * Set schedule as blocked type (prevents overlaps).\n */\n public function blocked(): self\n {\n $this->attributes['schedule_type'] = ScheduleTypes::BLOCKED;\n\n return $this;\n }\n\n /**\n * Set schedule as custom type.\n */\n public function custom(): self\n {\n $this->attributes['schedule_type'] = ScheduleTypes::CUSTOM;\n\n return $this;\n }\n\n /**\n * Set schedule type explicitly.\n */\n public function type(string $type): self\n {\n try {\n $scheduleType = ScheduleTypes::from($type);\n } catch (\\ValueError) {\n throw new \\InvalidArgumentException(\"Invalid schedule type: {$type}. Valid types are: \".implode(', ', ScheduleTypes::values()));\n }\n\n $this->attributes['schedule_type'] = $scheduleType;\n\n return $this;\n }\n\n /**\n * Add working hours only rule.\n */\n public function workingHoursOnly(string $start = '09:00', string $end = '17:00'): self\n {\n return $this->withRule('working_hours', compact('start', 'end'));\n }\n\n /**\n * Add maximum duration rule.\n */\n public function maxDuration(int $minutes): self\n {\n return $this->withRule('max_duration', ['minutes' => $minutes]);\n }\n\n /**\n * Add no weekends rule.\n */\n public function noWeekends(): self\n {\n return $this->withRule('no_weekends');\n }\n\n /**\n * Add custom metadata.\n */\n public function withMetadata(array $metadata): self\n {\n $this->attributes['metadata'] = array_merge($this->attributes['metadata'] ?? [], $metadata);\n\n return $this;\n }\n\n /**\n * Set the schedule as inactive.\n */\n public function inactive(): self\n {\n $this->attributes['is_active'] = false;\n\n return $this;\n }\n\n /**\n * Set the schedule as active (default).\n */\n public function active(): self\n {\n $this->attributes['is_active'] = true;\n\n return $this;\n }\n\n /**\n * Build and validate the schedule without saving.\n */\n public function build(): array\n {\n if (! $this->schedulable) {\n throw new \\InvalidArgumentException('Schedulable model must be set using for() method');\n }\n\n if (empty($this->attributes['start_date'])) {\n throw new \\InvalidArgumentException('Start date must be set using from() method');\n }\n\n // Set default schedule_type if not specified\n if (! isset($this->attributes['schedule_type'])) {\n $this->attributes['schedule_type'] = ScheduleTypes::CUSTOM;\n }\n\n return [\n 'schedulable' => $this->schedulable,\n 'attributes' => $this->attributes,\n 'periods' => $this->periods,\n 'rules' => $this->rules,\n ];\n }\n\n /**\n * Save the schedule.\n */\n public function save(): Schedule\n {\n $built = $this->build();\n\n return app(ScheduleService::class)->create(\n $built['schedulable'],\n $built['attributes'],\n $built['periods'],\n $built['rules']\n );\n }\n\n /**\n * Get the current attributes.\n */\n public function getAttributes(): array\n {\n return $this->attributes;\n }\n\n /**\n * Get the current periods.\n */\n public function getPeriods(): array\n {\n return $this->periods;\n }\n\n /**\n * Get the current rules.\n */\n public function getRules(): array\n {\n return $this->rules;\n }\n\n /**\n * Reset the builder to start fresh.\n */\n public function reset(): self\n {\n $this->schedulable = null;\n $this->attributes = [];\n $this->periods = [];\n $this->rules = [];\n\n return $this;\n }\n\n /**\n * Clone the builder with the same configuration.\n */\n public function clone(): self\n {\n $clone = new self;\n $clone->schedulable = $this->schedulable;\n $clone->attributes = $this->attributes;\n $clone->periods = $this->periods;\n $clone->rules = $this->rules;\n\n return $clone;\n }\n}\n"], ["/laravel-zap/src/Services/ScheduleService.php", "<?php\n\nnamespace Zap\\Services;\n\nuse Illuminate\\Database\\Eloquent\\Model;\nuse Illuminate\\Support\\Facades\\DB;\nuse Illuminate\\Support\\Facades\\Event;\nuse Zap\\Builders\\ScheduleBuilder;\nuse Zap\\Events\\ScheduleCreated;\nuse Zap\\Exceptions\\ScheduleConflictException;\nuse Zap\\Models\\Schedule;\n\nclass ScheduleService\n{\n public function __construct(\n private ValidationService $validator,\n private ConflictDetectionService $conflictService\n ) {}\n\n /**\n * Create a new schedule with validation and conflict detection.\n */\n public function create(\n Model $schedulable,\n array $attributes,\n array $periods = [],\n array $rules = []\n ): Schedule {\n return DB::transaction(function () use ($schedulable, $attributes, $periods, $rules) {\n // Set default values\n $attributes = array_merge([\n 'is_active' => true,\n 'is_recurring' => false,\n ], $attributes);\n\n // Validate the schedule data\n $this->validator->validate($schedulable, $attributes, $periods, $rules);\n\n // Create the schedule\n $schedule = new Schedule($attributes);\n $schedule->schedulable_type = get_class($schedulable);\n $schedule->schedulable_id = $schedulable->getKey();\n $schedule->save();\n\n // Create periods if provided\n if (! empty($periods)) {\n foreach ($periods as $period) {\n $period['schedule_id'] = $schedule->id;\n $schedule->periods()->create($period);\n }\n }\n\n // Note: Conflict checking is now done during validation phase\n // No need to check again after creation\n\n // Fire the created event\n Event::dispatch(new ScheduleCreated($schedule));\n\n return $schedule->load('periods');\n });\n }\n\n /**\n * Update an existing schedule.\n */\n public function update(Schedule $schedule, array $attributes, array $periods = []): Schedule\n {\n return DB::transaction(function () use ($schedule, $attributes, $periods) {\n // Update the schedule attributes\n $schedule->update($attributes);\n\n // Update periods if provided\n if (! empty($periods)) {\n // Delete existing periods and create new ones\n $schedule->periods()->delete();\n\n foreach ($periods as $period) {\n $period['schedule_id'] = $schedule->id;\n $schedule->periods()->create($period);\n }\n }\n\n // Check for conflicts after update\n $conflicts = $this->conflictService->findConflicts($schedule);\n if (! empty($conflicts)) {\n throw (new ScheduleConflictException(\n 'Updated schedule conflicts with existing schedules'\n ))->setConflictingSchedules($conflicts);\n }\n\n return $schedule->fresh('periods');\n });\n }\n\n /**\n * Delete a schedule.\n */\n public function delete(Schedule $schedule): bool\n {\n return DB::transaction(function () use ($schedule) {\n // Delete all periods first\n $schedule->periods()->delete();\n\n // Delete the schedule\n return $schedule->delete();\n });\n }\n\n /**\n * Create a schedule builder for a schedulable model.\n */\n public function for(Model $schedulable): ScheduleBuilder\n {\n return (new ScheduleBuilder)->for($schedulable);\n }\n\n /**\n * Create a new schedule builder.\n */\n public function schedule(): ScheduleBuilder\n {\n return new ScheduleBuilder;\n }\n\n /**\n * Find all schedules that conflict with the given schedule.\n */\n public function findConflicts(Schedule $schedule): array\n {\n return $this->conflictService->findConflicts($schedule);\n }\n\n /**\n * Check if a schedule has conflicts.\n */\n public function hasConflicts(Schedule $schedule): bool\n {\n return $this->conflictService->hasConflicts($schedule);\n }\n\n /**\n * Get available time slots for a schedulable on a given date.\n */\n public function getAvailableSlots(\n Model $schedulable,\n string $date,\n string $startTime = '09:00',\n string $endTime = '17:00',\n int $slotDuration = 60\n ): array {\n if (method_exists($schedulable, 'getAvailableSlots')) {\n return $schedulable->getAvailableSlots($date, $startTime, $endTime, $slotDuration);\n }\n\n return [];\n }\n\n /**\n * Check if a schedulable is available at a specific time.\n */\n public function isAvailable(\n Model $schedulable,\n string $date,\n string $startTime,\n string $endTime\n ): bool {\n if (method_exists($schedulable, 'isAvailableAt')) {\n return $schedulable->isAvailableAt($date, $startTime, $endTime);\n }\n\n return true; // Default to available if no schedule trait\n }\n\n /**\n * Get all schedules for a schedulable within a date range.\n */\n public function getSchedulesForDateRange(\n Model $schedulable,\n string $startDate,\n string $endDate\n ): \\Illuminate\\Database\\Eloquent\\Collection {\n if (method_exists($schedulable, 'schedulesForDateRange')) {\n return $schedulable->schedulesForDateRange($startDate, $endDate)->get();\n }\n\n return new \\Illuminate\\Database\\Eloquent\\Collection;\n }\n\n /**\n * Generate recurring schedule instances for a given period.\n */\n public function generateRecurringInstances(\n Schedule $schedule,\n string $startDate,\n string $endDate\n ): array {\n if (! $schedule->is_recurring) {\n return [];\n }\n\n $instances = [];\n $current = \\Carbon\\Carbon::parse($startDate);\n $end = \\Carbon\\Carbon::parse($endDate);\n\n while ($current->lte($end)) {\n if ($this->shouldCreateInstance($schedule, $current)) {\n $instances[] = [\n 'date' => $current->toDateString(),\n 'schedule' => $schedule,\n ];\n }\n\n $current = $this->getNextRecurrence($schedule, $current);\n }\n\n return $instances;\n }\n\n /**\n * Check if a recurring instance should be created for the given date.\n */\n private function shouldCreateInstance(Schedule $schedule, \\Carbon\\Carbon $date): bool\n {\n $frequency = $schedule->frequency;\n $config = $schedule->frequency_config ?? [];\n\n switch ($frequency) {\n case 'daily':\n return true;\n\n case 'weekly':\n $allowedDays = $config['days'] ?? [];\n\n return empty($allowedDays) || in_array(strtolower($date->format('l')), $allowedDays);\n\n case 'monthly':\n $dayOfMonth = $config['day_of_month'] ?? $date->day;\n\n return $date->day === $dayOfMonth;\n\n default:\n return false;\n }\n }\n\n /**\n * Get the next recurrence date.\n */\n private function getNextRecurrence(Schedule $schedule, \\Carbon\\Carbon $current): \\Carbon\\Carbon\n {\n $frequency = $schedule->frequency;\n\n switch ($frequency) {\n case 'daily':\n return $current->addDay();\n\n case 'weekly':\n return $current->addWeek();\n\n case 'monthly':\n return $current->addMonth();\n\n default:\n return $current->addDay();\n }\n }\n}\n"], ["/laravel-zap/src/Models/Schedule.php", "<?php\n\nnamespace Zap\\Models;\n\nuse Carbon\\Carbon;\nuse Illuminate\\Database\\Eloquent\\Builder;\nuse Illuminate\\Database\\Eloquent\\Collection;\nuse Illuminate\\Database\\Eloquent\\Model;\nuse Illuminate\\Database\\Eloquent\\Relations\\HasMany;\nuse Illuminate\\Database\\Eloquent\\Relations\\MorphTo;\nuse Zap\\Enums\\ScheduleTypes;\n\n/**\n * @property int $id\n * @property string $name\n * @property string|null $description\n * @property string $schedulable_type\n * @property int $schedulable_id\n * @property ScheduleTypes $schedule_type\n * @property Carbon $start_date\n * @property Carbon|null $end_date\n * @property bool $is_recurring\n * @property string|null $frequency\n * @property array|null $frequency_config\n * @property array|null $metadata\n * @property bool $is_active\n * @property Carbon|null $created_at\n * @property Carbon|null $updated_at\n * @property Carbon|null $deleted_at\n * @property-read \\Illuminate\\Database\\Eloquent\\Collection<int, SchedulePeriod> $periods\n * @property-read Model $schedulable\n * @property-read int $total_duration\n */\nclass Schedule extends Model\n{\n /**\n * The attributes that are mass assignable.\n */\n protected $fillable = [\n 'schedulable_type',\n 'schedulable_id',\n 'name',\n 'description',\n 'schedule_type',\n 'start_date',\n 'end_date',\n 'is_recurring',\n 'frequency',\n 'frequency_config',\n 'metadata',\n 'is_active',\n ];\n\n /**\n * The attributes that should be cast.\n */\n protected $casts = [\n 'schedule_type' => ScheduleTypes::class,\n 'start_date' => 'date',\n 'end_date' => 'date',\n 'is_recurring' => 'boolean',\n 'frequency_config' => 'array',\n 'metadata' => 'array',\n 'is_active' => 'boolean',\n ];\n\n /**\n * The attributes that should be guarded.\n */\n protected $guarded = [];\n\n /**\n * Get the parent schedulable model.\n */\n public function schedulable(): MorphTo\n {\n return $this->morphTo();\n }\n\n /**\n * Get the schedule periods.\n *\n * @return HasMany<SchedulePeriod, $this>\n */\n public function periods(): HasMany\n {\n return $this->hasMany(SchedulePeriod::class);\n }\n\n /**\n * Create a new Eloquent query builder for the model.\n */\n public function newEloquentBuilder($query): Builder\n {\n return new Builder($query);\n }\n\n /**\n * Create a new Eloquent Collection instance.\n *\n * @param array<int, static> $models\n * @return \\Illuminate\\Database\\Eloquent\\Collection<int, static>\n */\n public function newCollection(array $models = []): Collection\n {\n return new Collection($models);\n }\n\n /**\n * Scope a query to only include active schedules.\n */\n public function scopeActive(Builder $query): void\n {\n $query->where('is_active', true);\n }\n\n /**\n * Scope a query to only include recurring schedules.\n */\n public function scopeRecurring(Builder $query): void\n {\n $query->where('is_recurring', true);\n }\n\n /**\n * Scope a query to only include schedules of a specific type.\n */\n public function scopeOfType(Builder $query, string $type): void\n {\n $query->where('schedule_type', $type);\n }\n\n /**\n * Scope a query to only include availability schedules.\n */\n public function scopeAvailability(Builder $query): void\n {\n $query->where('schedule_type', ScheduleTypes::AVAILABILITY);\n }\n\n /**\n * Scope a query to only include appointment schedules.\n */\n public function scopeAppointments(Builder $query): void\n {\n $query->where('schedule_type', ScheduleTypes::APPOINTMENT);\n }\n\n /**\n * Scope a query to only include blocked schedules.\n */\n public function scopeBlocked(Builder $query): void\n {\n $query->where('schedule_type', ScheduleTypes::BLOCKED);\n }\n\n /**\n * Scope a query to only include schedules for a specific date.\n */\n public function scopeForDate(Builder $query, string $date): void\n {\n $checkDate = \\Carbon\\Carbon::parse($date);\n\n $query->where('start_date', '<=', $checkDate)\n ->where(function ($q) use ($checkDate) {\n $q->whereNull('end_date')\n ->orWhere('end_date', '>=', $checkDate);\n });\n }\n\n /**\n * Scope a query to only include schedules within a date range.\n */\n public function scopeForDateRange(Builder $query, string $startDate, string $endDate): void\n {\n $query->where(function ($q) use ($startDate, $endDate) {\n $q->whereBetween('start_date', [$startDate, $endDate])\n ->orWhereBetween('end_date', [$startDate, $endDate])\n ->orWhere(function ($q2) use ($startDate, $endDate) {\n $q2->where('start_date', '<=', $startDate)\n ->where('end_date', '>=', $endDate);\n });\n });\n }\n\n /**\n * Check if this schedule overlaps with another schedule.\n */\n public function overlapsWith(Schedule $other): bool\n {\n // Basic date range overlap check\n if ($this->end_date && $other->end_date) {\n return $this->start_date <= $other->end_date && $this->end_date >= $other->start_date;\n }\n\n // Handle open-ended schedules\n if (! $this->end_date && ! $other->end_date) {\n return $this->start_date <= $other->start_date;\n }\n\n if (! $this->end_date) {\n return $this->start_date <= ($other->end_date ?? $other->start_date);\n }\n\n if (! $other->end_date) {\n return $this->end_date >= $other->start_date;\n }\n\n return false;\n }\n\n /**\n * Get the total duration of all periods in minutes.\n */\n public function getTotalDurationAttribute(): int\n {\n return $this->periods->sum('duration_minutes');\n }\n\n /**\n * Check if the schedule is currently active.\n */\n public function isActiveOn(string $date): bool\n {\n if (! $this->is_active) {\n return false;\n }\n\n $checkDate = \\Carbon\\Carbon::parse($date);\n $startDate = $this->start_date;\n $endDate = $this->end_date;\n\n return $checkDate->greaterThanOrEqualTo($startDate) &&\n ($endDate === null || $checkDate->lessThanOrEqualTo($endDate));\n }\n\n /**\n * Check if this schedule is of availability type.\n */\n public function isAvailability(): bool\n {\n return $this->schedule_type->is(ScheduleTypes::AVAILABILITY);\n }\n\n /**\n * Check if this schedule is of appointment type.\n */\n public function isAppointment(): bool\n {\n return $this->schedule_type->is(ScheduleTypes::APPOINTMENT);\n }\n\n /**\n * Check if this schedule is of blocked type.\n */\n public function isBlocked(): bool\n {\n return $this->schedule_type->is(ScheduleTypes::BLOCKED);\n }\n\n /**\n * Check if this schedule is of custom type.\n */\n public function isCustom(): bool\n {\n return $this->schedule_type->is(ScheduleTypes::CUSTOM);\n }\n\n /**\n * Check if this schedule should prevent overlaps (appointments and blocked schedules).\n */\n public function preventsOverlaps(): bool\n {\n return $this->schedule_type->preventsOverlaps();\n }\n\n /**\n * Check if this schedule allows overlaps (availability schedules).\n */\n public function allowsOverlaps(): bool\n {\n return $this->schedule_type->allowsOverlaps();\n }\n}\n"], ["/laravel-zap/src/Models/SchedulePeriod.php", "<?php\n\nnamespace Zap\\Models;\n\nuse Carbon\\Carbon;\nuse Illuminate\\Database\\Eloquent\\Model;\nuse Illuminate\\Database\\Eloquent\\Relations\\BelongsTo;\n\n/**\n * @property int $id\n * @property int $schedule_id\n * @property Carbon $date\n * @property Carbon|null $start_time\n * @property Carbon|null $end_time\n * @property bool $is_available\n * @property array|null $metadata\n * @property Carbon|null $created_at\n * @property Carbon|null $updated_at\n * @property-read Schedule $schedule\n * @property-read int $duration_minutes\n * @property-read Carbon $start_date_time\n * @property-read Carbon $end_date_time\n */\nclass SchedulePeriod extends Model\n{\n /**\n * The attributes that are mass assignable.\n */\n protected $fillable = [\n 'schedule_id',\n 'date',\n 'start_time',\n 'end_time',\n 'is_available',\n 'metadata',\n ];\n\n /**\n * The attributes that should be cast.\n */\n protected $casts = [\n 'date' => 'date',\n 'start_time' => 'string',\n 'end_time' => 'string',\n 'is_available' => 'boolean',\n 'metadata' => 'array',\n ];\n\n /**\n * Get the schedule that owns the period.\n */\n public function schedule(): BelongsTo\n {\n return $this->belongsTo(Schedule::class);\n }\n\n /**\n * Get the duration in minutes.\n */\n public function getDurationMinutesAttribute(): int\n {\n if (! $this->start_time || ! $this->end_time) {\n return 0;\n }\n\n $baseDate = '2024-01-01'; // Use a consistent base date for time parsing\n $start = Carbon::parse($baseDate.' '.$this->start_time);\n $end = Carbon::parse($baseDate.' '.$this->end_time);\n\n return (int) $start->diffInMinutes($end);\n }\n\n /**\n * Get the full start datetime.\n */\n public function getStartDateTimeAttribute(): Carbon\n {\n return Carbon::parse($this->date->format('Y-m-d').' '.$this->start_time);\n }\n\n /**\n * Get the full end datetime.\n */\n public function getEndDateTimeAttribute(): Carbon\n {\n return Carbon::parse($this->date->format('Y-m-d').' '.$this->end_time);\n }\n\n /**\n * Check if this period overlaps with another period.\n */\n public function overlapsWith(SchedulePeriod $other): bool\n {\n // Must be on the same date\n if (! $this->date->eq($other->date)) {\n return false;\n }\n\n return $this->start_time < $other->end_time && $this->end_time > $other->start_time;\n }\n\n /**\n * Check if this period is currently active (happening now).\n */\n public function isActiveNow(): bool\n {\n $now = Carbon::now();\n $startDateTime = $this->start_date_time;\n $endDateTime = $this->end_date_time;\n\n return $now->between($startDateTime, $endDateTime);\n }\n\n /**\n * Scope a query to only include available periods.\n */\n public function scopeAvailable(\\Illuminate\\Database\\Eloquent\\Builder $query): \\Illuminate\\Database\\Eloquent\\Builder\n {\n return $query->where('is_available', true);\n }\n\n /**\n * Scope a query to only include periods for a specific date.\n */\n public function scopeForDate(\\Illuminate\\Database\\Eloquent\\Builder $query, string $date): \\Illuminate\\Database\\Eloquent\\Builder\n {\n return $query->where('date', $date);\n }\n\n /**\n * Scope a query to only include periods within a time range.\n */\n public function scopeForTimeRange(\\Illuminate\\Database\\Eloquent\\Builder $query, string $startTime, string $endTime): \\Illuminate\\Database\\Eloquent\\Builder\n {\n return $query->where('start_time', '>=', $startTime)\n ->where('end_time', '<=', $endTime);\n }\n\n /**\n * Scope a query to find overlapping periods.\n */\n public function scopeOverlapping(\\Illuminate\\Database\\Eloquent\\Builder $query, string $date, string $startTime, string $endTime): \\Illuminate\\Database\\Eloquent\\Builder\n {\n return $query->whereDate('date', $date)\n ->where('start_time', '<', $endTime)\n ->where('end_time', '>', $startTime);\n }\n\n /**\n * Convert the period to a human-readable string.\n */\n public function __toString(): string\n {\n return sprintf(\n '%s from %s to %s',\n $this->date->format('Y-m-d'),\n $this->start_time,\n $this->end_time\n );\n }\n}\n"], ["/laravel-zap/src/Exceptions/InvalidScheduleException.php", "<?php\n\nnamespace Zap\\Exceptions;\n\nclass InvalidScheduleException extends ZapException\n{\n /**\n * The validation errors.\n */\n protected array $errors = [];\n\n /**\n * Create a new invalid schedule exception.\n */\n public function __construct(\n string $message = 'Invalid schedule data provided',\n int $code = 422,\n ?\\Throwable $previous = null\n ) {\n parent::__construct($message, $code, $previous);\n }\n\n /**\n * Set the validation errors.\n */\n public function setErrors(array $errors): self\n {\n $this->errors = $errors;\n\n return $this;\n }\n\n /**\n * Get the validation errors.\n */\n public function getErrors(): array\n {\n return $this->errors;\n }\n\n /**\n * Get the exception as an array with validation errors.\n */\n public function toArray(): array\n {\n return array_merge(parent::toArray(), [\n 'errors' => $this->getErrors(),\n 'error_count' => count($this->errors),\n ]);\n }\n}\n"], ["/laravel-zap/src/Exceptions/ScheduleConflictException.php", "<?php\n\nnamespace Zap\\Exceptions;\n\nclass ScheduleConflictException extends ZapException\n{\n /**\n * The conflicting schedules.\n */\n protected array $conflictingSchedules = [];\n\n /**\n * Create a new schedule conflict exception.\n */\n public function __construct(\n string $message = 'Schedule conflicts detected',\n int $code = 409,\n ?\\Throwable $previous = null\n ) {\n parent::__construct($message, $code, $previous);\n }\n\n /**\n * Set the conflicting schedules.\n */\n public function setConflictingSchedules(array $schedules): self\n {\n $this->conflictingSchedules = $schedules;\n\n return $this;\n }\n\n /**\n * Get the conflicting schedules.\n */\n public function getConflictingSchedules(): array\n {\n return $this->conflictingSchedules;\n }\n\n /**\n * Get the exception as an array with conflict details.\n */\n public function toArray(): array\n {\n return array_merge(parent::toArray(), [\n 'conflicting_schedules' => $this->getConflictingSchedules(),\n 'conflict_count' => count($this->conflictingSchedules),\n ]);\n }\n}\n"], ["/laravel-zap/src/ZapServiceProvider.php", "<?php\n\nnamespace Zap;\n\nuse Illuminate\\Support\\ServiceProvider;\nuse Zap\\Services\\ConflictDetectionService;\nuse Zap\\Services\\ScheduleService;\nuse Zap\\Services\\ValidationService;\n\nclass ZapServiceProvider extends ServiceProvider\n{\n /**\n * Register any application services.\n */\n public function register(): void\n {\n $this->mergeConfigFrom(__DIR__.'/../config/zap.php', 'zap');\n\n // Register core services\n $this->app->singleton(ScheduleService::class);\n $this->app->singleton(ConflictDetectionService::class);\n $this->app->singleton(ValidationService::class);\n\n // Register the facade\n $this->app->bind('zap', ScheduleService::class);\n }\n\n /**\n * Bootstrap any application services.\n */\n public function boot(): void\n {\n $this->loadMigrationsFrom(__DIR__.'/../database/migrations');\n\n if ($this->app->runningInConsole()) {\n $this->publishes([\n __DIR__.'/../config/zap.php' => config_path('zap.php'),\n ], 'zap-config');\n\n $this->publishes([\n __DIR__.'/../database/migrations' => database_path('migrations'),\n ], 'zap-migrations');\n }\n }\n\n /**\n * Get the services provided by the provider.\n */\n public function provides(): array\n {\n return [\n 'zap',\n ScheduleService::class,\n ConflictDetectionService::class,\n ValidationService::class,\n ];\n }\n}\n"], ["/laravel-zap/src/Events/ScheduleCreated.php", "<?php\n\nnamespace Zap\\Events;\n\nuse Illuminate\\Foundation\\Events\\Dispatchable;\nuse Illuminate\\Queue\\SerializesModels;\nuse Zap\\Models\\Schedule;\n\nclass ScheduleCreated\n{\n use Dispatchable, SerializesModels;\n\n /**\n * Create a new event instance.\n */\n public function __construct(\n public Schedule $schedule\n ) {}\n\n /**\n * Get the schedule that was created.\n */\n public function getSchedule(): Schedule\n {\n return $this->schedule;\n }\n\n /**\n * Get the schedulable model.\n */\n public function getSchedulable()\n {\n return $this->schedule->schedulable;\n }\n\n /**\n * Check if the schedule is recurring.\n */\n public function isRecurring(): bool\n {\n return $this->schedule->is_recurring;\n }\n\n /**\n * Get the event as an array.\n */\n public function toArray(): array\n {\n return [\n 'schedule_id' => $this->schedule->id,\n 'schedulable_type' => $this->schedule->schedulable_type,\n 'schedulable_id' => $this->schedule->schedulable_id,\n 'name' => $this->schedule->name,\n 'start_date' => $this->schedule->start_date->toDateString(),\n 'end_date' => $this->schedule->end_date?->toDateString(),\n 'is_recurring' => $this->schedule->is_recurring,\n 'frequency' => $this->schedule->frequency,\n 'created_at' => $this->schedule->created_at->toISOString(),\n ];\n }\n}\n"], ["/laravel-zap/src/Enums/ScheduleTypes.php", "<?php\n\nnamespace Zap\\Enums;\n\nenum ScheduleTypes: string\n{\n case AVAILABILITY = 'availability';\n\n case APPOINTMENT = 'appointment';\n\n case BLOCKED = 'blocked';\n\n case CUSTOM = 'custom';\n\n /**\n * Get all available schedule types.\n *\n * @return string[]\n */\n public static function values(): array\n {\n return collect(self::cases())\n ->map(fn (ScheduleTypes $type): string => $type->value)\n ->all();\n }\n\n /**\n * Check this schedule type is of a specific availability type.\n */\n public function is(ScheduleTypes $type): bool\n {\n return $this->value === $type->value;\n }\n\n /**\n * Get the types that allow overlaps.\n */\n public function allowsOverlaps(): bool\n {\n return match ($this) {\n self::AVAILABILITY, self::CUSTOM => true,\n default => false,\n };\n }\n\n /**\n * Get types that prevent overlaps.\n */\n public function preventsOverlaps(): bool\n {\n return match ($this) {\n self::APPOINTMENT, self::BLOCKED => true,\n default => false,\n };\n }\n}\n"], ["/laravel-zap/src/Facades/Zap.php", "<?php\n\nnamespace Zap\\Facades;\n\nuse Illuminate\\Support\\Facades\\Facade;\nuse Zap\\Builders\\ScheduleBuilder;\n\n/**\n * @method static ScheduleBuilder for(mixed $schedulable)\n * @method static ScheduleBuilder schedule()\n * @method static array findConflicts(\\Zap\\Models\\Schedule $schedule)\n * @method static bool hasConflicts(\\Zap\\Models\\Schedule $schedule)\n *\n * @see \\Zap\\Services\\ScheduleService\n */\nclass Zap extends Facade\n{\n /**\n * Get the registered name of the component.\n */\n protected static function getFacadeAccessor(): string\n {\n return 'zap';\n }\n}\n"], ["/laravel-zap/src/Exceptions/ZapException.php", "<?php\n\nnamespace Zap\\Exceptions;\n\nuse Exception;\n\nabstract class ZapException extends Exception\n{\n /**\n * The error context data.\n */\n protected array $context = [];\n\n /**\n * Set context data for the exception.\n */\n public function setContext(array $context): self\n {\n $this->context = $context;\n\n return $this;\n }\n\n /**\n * Get the error context.\n */\n public function getContext(): array\n {\n return $this->context;\n }\n\n /**\n * Get the exception as an array.\n */\n public function toArray(): array\n {\n return [\n 'message' => $this->getMessage(),\n 'code' => $this->getCode(),\n 'file' => $this->getFile(),\n 'line' => $this->getLine(),\n 'context' => $this->getContext(),\n ];\n }\n}\n"]], "task_instance_info": {"created_time": "2025-08-20 21:27:15", "created_task_model": "DeepSeek-R1", "function_skeleton": "protected function shouldApplyNoOverlapRule (\\Zap\\Enums\\ScheduleTypes $scheduleType, array $noOverlapConfig, array $providedRules) : bool {}", "code_description": "This code segment functions to: Determine whether automatic conflict checking should be enabled based on configuration settings, explicit rule definitions, and schedule type compatibility."}, "inference_content": {"inference_model": "DeepSeek-R1", "inference_result": "```php\n[TASK_BEGIN]\nprotected function shouldApplyNoOverlapRule(\\Zap\\Enums\\ScheduleTypes $scheduleType, array $noOverlapConfig, array $providedRules): bool\n{\n return (\n ($scheduleType->is(\\Zap\\Enums\\ScheduleTypes::APPOINTMENT) || $scheduleType->is(\\Zap\\Enums\\ScheduleTypes::BLOCKED))\n && ($noOverlapConfig['enabled'] ?? true)\n && !isset($providedRules['no_overlap'])\n );\n}\n[TASK_END]\n```", "inference_time": "2025-08-20 21-27-54"}, "editdistance_info": {"edit_distance": 38.4615, "calculate_time": "2025-08-20 21:27:54", "true_code_clean": "protected function shouldApplyNoOverlapRule(\\Zap\\Enums\\ScheduleTypes $scheduleType, array $noOverlapConfig, array $providedRules): bool\n {\n if (isset($providedRules['no_overlap'])) {\n return false;\n }\n if (! ($noOverlapConfig['enabled'] ?? false)) {\n return false;\n }\n $appliesTo = $noOverlapConfig['applies_to'] ?? [];\n return in_array($scheduleType, $appliesTo);\n }", "predict_code_clean": "protected function shouldApplyNoOverlapRule(\\Zap\\Enums\\ScheduleTypes $scheduleType, array $noOverlapConfig, array $providedRules): bool\n{\n return (\n ($scheduleType->is(\\Zap\\Enums\\ScheduleTypes::APPOINTMENT) || $scheduleType->is(\\Zap\\Enums\\ScheduleTypes::BLOCKED))\n && ($noOverlapConfig['enabled'] ?? true)\n && !isset($providedRules['no_overlap'])\n );\n}"}}
{"repo_name": "laravel-zap", "file_name": "/laravel-zap/src/Services/ScheduleService.php", "inference_info": {"prefix_code": "<?php\n\nnamespace Zap\\Services;\n\nuse Illuminate\\Database\\Eloquent\\Model;\nuse Illuminate\\Support\\Facades\\DB;\nuse Illuminate\\Support\\Facades\\Event;\nuse Zap\\Builders\\ScheduleBuilder;\nuse Zap\\Events\\ScheduleCreated;\nuse Zap\\Exceptions\\ScheduleConflictException;\nuse Zap\\Models\\Schedule;\n\nclass ScheduleService\n{\n public function __construct(\n private ValidationService $validator,\n private ConflictDetectionService $conflictService\n ) {}\n\n /**\n * Create a new schedule with validation and conflict detection.\n */\n public function create(\n Model $schedulable,\n array $attributes,\n array $periods = [],\n array $rules = []\n ): Schedule {\n return DB::transaction(function () use ($schedulable, $attributes, $periods, $rules) {\n // Set default values\n $attributes = array_merge([\n 'is_active' => true,\n 'is_recurring' => false,\n ], $attributes);\n\n // Validate the schedule data\n $this->validator->validate($schedulable, $attributes, $periods, $rules);\n\n // Create the schedule\n $schedule = new Schedule($attributes);\n $schedule->schedulable_type = get_class($schedulable);\n $schedule->schedulable_id = $schedulable->getKey();\n $schedule->save();\n\n // Create periods if provided\n if (! empty($periods)) {\n foreach ($periods as $period) {\n $period['schedule_id'] = $schedule->id;\n $schedule->periods()->create($period);\n }\n }\n\n // Note: Conflict checking is now done during validation phase\n // No need to check again after creation\n\n // Fire the created event\n Event::dispatch(new ScheduleCreated($schedule));\n\n return $schedule->load('periods');\n });\n }\n\n /**\n * Update an existing schedule.\n */\n public function update(Schedule $schedule, array $attributes, array $periods = []): Schedule\n {\n return DB::transaction(function () use ($schedule, $attributes, $periods) {\n // Update the schedule attributes\n $schedule->update($attributes);\n\n // Update periods if provided\n if (! empty($periods)) {\n // Delete existing periods and create new ones\n $schedule->periods()->delete();\n\n foreach ($periods as $period) {\n $period['schedule_id'] = $schedule->id;\n $schedule->periods()->create($period);\n }\n }\n\n // Check for conflicts after update\n $conflicts = $this->conflictService->findConflicts($schedule);\n if (! empty($conflicts)) {\n throw (new ScheduleConflictException(\n 'Updated schedule conflicts with existing schedules'\n ))->setConflictingSchedules($conflicts);\n }\n\n return $schedule->fresh('periods');\n });\n }\n\n /**\n * Delete a schedule.\n */\n public function delete(Schedule $schedule): bool\n {\n return DB::transaction(function () use ($schedule) {\n // Delete all periods first\n $schedule->periods()->delete();\n\n // Delete the schedule\n return $schedule->delete();\n });\n }\n\n /**\n * Create a schedule builder for a schedulable model.\n */\n public function for(Model $schedulable): ScheduleBuilder\n {\n return (new ScheduleBuilder)->for($schedulable);\n }\n\n /**\n * Create a new schedule builder.\n */\n public function schedule(): ScheduleBuilder\n {\n return new ScheduleBuilder;\n }\n\n /**\n * Find all schedules that conflict with the given schedule.\n */\n public function findConflicts(Schedule $schedule): array\n {\n return $this->conflictService->findConflicts($schedule);\n }\n\n /**\n * Check if a schedule has conflicts.\n */\n public function hasConflicts(Schedule $schedule): bool\n {\n return $this->conflictService->hasConflicts($schedule);\n }\n\n /**\n * Get available time slots for a schedulable on a given date.\n */\n public function getAvailableSlots(\n Model $schedulable,\n string $date,\n string $startTime = '09:00',\n string $endTime = '17:00',\n int $slotDuration = 60\n ): array {\n if (method_exists($schedulable, 'getAvailableSlots')) {\n return $schedulable->getAvailableSlots($date, $startTime, $endTime, $slotDuration);\n }\n\n return [];\n }\n\n /**\n * Check if a schedulable is available at a specific time.\n */\n public function isAvailable(\n Model $schedulable,\n string $date,\n string $startTime,\n string $endTime\n ): bool {\n if (method_exists($schedulable, 'isAvailableAt')) {\n return $schedulable->isAvailableAt($date, $startTime, $endTime);\n }\n\n return true; // Default to available if no schedule trait\n }\n\n /**\n * Get all schedules for a schedulable within a date range.\n */\n ", "suffix_code": "\n\n /**\n * Generate recurring schedule instances for a given period.\n */\n public function generateRecurringInstances(\n Schedule $schedule,\n string $startDate,\n string $endDate\n ): array {\n if (! $schedule->is_recurring) {\n return [];\n }\n\n $instances = [];\n $current = \\Carbon\\Carbon::parse($startDate);\n $end = \\Carbon\\Carbon::parse($endDate);\n\n while ($current->lte($end)) {\n if ($this->shouldCreateInstance($schedule, $current)) {\n $instances[] = [\n 'date' => $current->toDateString(),\n 'schedule' => $schedule,\n ];\n }\n\n $current = $this->getNextRecurrence($schedule, $current);\n }\n\n return $instances;\n }\n\n /**\n * Check if a recurring instance should be created for the given date.\n */\n private function shouldCreateInstance(Schedule $schedule, \\Carbon\\Carbon $date): bool\n {\n $frequency = $schedule->frequency;\n $config = $schedule->frequency_config ?? [];\n\n switch ($frequency) {\n case 'daily':\n return true;\n\n case 'weekly':\n $allowedDays = $config['days'] ?? [];\n\n return empty($allowedDays) || in_array(strtolower($date->format('l')), $allowedDays);\n\n case 'monthly':\n $dayOfMonth = $config['day_of_month'] ?? $date->day;\n\n return $date->day === $dayOfMonth;\n\n default:\n return false;\n }\n }\n\n /**\n * Get the next recurrence date.\n */\n private function getNextRecurrence(Schedule $schedule, \\Carbon\\Carbon $current): \\Carbon\\Carbon\n {\n $frequency = $schedule->frequency;\n\n switch ($frequency) {\n case 'daily':\n return $current->addDay();\n\n case 'weekly':\n return $current->addWeek();\n\n case 'monthly':\n return $current->addMonth();\n\n default:\n return $current->addDay();\n }\n }\n}\n", "middle_code": "public function getSchedulesForDateRange(\n Model $schedulable,\n string $startDate,\n string $endDate\n ): \\Illuminate\\Database\\Eloquent\\Collection {\n if (method_exists($schedulable, 'schedulesForDateRange')) {\n return $schedulable->schedulesForDateRange($startDate, $endDate)->get();\n }\n return new \\Illuminate\\Database\\Eloquent\\Collection;\n }", "code_description": null, "fill_type": "FUNCTION_TYPE", "language_type": "php", "sub_task_type": null}, "context_code": [["/laravel-zap/src/Services/ConflictDetectionService.php", "<?php\n\nnamespace Zap\\Services;\n\nuse Illuminate\\Database\\Eloquent\\Model;\nuse Illuminate\\Support\\Collection;\nuse Zap\\Enums\\ScheduleTypes;\nuse Zap\\Models\\Schedule;\nuse Zap\\Models\\SchedulePeriod;\n\nclass ConflictDetectionService\n{\n /**\n * Check if a schedule has conflicts with existing schedules.\n */\n public function hasConflicts(Schedule $schedule): bool\n {\n return ! empty($this->findConflicts($schedule));\n }\n\n /**\n * Find all schedules that conflict with the given schedule.\n */\n public function findConflicts(Schedule $schedule): array\n {\n if (! config('zap.conflict_detection.enabled', true)) {\n return [];\n }\n\n $conflicts = [];\n $bufferMinutes = config('zap.conflict_detection.buffer_minutes', 0);\n\n // Get all other active schedules for the same schedulable\n $otherSchedules = $this->getOtherSchedules($schedule);\n\n foreach ($otherSchedules as $otherSchedule) {\n // Check conflicts based on schedule types and rules\n $shouldCheckConflict = $this->shouldCheckConflict($schedule, $otherSchedule);\n\n if ($shouldCheckConflict && $this->schedulesOverlap($schedule, $otherSchedule, $bufferMinutes)) {\n $conflicts[] = $otherSchedule;\n }\n }\n\n return $conflicts;\n }\n\n /**\n * Determine if two schedules should be checked for conflicts.\n */\n protected function shouldCheckConflict(Schedule $schedule1, Schedule $schedule2): bool\n {\n // Availability schedules never conflict with anything (they allow overlaps)\n if ($schedule1->schedule_type->is(ScheduleTypes::AVAILABILITY) ||\n $schedule2->schedule_type->is(ScheduleTypes::AVAILABILITY)) {\n return false;\n }\n\n // Check if no_overlap rule is enabled and applies to these schedule types\n $noOverlapConfig = config('zap.default_rules.no_overlap', []);\n if (! ($noOverlapConfig['enabled'] ?? true)) {\n return false;\n }\n\n $appliesTo = $noOverlapConfig['applies_to'] ?? [ScheduleTypes::APPOINTMENT->value, ScheduleTypes::BLOCKED->value];\n $schedule1ShouldCheck = in_array($schedule1->schedule_type->value, $appliesTo);\n $schedule2ShouldCheck = in_array($schedule2->schedule_type->value, $appliesTo);\n\n // Both schedules must be of types that should be checked for conflicts\n return $schedule1ShouldCheck && $schedule2ShouldCheck;\n }\n\n /**\n * Check if a schedulable has conflicts with a given schedule.\n */\n public function hasSchedulableConflicts(Model $schedulable, Schedule $schedule): bool\n {\n $conflicts = $this->findSchedulableConflicts($schedulable, $schedule);\n\n return ! empty($conflicts);\n }\n\n /**\n * Find conflicts for a schedulable with a given schedule.\n */\n public function findSchedulableConflicts(Model $schedulable, Schedule $schedule): array\n {\n // Create a temporary schedule for conflict checking\n $tempSchedule = new Schedule([\n 'schedulable_type' => get_class($schedulable),\n 'schedulable_id' => $schedulable->getKey(),\n 'start_date' => $schedule->start_date,\n 'end_date' => $schedule->end_date,\n 'is_active' => true,\n ]);\n\n // Copy periods if they exist\n if ($schedule->relationLoaded('periods')) {\n $tempSchedule->setRelation('periods', $schedule->periods);\n }\n\n return $this->findConflicts($tempSchedule);\n }\n\n /**\n * Check if two schedules overlap.\n */\n public function schedulesOverlap(\n Schedule $schedule1,\n Schedule $schedule2,\n int $bufferMinutes = 0\n ): bool {\n // First check date range overlap\n if (! $this->dateRangesOverlap($schedule1, $schedule2)) {\n return false;\n }\n\n // Then check period-level conflicts\n return $this->periodsOverlap($schedule1, $schedule2, $bufferMinutes);\n }\n\n /**\n * Check if two schedules have overlapping date ranges.\n */\n protected function dateRangesOverlap(Schedule $schedule1, Schedule $schedule2): bool\n {\n $start1 = $schedule1->start_date;\n $end1 = $schedule1->end_date ?? \\Carbon\\Carbon::parse('2099-12-31');\n $start2 = $schedule2->start_date;\n $end2 = $schedule2->end_date ?? \\Carbon\\Carbon::parse('2099-12-31');\n\n return $start1 <= $end2 && $end1 >= $start2;\n }\n\n /**\n * Check if periods from two schedules overlap.\n */\n protected function periodsOverlap(\n Schedule $schedule1,\n Schedule $schedule2,\n int $bufferMinutes = 0\n ): bool {\n $periods1 = $this->getSchedulePeriods($schedule1);\n $periods2 = $this->getSchedulePeriods($schedule2);\n\n foreach ($periods1 as $period1) {\n foreach ($periods2 as $period2) {\n if ($this->periodPairOverlaps($period1, $period2, $bufferMinutes)) {\n return true;\n }\n }\n }\n\n return false;\n }\n\n /**\n * Check if two specific periods overlap.\n */\n protected function periodPairOverlaps(\n SchedulePeriod $period1,\n SchedulePeriod $period2,\n int $bufferMinutes = 0\n ): bool {\n // Must be on the same date\n if (! $period1->date->eq($period2->date)) {\n return false;\n }\n\n $start1 = $this->parseTime($period1->start_time);\n $end1 = $this->parseTime($period1->end_time);\n $start2 = $this->parseTime($period2->start_time);\n $end2 = $this->parseTime($period2->end_time);\n\n // Apply buffer\n if ($bufferMinutes > 0) {\n $start1->subMinutes($bufferMinutes);\n $end1->addMinutes($bufferMinutes);\n }\n\n return $start1 < $end2 && $end1 > $start2;\n }\n\n /**\n * Get periods for a schedule, handling recurring schedules.\n */\n protected function getSchedulePeriods(Schedule $schedule): Collection\n {\n $periods = $schedule->relationLoaded('periods')\n ? $schedule->periods\n : $schedule->periods()->get();\n\n // If this is a recurring schedule, we need to generate recurring instances\n if ($schedule->is_recurring) {\n return $this->generateRecurringPeriods($schedule, $periods);\n }\n\n return $periods;\n }\n\n /**\n * Generate recurring periods for a recurring schedule within a reasonable range.\n */\n protected function generateRecurringPeriods(Schedule $schedule, Collection $basePeriods): Collection\n {\n if (! $schedule->is_recurring || $basePeriods->isEmpty()) {\n return $basePeriods;\n }\n\n $allPeriods = collect();\n\n // Generate recurring instances for the next year to cover reasonable conflicts\n $startDate = $schedule->start_date;\n $endDate = $schedule->end_date ?? $startDate->copy()->addYear();\n\n // Limit the range to avoid infinite generation\n $maxEndDate = $startDate->copy()->addYear();\n if ($endDate->gt($maxEndDate)) {\n $endDate = $maxEndDate;\n }\n\n $current = $startDate->copy();\n\n while ($current->lte($endDate)) {\n // Check if this date should have a recurring instance\n if ($this->shouldCreateRecurringInstance($schedule, $current)) {\n // Generate periods for this recurring date\n foreach ($basePeriods as $basePeriod) {\n $recurringPeriod = new \\Zap\\Models\\SchedulePeriod([\n 'schedule_id' => $schedule->id,\n 'date' => $current->toDateString(),\n 'start_time' => $basePeriod->start_time,\n 'end_time' => $basePeriod->end_time,\n 'is_available' => $basePeriod->is_available,\n 'metadata' => $basePeriod->metadata,\n ]);\n\n $allPeriods->push($recurringPeriod);\n }\n }\n\n $current = $this->getNextRecurrence($schedule, $current);\n\n if ($current->gt($endDate)) {\n break;\n }\n }\n\n return $allPeriods;\n }\n\n /**\n * Check if a recurring instance should be created for the given date.\n */\n protected function shouldCreateRecurringInstance(Schedule $schedule, \\Carbon\\Carbon $date): bool\n {\n $frequency = $schedule->frequency;\n $config = $schedule->frequency_config ?? [];\n\n switch ($frequency) {\n case 'daily':\n return true;\n\n case 'weekly':\n $allowedDays = $config['days'] ?? ['monday'];\n $allowedDayNumbers = array_map(function ($day) {\n return match (strtolower($day)) {\n 'sunday' => 0,\n 'monday' => 1,\n 'tuesday' => 2,\n 'wednesday' => 3,\n 'thursday' => 4,\n 'friday' => 5,\n 'saturday' => 6,\n default => 1, // Default to Monday\n };\n }, $allowedDays);\n\n return in_array($date->dayOfWeek, $allowedDayNumbers);\n\n case 'monthly':\n $dayOfMonth = $config['day_of_month'] ?? $schedule->start_date->day;\n\n return $date->day === $dayOfMonth;\n\n default:\n return false;\n }\n }\n\n /**\n * Get the next recurrence date for a recurring schedule.\n */\n protected function getNextRecurrence(Schedule $schedule, \\Carbon\\Carbon $current): \\Carbon\\Carbon\n {\n $frequency = $schedule->frequency;\n $config = $schedule->frequency_config ?? [];\n\n switch ($frequency) {\n case 'daily':\n return $current->copy()->addDay();\n\n case 'weekly':\n $allowedDays = $config['days'] ?? ['monday'];\n\n return $this->getNextWeeklyOccurrence($current, $allowedDays);\n\n case 'monthly':\n $dayOfMonth = $config['day_of_month'] ?? $current->day;\n\n return $current->copy()->addMonth()->day($dayOfMonth);\n\n default:\n return $current->copy()->addDay();\n }\n }\n\n /**\n * Get the next weekly occurrence for the given days.\n */\n protected function getNextWeeklyOccurrence(\\Carbon\\Carbon $current, array $allowedDays): \\Carbon\\Carbon\n {\n $next = $current->copy()->addDay();\n\n // Convert day names to numbers (0 = Sunday, 1 = Monday, etc.)\n $allowedDayNumbers = array_map(function ($day) {\n return match (strtolower($day)) {\n 'sunday' => 0,\n 'monday' => 1,\n 'tuesday' => 2,\n 'wednesday' => 3,\n 'thursday' => 4,\n 'friday' => 5,\n 'saturday' => 6,\n default => 1, // Default to Monday\n };\n }, $allowedDays);\n\n // Find the next allowed day\n while (! in_array($next->dayOfWeek, $allowedDayNumbers)) {\n $next->addDay();\n\n // Prevent infinite loop\n if ($next->diffInDays($current) > 7) {\n break;\n }\n }\n\n return $next;\n }\n\n /**\n * Get other active schedules for the same schedulable.\n */\n protected function getOtherSchedules(Schedule $schedule): Collection\n {\n return Schedule::where('schedulable_type', $schedule->schedulable_type)\n ->where('schedulable_id', $schedule->schedulable_id)\n ->where('id', '!=', $schedule->id)\n ->active()\n ->with('periods')\n ->get();\n }\n\n /**\n * Parse a time string to Carbon instance.\n */\n protected function parseTime(string $time): \\Carbon\\Carbon\n {\n $baseDate = '2024-01-01'; // Use a consistent base date for time parsing\n\n return \\Carbon\\Carbon::parse($baseDate.' '.$time);\n }\n\n /**\n * Get conflicts for a specific time period.\n */\n public function findPeriodConflicts(\n Model $schedulable,\n string $date,\n string $startTime,\n string $endTime\n ): Collection {\n return Schedule::where('schedulable_type', get_class($schedulable))\n ->where('schedulable_id', $schedulable->getKey())\n ->active()\n ->forDate($date)\n ->whereHas('periods', function ($query) use ($date, $startTime, $endTime) {\n $query->whereDate('date', $date)\n ->where('start_time', '<', $endTime)\n ->where('end_time', '>', $startTime);\n })\n ->with('periods')\n ->get();\n }\n\n /**\n * Check if a specific time slot is available.\n */\n public function isTimeSlotAvailable(\n Model $schedulable,\n string $date,\n string $startTime,\n string $endTime\n ): bool {\n return $this->findPeriodConflicts($schedulable, $date, $startTime, $endTime)->isEmpty();\n }\n}\n"], ["/laravel-zap/src/Models/Concerns/HasSchedules.php", "<?php\n\nnamespace Zap\\Models\\Concerns;\n\nuse Illuminate\\Database\\Eloquent\\Relations\\MorphMany;\nuse Zap\\Builders\\ScheduleBuilder;\nuse Zap\\Enums\\ScheduleTypes;\nuse Zap\\Models\\Schedule;\nuse Zap\\Services\\ConflictDetectionService;\n\n/**\n * Trait HasSchedules\n *\n * This trait provides scheduling capabilities to any Eloquent model.\n * Use this trait in models that need to be schedulable.\n *\n * @mixin \\Illuminate\\Database\\Eloquent\\Model\n */\ntrait HasSchedules\n{\n /**\n * Get all schedules for this model.\n *\n * @return MorphMany<Schedule, $this>\n */\n public function schedules(): MorphMany\n {\n return $this->morphMany(Schedule::class, 'schedulable');\n }\n\n /**\n * Get only active schedules.\n *\n * @return MorphMany<Schedule, $this>\n */\n public function activeSchedules(): MorphMany\n {\n return $this->schedules()->active();\n }\n\n /**\n * Get availability schedules.\n *\n * @return MorphMany<Schedule, $this>\n */\n public function availabilitySchedules(): MorphMany\n {\n return $this->schedules()->availability();\n }\n\n /**\n * Get appointment schedules.\n *\n * @return MorphMany<Schedule, $this>\n */\n public function appointmentSchedules(): MorphMany\n {\n return $this->schedules()->appointments();\n }\n\n /**\n * Get blocked schedules.\n *\n * @return MorphMany<Schedule, $this>\n */\n public function blockedSchedules(): MorphMany\n {\n return $this->schedules()->blocked();\n }\n\n /**\n * Get schedules for a specific date.\n *\n * @return MorphMany<Schedule, $this>\n */\n public function schedulesForDate(string $date): MorphMany\n {\n return $this->schedules()->forDate($date);\n }\n\n /**\n * Get schedules within a date range.\n *\n * @return MorphMany<Schedule, $this>\n */\n public function schedulesForDateRange(string $startDate, string $endDate): MorphMany\n {\n return $this->schedules()->forDateRange($startDate, $endDate);\n }\n\n /**\n * Get recurring schedules.\n *\n * @return MorphMany<Schedule, $this>\n */\n public function recurringSchedules(): MorphMany\n {\n return $this->schedules()->recurring();\n }\n\n /**\n * Get schedules of a specific type.\n *\n * @return MorphMany<Schedule, $this>\n */\n public function schedulesOfType(string $type): MorphMany\n {\n return $this->schedules()->ofType($type);\n }\n\n /**\n * Create a new schedule builder for this model.\n */\n public function createSchedule(): ScheduleBuilder\n {\n return (new ScheduleBuilder)->for($this);\n }\n\n /**\n * Check if this model has any schedule conflicts with the given schedule.\n */\n public function hasScheduleConflict(Schedule $schedule): bool\n {\n return app(ConflictDetectionService::class)->hasConflicts($schedule);\n }\n\n /**\n * Find all schedules that conflict with the given schedule.\n */\n public function findScheduleConflicts(Schedule $schedule): array\n {\n return app(ConflictDetectionService::class)->findConflicts($schedule);\n }\n\n /**\n * Check if this model is available during a specific time period.\n */\n public function isAvailableAt(string $date, string $startTime, string $endTime): bool\n {\n // Get all active schedules for this model on this date\n $schedules = \\Zap\\Models\\Schedule::where('schedulable_type', get_class($this))\n ->where('schedulable_id', $this->getKey())\n ->active()\n ->forDate($date)\n ->with('periods')\n ->get();\n\n foreach ($schedules as $schedule) {\n $shouldBlock = $schedule->schedule_type === null\n || $schedule->schedule_type->is(ScheduleTypes::CUSTOM)\n || $schedule->preventsOverlaps();\n\n if ($shouldBlock && $this->scheduleBlocksTime($schedule, $date, $startTime, $endTime)) {\n return false;\n }\n }\n\n return true;\n }\n\n /**\n * Check if a specific schedule blocks the given time period.\n */\n protected function scheduleBlocksTime(\\Zap\\Models\\Schedule $schedule, string $date, string $startTime, string $endTime): bool\n {\n if (! $schedule->isActiveOn($date)) {\n return false;\n }\n\n if ($schedule->is_recurring) {\n return $this->recurringScheduleBlocksTime($schedule, $date, $startTime, $endTime);\n }\n\n // For non-recurring schedules, check stored periods\n return $schedule->periods()->overlapping($date, $startTime, $endTime)->exists();\n }\n\n /**\n * Check if a recurring schedule blocks the given time period.\n */\n protected function recurringScheduleBlocksTime(\\Zap\\Models\\Schedule $schedule, string $date, string $startTime, string $endTime): bool\n {\n $checkDate = \\Carbon\\Carbon::parse($date);\n\n // Check if this date should have a recurring instance\n if (! $this->shouldCreateRecurringInstance($schedule, $checkDate)) {\n return false;\n }\n\n // Get the base periods and check if any would overlap on this date\n $basePeriods = $schedule->periods;\n\n foreach ($basePeriods as $basePeriod) {\n if ($this->timePeriodsOverlap($basePeriod->start_time, $basePeriod->end_time, $startTime, $endTime)) {\n return true;\n }\n }\n\n return false;\n }\n\n /**\n * Check if a recurring instance should be created for the given date.\n */\n protected function shouldCreateRecurringInstance(\\Zap\\Models\\Schedule $schedule, \\Carbon\\Carbon $date): bool\n {\n $frequency = $schedule->frequency;\n $config = $schedule->frequency_config ?? [];\n\n switch ($frequency) {\n case 'daily':\n return true;\n\n case 'weekly':\n $allowedDays = $config['days'] ?? ['monday'];\n $allowedDayNumbers = array_map(function ($day) {\n return match (strtolower($day)) {\n 'sunday' => 0,\n 'monday' => 1,\n 'tuesday' => 2,\n 'wednesday' => 3,\n 'thursday' => 4,\n 'friday' => 5,\n 'saturday' => 6,\n default => 1, // Default to Monday\n };\n }, $allowedDays);\n\n return in_array($date->dayOfWeek, $allowedDayNumbers);\n\n case 'monthly':\n $dayOfMonth = $config['day_of_month'] ?? $schedule->start_date->day;\n\n return $date->day === $dayOfMonth;\n\n default:\n return false;\n }\n }\n\n /**\n * Check if two time periods overlap.\n */\n protected function timePeriodsOverlap(string $start1, string $end1, string $start2, string $end2): bool\n {\n return $start1 < $end2 && $end1 > $start2;\n }\n\n /**\n * Get available time slots for a specific date.\n */\n public function getAvailableSlots(\n string $date,\n string $dayStart = '09:00',\n string $dayEnd = '17:00',\n int $slotDuration = 60\n ): array {\n // Validate inputs to prevent infinite loops\n if ($slotDuration <= 0) {\n return [];\n }\n\n $slots = [];\n $currentTime = \\Carbon\\Carbon::parse($date.' '.$dayStart);\n $endTime = \\Carbon\\Carbon::parse($date.' '.$dayEnd);\n\n // If end time is before or equal to start time, return empty array\n if ($endTime->lessThanOrEqualTo($currentTime)) {\n return [];\n }\n\n // Safety counter to prevent infinite loops (max 1440 minutes in a day / min slot duration)\n $maxIterations = 1440;\n $iterations = 0;\n\n while ($currentTime->lessThan($endTime) && $iterations < $maxIterations) {\n $slotEnd = $currentTime->copy()->addMinutes($slotDuration);\n\n if ($slotEnd->lessThanOrEqualTo($endTime)) {\n $isAvailable = $this->isAvailableAt(\n $date,\n $currentTime->format('H:i'),\n $slotEnd->format('H:i')\n );\n\n $slots[] = [\n 'start_time' => $currentTime->format('H:i'),\n 'end_time' => $slotEnd->format('H:i'),\n 'is_available' => $isAvailable,\n ];\n }\n\n $currentTime->addMinutes($slotDuration);\n $iterations++;\n }\n\n return $slots;\n }\n\n /**\n * Get the next available time slot.\n */\n public function getNextAvailableSlot(\n ?string $afterDate = null,\n int $duration = 60,\n string $dayStart = '09:00',\n string $dayEnd = '17:00'\n ): ?array {\n // Validate inputs\n if ($duration <= 0) {\n return null;\n }\n\n $startDate = $afterDate ?? now()->format('Y-m-d');\n $checkDate = \\Carbon\\Carbon::parse($startDate);\n\n // Check up to 30 days in the future\n for ($i = 0; $i < 30; $i++) {\n $dateString = $checkDate->format('Y-m-d');\n $slots = $this->getAvailableSlots($dateString, $dayStart, $dayEnd, $duration);\n\n foreach ($slots as $slot) {\n if ($slot['is_available']) {\n return array_merge($slot, ['date' => $dateString]);\n }\n }\n\n $checkDate->addDay();\n }\n\n return null;\n }\n\n /**\n * Count total scheduled time for a date range.\n */\n public function getTotalScheduledTime(string $startDate, string $endDate): int\n {\n return $this->schedules()\n ->active()\n ->forDateRange($startDate, $endDate)\n ->with('periods')\n ->get()\n ->sum(function ($schedule) {\n return $schedule->periods->sum('duration_minutes');\n });\n }\n\n /**\n * Check if the model has any schedules.\n */\n public function hasSchedules(): bool\n {\n return $this->schedules()->exists();\n }\n\n /**\n * Check if the model has any active schedules.\n */\n public function hasActiveSchedules(): bool\n {\n return $this->activeSchedules()->exists();\n }\n}\n"], ["/laravel-zap/src/Services/ValidationService.php", "<?php\n\nnamespace Zap\\Services;\n\nuse Illuminate\\Database\\Eloquent\\Model;\nuse Zap\\Exceptions\\InvalidScheduleException;\n\nclass ValidationService\n{\n /**\n * Validate a schedule before creation.\n */\n public function validate(\n Model $schedulable,\n array $attributes,\n array $periods,\n array $rules = []\n ): void {\n $errors = [];\n\n // Basic validation\n $basicErrors = $this->validateBasicAttributes($attributes);\n if (! empty($basicErrors)) {\n $errors = array_merge($errors, $basicErrors);\n }\n\n // Period validation\n $periodErrors = $this->validatePeriods($periods);\n if (! empty($periodErrors)) {\n $errors = array_merge($errors, $periodErrors);\n }\n\n // Business rules validation\n $ruleErrors = $this->validateRules($rules, $schedulable, $attributes, $periods);\n if (! empty($ruleErrors)) {\n $errors = array_merge($errors, $ruleErrors);\n }\n\n if (! empty($errors)) {\n $message = $this->buildValidationErrorMessage($errors);\n throw (new InvalidScheduleException($message))->setErrors($errors);\n }\n }\n\n /**\n * Validate basic schedule attributes.\n */\n protected function validateBasicAttributes(array $attributes): array\n {\n $errors = [];\n\n // Start date is required\n if (empty($attributes['start_date'])) {\n $errors['start_date'] = 'A start date is required for the schedule';\n }\n\n // End date must be after start date if provided\n if (! empty($attributes['end_date']) && ! empty($attributes['start_date'])) {\n $startDate = \\Carbon\\Carbon::parse($attributes['start_date']);\n $endDate = \\Carbon\\Carbon::parse($attributes['end_date']);\n\n if ($endDate->lte($startDate)) {\n $errors['end_date'] = 'The end date must be after the start date';\n }\n }\n\n // Check date range limits\n if (! empty($attributes['start_date']) && ! empty($attributes['end_date'])) {\n $startDate = \\Carbon\\Carbon::parse($attributes['start_date']);\n $endDate = \\Carbon\\Carbon::parse($attributes['end_date']);\n $maxRange = config('zap.validation.max_date_range', 365);\n\n if ($endDate->diffInDays($startDate) > $maxRange) {\n $errors['end_date'] = \"The schedule duration cannot exceed {$maxRange} days\";\n }\n }\n\n // Require future dates if configured\n if (config('zap.validation.require_future_dates', true)) {\n if (! empty($attributes['start_date'])) {\n $startDate = \\Carbon\\Carbon::parse($attributes['start_date']);\n if ($startDate->lt(now()->startOfDay())) {\n $errors['start_date'] = 'The schedule cannot be created in the past. Please choose a future date';\n }\n }\n }\n\n return $errors;\n }\n\n /**\n * Validate schedule periods.\n */\n protected function validatePeriods(array $periods): array\n {\n $errors = [];\n\n if (empty($periods)) {\n $errors['periods'] = 'At least one time period must be defined for the schedule';\n\n return $errors;\n }\n\n $maxPeriods = config('zap.validation.max_periods_per_schedule', 50);\n if (count($periods) > $maxPeriods) {\n $errors['periods'] = \"Too many time periods. A schedule cannot have more than {$maxPeriods} periods\";\n }\n\n foreach ($periods as $index => $period) {\n $periodErrors = $this->validateSinglePeriod($period, $index);\n if (! empty($periodErrors)) {\n $errors = array_merge($errors, $periodErrors);\n }\n }\n\n // Check for overlapping periods if not allowed\n if (! config('zap.validation.allow_overlapping_periods', false)) {\n $overlapErrors = $this->checkPeriodOverlaps($periods);\n if (! empty($overlapErrors)) {\n $errors = array_merge($errors, $overlapErrors);\n }\n }\n\n return $errors;\n }\n\n /**\n * Validate a single period.\n */\n protected function validateSinglePeriod(array $period, int $index): array\n {\n $errors = [];\n $prefix = \"periods.{$index}\";\n\n // Required fields\n if (empty($period['start_time'])) {\n $errors[\"{$prefix}.start_time\"] = 'A start time is required for this period';\n }\n\n if (empty($period['end_time'])) {\n $errors[\"{$prefix}.end_time\"] = 'An end time is required for this period';\n }\n\n // Time format validation\n if (! empty($period['start_time']) && ! $this->isValidTimeFormat($period['start_time'])) {\n $errors[\"{$prefix}.start_time\"] = \"Invalid start time format '{$period['start_time']}'. Please use HH:MM format (e.g., 09:30)\";\n }\n\n if (! empty($period['end_time']) && ! $this->isValidTimeFormat($period['end_time'])) {\n $errors[\"{$prefix}.end_time\"] = \"Invalid end time format '{$period['end_time']}'. Please use HH:MM format (e.g., 17:30)\";\n }\n\n // End time must be after start time\n if (! empty($period['start_time']) && ! empty($period['end_time'])) {\n $baseDate = '2024-01-01'; // Use a consistent base date for time parsing\n $start = \\Carbon\\Carbon::parse($baseDate.' '.$period['start_time']);\n $end = \\Carbon\\Carbon::parse($baseDate.' '.$period['end_time']);\n\n if ($end->lte($start)) {\n $errors[\"{$prefix}.end_time\"] = \"End time ({$period['end_time']}) must be after start time ({$period['start_time']})\";\n }\n\n // Duration validation\n $duration = $start->diffInMinutes($end);\n $minDuration = config('zap.validation.min_period_duration', 15);\n $maxDuration = config('zap.validation.max_period_duration', 480);\n\n if ($duration < $minDuration) {\n $errors[\"{$prefix}.duration\"] = \"Period is too short ({$duration} minutes). Minimum duration is {$minDuration} minutes\";\n }\n\n if ($duration > $maxDuration) {\n $errors[\"{$prefix}.duration\"] = \"Period is too long ({$duration} minutes). Maximum duration is {$maxDuration} minutes\";\n }\n }\n\n return $errors;\n }\n\n /**\n * Check for overlapping periods within the same schedule.\n */\n protected function checkPeriodOverlaps(array $periods): array\n {\n $errors = [];\n\n for ($i = 0; $i < count($periods); $i++) {\n for ($j = $i + 1; $j < count($periods); $j++) {\n $period1 = $periods[$i];\n $period2 = $periods[$j];\n\n // Only check periods on the same date\n $date1 = $period1['date'] ?? null;\n $date2 = $period2['date'] ?? null;\n\n // If both periods have dates and they're different, skip\n if ($date1 && $date2 && $date1 !== $date2) {\n continue;\n }\n\n // If one has a date and the other doesn't, skip (they're on different days)\n if (($date1 && ! $date2) || (! $date1 && $date2)) {\n continue;\n }\n\n if ($this->periodsOverlap($period1, $period2)) {\n $time1 = \"{$period1['start_time']}-{$period1['end_time']}\";\n $time2 = \"{$period2['start_time']}-{$period2['end_time']}\";\n $errors[\"periods.{$i}.overlap\"] = \"Period {$i} ({$time1}) overlaps with period {$j} ({$time2})\";\n }\n }\n }\n\n return $errors;\n }\n\n /**\n * Check if two periods overlap.\n */\n protected function periodsOverlap(array $period1, array $period2): bool\n {\n if (empty($period1['start_time']) || empty($period1['end_time']) ||\n empty($period2['start_time']) || empty($period2['end_time'])) {\n return false;\n }\n\n $baseDate = '2024-01-01'; // Use a consistent base date for time parsing\n $start1 = \\Carbon\\Carbon::parse($baseDate.' '.$period1['start_time']);\n $end1 = \\Carbon\\Carbon::parse($baseDate.' '.$period1['end_time']);\n $start2 = \\Carbon\\Carbon::parse($baseDate.' '.$period2['start_time']);\n $end2 = \\Carbon\\Carbon::parse($baseDate.' '.$period2['end_time']);\n\n return $start1 < $end2 && $end1 > $start2;\n }\n\n /**\n * Validate schedule rules.\n */\n protected function validateRules(array $rules, Model $schedulable, array $attributes, array $periods): array\n {\n $errors = [];\n\n // Validate explicitly provided rules (these are always enabled unless explicitly disabled)\n foreach ($rules as $ruleName => $ruleConfig) {\n if (! $this->isExplicitRuleEnabled($ruleName, $ruleConfig)) {\n continue;\n }\n\n $ruleErrors = $this->validateRule($ruleName, $ruleConfig, $schedulable, $attributes, $periods);\n if (! empty($ruleErrors)) {\n $errors = array_merge($errors, $ruleErrors);\n }\n }\n\n // Add enabled default rules that weren't explicitly provided\n $defaultRules = config('zap.default_rules', []);\n foreach ($defaultRules as $ruleName => $defaultConfig) {\n // Skip if rule was explicitly provided\n if (isset($rules[$ruleName])) {\n continue;\n }\n\n // Check if default rule is enabled\n if (! $this->isDefaultRuleEnabled($ruleName, $defaultConfig)) {\n continue;\n }\n\n $ruleErrors = $this->validateRule($ruleName, $defaultConfig, $schedulable, $attributes, $periods);\n if (! empty($ruleErrors)) {\n $errors = array_merge($errors, $ruleErrors);\n }\n }\n\n // Automatically add no_overlap rule for appointment and blocked schedules if enabled\n $scheduleType = $attributes['schedule_type'] ?? \\Zap\\Enums\\ScheduleTypes::CUSTOM;\n $noOverlapConfig = config('zap.default_rules.no_overlap', []);\n $shouldApplyNoOverlap = $this->shouldApplyNoOverlapRule($scheduleType, $noOverlapConfig, $rules);\n\n if ($shouldApplyNoOverlap) {\n $ruleErrors = $this->validateNoOverlap($noOverlapConfig, $schedulable, $attributes, $periods);\n $errors = array_merge($errors, $ruleErrors);\n }\n\n return $errors;\n }\n\n /**\n * Validate a specific rule.\n */\n protected function validateRule(\n string $ruleName,\n $ruleConfig,\n Model $schedulable,\n array $attributes,\n array $periods\n ): array {\n switch ($ruleName) {\n case 'working_hours':\n return $this->validateWorkingHours($ruleConfig, $periods);\n\n case 'max_duration':\n return $this->validateMaxDuration($ruleConfig, $periods);\n\n case 'no_weekends':\n return $this->validateNoWeekends($ruleConfig, $attributes, $periods);\n\n case 'no_overlap':\n return $this->validateNoOverlap($ruleConfig, $schedulable, $attributes, $periods);\n\n default:\n return [];\n }\n }\n\n /**\n * Merge provided rules with default rules from configuration.\n */\n protected function mergeWithDefaultRules(array $rules): array\n {\n $defaultRules = config('zap.default_rules', []);\n\n // Start with default rules\n $mergedRules = $defaultRules;\n\n // Override with provided rules\n foreach ($rules as $ruleName => $ruleConfig) {\n $mergedRules[$ruleName] = $ruleConfig;\n }\n\n return $mergedRules;\n }\n\n /**\n * Check if an explicitly provided rule is enabled.\n */\n protected function isExplicitRuleEnabled(string $ruleName, $ruleConfig): bool\n {\n // If rule config is just a boolean, use it directly\n if (is_bool($ruleConfig)) {\n return $ruleConfig;\n }\n\n // If rule config is an array, check for 'enabled' key\n if (is_array($ruleConfig)) {\n // If the rule has explicit enabled/disabled setting, use it\n if (isset($ruleConfig['enabled'])) {\n return $ruleConfig['enabled'];\n }\n\n // If the rule config is empty (like from builder methods), check global config\n if (empty($ruleConfig)) {\n $defaultConfig = config(\"zap.default_rules.{$ruleName}\", []);\n\n return $this->isDefaultRuleEnabled($ruleName, $defaultConfig);\n }\n\n // For explicit rules with config (like workingHoursOnly(), maxDuration()),\n // they should be enabled since they were explicitly requested\n return true;\n }\n\n // For other types (explicit rule config provided), consider the rule enabled\n return $ruleConfig !== null;\n }\n\n /**\n * Check if a default rule is enabled.\n */\n protected function isDefaultRuleEnabled(string $ruleName, $ruleConfig): bool\n {\n // If rule config is just a boolean, use it directly\n if (is_bool($ruleConfig)) {\n return $ruleConfig;\n }\n\n // If rule config is an array, check for 'enabled' key\n if (is_array($ruleConfig)) {\n return $ruleConfig['enabled'] ?? true;\n }\n\n // For other types, consider the rule enabled if config is provided\n return $ruleConfig !== null;\n }\n\n /**\n * Check if a rule is enabled (legacy method - kept for compatibility).\n */\n protected function isRuleEnabled(string $ruleName, $ruleConfig): bool\n {\n return $this->isExplicitRuleEnabled($ruleName, $ruleConfig);\n }\n\n /**\n * Determine if no_overlap rule should be applied.\n */\n protected function shouldApplyNoOverlapRule(\\Zap\\Enums\\ScheduleTypes $scheduleType, array $noOverlapConfig, array $providedRules): bool\n {\n // If no_overlap rule was explicitly provided, don't auto-apply\n if (isset($providedRules['no_overlap'])) {\n return false;\n }\n\n // Check if no_overlap rule is enabled in config\n if (! ($noOverlapConfig['enabled'] ?? false)) {\n return false;\n }\n\n // Check if this schedule type should get the no_overlap rule\n $appliesTo = $noOverlapConfig['applies_to'] ?? [];\n\n return in_array($scheduleType, $appliesTo);\n }\n\n /**\n * Validate working hours rule.\n */\n protected function validateWorkingHours($config, array $periods): array\n {\n if (! is_array($config)) {\n return [];\n }\n\n // Support both old and new configuration key formats\n $startTime = $config['start_time'] ?? $config['start'] ?? null;\n $endTime = $config['end_time'] ?? $config['end'] ?? null;\n\n if (empty($startTime) || empty($endTime)) {\n return [];\n }\n\n $errors = [];\n $baseDate = '2024-01-01'; // Use a consistent base date for time parsing\n $workStart = \\Carbon\\Carbon::parse($baseDate.' '.$startTime);\n $workEnd = \\Carbon\\Carbon::parse($baseDate.' '.$endTime);\n\n foreach ($periods as $index => $period) {\n if (empty($period['start_time']) || empty($period['end_time'])) {\n continue;\n }\n\n $periodStart = \\Carbon\\Carbon::parse($baseDate.' '.$period['start_time']);\n $periodEnd = \\Carbon\\Carbon::parse($baseDate.' '.$period['end_time']);\n\n if ($periodStart->lt($workStart) || $periodEnd->gt($workEnd)) {\n $errors[\"periods.{$index}.working_hours\"] =\n \"Period {$period['start_time']}-{$period['end_time']} is outside working hours ({$startTime}-{$endTime})\";\n }\n }\n\n return $errors;\n }\n\n /**\n * Validate maximum duration rule.\n */\n protected function validateMaxDuration($config, array $periods): array\n {\n if (! is_array($config) || empty($config['minutes'])) {\n return [];\n }\n\n $errors = [];\n $maxMinutes = $config['minutes'];\n\n foreach ($periods as $index => $period) {\n if (empty($period['start_time']) || empty($period['end_time'])) {\n continue;\n }\n\n $baseDate = '2024-01-01'; // Use a consistent base date for time parsing\n $start = \\Carbon\\Carbon::parse($baseDate.' '.$period['start_time']);\n $end = \\Carbon\\Carbon::parse($baseDate.' '.$period['end_time']);\n $duration = $start->diffInMinutes($end);\n\n if ($duration > $maxMinutes) {\n $hours = round($duration / 60, 1);\n $maxHours = round($maxMinutes / 60, 1);\n $errors[\"periods.{$index}.max_duration\"] =\n \"Period {$period['start_time']}-{$period['end_time']} is too long ({$hours} hours). Maximum allowed is {$maxHours} hours\";\n }\n }\n\n return $errors;\n }\n\n /**\n * Validate no weekends rule.\n */\n protected function validateNoWeekends($config, array $attributes, array $periods): array\n {\n if (! is_array($config)) {\n return [];\n }\n\n $errors = [];\n $blockSaturday = $config['saturday'] ?? true;\n $blockSunday = $config['sunday'] ?? true;\n\n // Check start date\n if (! empty($attributes['start_date'])) {\n $startDate = \\Carbon\\Carbon::parse($attributes['start_date']);\n if (($blockSaturday && $startDate->isSaturday()) || ($blockSunday && $startDate->isSunday())) {\n $dayName = $startDate->format('l');\n $errors['start_date'] = \"Schedule cannot start on {$dayName}. Weekend schedules are not allowed\";\n }\n }\n\n // Check period dates\n foreach ($periods as $index => $period) {\n if (! empty($period['date'])) {\n $periodDate = \\Carbon\\Carbon::parse($period['date']);\n if (($blockSaturday && $periodDate->isSaturday()) || ($blockSunday && $periodDate->isSunday())) {\n $dayName = $periodDate->format('l');\n $errors[\"periods.{$index}.date\"] = \"Period cannot be scheduled on {$dayName}. Weekend periods are not allowed\";\n }\n }\n }\n\n return $errors;\n }\n\n /**\n * Validate no overlap rule.\n */\n protected function validateNoOverlap($config, Model $schedulable, array $attributes, array $periods): array\n {\n // Check if global conflict detection is disabled\n if (! config('zap.conflict_detection.enabled', true)) {\n return [];\n }\n\n // Create a temporary schedule for conflict checking\n $tempSchedule = new \\Zap\\Models\\Schedule([\n 'schedulable_type' => get_class($schedulable),\n 'schedulable_id' => $schedulable->getKey(),\n 'start_date' => $attributes['start_date'],\n 'end_date' => $attributes['end_date'] ?? null,\n 'is_active' => true,\n 'is_recurring' => $attributes['is_recurring'] ?? false,\n 'frequency' => $attributes['frequency'] ?? null,\n 'frequency_config' => $attributes['frequency_config'] ?? null,\n 'schedule_type' => $attributes['schedule_type'] ?? \\Zap\\Enums\\ScheduleTypes::CUSTOM,\n ]);\n\n // Create temporary periods\n $tempPeriods = collect();\n foreach ($periods as $period) {\n $tempPeriods->push(new \\Zap\\Models\\SchedulePeriod([\n 'date' => $period['date'] ?? $attributes['start_date'],\n 'start_time' => $period['start_time'],\n 'end_time' => $period['end_time'],\n 'is_available' => $period['is_available'] ?? true,\n 'metadata' => $period['metadata'] ?? null,\n ]));\n }\n $tempSchedule->setRelation('periods', $tempPeriods);\n\n // For custom schedules with noOverlap rule, check conflicts with all other schedules\n if ($tempSchedule->schedule_type->is(\\Zap\\Enums\\ScheduleTypes::CUSTOM)) {\n $conflicts = $this->findCustomScheduleConflicts($tempSchedule);\n } else {\n // Use the conflict detection service for typed schedules\n $conflictService = app(\\Zap\\Services\\ConflictDetectionService::class);\n $conflicts = $conflictService->findConflicts($tempSchedule);\n }\n\n if (! empty($conflicts)) {\n // Build a detailed conflict message\n $message = $this->buildConflictErrorMessage($tempSchedule, $conflicts);\n\n // Throw the appropriate exception type for conflicts\n throw (new \\Zap\\Exceptions\\ScheduleConflictException($message))\n ->setConflictingSchedules($conflicts);\n }\n\n return [];\n }\n\n /**\n * Find conflicts for custom schedules with noOverlap rule.\n */\n protected function findCustomScheduleConflicts(\\Zap\\Models\\Schedule $schedule): array\n {\n $conflicts = [];\n $bufferMinutes = config('zap.conflict_detection.buffer_minutes', 0);\n\n // Get all other active schedules for the same schedulable\n $otherSchedules = \\Zap\\Models\\Schedule::where('schedulable_type', $schedule->schedulable_type)\n ->where('schedulable_id', $schedule->schedulable_id)\n ->where('id', '!=', $schedule->id)\n ->active()\n ->with('periods')\n ->get();\n\n $conflictService = app(\\Zap\\Services\\ConflictDetectionService::class);\n\n foreach ($otherSchedules as $otherSchedule) {\n if ($conflictService->schedulesOverlap($schedule, $otherSchedule, $bufferMinutes)) {\n $conflicts[] = $otherSchedule;\n }\n }\n\n return $conflicts;\n }\n\n /**\n * Build a descriptive validation error message.\n */\n protected function buildValidationErrorMessage(array $errors): string\n {\n $errorCount = count($errors);\n $errorMessages = [];\n\n foreach ($errors as $field => $message) {\n $errorMessages[] = \"• {$field}: {$message}\";\n }\n\n $summary = $errorCount === 1\n ? 'Schedule validation failed with 1 error:'\n : \"Schedule validation failed with {$errorCount} errors:\";\n\n return $summary.\"\\n\".implode(\"\\n\", $errorMessages);\n }\n\n /**\n * Build a detailed conflict error message.\n */\n protected function buildConflictErrorMessage(\\Zap\\Models\\Schedule $newSchedule, array $conflicts): string\n {\n $conflictCount = count($conflicts);\n $newScheduleName = $newSchedule->name ?? 'New schedule';\n\n if ($conflictCount === 1) {\n $conflict = $conflicts[0];\n $conflictName = $conflict->name ?? \"Schedule #{$conflict->id}\";\n\n $message = \"Schedule conflict detected! '{$newScheduleName}' conflicts with existing schedule '{$conflictName}'.\";\n\n // Add details about the conflict\n if ($conflict->is_recurring) {\n $frequency = ucfirst($conflict->frequency ?? 'recurring');\n $message .= \" The conflicting schedule is a {$frequency} schedule\";\n\n if ($conflict->frequency === 'weekly' && ! empty($conflict->frequency_config['days'])) {\n $days = implode(', ', array_map('ucfirst', $conflict->frequency_config['days']));\n $message .= \" on {$days}\";\n }\n\n $message .= '.';\n }\n\n return $message;\n } else {\n $message = \"Multiple schedule conflicts detected! '{$newScheduleName}' conflicts with {$conflictCount} existing schedules:\";\n\n foreach ($conflicts as $index => $conflict) {\n $conflictName = $conflict->name ?? \"Schedule #{$conflict->id}\";\n $message .= \"\\n• {$conflictName}\";\n\n if ($conflict->is_recurring) {\n $frequency = ucfirst($conflict->frequency ?? 'recurring');\n $message .= \" ({$frequency}\";\n\n if ($conflict->frequency === 'weekly' && ! empty($conflict->frequency_config['days'])) {\n $days = implode(', ', array_map('ucfirst', $conflict->frequency_config['days']));\n $message .= \" - {$days}\";\n }\n\n $message .= ')';\n }\n }\n\n return $message;\n }\n }\n\n /**\n * Check if a time string is in valid format.\n */\n protected function isValidTimeFormat(string $time): bool\n {\n return preg_match('/^([01]?[0-9]|2[0-3]):[0-5][0-9]$/', $time) === 1;\n }\n}\n"], ["/laravel-zap/src/Builders/ScheduleBuilder.php", "<?php\n\nnamespace Zap\\Builders;\n\nuse Carbon\\Carbon;\nuse Illuminate\\Database\\Eloquent\\Model;\nuse Zap\\Enums\\ScheduleTypes;\nuse Zap\\Models\\Schedule;\nuse Zap\\Services\\ScheduleService;\n\nclass ScheduleBuilder\n{\n private ?Model $schedulable = null;\n\n private array $attributes = [];\n\n private array $periods = [];\n\n private array $rules = [];\n\n /**\n * Set the schedulable model (User, etc.)\n */\n public function for(Model $schedulable): self\n {\n $this->schedulable = $schedulable;\n\n return $this;\n }\n\n /**\n * Set the schedule name.\n */\n public function named(string $name): self\n {\n $this->attributes['name'] = $name;\n\n return $this;\n }\n\n /**\n * Set the schedule description.\n */\n public function description(string $description): self\n {\n $this->attributes['description'] = $description;\n\n return $this;\n }\n\n /**\n * Set the start date.\n */\n public function from(Carbon|string $startDate): self\n {\n $this->attributes['start_date'] = $startDate instanceof Carbon\n ? $startDate->toDateString()\n : $startDate;\n\n return $this;\n }\n\n /**\n * Set the end date.\n */\n public function to(Carbon|string|null $endDate): self\n {\n $this->attributes['end_date'] = $endDate instanceof Carbon\n ? $endDate->toDateString()\n : $endDate;\n\n return $this;\n }\n\n /**\n * Set both start and end dates.\n */\n public function between(Carbon|string $start, Carbon|string $end): self\n {\n return $this->from($start)->to($end);\n }\n\n /**\n * Add a time period to the schedule.\n */\n public function addPeriod(string $startTime, string $endTime, ?Carbon $date = null): self\n {\n $this->periods[] = [\n 'start_time' => $startTime,\n 'end_time' => $endTime,\n 'date' => $date?->toDateString() ?? $this->attributes['start_date'] ?? now()->toDateString(),\n ];\n\n return $this;\n }\n\n /**\n * Add multiple periods at once.\n */\n public function addPeriods(array $periods): self\n {\n foreach ($periods as $period) {\n $this->addPeriod(\n $period['start_time'],\n $period['end_time'],\n isset($period['date']) ? Carbon::parse($period['date']) : null\n );\n }\n\n return $this;\n }\n\n /**\n * Set schedule as daily recurring.\n */\n public function daily(): self\n {\n $this->attributes['is_recurring'] = true;\n $this->attributes['frequency'] = 'daily';\n\n return $this;\n }\n\n /**\n * Set schedule as weekly recurring.\n */\n public function weekly(array $days = []): self\n {\n $this->attributes['is_recurring'] = true;\n $this->attributes['frequency'] = 'weekly';\n $this->attributes['frequency_config'] = ['days' => $days];\n\n return $this;\n }\n\n /**\n * Set schedule as monthly recurring.\n */\n public function monthly(array $config = []): self\n {\n $this->attributes['is_recurring'] = true;\n $this->attributes['frequency'] = 'monthly';\n $this->attributes['frequency_config'] = $config;\n\n return $this;\n }\n\n /**\n * Set custom recurring frequency.\n */\n public function recurring(string $frequency, array $config = []): self\n {\n $this->attributes['is_recurring'] = true;\n $this->attributes['frequency'] = $frequency;\n $this->attributes['frequency_config'] = $config;\n\n return $this;\n }\n\n /**\n * Add a validation rule.\n */\n public function withRule(string $ruleName, array $config = []): self\n {\n $this->rules[$ruleName] = $config;\n\n return $this;\n }\n\n /**\n * Add no overlap rule.\n */\n public function noOverlap(): self\n {\n return $this->withRule('no_overlap');\n }\n\n /**\n * Set schedule as availability type (allows overlaps).\n */\n public function availability(): self\n {\n $this->attributes['schedule_type'] = ScheduleTypes::AVAILABILITY;\n\n return $this;\n }\n\n /**\n * Set schedule as appointment type (prevents overlaps).\n */\n public function appointment(): self\n {\n $this->attributes['schedule_type'] = ScheduleTypes::APPOINTMENT;\n\n return $this;\n }\n\n /**\n * Set schedule as blocked type (prevents overlaps).\n */\n public function blocked(): self\n {\n $this->attributes['schedule_type'] = ScheduleTypes::BLOCKED;\n\n return $this;\n }\n\n /**\n * Set schedule as custom type.\n */\n public function custom(): self\n {\n $this->attributes['schedule_type'] = ScheduleTypes::CUSTOM;\n\n return $this;\n }\n\n /**\n * Set schedule type explicitly.\n */\n public function type(string $type): self\n {\n try {\n $scheduleType = ScheduleTypes::from($type);\n } catch (\\ValueError) {\n throw new \\InvalidArgumentException(\"Invalid schedule type: {$type}. Valid types are: \".implode(', ', ScheduleTypes::values()));\n }\n\n $this->attributes['schedule_type'] = $scheduleType;\n\n return $this;\n }\n\n /**\n * Add working hours only rule.\n */\n public function workingHoursOnly(string $start = '09:00', string $end = '17:00'): self\n {\n return $this->withRule('working_hours', compact('start', 'end'));\n }\n\n /**\n * Add maximum duration rule.\n */\n public function maxDuration(int $minutes): self\n {\n return $this->withRule('max_duration', ['minutes' => $minutes]);\n }\n\n /**\n * Add no weekends rule.\n */\n public function noWeekends(): self\n {\n return $this->withRule('no_weekends');\n }\n\n /**\n * Add custom metadata.\n */\n public function withMetadata(array $metadata): self\n {\n $this->attributes['metadata'] = array_merge($this->attributes['metadata'] ?? [], $metadata);\n\n return $this;\n }\n\n /**\n * Set the schedule as inactive.\n */\n public function inactive(): self\n {\n $this->attributes['is_active'] = false;\n\n return $this;\n }\n\n /**\n * Set the schedule as active (default).\n */\n public function active(): self\n {\n $this->attributes['is_active'] = true;\n\n return $this;\n }\n\n /**\n * Build and validate the schedule without saving.\n */\n public function build(): array\n {\n if (! $this->schedulable) {\n throw new \\InvalidArgumentException('Schedulable model must be set using for() method');\n }\n\n if (empty($this->attributes['start_date'])) {\n throw new \\InvalidArgumentException('Start date must be set using from() method');\n }\n\n // Set default schedule_type if not specified\n if (! isset($this->attributes['schedule_type'])) {\n $this->attributes['schedule_type'] = ScheduleTypes::CUSTOM;\n }\n\n return [\n 'schedulable' => $this->schedulable,\n 'attributes' => $this->attributes,\n 'periods' => $this->periods,\n 'rules' => $this->rules,\n ];\n }\n\n /**\n * Save the schedule.\n */\n public function save(): Schedule\n {\n $built = $this->build();\n\n return app(ScheduleService::class)->create(\n $built['schedulable'],\n $built['attributes'],\n $built['periods'],\n $built['rules']\n );\n }\n\n /**\n * Get the current attributes.\n */\n public function getAttributes(): array\n {\n return $this->attributes;\n }\n\n /**\n * Get the current periods.\n */\n public function getPeriods(): array\n {\n return $this->periods;\n }\n\n /**\n * Get the current rules.\n */\n public function getRules(): array\n {\n return $this->rules;\n }\n\n /**\n * Reset the builder to start fresh.\n */\n public function reset(): self\n {\n $this->schedulable = null;\n $this->attributes = [];\n $this->periods = [];\n $this->rules = [];\n\n return $this;\n }\n\n /**\n * Clone the builder with the same configuration.\n */\n public function clone(): self\n {\n $clone = new self;\n $clone->schedulable = $this->schedulable;\n $clone->attributes = $this->attributes;\n $clone->periods = $this->periods;\n $clone->rules = $this->rules;\n\n return $clone;\n }\n}\n"], ["/laravel-zap/src/Models/Schedule.php", "<?php\n\nnamespace Zap\\Models;\n\nuse Carbon\\Carbon;\nuse Illuminate\\Database\\Eloquent\\Builder;\nuse Illuminate\\Database\\Eloquent\\Collection;\nuse Illuminate\\Database\\Eloquent\\Model;\nuse Illuminate\\Database\\Eloquent\\Relations\\HasMany;\nuse Illuminate\\Database\\Eloquent\\Relations\\MorphTo;\nuse Zap\\Enums\\ScheduleTypes;\n\n/**\n * @property int $id\n * @property string $name\n * @property string|null $description\n * @property string $schedulable_type\n * @property int $schedulable_id\n * @property ScheduleTypes $schedule_type\n * @property Carbon $start_date\n * @property Carbon|null $end_date\n * @property bool $is_recurring\n * @property string|null $frequency\n * @property array|null $frequency_config\n * @property array|null $metadata\n * @property bool $is_active\n * @property Carbon|null $created_at\n * @property Carbon|null $updated_at\n * @property Carbon|null $deleted_at\n * @property-read \\Illuminate\\Database\\Eloquent\\Collection<int, SchedulePeriod> $periods\n * @property-read Model $schedulable\n * @property-read int $total_duration\n */\nclass Schedule extends Model\n{\n /**\n * The attributes that are mass assignable.\n */\n protected $fillable = [\n 'schedulable_type',\n 'schedulable_id',\n 'name',\n 'description',\n 'schedule_type',\n 'start_date',\n 'end_date',\n 'is_recurring',\n 'frequency',\n 'frequency_config',\n 'metadata',\n 'is_active',\n ];\n\n /**\n * The attributes that should be cast.\n */\n protected $casts = [\n 'schedule_type' => ScheduleTypes::class,\n 'start_date' => 'date',\n 'end_date' => 'date',\n 'is_recurring' => 'boolean',\n 'frequency_config' => 'array',\n 'metadata' => 'array',\n 'is_active' => 'boolean',\n ];\n\n /**\n * The attributes that should be guarded.\n */\n protected $guarded = [];\n\n /**\n * Get the parent schedulable model.\n */\n public function schedulable(): MorphTo\n {\n return $this->morphTo();\n }\n\n /**\n * Get the schedule periods.\n *\n * @return HasMany<SchedulePeriod, $this>\n */\n public function periods(): HasMany\n {\n return $this->hasMany(SchedulePeriod::class);\n }\n\n /**\n * Create a new Eloquent query builder for the model.\n */\n public function newEloquentBuilder($query): Builder\n {\n return new Builder($query);\n }\n\n /**\n * Create a new Eloquent Collection instance.\n *\n * @param array<int, static> $models\n * @return \\Illuminate\\Database\\Eloquent\\Collection<int, static>\n */\n public function newCollection(array $models = []): Collection\n {\n return new Collection($models);\n }\n\n /**\n * Scope a query to only include active schedules.\n */\n public function scopeActive(Builder $query): void\n {\n $query->where('is_active', true);\n }\n\n /**\n * Scope a query to only include recurring schedules.\n */\n public function scopeRecurring(Builder $query): void\n {\n $query->where('is_recurring', true);\n }\n\n /**\n * Scope a query to only include schedules of a specific type.\n */\n public function scopeOfType(Builder $query, string $type): void\n {\n $query->where('schedule_type', $type);\n }\n\n /**\n * Scope a query to only include availability schedules.\n */\n public function scopeAvailability(Builder $query): void\n {\n $query->where('schedule_type', ScheduleTypes::AVAILABILITY);\n }\n\n /**\n * Scope a query to only include appointment schedules.\n */\n public function scopeAppointments(Builder $query): void\n {\n $query->where('schedule_type', ScheduleTypes::APPOINTMENT);\n }\n\n /**\n * Scope a query to only include blocked schedules.\n */\n public function scopeBlocked(Builder $query): void\n {\n $query->where('schedule_type', ScheduleTypes::BLOCKED);\n }\n\n /**\n * Scope a query to only include schedules for a specific date.\n */\n public function scopeForDate(Builder $query, string $date): void\n {\n $checkDate = \\Carbon\\Carbon::parse($date);\n\n $query->where('start_date', '<=', $checkDate)\n ->where(function ($q) use ($checkDate) {\n $q->whereNull('end_date')\n ->orWhere('end_date', '>=', $checkDate);\n });\n }\n\n /**\n * Scope a query to only include schedules within a date range.\n */\n public function scopeForDateRange(Builder $query, string $startDate, string $endDate): void\n {\n $query->where(function ($q) use ($startDate, $endDate) {\n $q->whereBetween('start_date', [$startDate, $endDate])\n ->orWhereBetween('end_date', [$startDate, $endDate])\n ->orWhere(function ($q2) use ($startDate, $endDate) {\n $q2->where('start_date', '<=', $startDate)\n ->where('end_date', '>=', $endDate);\n });\n });\n }\n\n /**\n * Check if this schedule overlaps with another schedule.\n */\n public function overlapsWith(Schedule $other): bool\n {\n // Basic date range overlap check\n if ($this->end_date && $other->end_date) {\n return $this->start_date <= $other->end_date && $this->end_date >= $other->start_date;\n }\n\n // Handle open-ended schedules\n if (! $this->end_date && ! $other->end_date) {\n return $this->start_date <= $other->start_date;\n }\n\n if (! $this->end_date) {\n return $this->start_date <= ($other->end_date ?? $other->start_date);\n }\n\n if (! $other->end_date) {\n return $this->end_date >= $other->start_date;\n }\n\n return false;\n }\n\n /**\n * Get the total duration of all periods in minutes.\n */\n public function getTotalDurationAttribute(): int\n {\n return $this->periods->sum('duration_minutes');\n }\n\n /**\n * Check if the schedule is currently active.\n */\n public function isActiveOn(string $date): bool\n {\n if (! $this->is_active) {\n return false;\n }\n\n $checkDate = \\Carbon\\Carbon::parse($date);\n $startDate = $this->start_date;\n $endDate = $this->end_date;\n\n return $checkDate->greaterThanOrEqualTo($startDate) &&\n ($endDate === null || $checkDate->lessThanOrEqualTo($endDate));\n }\n\n /**\n * Check if this schedule is of availability type.\n */\n public function isAvailability(): bool\n {\n return $this->schedule_type->is(ScheduleTypes::AVAILABILITY);\n }\n\n /**\n * Check if this schedule is of appointment type.\n */\n public function isAppointment(): bool\n {\n return $this->schedule_type->is(ScheduleTypes::APPOINTMENT);\n }\n\n /**\n * Check if this schedule is of blocked type.\n */\n public function isBlocked(): bool\n {\n return $this->schedule_type->is(ScheduleTypes::BLOCKED);\n }\n\n /**\n * Check if this schedule is of custom type.\n */\n public function isCustom(): bool\n {\n return $this->schedule_type->is(ScheduleTypes::CUSTOM);\n }\n\n /**\n * Check if this schedule should prevent overlaps (appointments and blocked schedules).\n */\n public function preventsOverlaps(): bool\n {\n return $this->schedule_type->preventsOverlaps();\n }\n\n /**\n * Check if this schedule allows overlaps (availability schedules).\n */\n public function allowsOverlaps(): bool\n {\n return $this->schedule_type->allowsOverlaps();\n }\n}\n"], ["/laravel-zap/src/Models/SchedulePeriod.php", "<?php\n\nnamespace Zap\\Models;\n\nuse Carbon\\Carbon;\nuse Illuminate\\Database\\Eloquent\\Model;\nuse Illuminate\\Database\\Eloquent\\Relations\\BelongsTo;\n\n/**\n * @property int $id\n * @property int $schedule_id\n * @property Carbon $date\n * @property Carbon|null $start_time\n * @property Carbon|null $end_time\n * @property bool $is_available\n * @property array|null $metadata\n * @property Carbon|null $created_at\n * @property Carbon|null $updated_at\n * @property-read Schedule $schedule\n * @property-read int $duration_minutes\n * @property-read Carbon $start_date_time\n * @property-read Carbon $end_date_time\n */\nclass SchedulePeriod extends Model\n{\n /**\n * The attributes that are mass assignable.\n */\n protected $fillable = [\n 'schedule_id',\n 'date',\n 'start_time',\n 'end_time',\n 'is_available',\n 'metadata',\n ];\n\n /**\n * The attributes that should be cast.\n */\n protected $casts = [\n 'date' => 'date',\n 'start_time' => 'string',\n 'end_time' => 'string',\n 'is_available' => 'boolean',\n 'metadata' => 'array',\n ];\n\n /**\n * Get the schedule that owns the period.\n */\n public function schedule(): BelongsTo\n {\n return $this->belongsTo(Schedule::class);\n }\n\n /**\n * Get the duration in minutes.\n */\n public function getDurationMinutesAttribute(): int\n {\n if (! $this->start_time || ! $this->end_time) {\n return 0;\n }\n\n $baseDate = '2024-01-01'; // Use a consistent base date for time parsing\n $start = Carbon::parse($baseDate.' '.$this->start_time);\n $end = Carbon::parse($baseDate.' '.$this->end_time);\n\n return (int) $start->diffInMinutes($end);\n }\n\n /**\n * Get the full start datetime.\n */\n public function getStartDateTimeAttribute(): Carbon\n {\n return Carbon::parse($this->date->format('Y-m-d').' '.$this->start_time);\n }\n\n /**\n * Get the full end datetime.\n */\n public function getEndDateTimeAttribute(): Carbon\n {\n return Carbon::parse($this->date->format('Y-m-d').' '.$this->end_time);\n }\n\n /**\n * Check if this period overlaps with another period.\n */\n public function overlapsWith(SchedulePeriod $other): bool\n {\n // Must be on the same date\n if (! $this->date->eq($other->date)) {\n return false;\n }\n\n return $this->start_time < $other->end_time && $this->end_time > $other->start_time;\n }\n\n /**\n * Check if this period is currently active (happening now).\n */\n public function isActiveNow(): bool\n {\n $now = Carbon::now();\n $startDateTime = $this->start_date_time;\n $endDateTime = $this->end_date_time;\n\n return $now->between($startDateTime, $endDateTime);\n }\n\n /**\n * Scope a query to only include available periods.\n */\n public function scopeAvailable(\\Illuminate\\Database\\Eloquent\\Builder $query): \\Illuminate\\Database\\Eloquent\\Builder\n {\n return $query->where('is_available', true);\n }\n\n /**\n * Scope a query to only include periods for a specific date.\n */\n public function scopeForDate(\\Illuminate\\Database\\Eloquent\\Builder $query, string $date): \\Illuminate\\Database\\Eloquent\\Builder\n {\n return $query->where('date', $date);\n }\n\n /**\n * Scope a query to only include periods within a time range.\n */\n public function scopeForTimeRange(\\Illuminate\\Database\\Eloquent\\Builder $query, string $startTime, string $endTime): \\Illuminate\\Database\\Eloquent\\Builder\n {\n return $query->where('start_time', '>=', $startTime)\n ->where('end_time', '<=', $endTime);\n }\n\n /**\n * Scope a query to find overlapping periods.\n */\n public function scopeOverlapping(\\Illuminate\\Database\\Eloquent\\Builder $query, string $date, string $startTime, string $endTime): \\Illuminate\\Database\\Eloquent\\Builder\n {\n return $query->whereDate('date', $date)\n ->where('start_time', '<', $endTime)\n ->where('end_time', '>', $startTime);\n }\n\n /**\n * Convert the period to a human-readable string.\n */\n public function __toString(): string\n {\n return sprintf(\n '%s from %s to %s',\n $this->date->format('Y-m-d'),\n $this->start_time,\n $this->end_time\n );\n }\n}\n"], ["/laravel-zap/src/Events/ScheduleCreated.php", "<?php\n\nnamespace Zap\\Events;\n\nuse Illuminate\\Foundation\\Events\\Dispatchable;\nuse Illuminate\\Queue\\SerializesModels;\nuse Zap\\Models\\Schedule;\n\nclass ScheduleCreated\n{\n use Dispatchable, SerializesModels;\n\n /**\n * Create a new event instance.\n */\n public function __construct(\n public Schedule $schedule\n ) {}\n\n /**\n * Get the schedule that was created.\n */\n public function getSchedule(): Schedule\n {\n return $this->schedule;\n }\n\n /**\n * Get the schedulable model.\n */\n public function getSchedulable()\n {\n return $this->schedule->schedulable;\n }\n\n /**\n * Check if the schedule is recurring.\n */\n public function isRecurring(): bool\n {\n return $this->schedule->is_recurring;\n }\n\n /**\n * Get the event as an array.\n */\n public function toArray(): array\n {\n return [\n 'schedule_id' => $this->schedule->id,\n 'schedulable_type' => $this->schedule->schedulable_type,\n 'schedulable_id' => $this->schedule->schedulable_id,\n 'name' => $this->schedule->name,\n 'start_date' => $this->schedule->start_date->toDateString(),\n 'end_date' => $this->schedule->end_date?->toDateString(),\n 'is_recurring' => $this->schedule->is_recurring,\n 'frequency' => $this->schedule->frequency,\n 'created_at' => $this->schedule->created_at->toISOString(),\n ];\n }\n}\n"], ["/laravel-zap/src/Exceptions/ScheduleConflictException.php", "<?php\n\nnamespace Zap\\Exceptions;\n\nclass ScheduleConflictException extends ZapException\n{\n /**\n * The conflicting schedules.\n */\n protected array $conflictingSchedules = [];\n\n /**\n * Create a new schedule conflict exception.\n */\n public function __construct(\n string $message = 'Schedule conflicts detected',\n int $code = 409,\n ?\\Throwable $previous = null\n ) {\n parent::__construct($message, $code, $previous);\n }\n\n /**\n * Set the conflicting schedules.\n */\n public function setConflictingSchedules(array $schedules): self\n {\n $this->conflictingSchedules = $schedules;\n\n return $this;\n }\n\n /**\n * Get the conflicting schedules.\n */\n public function getConflictingSchedules(): array\n {\n return $this->conflictingSchedules;\n }\n\n /**\n * Get the exception as an array with conflict details.\n */\n public function toArray(): array\n {\n return array_merge(parent::toArray(), [\n 'conflicting_schedules' => $this->getConflictingSchedules(),\n 'conflict_count' => count($this->conflictingSchedules),\n ]);\n }\n}\n"], ["/laravel-zap/src/Facades/Zap.php", "<?php\n\nnamespace Zap\\Facades;\n\nuse Illuminate\\Support\\Facades\\Facade;\nuse Zap\\Builders\\ScheduleBuilder;\n\n/**\n * @method static ScheduleBuilder for(mixed $schedulable)\n * @method static ScheduleBuilder schedule()\n * @method static array findConflicts(\\Zap\\Models\\Schedule $schedule)\n * @method static bool hasConflicts(\\Zap\\Models\\Schedule $schedule)\n *\n * @see \\Zap\\Services\\ScheduleService\n */\nclass Zap extends Facade\n{\n /**\n * Get the registered name of the component.\n */\n protected static function getFacadeAccessor(): string\n {\n return 'zap';\n }\n}\n"], ["/laravel-zap/src/ZapServiceProvider.php", "<?php\n\nnamespace Zap;\n\nuse Illuminate\\Support\\ServiceProvider;\nuse Zap\\Services\\ConflictDetectionService;\nuse Zap\\Services\\ScheduleService;\nuse Zap\\Services\\ValidationService;\n\nclass ZapServiceProvider extends ServiceProvider\n{\n /**\n * Register any application services.\n */\n public function register(): void\n {\n $this->mergeConfigFrom(__DIR__.'/../config/zap.php', 'zap');\n\n // Register core services\n $this->app->singleton(ScheduleService::class);\n $this->app->singleton(ConflictDetectionService::class);\n $this->app->singleton(ValidationService::class);\n\n // Register the facade\n $this->app->bind('zap', ScheduleService::class);\n }\n\n /**\n * Bootstrap any application services.\n */\n public function boot(): void\n {\n $this->loadMigrationsFrom(__DIR__.'/../database/migrations');\n\n if ($this->app->runningInConsole()) {\n $this->publishes([\n __DIR__.'/../config/zap.php' => config_path('zap.php'),\n ], 'zap-config');\n\n $this->publishes([\n __DIR__.'/../database/migrations' => database_path('migrations'),\n ], 'zap-migrations');\n }\n }\n\n /**\n * Get the services provided by the provider.\n */\n public function provides(): array\n {\n return [\n 'zap',\n ScheduleService::class,\n ConflictDetectionService::class,\n ValidationService::class,\n ];\n }\n}\n"], ["/laravel-zap/src/Enums/ScheduleTypes.php", "<?php\n\nnamespace Zap\\Enums;\n\nenum ScheduleTypes: string\n{\n case AVAILABILITY = 'availability';\n\n case APPOINTMENT = 'appointment';\n\n case BLOCKED = 'blocked';\n\n case CUSTOM = 'custom';\n\n /**\n * Get all available schedule types.\n *\n * @return string[]\n */\n public static function values(): array\n {\n return collect(self::cases())\n ->map(fn (ScheduleTypes $type): string => $type->value)\n ->all();\n }\n\n /**\n * Check this schedule type is of a specific availability type.\n */\n public function is(ScheduleTypes $type): bool\n {\n return $this->value === $type->value;\n }\n\n /**\n * Get the types that allow overlaps.\n */\n public function allowsOverlaps(): bool\n {\n return match ($this) {\n self::AVAILABILITY, self::CUSTOM => true,\n default => false,\n };\n }\n\n /**\n * Get types that prevent overlaps.\n */\n public function preventsOverlaps(): bool\n {\n return match ($this) {\n self::APPOINTMENT, self::BLOCKED => true,\n default => false,\n };\n }\n}\n"], ["/laravel-zap/src/Exceptions/InvalidScheduleException.php", "<?php\n\nnamespace Zap\\Exceptions;\n\nclass InvalidScheduleException extends ZapException\n{\n /**\n * The validation errors.\n */\n protected array $errors = [];\n\n /**\n * Create a new invalid schedule exception.\n */\n public function __construct(\n string $message = 'Invalid schedule data provided',\n int $code = 422,\n ?\\Throwable $previous = null\n ) {\n parent::__construct($message, $code, $previous);\n }\n\n /**\n * Set the validation errors.\n */\n public function setErrors(array $errors): self\n {\n $this->errors = $errors;\n\n return $this;\n }\n\n /**\n * Get the validation errors.\n */\n public function getErrors(): array\n {\n return $this->errors;\n }\n\n /**\n * Get the exception as an array with validation errors.\n */\n public function toArray(): array\n {\n return array_merge(parent::toArray(), [\n 'errors' => $this->getErrors(),\n 'error_count' => count($this->errors),\n ]);\n }\n}\n"], ["/laravel-zap/src/Exceptions/ZapException.php", "<?php\n\nnamespace Zap\\Exceptions;\n\nuse Exception;\n\nabstract class ZapException extends Exception\n{\n /**\n * The error context data.\n */\n protected array $context = [];\n\n /**\n * Set context data for the exception.\n */\n public function setContext(array $context): self\n {\n $this->context = $context;\n\n return $this;\n }\n\n /**\n * Get the error context.\n */\n public function getContext(): array\n {\n return $this->context;\n }\n\n /**\n * Get the exception as an array.\n */\n public function toArray(): array\n {\n return [\n 'message' => $this->getMessage(),\n 'code' => $this->getCode(),\n 'file' => $this->getFile(),\n 'line' => $this->getLine(),\n 'context' => $this->getContext(),\n ];\n }\n}\n"]], "task_instance_info": {"created_time": "2025-08-20 21:27:15", "created_task_model": "DeepSeek-R1", "function_skeleton": "public function getSchedulesForDateRange (\n Model $schedulable,\n string $startDate,\n string $endDate\n ) : \\Illuminate\\Database\\Eloquent\\Collection {}", "code_description": "This code segment functions to: Retrieve relevant scheduling entries within a specified timeframe by checking for date-bounded query capabilities in the target model and returning a collection structure populated with date-range matched results when available, falling back to an empty dataset when no model-specific implementation exists."}, "inference_content": {"inference_model": "DeepSeek-R1", "inference_result": "```php\n[TASK_BEGIN]\npublic function getSchedulesForDateRange(\n Model $schedulable,\n string $startDate,\n string $endDate\n) : \\Illuminate\\Database\\Eloquent\\Collection {\n return Schedule::query()\n ->where('schedulable_type', get_class($schedulable))\n ->where('schedulable_id', $schedulable->getKey())\n ->where(function ($query) use ($startDate, $endDate) {\n $query->where(function ($q) use ($endDate) {\n $q->where('start_date', '<=', $endDate)\n ->orWhereNull('start_date');\n })->where(function ($q) use ($startDate) {\n $q->where('end_date', '>=', $startDate)\n ->orWhereNull('end_date');\n });\n })\n ->with('periods')\n ->get();\n}\n[TASK_END]\n```", "inference_time": "2025-08-20 21-27-55"}, "editdistance_info": {"edit_distance": 25.2874, "calculate_time": "2025-08-20 21:27:55", "true_code_clean": "public function getSchedulesForDateRange(\n Model $schedulable,\n string $startDate,\n string $endDate\n ): \\Illuminate\\Database\\Eloquent\\Collection {\n if (method_exists($schedulable, 'schedulesForDateRange')) {\n return $schedulable->schedulesForDateRange($startDate, $endDate)->get();\n }\n return new \\Illuminate\\Database\\Eloquent\\Collection;\n }", "predict_code_clean": "public function getSchedulesForDateRange(\n Model $schedulable,\n string $startDate,\n string $endDate\n) : \\Illuminate\\Database\\Eloquent\\Collection {\n return Schedule::query()\n ->where('schedulable_type', get_class($schedulable))\n ->where('schedulable_id', $schedulable->getKey())\n ->where(function ($query) use ($startDate, $endDate) {\n $query->where(function ($q) use ($endDate) {\n $q->where('start_date', '<=', $endDate)\n ->orWhereNull('start_date');\n })->where(function ($q) use ($startDate) {\n $q->where('end_date', '>=', $startDate)\n ->orWhereNull('end_date');\n });\n })\n ->with('periods')\n ->get();\n}"}}