<?php
namespace App\Controllers;

use Core\Database;
use PDO;

class ManageKRSController
{
    private $db;

    public function __construct()
    {
        $this->db = Database::getConnection();
    }

    // Halaman utama
    public function index()
    {
        // -------------------------
        // Mahasiswa (atas)
        // -------------------------
        $searchUser = $_GET['search_user'] ?? '';
        $pageUser = isset($_GET['page_user']) ? max(1, (int)$_GET['page_user']) : 1;
        $limitUser = 15;
        $offsetUser = ($pageUser - 1) * $limitUser;

        $sqlUser = "SELECT u.id_user, u.username, m.nim, m.nisn, m.nama, m.pusat_pokjar 
                    FROM tb_user u 
                    INNER JOIN tb_mahasiswa m ON u.username = m.nim
                    WHERE m.nim = m.nisn 
                    AND (u.username LIKE :search OR m.nama LIKE :search)
                    LIMIT :offset, :limit";
        $stmtUser = $this->db->prepare($sqlUser);
        $stmtUser->bindValue(':search', "%$searchUser%", PDO::PARAM_STR);
        $stmtUser->bindValue(':offset', $offsetUser, PDO::PARAM_INT);
        $stmtUser->bindValue(':limit', $limitUser, PDO::PARAM_INT);
        $stmtUser->execute();
        $users = $stmtUser->fetchAll(PDO::FETCH_ASSOC);

        $countUser = "SELECT COUNT(*) as total 
                      FROM tb_user u 
                      INNER JOIN tb_mahasiswa m ON u.username = m.nim
                      WHERE m.nim = m.nisn 
                      AND (u.username LIKE :search OR m.nama LIKE :search)";
        $stmtCountUser = $this->db->prepare($countUser);
        $stmtCountUser->bindValue(':search', "%$searchUser%", PDO::PARAM_STR);
        $stmtCountUser->execute();
        $totalUsers = (int)$stmtCountUser->fetch(PDO::FETCH_ASSOC)['total'];
        $totalPagesUser = max(1, (int)ceil($totalUsers / $limitUser));

        // -------------------------
        // Kelas (bawah)
        // -------------------------
        $searchKelas = $_GET['search_kelas'] ?? '';
        $pageKelas = isset($_GET['page_kelas']) ? max(1, (int)$_GET['page_kelas']) : 1;
        $limitKelas = 15;
        $offsetKelas = ($pageKelas - 1) * $limitKelas;

        $sqlKelas = "SELECT * FROM tb_kelas 
                     WHERE (kode_kelas LIKE :search OR nim LIKE :search) 
                     ORDER BY id_kelas DESC 
                     LIMIT :offset, :limit";
        $stmtKelas = $this->db->prepare($sqlKelas);
        $stmtKelas->bindValue(':search', "%$searchKelas%", PDO::PARAM_STR);
        $stmtKelas->bindValue(':offset', $offsetKelas, PDO::PARAM_INT);
        $stmtKelas->bindValue(':limit', $limitKelas, PDO::PARAM_INT);
        $stmtKelas->execute();
        $kelas = $stmtKelas->fetchAll(PDO::FETCH_ASSOC);

        $countKelas = "SELECT COUNT(*) as total FROM tb_kelas 
                       WHERE (kode_kelas LIKE :search OR nim LIKE :search)";
        $stmtCountKelas = $this->db->prepare($countKelas);
        $stmtCountKelas->bindValue(':search', "%$searchKelas%", PDO::PARAM_STR);
        $stmtCountKelas->execute();
        $totalKelas = (int)$stmtCountKelas->fetch(PDO::FETCH_ASSOC)['total'];
        $totalPagesKelas = max(1, (int)ceil($totalKelas / $limitKelas));

        // -------------------------
        // Tahun akademik (untuk select dalam modal tambah kelas)
        // Ambil dari tb_akademik jika ada; kalau tidak ada nanti view fallback ke input text.
        // -------------------------
        $tahun_akademik = [];
        try {
            $stmtTA = $this->db->query("SELECT tahun_akademik FROM tb_akademik ORDER BY tahun_akademik DESC");
            $tahun_akademik = $stmtTA->fetchAll(PDO::FETCH_ASSOC);
        } catch (\Throwable $e) {
            // jika tabel tb_akademik tidak ada/eror, jangan pecah halaman — biarkan kosong
            $tahun_akademik = [];
        }

        // Variabel yang akan dipakai di view: $users, $totalPagesUser, $pageUser, $searchUser
        // dan $kelas, $totalPagesKelas, $pageKelas, $searchKelas, $tahun_akademik

        require_once __DIR__ . '/../Views/admin/manage_angkatan.php';
    }

    // Insert Kelas
    public function insertKelas()
    {
        $kode_kelas = $_POST['kode_kelas'] ?? '';
        $nim = $_POST['nim'] ?? '';
        $smt = $_POST['smt'] ?? '';
        $tahun_akademik = $_POST['tahun_akademik'] ?? '';
        $status = $_POST['status'] ?? 'Aktif';

        $sql = "INSERT INTO tb_kelas (kode_kelas, nim, smt, tahun_akademik, status) 
                VALUES (:kode_kelas, :nim, :smt, :tahun_akademik, :status)";
        $stmt = $this->db->prepare($sql);
        $stmt->execute([
            ':kode_kelas' => $kode_kelas,
            ':nim' => $nim,
            ':smt' => $smt,
            ':tahun_akademik' => $tahun_akademik,
            ':status' => $status
        ]);

        header('Location: /dashboard/admin-mbr');
        exit;
    }

    // Update User Mahasiswa (dari modal)
    public function updateUser()
    {
        $id_user   = $_POST['id_user'] ?? null;
        $username  = $_POST['username'] ?? null; // nim baru
        $level     = $_POST['level'] ?? 'Mahasiswa';
        $passwordRaw = $_POST['password'] ?? ''; // di form default "mahasiswa"
        $nim_lama  = $_POST['nim_lama'] ?? null; // nim lama (hidden di form supaya tau yang lama)
    
        if (!$id_user || !$username) {
            header('Location: /dashboard/admin-mbr');
            exit;
        }
    
        // password md5 hanya jika dikirim (tidak kosong)
        $passwordHash = $passwordRaw !== '' ? md5($passwordRaw) : null;
    
        // update tb_user
        if ($passwordHash !== null) {
            $sql = "UPDATE tb_user 
                    SET username = :username, level = :level, password = :password 
                    WHERE id_user = :id_user";
            $stmt = $this->db->prepare($sql);
            $stmt->execute([
                ':username' => $username,
                ':level' => $level,
                ':password' => $passwordHash,
                ':id_user' => $id_user
            ]);
        } else {
            $sql = "UPDATE tb_user 
                    SET username = :username, level = :level 
                    WHERE id_user = :id_user";
            $stmt = $this->db->prepare($sql);
            $stmt->execute([
                ':username' => $username,
                ':level' => $level,
                ':id_user' => $id_user
            ]);
        }
    
        // update nim di tb_mahasiswa (supaya sinkron)
        if ($nim_lama !== null) {
            $sql = "UPDATE tb_mahasiswa SET nim = :nim_baru WHERE nim = :nim_lama";
            $stmt = $this->db->prepare($sql);
            $stmt->execute([
                ':nim_baru' => $username,
                ':nim_lama' => $nim_lama
            ]);
        }
    
        header('Location: /dashboard/admin-mbr');
        exit;
    }

    // Delete Kelas
    public function deleteKelas($id_kelas)
    {
        $sql = "DELETE FROM tb_kelas WHERE id_kelas = :id_kelas";
        $stmt = $this->db->prepare($sql);
        $stmt->execute([':id_kelas' => $id_kelas]);
        header('Location: /dashboard/admin-mbr');
        exit;
    }

    // Delete User (dari tombol trash pada mahasiswa)
    public function deleteUser($id_user)
    {
        // hanya hapus dari tb_user (tidak otomatis hapus tb_mahasiswa)
        $sql = "DELETE FROM tb_user WHERE id_user = :id_user";
        $stmt = $this->db->prepare($sql);
        $stmt->execute([':id_user' => $id_user]);
        header('Location: /dashboard/admin-mbr');
        exit;
    }
}
