<?php

namespace App\Modules\Attendance\Controllers;

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

/**
 * Face link API: menghubungkan ID wajah eksternal dengan siswa.
 *
 * Catatan:
 * - Engine AI / OpenCV bertugas menghasilkan face_external_id.
 * - Backend hanya menyimpan mapping face_external_id -> student_id.
 */
class FaceLinkController extends BaseApiController
{
    /**
     * POST /api/attendance/face/enroll
     * Body: { student_id: int, face_external_id: string }
     */
    public function enroll(): ResponseInterface
    {
        $payload = $this->request->getJSON(true) ?? [];
        $studentId = (int) ($payload['student_id'] ?? 0);
        $faceId    = trim((string) ($payload['face_external_id'] ?? ''));

        if ($studentId <= 0 || $faceId === '') {
            return $this->errorResponse(
                'student_id dan face_external_id wajib diisi',
                null,
                null,
                ResponseInterface::HTTP_UNPROCESSABLE_ENTITY
            );
        }

        $studentModel = new StudentModel();
        $student      = $studentModel->find($studentId);
        if (! $student) {
            return $this->errorResponse('Siswa tidak ditemukan', null, null, ResponseInterface::HTTP_NOT_FOUND);
        }

        // Pastikan face_external_id belum dipakai siswa lain
        $existing = $studentModel
            ->where('face_external_id', $faceId)
            ->where('id !=', $studentId)
            ->first();
        if ($existing) {
            return $this->errorResponse('face_external_id sudah terpakai siswa lain', null, null, ResponseInterface::HTTP_CONFLICT);
        }

        $studentModel->skipValidation(true);
        $studentModel->update($studentId, ['face_external_id' => $faceId]);

        return $this->successResponse([
            'student_id'       => $studentId,
            'face_external_id' => $faceId,
        ], 'Face ID berhasil dihubungkan dengan siswa');
    }

    /**
     * POST /api/attendance/face/resolve
     * Body: { face_external_id: string }
     * Return: { student_id, name, class_id } atau 404.
     */
    public function resolve(): ResponseInterface
    {
        $payload = $this->request->getJSON(true) ?? [];
        $faceId  = trim((string) ($payload['face_external_id'] ?? ''));

        if ($faceId === '') {
            return $this->errorResponse(
                'face_external_id wajib diisi',
                null,
                null,
                ResponseInterface::HTTP_UNPROCESSABLE_ENTITY
            );
        }

        $studentModel = new StudentModel();
        $student = $studentModel->where('face_external_id', $faceId)->first();
        if (! $student) {
            return $this->errorResponse('Siswa untuk face_external_id ini tidak ditemukan', null, null, ResponseInterface::HTTP_NOT_FOUND);
        }

        return $this->successResponse([
            'student_id' => (int) $student->id,
            'name'       => (string) $student->name,
            'class_id'   => $student->class_id !== null ? (int) $student->class_id : null,
        ], 'Face ID berhasil dikenali');
    }
}

