<?php

namespace App\Controllers;

use App\Models\Khs;

class KhsController extends \Core\Controller
{
    protected $model;

    public function __construct()
    {
        $this->model = new Khs();
    }

    // Tampilkan daftar semester
    public function index()
    {
        if (!isset($_SESSION['user'])) {
            header('Location: /login');
            exit;
        }

        $nim = $_SESSION['user']['nim'] ?? null;
        $semesters = $this->model->getAvailableSemesters($nim);

        $this->view('mahasiswa/Khs', [
            'nim' => $nim,
            'semesters' => $semesters
        ]);
    }

    // Tampilkan detail semester atau form token
    public function detail()
    {
        if (!isset($_SESSION['user'])) {
            header('Location: /login');
            exit;
        }

        $nim = $_SESSION['user']['nim'] ?? null;
        $smt = $_GET['smt'] ?? null;
        $error = null;

        if (!$smt) {
            die('Semester tidak dipilih.');
        }

        $tokenUsed = $this->model->isTokenUsed($nim, $smt);

        // Jika token belum digunakan dan form token dikirim
        if (!$tokenUsed && isset($_POST['kirim_token'])) {
            $token = trim($_POST['token']);

            if ($this->model->isValidToken($token)) {
                $this->model->markTokenAsUsed($nim, $smt, $token);
                $tokenUsed = true;
            } else {
                $error = "Token tidak valid atau sudah digunakan.";
            }
        }

        $khs = $tokenUsed ? $this->model->getKhsByNimAndSemester($nim, $smt) : [];

        $this->view('mahasiswa/KhsDetail', [
            'nim' => $nim,
            'smt' => $smt,
            'tokenUsed' => $tokenUsed,
            'khs' => $khs,
            'error' => $error
        ]);
    }

public function detailNilai()
{
    $kode_mk = $_GET['kode_mk'] ?? '';
    $nim = $_GET['nim'] ?? '';
    $smt = $_GET['smt'] ?? '';
    $id_krs = $_GET['id_krs'] ?? '';

    $khsModel = new \App\Models\Khs();

    $nilai_uts = $khsModel->getNilaiUjian($kode_mk, $nim, 1); // 1 = UTS
    $nilai_uas = $khsModel->getNilaiUjian($kode_mk, $nim, 2); // 2 = UAS
    $nilai_tugas = $khsModel->getNilaiTugas($kode_mk, $nim);
    $nilai_presensi = $khsModel->getNilaiPresensi($kode_mk, $id_krs);

    $data = compact(
        'kode_mk', 'nim', 'smt',
        'nilai_uts', 'nilai_uas', 'nilai_tugas', 'nilai_presensi'
    );

    extract($data);
    require __DIR__ . '/../Views/mahasiswa/detailnilai.php';
}


}
