<?php

namespace App\Modules\Academic\Models;

use CodeIgniter\Model;

class TeacherSubjectModel extends Model
{
    protected $table            = 'teacher_subjects';
    protected $primaryKey       = 'id';
    protected $useAutoIncrement = true;
    protected $returnType       = 'array';
    protected $useSoftDeletes   = false;
    protected $protectFields    = true;
    protected $allowedFields    = [
        'teacher_user_id',
        'subject_id',
    ];

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

    /**
     * Get subject IDs for a teacher.
     *
     * @param int $teacherId
     * @return array<int>
     */
    public function getSubjectIdsForTeacher(int $teacherId): array
    {
        $rows = $this->select('subject_id')
            ->where('teacher_user_id', $teacherId)
            ->findAll();

        return array_map(static fn ($row) => (int) $row['subject_id'], $rows);
    }

    /**
     * Get mapping: subject_id => [teacher_user_id, ...].
     *
     * @return array<int, array<int>>
     */
    public function getMapSubjectToTeacherIds(): array
    {
        $rows = $this->select('teacher_user_id, subject_id')->findAll();
        $map  = [];
        foreach ($rows as $r) {
            $s = (int) $r['subject_id'];
            $t = (int) $r['teacher_user_id'];
            $map[$s][] = $t;
        }
        return $map;
    }
}

