<?php

namespace App\Controllers;

use App\Models\KrsModel;
use App\Models\PesertaKelasModel;
use App\Models\TahunAkademikModel;
use App\Models\MahasiswaModel;
use App\Models\DosenModel;

class PersetujuanKrs extends BaseController
{
    protected KrsModel $krsModel;
    protected PesertaKelasModel $pesertaKelasModel;
    protected TahunAkademikModel $taModel;
    protected MahasiswaModel $mahasiswaModel;
    protected DosenModel $dosenModel;

    public function __construct()
    {
        $this->krsModel = new KrsModel();
        $this->pesertaKelasModel = new PesertaKelasModel();
        $this->taModel = new TahunAkademikModel();
        $this->mahasiswaModel = new MahasiswaModel();
        $this->dosenModel = new DosenModel();
    }

    private function getActiveDosen()
    {
        $userId = session()->get('id');
        if (!$userId) return null;
        return $this->dosenModel->where('user_id', $userId)->first();
    }

    private function getActiveTa()
    {
        return $this->taModel->where('status', 'Aktif')->first();
    }

    public function index()
    {
        $dosen = $this->getActiveDosen();
        if (!$dosen) {
            return redirect()->to('/')->with('error', 'Data dosen tidak ditemukan (Pastikan Anda login sebagai Dosen PA).');
        }

        $ta = $this->getActiveTa();
        if (!$ta) {
            return redirect()->to('/')->with('error', 'Tidak ada semester aktif.');
        }

        // Get students supervised by this Dosen PA
        // and their KRS for the active semester
        $krsList = $this->krsModel->select('krs.*, mahasiswa.nim, mahasiswa.nama_lengkap, program_studi.nama_prodi')
            ->join('mahasiswa', 'mahasiswa.id = krs.mahasiswa_id')
            ->join('program_studi', 'program_studi.id = mahasiswa.prodi_id', 'left')
            ->where('mahasiswa.dosen_pa_id', $dosen['id'])
            ->where('krs.tahun_akademik_id', $ta['id'])
            ->whereIn('krs.status', ['Menunggu Persetujuan', 'Disetujui', 'Ditolak'])
            ->orderBy('krs.updated_at', 'DESC')
            ->findAll();

        $data = [
            'title'   => 'Persetujuan KRS | SIAKAD ITKA',
            'ta'      => $ta,
            'krsList' => $krsList
        ];

        return view('persetujuan_krs/index', $data);
    }

    public function detail(string $id)
    {
        $dosen = $this->getActiveDosen();
        if (!$dosen) return redirect()->to('/persetujuan-krs');

        $krs = $this->krsModel->select('krs.*, mahasiswa.nim, mahasiswa.nama_lengkap, mahasiswa.dosen_pa_id, program_studi.nama_prodi')
            ->join('mahasiswa', 'mahasiswa.id = krs.mahasiswa_id')
            ->join('program_studi', 'program_studi.id = mahasiswa.prodi_id', 'left')
            ->where('krs.id', $id)
            ->first();

        if (!$krs || $krs['dosen_pa_id'] != $dosen['id']) {
            return redirect()->to('/persetujuan-krs')->with('error', 'KRS tidak ditemukan atau Anda bukan Dosen PA mahasiswa ini.');
        }

        $pesertaKelas = $this->pesertaKelasModel->select('peserta_kelas.*, kelas_perkuliahan.nama_mata_kuliah, kelas_perkuliahan.nama_kelas_kuliah, kelas_perkuliahan.sks')
            ->join('kelas_perkuliahan', 'kelas_perkuliahan.id_kelas_kuliah_pddikti = peserta_kelas.id_kelas_kuliah_pddikti', 'left')
            ->where('peserta_kelas.krs_id', $krs['id'])
            ->findAll();

        $totalSks = 0;
        foreach ($pesertaKelas as $pk) {
            $totalSks += (int) $pk['sks'];
        }

        $data = [
            'title'        => 'Detail Persetujuan KRS | SIAKAD ITKA',
            'krs'          => $krs,
            'pesertaKelas' => $pesertaKelas,
            'totalSks'     => $totalSks
        ];

        return view('persetujuan_krs/detail', $data);
    }

    public function proses(string $id)
    {
        $dosen = $this->getActiveDosen();
        if (!$dosen) return redirect()->to('/persetujuan-krs');

        $krs = $this->krsModel->select('krs.*, mahasiswa.dosen_pa_id')
            ->join('mahasiswa', 'mahasiswa.id = krs.mahasiswa_id')
            ->where('krs.id', $id)
            ->first();

        if (!$krs || $krs['dosen_pa_id'] != $dosen['id']) {
            return redirect()->to('/persetujuan-krs')->with('error', 'KRS tidak valid.');
        }

        $action = $this->request->getPost('action');
        $catatan = $this->request->getPost('catatan');

        $status = ($action == 'setujui') ? 'Disetujui' : 'Ditolak';

        $this->krsModel->update($id, [
            'status'  => $status,
            'catatan' => $catatan
        ]);

        return redirect()->to('/persetujuan-krs/detail/' . $id)->with('success', 'KRS berhasil ' . strtolower($status));
    }
}
