<?php

namespace App\Controllers;

use App\Controllers\BaseController;
use App\Services\GraduationService;
use App\Models\AcademicYearModel;
use CodeIgniter\HTTP\ResponseInterface;
use CodeIgniter\Validation\ValidationErrors;

class Graduation extends BaseController
{
    protected $graduationService;
    protected $academicYearModel;

    public function __construct()
    {
        $this->graduationService = new GraduationService();
        $this->academicYearModel = new AcademicYearModel();
    }

    public function index()
    {
        $statusData = $this->graduationService->getPublicGraduationStatus();

        $data = [
            'title' => 'Pengumuman Kelulusan Online',
            'statusData' => $statusData,
            'academicYear' => $statusData['academic_year'] ?? null,
            'settings' => $statusData['settings'] ?? null,
        ];

        if (!$statusData['is_active'] || !$statusData['is_open']) {
            return view('graduation/public_countdown', $data);
        } else {
            $captcha = $this->graduationService->generateMathCaptcha();
            $data['captcha_question'] = $captcha['question'];
            $data['captcha_key'] = $captcha['key'];
            return view('graduation/public_check', $data);
        }
    }

    public function checkGraduation()
    {
        $rules = [
            'nisn' => 'required|min_length[5]|max_length[20]|numeric',
            'captcha_answer' => 'required',
            'captcha_key' => 'required'
        ];

        if (!$this->validate($rules)) {
            return $this->response->setJSON([
                'success' => false,
                'message' => 'Validasi gagal.',
                'errors'  => $this->validator->getErrors(),
                'csrf_token' => csrf_hash(),
            ]);
        }

        $nisn             = $this->request->getPost('nisn');
        $userCaptchaAnswer = $this->request->getPost('captcha_answer');
        $captchaKey       = $this->request->getPost('captcha_key');

        if (!$this->graduationService->validateMathCaptcha($userCaptchaAnswer, $captchaKey)) {
            return $this->response->setJSON([
                'success' => false,
                'message' => 'Jawaban Captcha salah.',
                'csrf_token' => csrf_hash(),
            ]);
        }

        $activeYear = $this->academicYearModel->getActive();
        if (!$activeYear) {
            return $this->response->setJSON([
                'success' => false,
                'message' => 'Fitur kelulusan belum aktif.',
                'csrf_token' => csrf_hash(),
            ]);
        }

        $studentData = $this->graduationService->checkStudentGraduation($nisn, $activeYear['id']);

        if (!$studentData) {
            return $this->response->setJSON([
                'success' => false,
                'message' => 'NISN tidak ditemukan.',
                'csrf_token' => csrf_hash(),
            ]);
        }

        $downloadToken = null;
        if (
            $studentData['kelulusan_status'] === 'LULUS'
            && !empty($studentData['skl_file_path'])
            && !empty($studentData['allow_skl_download'])
        ) {
            $downloadToken = $this->graduationService->generateDownloadToken($studentData['student_id'], $activeYear['id']);
        }

        return $this->response->setJSON([
            'success' => true,
            'data' => $studentData,
            'download_token' => $downloadToken,
            'csrf_token' => csrf_hash(),
        ]);
    }

    public function downloadSkl(string $token)
    {
        $filePath = $this->graduationService->validateDownloadToken($token);
        if (!$filePath) throw \CodeIgniter\Exceptions\PageNotFoundException::forPageNotFound();
        return $this->response->download(WRITEPATH . $filePath, null);
    }

    public function getPublicGraduationStatus()
    {
        $statusData = $this->graduationService->getPublicGraduationStatus();
        return $this->response->setJSON($statusData);
    }

    public function getCsrfToken()
    {
        return $this->response->setJSON([
            'csrf_token' => csrf_hash()
        ]);
    }
}
