<?php

namespace App\Models;

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

class Event extends Model
{
    use HasFactory;

    protected $table = 'events';
    protected $primaryKey = 'Id';
    public $timestamps = true;

    protected $fillable = [
        'Name',
        'Type',
        'EventDate',
        'EndDate',
        'dFees',
        'cFees',
        'EarlyDisc',
        'EarlyDate',
        'Regstart',
        'regend',
        'isexternal',
    ];

    protected $casts = [
        'EventDate' => 'datetime',
        'EndDate' => 'datetime',
        'EarlyDate' => 'datetime',
        'Regstart' => 'date',
        'regend' => 'date',
        'dFees' => 'decimal:2',
        'cFees' => 'decimal:2',
        'EarlyDisc' => 'decimal:2',
        'isexternal' => 'boolean',
    ];

    /**
     * Get all registrations for this event
     */
    public function registrations()
    {
        return $this->hasMany(EventRegistration::class, 'eventid', 'Id');
    }

    /**
     * Scope: Get only active events (registration open and external)
     */
    public function scopeActive($query)
    {
        $today = Carbon::today();
        
        return $query->where('isexternal', true)
                    ->whereDate('Regstart', '<=', $today)
                    ->whereDate('regend', '>=', $today);
    }

    /**
     * Check if registration is open for this event
     */
    public function isRegistrationOpen(): bool
    {
        $today = Carbon::today();
        return $this->isexternal &&
               $this->Regstart->lte($today) &&
               $this->regend->gte($today);
    }

    /**
     * Calculate the actual fees (considering early bird discount)
     */
    public function getActualFees(): float
    {
        $today = Carbon::today();
        
        // Check if early bird discount applies
        if ($this->EarlyDate && $today->lte($this->EarlyDate) && $this->EarlyDisc > 0) {
            $discount = min($this->dFees, $this->EarlyDisc);
            return max(0, $this->dFees - $discount);
        }
        
        return (float) $this->dFees;
    }

    /**
     * Get total registrations count
     */
    public function getRegistrationCountAttribute(): int
    {
        return $this->registrations()
                   ->where('status', 'success')
                   ->count();
    }
}
