<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Builder;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\SoftDeletes;
use DateTimeInterface;

final class ExpRateSchedule extends Model
{
    protected $fillable = [
        'name',
        'type',
        'exp_rate_value',
        'double_money_value',
        'double_drop_value',
        'double_sp_value',
        'no_trade_value',
        'no_auction_value',
        'no_mail_value',
        'start_time',
        'end_time',
        'is_active',
        'is_applied',
        'original_value',
        'broadcast_enabled',
        'broadcast_message',
        'end_broadcast_enabled',
        'end_broadcast_message',
    ];

    protected $casts = [
        'start_time' => 'datetime',
        'end_time' => 'datetime',
        'is_active' => 'boolean',
        'is_applied' => 'boolean',
        'double_money_value' => 'boolean',
        'double_drop_value' => 'boolean',
        'double_sp_value' => 'boolean',
        'no_trade_value' => 'boolean',
        'no_auction_value' => 'boolean',
        'no_auction_value' => 'boolean',
        'no_mail_value' => 'boolean',
        'broadcast_enabled' => 'boolean',
        'end_broadcast_enabled' => 'boolean',
    ];

    protected function serializeDate(DateTimeInterface $date)
    {
        return $date->toJSON();
    }

    public function getStartTimeAttribute($value)
    {
        return $this->asDateTime($value)->format('Y-m-d\TH:i:s');
    }

    public function getEndTimeAttribute($value)
    {
        return $this->asDateTime($value)->format('Y-m-d\TH:i:s');
    }

    public function scopeActive(Builder $query): Builder
    {
        return $query->where('is_active', true);
    }

    public function scopePending(Builder $query): Builder
    {
        return $query->where('is_applied', false);
    }

    public function scopeForDate(Builder $query, $date): Builder
    {
        return $query->where('start_time', '<=', $date)
            ->where('end_time', '>=', $date);
    }

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

    public function shouldApply()
    {
        return $this->is_active && 
               !$this->is_applied && 
               $this->start_time->isPast();
    }
}
