<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Builder;
use App\Models\BaseModel;
use Illuminate\Database\Eloquent\Relations\BelongsTo;

class StudentAllergy extends BaseModel
{
    protected $table = 'student_allergies';

    /**
     * CI: timestamps disabled
     */
    public $timestamps = false;

    protected $fillable = [
        'student_id',
        'allergy',
    ];

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

    /* ============================================================
     * Relationships (optional)
     * ============================================================
     */

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

    /* ============================================================
     * Scopes
     * ============================================================
     */

    public function scopeForStudent(Builder $q, int $studentId): Builder
    {
        return $q->where('student_id', $studentId);
    }

    public function scopeForStudents(Builder $q, array $studentIds): Builder
    {
        $ids = array_values(array_unique(array_filter(array_map('intval', $studentIds))));
        return empty($ids) ? $q->whereRaw('1=0') : $q->whereIn('student_id', $ids);
    }

    /* ============================================================
     * CI-compatible methods
     * ============================================================
     */

    /**
     * Get all allergies for a given student.
     * CI: getAllergiesByStudentId()
     */
    public static function getAllergiesByStudentId(int $studentId): array
    {
        return static::query()
            ->forStudent($studentId)
            ->orderBy('id', 'asc')
            ->get()
            ->all();
    }

    /**
     * Get allergies for multiple students, grouped by student_id.
     * CI: getAllergiesByStudentIds()
     */
    public static function getAllergiesByStudentIds(array $studentIds): array
    {
        $rows = static::query()
            ->forStudents($studentIds)
            ->orderBy('student_id', 'asc')
            ->orderBy('id', 'asc')
            ->get()
            ->all();

        $grouped = [];
        foreach ($rows as $row) {
            // $row is a model instance; convert as needed
            $sid = (int) $row->student_id;
            $grouped[$sid][] = $row;
        }

        return $grouped;
    }

    /* ============================================================
     * Validation rules helper (FormRequest/controller)
     * Mirrors CI validation intent
     * ============================================================
     */

    public static function rules(bool $updating = false): array
    {
        $req = $updating ? 'sometimes' : 'required';

        return [
            'student_id' => [$req, 'integer', 'min:1', 'exists:students,id'],
            'allergy'    => [$req, 'string', 'max:100'],
        ];
    }

    public static function messages(): array
    {
        return [
            'student_id.required' => 'Student ID is required.',
            'student_id.min'      => 'Invalid Student ID.',
            'allergy.required'    => 'Allergy is required.',
            'allergy.max'         => 'Allergy must be 100 characters or fewer.',
        ];
    }
}