<?php
namespace App\Models;

use CodeIgniter\Model;

class TeacherModel extends Model
{
    protected $table = 'users'; // Use the 'users' table
    protected $primaryKey = 'id';
    protected $allowedFields = [
        'firstname', 
        'lastname', 
        'email', 
        'cellphone'
    ];

    // Fetches a specific teacher based on ID
 

    // Retrieves all teachers
    public function getAllTeachers()
    {
        return $this->db->table($this->table)
            ->select('users.id, users.firstname, users.lastname, users.email, users.cellphone') // Added email and cellphone
            ->join('user_roles', 'user_roles.user_id = users.id')
            ->join('roles', 'roles.id = user_roles.role_id')
            ->where('LOWER(roles.name)', 'teacher') // Ensuring case-insensitive role name matching
            ->get()
            ->getResultArray();
    }



public function getTeachersAndTAs(): array
{
    return $this->db->table('users u')
        ->select('u.id, u.firstname, u.lastname, u.email, u.cellphone, MIN(r.name) as role')
        ->join('user_roles ur', 'ur.user_id = u.id')
        ->join('roles r', 'r.id = ur.role_id')
        ->whereIn('r.name', ['teacher', 'teacher_assistant']) // ✅ Filter only relevant roles
        ->groupBy('u.id, u.firstname, u.lastname, u.email, u.cellphone')
        ->orderBy('u.lastname', 'ASC')
        ->get()
        ->getResultArray();
}



    // Retrieves teachers with their current class assignments and the school year
    public function getTeachersWithAssignments()
    {
        // Retrieve the school year from the configuration table
        $schoolYearConfig = $this->db->table('configuration')
            ->select('config_value')
            ->where('config_key', 'current_school_year')
            ->get()
            ->getRowArray();

        // Default to 'Unknown' if the school year is not found
        $schoolYear = isset($schoolYearConfig['config_value']) ? $schoolYearConfig['config_value'] : 'Unknown';

        // Main query to fetch teachers with their class and school year
        return $this->db->table('users')
            ->select('users.id, users.firstname, users.lastname, users.email, users.cellphone, 
                      IFNULL(classSection.class_section_name, "No Class Assigned") AS current_class, 
                      "' . $schoolYear . '" AS school_year') // Adding school year to the result
            ->join('teacher_class', 'teacher_class.teacher_id = users.id', 'left')
            ->join('class_section', 'teacher_class.class_section_id = classSection.id', 'left')
            ->join('user_roles', 'user_roles.user_id = users.id')
            ->join('roles', 'roles.id = user_roles.role_id')
            ->where('LOWER(roles.name)', 'teacher') // Ensuring case-insensitive role name matching
            ->get()
            ->getResultArray();
    }
}
