<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Model;

class PromoCode extends Model
{
    use \App\Models\Concerns\BelongsToHotel;

    protected $guarded = [];
    protected $casts = [
        'starts_at' => 'date',
        'expires_at' => 'date',
    ];

    public function isValid(): bool
    {
        if ($this->status !== 'active') {
            return false;
        }

        if ($this->starts_at && $this->starts_at->isFuture()) {
            return false;
        }

        if ($this->expires_at && $this->expires_at->endOfDay()->isPast()) {
            return false;
        }

        if ((int) $this->max_uses > 0 && (int) $this->used_count >= (int) $this->max_uses) {
            return false;
        }

        return true;
    }

    public function discountFor(float $amount): float
    {
        $discount = $this->type === 'percent'
            ? $amount * (float) $this->value / 100
            : (float) $this->value;

        return round(min($discount, $amount), 2);
    }
}
