<?php

namespace App\Models;

use CodeIgniter\Model;

class StudentAllergyModel extends Model
{
    protected $table            = 'student_allergies';
    protected $primaryKey       = 'id';
    protected $allowedFields    = [
        'student_id',
         'allergy'
        ];
        
    public    $timestamps       = false;

    protected $validationRules = [
        'student_id' => 'required|is_natural_no_zero',
        'allergy'    => 'required|string|max_length[100]',
    ];

    protected $validationMessages = [
        'student_id' => [
            'required'            => 'Student ID is required.',
            'is_natural_no_zero' => 'Invalid Student ID.',
        ],
        'allergy' => [
            'required'   => 'Allergy is required.',
            'max_length' => 'Allergy must be 100 characters or fewer.',
        ],
    ];

        /**
     * Get all allergies for a given student.
     *
     * @param int $studentId
     * @return array
     */
    public function getAllergiesByStudentId(int $studentId): array
    {
        return $this->where('student_id', $studentId)
                    ->findAll();
    }

        /**
     * Get allergies for multiple students.
     *
     * @param array $studentIds
     * @return array grouped by student_id
     */
    public function getAllergiesByStudentIds(array $studentIds): array
    {
        $rows = $this->whereIn('student_id', $studentIds)->findAll();

        $grouped = [];
        foreach ($rows as $row) {
            $grouped[$row['student_id']][] = $row;
        }

        return $grouped;
    }
}
