<?php

namespace App\Models;

use CodeIgniter\Model;

class EmergencyContactModel extends Model
{
    protected $table = 'emergency_contacts';
    protected $primaryKey = 'id';
    protected $useAutoIncrement = true;

    protected $allowedFields = [
        'parent_id',
        'emergency_contact_name',
        'cellphone',
        'email',
        'relation',
        'created_at',
        'updated_at'
    ];

    protected $returnType = 'array';
    protected $useTimestamps = true;
    protected $createdField = 'created_at';
    protected $updatedField = 'updated_at';


    /**
     * Get emergency contact by student ID.
     *
     * @param int $studentId
     * @return array
     */
    public function getEmergencyContactsByStudentId($studentId)
    {
        return $this->where('student_id', $studentId)
            ->findAll();
    }

    /**
     * Get emergency contact by parent ID.
     *
     * @param int $parentId
     * @return array
     */
    /*
    public function getEmergencyContactsByParentId($parentId)
    {
        return $this->groupStart()
            ->where('parent_id', $parentId)
            ->groupEnd()
            ->findAll();
    }
*/
    /**
     * Get authorized user's emergency contact.
     *
     * @param int $authorizedUserId
     * @return array|null
     */
    public function getEmergencyContactByAuthorizedUserId($authorizedUserId)
    {
        return $this->where('authorized_user_id', $authorizedUserId)
            ->first();
    }

    /**
     * Get all emergency contacts for a specific student and their associated parents or authorized user.
     *
     * @param int $studentId
     * @return array
     */
    public function getAllEmergencyContacts($studentId)
    {
        return $this->groupStart()
            ->where('student_id', $studentId)
            ->orWhere('parent_id', $studentId)
            ->groupEnd()
            ->findAll();
    }

    // Function to get the emergency contact based on parent_id
    public function getEmergencyContactByParentId($parentId)
    {
        // Query to retrieve the emergency contact details using either parent_id or secondparent_id
        return $this->where('parent_id', $parentId)
            ->select('emergency_contact_name, cellphone')
            ->first(); // Use `first()` to get a single result
    }

    public function getEmergencyContactsByParentId($parentId)
    {
        return $this->where('parent_id', $parentId)->findAll();
    }
}
