<?php

namespace App\Models;

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

class Event extends Model
{
    use HasFactory;

    protected $fillable = [
        'user_id',
        'name',
        'description',
        'location',
        'start_date',
        'start_time',
        'end_date',
        'end_time',
        'cover_image',
        'event_url',
        'type',
        'slug',
        'category',
        'status',
        'allow_guests',
        'require_approval',
        'max_participants'
    ];

    /**
     * The attributes that should be cast.
     *
     * @var array
     */
    protected $casts = [
        'allow_guests' => 'boolean',
        'require_approval' => 'boolean',
        'max_participants' => 'integer',
    ];

    /**
     * Get the event organizer (user who created the event)
     */
    public function organizer()
    {
        return $this->belongsTo(User::class, 'user_id');
    }

    /**
     * Get all participants for this event
     */
    public function participants()
    {
        return $this->hasMany(EventParticipant::class);
    }

    /**
     * Check if a user is marked as "going" to this event
     */
    public function isGoing($userId)
    {
        return $this->participants()->where('user_id', $userId)->where('status', 'going')->exists();
    }

    /**
     * Check if a user is marked as "interested" in this event
     */
    public function isInterested($userId)
    {
        return $this->participants()->where('user_id', $userId)->where('status', 'interested')->exists();
    }

    /**
     * Get users who are attending the event
     */
    public function attendees()
    {
        return $this->hasManyThrough(
            User::class,
            EventParticipant::class,
            'event_id', // Foreign key on EventParticipant table
            'id', // Foreign key on User table
            'id', // Local key on Event table
            'user_id' // Local key on EventParticipant table
        )->whereHas('eventParticipants', function ($query) {
            $query->where('status', 'going');
        });
    }

    /**
     * Get users who are interested in the event
     */
    public function interestedUsers()
    {
        return $this->hasManyThrough(
            User::class,
            EventParticipant::class,
            'event_id', // Foreign key on EventParticipant table
            'id', // Foreign key on User table
            'id', // Local key on Event table
            'user_id' // Local key on EventParticipant table
        )->whereHas('eventParticipants', function ($query) {
            $query->where('status', 'interested');
        });
    }

    /**
     * Scope a query to only include upcoming events.
     */
    public function scopeUpcoming($query)
    {
        return $query->where('start_date', '>=', Carbon::now()->toDateString());
    }

    /**
     * Scope a query to only include past events.
     */
    public function scopePast($query)
    {
        return $query->where('end_date', '<', Carbon::now()->toDateString());
    }

    /**
     * Scope a query to only include ongoing events.
     */
    public function scopeOngoing($query)
    {
        $now = Carbon::now()->toDateString();
        return $query->where('start_date', '<=', $now)
            ->where('end_date', '>=', $now);
    }

    /**
     * Check if an event is ongoing.
     */
    public function isOngoing()
    {
        $now = Carbon::now();
        $startDateTime = Carbon::parse("{$this->start_date} {$this->start_time}");
        $endDateTime = Carbon::parse("{$this->end_date} {$this->end_time}");

        return $now->between($startDateTime, $endDateTime);
    }

    /**
     * Get the creator of the event (alias for organizer).
     */
    public function creator()
    {
        return $this->belongsTo(User::class, 'user_id');
    }

    /**
     * Get the post associated with this event.
     */
    public function post()
    {
        return $this->hasOne(Post::class, 'event_id');
    }
    public function deleteEvent($event)
    {
        $postModel = new Post();
        $posts = $postModel->where('event_id', $event->id)->pluck('id')->toArray();
        EventParticipant::where('event_id', $event->id)->delete();
        $postModel->deletePosts($posts);
        $event->delete();
    }
}
