<?php

namespace App\Models;

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

class Promo extends Model
{
    use HasFactory;

    protected $guarded = [];

    protected $casts = [
        'eligible_cars' => 'array',
        'expiration_date' => 'date',
        'is_active' => 'boolean',
    ];
    
    protected $attributes = ['eligible_cars' => '[]'];

    public function isExpired()
    {
        return $this->expiration_date->isPast();
    }

    public function isActive()
    {
        return $this->is_active && !$this->isExpired();
    }

    public function isUsable()
    {
        return is_null($this->usage_limit) || $this->times_used < $this->usage_limit;
    }

    public static function isValidPromo($code)
    {
        return self::active()->where('code', $code)
            ->where(function ($query) {
                $query->whereNull('usage_limit')
                      ->orWhereColumn('times_used', '<', 'usage_limit');
            })->exists();
    }

    public function usePromo()
    {
        if ($this->isValidPromo($this->code)) {
            $this->increment('times_used');
            return true;
        }
        return false;
    }

    public function scopeActive($query)
    {
        return $query->where('is_active', true)
                     ->where('expiration_date', '>=', now());
    }
}
