<?php

namespace App\Modules\Mobile\Controllers;

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

/**
 * Mengambil foto wajah referensi siswa untuk verifikasi di aplikasi mobile.
 * Foto disimpan di writable/faces/{student_id}.jpg (atau .png).
 * Sumber foto bisa dari sync Google Drive (folder Foto Siswa per kelas).
 */
class FacePhotoController extends BaseApiController
{
    /** Subfolder di writable untuk foto wajah */
    protected string $facesDir = 'faces';

    /**
     * GET /api/mobile/student/face-photo?student_id=123
     * Mengembalikan gambar foto wajah siswa atau 404 jika belum ada.
     */
    public function show(): ResponseInterface
    {
        $studentId = (int) $this->request->getGet('student_id');
        if ($studentId < 1) {
            return $this->response->setStatusCode(400)->setJSON([
                'success' => false,
                'message' => 'student_id wajib',
            ]);
        }

        $studentModel = new StudentModel();
        $student      = $studentModel->find($studentId);
        if (! $student) {
            return $this->response->setStatusCode(404)->setJSON([
                'success' => false,
                'message' => 'Siswa tidak ditemukan',
            ]);
        }

        $writable = defined('WRITEPATH') ? WRITEPATH : rtrim(realpath(FCPATH . '..' . DIRECTORY_SEPARATOR . 'writable') ?: FCPATH, DIRECTORY_SEPARATOR);
        $facesPath = $writable . DIRECTORY_SEPARATOR . $this->facesDir;

        $extensions = ['jpg', 'jpeg', 'png'];
        $filePath   = null;
        foreach ($extensions as $ext) {
            $p = $facesPath . DIRECTORY_SEPARATOR . $studentId . '.' . $ext;
            if (is_file($p)) {
                $filePath = $p;
                break;
            }
        }

        if ($filePath === null) {
            return $this->response->setStatusCode(404)->setJSON([
                'success' => false,
                'message' => 'Foto wajah belum diunggah untuk siswa ini. Hubungi admin.',
            ]);
        }

        $mime = mime_content_type($filePath);
        if (! in_array($mime, ['image/jpeg', 'image/png'], true)) {
            $mime = 'image/jpeg';
        }

        $faceHash = isset($student->face_hash) ? (string) $student->face_hash : md5_file($filePath);

        return $this->response
            ->setHeader('Content-Type', $mime)
            ->setHeader('Cache-Control', 'public, max-age=31536000')
            ->setHeader('X-Face-Hash', $faceHash)
            ->setHeader('Access-Control-Allow-Origin', '*')
            ->setBody(file_get_contents($filePath));
    }
}
