<?php

namespace App\Modules\Academic\Controllers;

use App\Core\BaseApiController;
use App\Modules\Auth\Models\RoleModel;
use App\Modules\Auth\Models\UserModel;
use App\Modules\Auth\Models\UserRoleModel;
use CodeIgniter\HTTP\ResponseInterface;

/**
 * Teachers list API (ADMIN only). Returns users with role GURU_MAPEL or WALI_KELAS.
 */
class TeacherController extends BaseApiController
{
    /**
     * GET /api/academic/teachers
     */
    public function index(): ResponseInterface
    {
        $roleModel = new RoleModel();
        $waliRole  = $roleModel->findByCode('WALI_KELAS');
        $guruRole  = $roleModel->findByCode('GURU_MAPEL');
        if (!$waliRole || !$guruRole) {
            return $this->successResponse([], 'Teachers');
        }

        $db     = \Config\Database::connect();
        $userIdList = $db->table('user_roles')
            ->select('user_id')
            ->whereIn('role_id', [$waliRole->id, $guruRole->id])
            ->get()
            ->getResultArray();
        $userIdList = array_values(array_unique(array_map(static fn ($r) => (int) $r['user_id'], $userIdList)));
        if ($userIdList === []) {
            return $this->successResponse([], 'Teachers');
        }

        $userModel = new UserModel();
        $userRoleModel = new UserRoleModel();
        $users = $userModel->whereIn('id', $userIdList)->findAll();
        $data  = [];
        foreach ($users as $u) {
            $roleIds = $userRoleModel->getRoleIdsForUser((int) $u->id);
            $roles   = [];
            foreach ($roleIds as $rid) {
                $r = $roleModel->find($rid);
                if ($r && in_array($r->role_code, ['GURU_MAPEL', 'WALI_KELAS'], true)) {
                    $roles[] = ['role_code' => $r->role_code, 'role_name' => $r->role_name];
                }
            }
            $data[] = [
                'id'    => (int) $u->id,
                'name'  => (string) $u->name,
                'email' => (string) $u->email,
                'roles' => $roles,
            ];
        }
        usort($data, static fn ($a, $b) => strcasecmp($a['name'], $b['name']));

        return $this->successResponse($data, 'Teachers');
    }
}
