<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;

class Coupon extends Model
{
    use HasFactory;

    protected $fillable = [
        'code',
        'discount_type',
        'discount_value',
        'min_amount',
        'max_uses',
        'used_count',
        'valid_from',
        'valid_to',
        'applicable_brands',
        'applicable_products',
        'is_active',
    ];

    protected $casts = [
        'discount_value' => 'decimal:2',
        'min_amount' => 'decimal:2',
        'valid_from' => 'date',
        'valid_to' => 'date',
        'applicable_brands' => 'array',
        'applicable_products' => 'array',
        'is_active' => 'boolean',
    ];

    public function reservations()
    {
        return $this->hasMany(Reservation::class);
    }

    public function isValid($amount = null, $brandId = null, $productId = null)
    {
        if (!$this->is_active) return false;
        
        if ($this->valid_from && now() < $this->valid_from) return false;
        if ($this->valid_to && now() > $this->valid_to) return false;
        
        if ($this->max_uses && $this->used_count >= $this->max_uses) return false;
        
        if ($amount && $this->min_amount && $amount < $this->min_amount) return false;
        
        if ($brandId && $this->applicable_brands && !in_array($brandId, $this->applicable_brands)) return false;
        
        return true;
    }
}
