<?php

namespace App\Controllers;

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

class Krs extends BaseController
{
    protected KrsModel $krsModel;
    protected PesertaKelasModel $pesertaKelasModel;
    protected KelasPerkuliahanModel $kelasModel;
    protected TahunAkademikModel $taModel;
    protected MahasiswaModel $mahasiswaModel;

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

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

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

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

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

        $krs = $this->krsModel->getKrsMahasiswa($mahasiswa['id'], $ta['id']);
        
        // Get enrolled classes
        $pesertaKelas = [];
        $totalSks = 0;
        if ($krs) {
            $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();

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

        $data = [
            'title'        => 'Kartu Rencana Studi (KRS) | SIAKAD ITKA',
            'mahasiswa'    => $mahasiswa,
            'ta'           => $ta,
            'krs'          => $krs,
            'pesertaKelas' => $pesertaKelas,
            'totalSks'     => $totalSks,
        ];

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

    public function pilih_kelas()
    {
        $mahasiswa = $this->getActiveMahasiswa();
        $ta = $this->getActiveTa();
        
        if (!$mahasiswa || !$ta) return redirect()->to('/krs');

        $krs = $this->krsModel->getKrsMahasiswa($mahasiswa['id'], $ta['id']);
        
        // Check if KRS is locked
        if ($krs && in_array($krs['status'], ['Menunggu Persetujuan', 'Disetujui'])) {
            return redirect()->to('/krs')->with('error', 'KRS sedang diproses atau sudah disetujui, tidak bisa memilih kelas lagi.');
        }

        // Get enrolled classes to calculate current SKS
        $currentSks = 0;
        $enrolledKelasIds = [];
        if ($krs) {
            $pesertaKelas = $this->pesertaKelasModel->select('peserta_kelas.id_kelas_kuliah_pddikti, 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();

            foreach ($pesertaKelas as $pk) {
                $currentSks += (int) $pk['sks'];
                $enrolledKelasIds[] = $pk['id_kelas_kuliah_pddikti'];
            }
        }

        // Calculate expected semester for the student
        $angkatan = $mahasiswa['angkatan'] ?? '';
        $kodeTa = $ta['kode_ta'] ?? '';
        $expectedSemester = 1;
        if (strlen(trim($angkatan)) >= 4 && strlen(trim($kodeTa)) >= 5) {
            $tahunMasuk = (int) substr(trim($angkatan), 0, 4);
            $tahunTa = (int) substr(trim($kodeTa), 0, 4);
            $smtTa = (int) substr(trim($kodeTa), 4, 1);
            
            $expectedSemester = (($tahunTa - $tahunMasuk) * 2) + $smtTa;
            if ($expectedSemester < 1) $expectedSemester = 1;
        }

        // Find kurikulum mapping for this student's prodi and angkatan
        $pemetaanModel = new \App\Models\PemetaanKurikulumModel();
        $pemetaan = $pemetaanModel->where('prodi_id', $mahasiswa['prodi_id'])
                                  ->where('angkatan', trim($angkatan))
                                  ->first();
                                  
        if (!$pemetaan) {
            return redirect()->to('/krs')->with('error', 'Peringatan: Kurikulum untuk angkatan Anda belum diatur oleh admin. Tidak dapat mengisi KRS. Silakan hubungi bagian Akademik.');
        }
        $kurikulumId = $pemetaan['kurikulum_id'];

        $filterSemester = $this->request->getGet('semester');
        $filterProdi = $this->request->getGet('prodi_id');

        // Apply filters, default to expected semester and student's prodi
        $activeSemesterFilter = ($filterSemester !== null) ? $filterSemester : $expectedSemester;
        $activeProdiFilter = ($filterProdi !== null) ? $filterProdi : $mahasiswa['prodi_id'];

        $builder = $this->kelasModel->select('kelas_perkuliahan.*, mata_kuliah.semester')
            ->join('mata_kuliah', 'mata_kuliah.nama_mata_kuliah = kelas_perkuliahan.nama_mata_kuliah AND mata_kuliah.id_program_studi = kelas_perkuliahan.id_program_studi', 'left', false)
            ->where('kelas_perkuliahan.id_semester', $ta['id_semester_pddikti'] ?? $ta['kode_ta'])
            ->where('mata_kuliah.id_kurikulum', $kurikulumId);

        if ($activeSemesterFilter !== 'all' && $activeSemesterFilter !== '') {
            $builder->where('mata_kuliah.semester', $activeSemesterFilter);
        }
        if ($activeProdiFilter !== 'all' && $activeProdiFilter !== '') {
            $builder->where('kelas_perkuliahan.id_program_studi', $activeProdiFilter);
        }

        $availableKelas = $builder->findAll();

        $prodiModel = new \App\Models\ProgramStudiModel();
        $listProdi = $prodiModel->findAll();

        $data = [
            'title'                => 'Pilih Kelas KRS | SIAKAD ITKA',
            'mahasiswa'            => $mahasiswa,
            'ta'                   => $ta,
            'krs'                  => $krs,
            'availableKelas'       => $availableKelas,
            'enrolledKelasIds'     => $enrolledKelasIds,
            'currentSks'           => $currentSks,
            'maxSks'               => 24,
            'expectedSemester'     => $expectedSemester,
            'activeSemesterFilter' => $activeSemesterFilter,
            'activeProdiFilter'    => $activeProdiFilter,
            'listProdi'            => $listProdi,
        ];

        return view('krs/pilih_kelas', $data);
    }

    public function simpan()
    {
        $mahasiswa = $this->getActiveMahasiswa();
        $ta = $this->getActiveTa();
        
        if (!$mahasiswa || !$ta) return redirect()->to('/krs');

        $krs = $this->krsModel->getKrsMahasiswa($mahasiswa['id'], $ta['id']);
        
        if ($krs && in_array($krs['status'], ['Menunggu Persetujuan', 'Disetujui'])) {
            return redirect()->to('/krs')->with('error', 'KRS sedang diproses atau sudah disetujui.');
        }

        $selectedKelasIds = $this->request->getPost('kelas_ids');
        if (!is_array($selectedKelasIds)) {
            $selectedKelasIds = [];
        }

        // Calculate total SKS from selected classes
        $totalSks = 0;
        if (!empty($selectedKelasIds)) {
            $kelas = $this->kelasModel->whereIn('id_kelas_kuliah_pddikti', $selectedKelasIds)->findAll();
            foreach ($kelas as $k) {
                $totalSks += (int) $k['sks'];
            }
        }

        if ($totalSks > 24) {
            return redirect()->to('/krs/pilih-kelas')->with('error', 'Total SKS yang dipilih ('.$totalSks.') melebihi batas maksimal 24 SKS.');
        }

        // Create or get KRS
        if (!$krs) {
            $this->krsModel->insert([
                'mahasiswa_id'      => $mahasiswa['id'],
                'tahun_akademik_id' => $ta['id'],
                'status'            => 'Draft',
            ]);
            $krsId = $this->krsModel->getInsertID();
        } else {
            $krsId = $krs['id'];
            // If it was rejected, reset to draft upon edit
            if ($krs['status'] == 'Ditolak') {
                $this->krsModel->update($krsId, ['status' => 'Draft', 'catatan' => null]);
            }
        }

        // Remove old classes for this KRS that are not in selected
        if ($krs) {
            $this->pesertaKelasModel->where('krs_id', $krsId)->delete();
        }

        // Insert new selected classes
        if (!empty($selectedKelasIds)) {
            $insertData = [];
            foreach ($selectedKelasIds as $kelasId) {
                $insertData[] = [
                    'krs_id'                  => $krsId,
                    'id_kelas_kuliah_pddikti' => $kelasId,
                    'id_mahasiswa_pddikti'    => $mahasiswa['id_mahasiswa_pddikti'],
                    'nim'                     => $mahasiswa['nim'],
                    'nama_mahasiswa'          => $mahasiswa['nama_lengkap'],
                ];
            }
            $this->pesertaKelasModel->insertBatch($insertData);
        }

        return redirect()->to('/krs')->with('success', 'KRS berhasil disimpan sebagai Draft.');
    }

    public function ajukan()
    {
        $mahasiswa = $this->getActiveMahasiswa();
        $ta = $this->getActiveTa();
        
        if (!$mahasiswa || !$ta) return redirect()->to('/krs');

        $krs = $this->krsModel->getKrsMahasiswa($mahasiswa['id'], $ta['id']);
        if (!$krs) return redirect()->to('/krs');

        // Check if no classes
        $pesertaCount = $this->pesertaKelasModel->where('krs_id', $krs['id'])->countAllResults();
        if ($pesertaCount == 0) {
            return redirect()->to('/krs')->with('error', 'Anda belum memilih mata kuliah apa pun.');
        }

        $this->krsModel->update($krs['id'], ['status' => 'Menunggu Persetujuan']);
        
        return redirect()->to('/krs')->with('success', 'KRS berhasil diajukan ke Dosen PA.');
    }

    public function hapus_kelas(string $pesertaKelasId)
    {
        $mahasiswa = $this->getActiveMahasiswa();
        if (!$mahasiswa) return redirect()->to('/krs');

        $peserta = $this->pesertaKelasModel->find($pesertaKelasId);
        if (!$peserta) return redirect()->to('/krs');

        $krs = $this->krsModel->find($peserta['krs_id']);
        if ($krs['mahasiswa_id'] != $mahasiswa['id']) return redirect()->to('/krs');

        if (in_array($krs['status'], ['Menunggu Persetujuan', 'Disetujui'])) {
            return redirect()->to('/krs')->with('error', 'KRS sedang diproses atau sudah disetujui.');
        }

        $this->pesertaKelasModel->delete($pesertaKelasId);
        
        // Reset status to draft if ditolak
        if ($krs['status'] == 'Ditolak') {
            $this->krsModel->update($krs['id'], ['status' => 'Draft']);
        }

        return redirect()->to('/krs')->with('success', 'Mata kuliah berhasil dihapus dari KRS.');
    }
}
