<?php

namespace App\Models;

use App\Models\BaseModel;
use Illuminate\Support\Facades\DB;

class EventCharges extends BaseModel
{
    protected $table = 'event_charges';

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

    protected $fillable = [
        'event_id',
        'parent_id',
        'student_id',
        'participation',
        'charged',
        'semester',
        'school_year',
        'updated_by',
        'created_at',
        'updated_at',
    ];

    protected $casts = [
        'event_id'       => 'integer',
        'parent_id'      => 'integer',
        'student_id'     => 'integer',
        'participation'  => 'boolean', // change if stored as string/enum
        'charged'        => 'boolean', // change if stored as string/enum
        'updated_by'     => 'integer',
    ];

    /* Optional relationships */
    public function event()
    {
        return $this->belongsTo(Event::class, 'event_id');
    }

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

    public function student()
    {
        return $this->belongsTo(Student::class, 'student_id');
    }

    /**
     * Equivalent of CI getChargesWithEventInfo()
     * Returns rows with: event_charges.*, events.event_name, events.amount
     */
    public static function getChargesWithEventInfo(?int $parentId = null, ?string $schoolYear = null, ?string $semester = null): array
    {
        $q = DB::table('event_charges')
            ->leftJoin('events', 'events.id', '=', 'event_charges.event_id')
            ->select('event_charges.*', 'events.event_name', 'events.amount');

        if (!empty($parentId)) {
            $q->where('event_charges.parent_id', $parentId);
        }

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

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

        return $q->get()->map(fn ($r) => (array) $r)->all();
    }
}
