<?php

namespace App\Models;

use App\Models\BaseModel;

class Event extends BaseModel
{
    protected $table = 'events';

    // ✅ CI: timestamps enabled (created_at/updated_at)
    public $timestamps = true;

    protected $fillable = [
        'event_name',
        'event_category',
        'description',
        'amount',
        'flyer',
        'expiration_date',
        'semester',
        'school_year',
        'created_by',
        'created_at',
        'updated_at',
    ];

    protected $casts = [
        'amount'          => 'decimal:2', // adjust precision if needed
        'expiration_date' => 'date',      // change to 'datetime' if stored as DATETIME
        'created_by'      => 'integer',
    ];

    /* Optional relationships */
    public function charges()
    {
        return $this->hasMany(EventCharge::class, 'event_id');
    }

    public function creator()
    {
        return $this->belongsTo(User::class, 'created_by');
    }

    /* =========================
     * CI method equivalents
     * ========================= */

    /**
     * Get all upcoming events (not expired).
     */
    public static function getUpcomingEvents(?string $schoolYear = null)
    {
        $q = static::query()
            ->whereDate('expiration_date', '>=', now()->toDateString());

        if (!empty($schoolYear)) {
            $q->where('school_year', $schoolYear);
        }

        return $q->orderBy('expiration_date', 'asc')->get();
    }

    /**
     * Get events by name (partial match).
     */
    public static function getEventsByName(string $name, ?string $schoolYear = null)
    {
        $q = static::query()
            ->where('event_name', 'like', '%' . $name . '%');

        if (!empty($schoolYear)) {
            $q->where('school_year', $schoolYear);
        }

        return $q->orderBy('expiration_date', 'asc')->get();
    }

    /**
     * Get all events (optionally filtered by school year).
     */
    public static function getAllEvents(?string $schoolYear = null)
    {
        $q = static::query();

        if (!empty($schoolYear)) {
            $q->where('school_year', $schoolYear);
        }

        return $q->orderByDesc('created_at')->get();
    }

    /**
     * Add a new event. Returns inserted id.
     */
    public static function addEvent(array $data): int
    {
        $row = static::create($data);
        return (int) $row->id;
    }

    /**
     * Get events by expiration date.
     */
    public static function getEventsByDate(string $date, ?string $schoolYear = null)
    {
        $q = static::query()->whereDate('expiration_date', $date);

        if (!empty($schoolYear)) {
            $q->where('school_year', $schoolYear);
        }

        return $q->get();
    }

    /**
     * Get all active (not expired) events (optionally filtered by year/semester).
     */
    public static function getActiveEvents(?string $schoolYear = null, ?string $semester = null)
    {
        $q = static::query()
            ->whereDate('expiration_date', '>=', now()->toDateString());

        if (!empty($schoolYear)) {
            $q->where('school_year', $schoolYear);
        }

        if (!empty($semester)) {
            $q->where('semester', $semester);
        }

        return $q->orderBy('expiration_date', 'asc')->get();
    }

    /**
     * Get event by id (optionally filtered by school year).
     */
    public static function getEvent(int $id, ?string $schoolYear = null): ?self
    {
        $q = static::query()->whereKey($id);

        if (!empty($schoolYear)) {
            $q->where('school_year', $schoolYear);
        }

        return $q->first();
    }

    /**
     * Update event by id (optionally constrained to a school year).
     */
    public static function updateEvent(int $id, array $data, ?string $schoolYear = null): bool
    {
        $q = static::query()->whereKey($id);

        if (!empty($schoolYear)) {
            $q->where('school_year', $schoolYear);
        }

        return $q->update($data) >= 0;
    }

    /**
     * Delete event by id (optionally constrained to a school year).
     */
    public static function deleteEvent(int $id, ?string $schoolYear = null): bool
    {
        $q = static::query()->whereKey($id);

        if (!empty($schoolYear)) {
            $q->where('school_year', $schoolYear);
        }

        return (bool) $q->delete();
    }
}