*/ use HasFactory; /** * Get the attributes that should be cast. * * @return array */ protected function casts(): array { return [ 'is_active' => 'boolean', 'is_public' => 'boolean', 'is_combinable' => 'boolean', 'discount_type' => DiscountType::class, 'stay_from' => 'immutable_date', 'stay_until' => 'immutable_date', 'bookable_from' => 'immutable_datetime', 'bookable_until' => 'immutable_datetime', 'arrival_weekdays' => 'array', 'season_names' => 'array', ]; } /** * @return BelongsTo */ public function property(): BelongsTo { return $this->belongsTo(Property::class); } /** * @param Builder $query * @return Builder */ #[Scope] protected function active(Builder $query): Builder { return $query->where('is_active', true); } /** * Whether all conditions are met. Offers with a code only apply when the guest entered that code. */ public function appliesTo(StayRequest $stay, string $arrivalSeasonName, CarbonImmutable $bookedAt): bool { $nights = $stay->nights(); $daysBeforeArrival = (int) $bookedAt->startOfDay()->diffInDays($stay->arrival, false); return $this->is_active && ($this->code === null || strcasecmp($this->code, (string) $stay->promoCode) === 0) && ($this->stay_from === null || $stay->arrival->greaterThanOrEqualTo($this->stay_from)) && ($this->stay_until === null || $stay->departure->lessThanOrEqualTo($this->stay_until)) && ($this->bookable_from === null || $bookedAt->greaterThanOrEqualTo($this->bookable_from)) && ($this->bookable_until === null || $bookedAt->lessThanOrEqualTo($this->bookable_until)) && ($this->min_days_before_arrival === null || $daysBeforeArrival >= $this->min_days_before_arrival) && ($this->max_days_before_arrival === null || $daysBeforeArrival <= $this->max_days_before_arrival) && ($this->min_nights === null || $nights >= $this->min_nights) && ($this->max_nights === null || $nights <= $this->max_nights) && (empty($this->arrival_weekdays) || in_array($stay->arrival->isoWeekday(), array_map('intval', $this->arrival_weekdays), true)) && (empty($this->season_names) || in_array($arrivalSeasonName, $this->season_names, true)); } /** * The discount in cents for the given nightly rates (one entry per night, in cents). * * @param list $nightlyRates */ public function discountFor(array $nightlyRates): int { $accommodation = array_sum($nightlyRates); $discount = match ($this->discount_type) { DiscountType::Percent => intdiv($accommodation * min($this->discount_value, 100) + 50, 100), DiscountType::AmountPerStay => $this->discount_value, DiscountType::NightlyRate => array_sum(array_map(fn (int $rate): int => max(0, $rate - $this->discount_value), $nightlyRates)), DiscountType::FreeNights => array_sum(array_slice($this->sortedAscending($nightlyRates), 0, $this->discount_value)), }; return min($discount, $accommodation); } /** * @param list $rates * @return list */ private function sortedAscending(array $rates): array { sort($rates); return $rates; } }