<?php

namespace App\Modules\Academic\Controllers;

use App\Core\BaseApiController;
use App\Modules\Academic\Models\TeacherSubjectModel;
use CodeIgniter\HTTP\ResponseInterface;

/**
 * Assign mapel per guru (ADMIN only).
 */
class TeacherSubjectController extends BaseApiController
{
    /**
     * GET /api/academic/teacher-subjects/{teacherId}
     * Return: { teacher_user_id, subject_ids: [...] }
     */
    public function getByTeacher(int $teacherId): ResponseInterface
    {
        $model = new TeacherSubjectModel();
        $ids   = $model->getSubjectIdsForTeacher($teacherId);

        return $this->successResponse([
            'teacher_user_id' => $teacherId,
            'subject_ids'     => $ids,
        ], 'Teacher subjects');
    }

    /**
     * PUT /api/academic/teacher-subjects/{teacherId}
     * Body: { subject_ids: [1,2,3] }
     */
    public function updateForTeacher(int $teacherId): ResponseInterface
    {
        $payload = $this->request->getJSON(true) ?? [];
        $ids     = $payload['subject_ids'] ?? [];

        if (! is_array($ids)) {
            return $this->errorResponse('subject_ids must be an array', null, null, 422);
        }

        $cleanIds = [];
        foreach ($ids as $id) {
            $id = (int) $id;
            if ($id > 0) {
                $cleanIds[$id] = true;
            }
        }
        $subjectIds = array_keys($cleanIds);

        $model = new TeacherSubjectModel();
        $db    = \Config\Database::connect();
        $db->transStart();

        try {
            $model->where('teacher_user_id', $teacherId)->delete();
            foreach ($subjectIds as $sid) {
                $model->insert([
                    'teacher_user_id' => $teacherId,
                    'subject_id'      => $sid,
                ]);
            }
            $db->transComplete();
        } catch (\Throwable $e) {
            $db->transRollback();
            return $this->errorResponse($e->getMessage(), null, null, 500);
        }

        if ($db->transStatus() === false) {
            return $this->errorResponse('Database transaction failed', null, null, 500);
        }

        return $this->successResponse([
            'teacher_user_id' => $teacherId,
            'subject_ids'     => $subjectIds,
        ], 'Teacher subjects updated');
    }

    /**
     * GET /api/academic/teacher-subjects/map
     * Return: { [subject_id]: [teacher_user_id, ...], ... }
     */
    public function map(): ResponseInterface
    {
        $model = new TeacherSubjectModel();
        $map   = $model->getMapSubjectToTeacherIds();

        return $this->successResponse($map, 'Subject to teacher map');
    }
}

