<?php

namespace App\Models;

use App\Models\BaseModel;

class EmergencyContact extends BaseModel
{
    protected $table = 'emergency_contacts';

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

    protected $fillable = [
        'emergency_contact_name',
        'parent_id',
        'cellphone',
        'email',
        'relation',
        'semester',
        'school_year',
        'created_at',
        'updated_at',
    ];

    protected $casts = [
        'parent_id'          => 'integer',
        'student_id'         => 'integer',
        'authorized_user_id' => 'integer',
    ];

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

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

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

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

    public static function getEmergencyContactsByStudentId(int $studentId)
    {
        return static::query()
            ->where('student_id', $studentId)
            ->get();
    }

    public static function getEmergencyContactByAuthorizedUserId(int $authorizedUserId): ?self
    {
        return static::query()
            ->where('authorized_user_id', $authorizedUserId)
            ->first();
    }

    /**
     * Your CI logic: (student_id = $studentId) OR (parent_id = $studentId)
     * Keeping it exactly as-is, even though the 2nd condition looks unusual.
     */
    public static function getAllEmergencyContacts(int $studentId)
    {
        return static::query()
            ->where(function ($q) use ($studentId) {
                $q->where('student_id', $studentId)
                  ->orWhere('parent_id', $studentId);
            })
            ->get();
    }

    public static function getEmergencyContactByParentId(int $parentId): ?array
    {
        $row = static::query()
            ->where('parent_id', $parentId)
            ->select(['emergency_contact_name', 'cellphone'])
            ->first();

        return $row ? $row->toArray() : null;
    }

    public static function getEmergencyContactsByParentId(int $parentId)
    {
        return static::query()
            ->where('parent_id', $parentId)
            ->get();
    }
}