<?php

namespace App\Controllers;

use App\Models\AkademikModel;
use App\Models\KelasModel;
use App\Models\MahasiswaModel;
use App\Models\MatkulModel;
use App\Models\KrsModel;
use App\Models\KhsModel;
use App\Models\SksModel;

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

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

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

        $nim = $_SESSION['user']['nim'] ?? null;
        if (!$nim) {
            die('NIM tidak ditemukan di session.');
        }

        $tokenAda = $this->model->cekTokenKrsSudahAda($nim, $this->model->getTahunAktif());

        if ($tokenAda) {
			
			$akademik = (new AkademikModel())->getAktif();
			$semester = (new KelasModel())->getSemesterAktif($nim);
			$datas = (new MahasiswaModel())->getProdi($nim);
				$prodi = $datas['id_prodi'] ?? null;
				$id_kurikulum = $datas['id_kurikulum'] ?? null;
			$matkul = (new MatkulModel())->getBySmtProdi($semester, $id_kurikulum, $prodi);
			$krs = (new KrsModel())->getKrsStatus($nim, $akademik);
		
            $dataKontrak = $this->model->getDataKontrakMataKuliah($nim);
            $this->view('mahasiswa/form_kontrak', [
			    'nim' => $nim,
				'tahun_akademik' => $akademik,
				'semester' => $semester,
				'nama_prodi' => $prodi,
				'matakuliah_list' => $matkul,
				'krs_mahasiswa' => $krs,
                'kontrak' => $dataKontrak,
                'token' => $tokenAda,
            ]);
        } else {
            $dataKrs = $this->model->getKrsByNim($nim);
            $this->view('mahasiswa/Krs', [
                'krs' => $dataKrs,
            ]);
        }
    }

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

        $nim = $_SESSION['user']['nim'] ?? null;
        $tokenInput = $_POST['token'] ?? null;

        if (!$tokenInput) {
            $_SESSION['error'] = "Token tidak boleh kosong.";
            header('Location: /dashboard/mahasiswa-krs');
            exit;
        }

        $tahunAktif = $this->model->getTahunAktif();
        if (!$tahunAktif) {
            $_SESSION['error'] = "Tahun akademik aktif tidak ditemukan.";
            header('Location: /dashboard/mahasiswa-krs');
            exit;
        }

        $tokenValid = $this->model->cekTokenDiTbToken($tokenInput);
        if (!$tokenValid) {
            $_SESSION['error'] = "Token yang anda masukkan tidak valid.";
            header('Location: /dashboard/mahasiswa-krs');
            exit;
        }

        $tokenSudahDipakai = $this->model->cekTokenKrsSudahAda($nim, $tahunAktif);
        if ($tokenSudahDipakai) {
            $_SESSION['error'] = "Anda sudah memasukkan token sebelumnya.";
            header('Location: /dashboard/mahasiswa-krs');
            exit;
        }

        $this->model->simpanTokenKrs($nim, $tokenInput, $tahunAktif);

        $_SESSION['success'] = "Token berhasil disimpan.";
        header('Location: /dashboard/mahasiswa-krs');
        exit;
    }

	public function submit()
	{
		$nim = $_SESSION['user']['nim'] ?? null;
		if (!$nim) return;

		$tahun = (new AkademikModel())->getAktif();
		$semester = (new KelasModel())->getSemesterAktif($nim);
		$kodeList = explode(',', $_POST['kode_mk_list'] ?? '');
		$totalSKS = intval($_POST['total_sks'] ?? 0);

		$krsModel = new KrsModel();
		$khsModel = new KhsModel();
		$sksModel = new SksModel();

		$jumlahBerhasil = 0;

		foreach ($kodeList as $kode) {
			$kode = trim($kode);
			if (!$kode) continue;

			if (!$krsModel->exists($nim, $kode, $tahun)) {
				$krsModel->insert([
					'nim' => $nim,
					'kode_mk' => $kode,
					'tahun_akademik' => $tahun,
					'accept' => 1
				]);

				$khsModel->insert([
					'nim' => $nim,
					'kode_mk' => $kode,
					'smt' => $semester,
					'nilai' => 0,
					'accept' => 1
				]);

				$jumlahBerhasil++;
			}
		}

		// Update jml_sks hanya jika ada MK baru yang berhasil dikontrak dan totalSKS > 0
		if ($jumlahBerhasil > 0 && $totalSKS > 0) {
			$sksModel->updateOrInsert($nim, $tahun, $totalSKS);
			$_SESSION['info'] = 'Proses Kontrak Mata Kuliah Berhasil Dilakukan';
			$_SESSION['info_type'] = 'success';
		} elseif ($jumlahBerhasil == 0) {
			$_SESSION['info'] = 'Seluruh Mata Kuliah Sudah Dikontrak';
			$_SESSION['info_type'] = 'info';
		} else {
			$_SESSION['info'] = 'Proses Kontrak Mata Kuliah Gagal Dilakukan';
			$_SESSION['info_type'] = 'error';
		}

		header('Location: /dashboard/mahasiswa-krs');
		exit;
	}

}
