<?php

namespace App\Models;

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

class AlumniEvent extends Model
{
    use HasFactory, SoftDeletes;

    protected $fillable = [
        'school_id',
        'title',
        'description',
        'event_date',
        'start_time',
        'end_time',
        'venue',
        'organizer_name',
        'organizer_phone',
        'organizer_email',
        'max_participants',
        'registration_fee',
        'registration_start_date',
        'registration_end_date',
        'event_image',
        'status',
        'is_published',
    ];

    protected $casts = [
        'event_date' => 'date',
        'start_time' => 'datetime',
        'end_time' => 'datetime',
        'registration_start_date' => 'date',
        'registration_end_date' => 'date',
        'max_participants' => 'integer',
        'registration_fee' => 'decimal:2',
        'is_published' => 'boolean',
    ];

    // Relationships
    public function school()
    {
        return $this->belongsTo(School::class);
    }

    public function registrations()
    {
        return $this->hasMany(AlumniEventRegistration::class, 'alumni_event_id');
    }

    public function alumni()
    {
        return $this->belongsToMany(Alumni::class, 'alumni_event_registrations')
                    ->withPivot('registration_date', 'payment_status', 'attendance_status')
                    ->withTimestamps();
    }

    public function gallery()
    {
        return $this->hasMany(AlumniGallery::class, 'event_id');
    }

    // Scopes
    public function scopePublished($query)
    {
        return $query->where('is_published', true);
    }

    public function scopeUpcoming($query)
    {
        return $query->where('event_date', '>', now());
    }

    public function scopePast($query)
    {
        return $query->where('event_date', '<', now());
    }

    public function scopeRegistrationOpen($query)
    {
        return $query->where('registration_start_date', '<=', now())
                     ->where('registration_end_date', '>=', now());
    }

    // Accessors
    public function getIsRegistrationOpenAttribute()
    {
        $now = now();
        return $this->registration_start_date <= $now && $this->registration_end_date >= $now;
    }

    public function getRegistrationCountAttribute()
    {
        return $this->registrations()->count();
    }
}
