<?php

namespace App\Controllers;

use Core\Database;
use PDO;

class ValidasiKRSController
{
    private $db;

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

    public function index()
    {
        // Proses hapus massal jika ada
        if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['hapus_massal'])) {
            if (!empty($_POST['id_krs'])) {
                $ids = $_POST['id_krs'];
    
                // Buat placeholder dinamis (?, ?, ?)
                $placeholders = implode(',', array_fill(0, count($ids), '?'));
                $queryDelete = "DELETE FROM tb_krs WHERE id_krs IN ($placeholders)";
                $stmtDelete = $this->db->prepare($queryDelete);
    
                if ($stmtDelete->execute($ids)) {
                    $_SESSION['pesan'] = "Data berhasil dihapus!";
                } else {
                    $error = $stmtDelete->errorInfo();
                    $_SESSION['pesan'] = "Gagal menghapus data: " . $error[2];
                }
            } else {
                $_SESSION['pesan'] = "Tidak ada data yang dipilih!";
            }
    
            // Redirect untuk hindari resubmission
            header('Location: /dashboard/admin-validasi_krs');
            exit;
        }
    
        // Ambil data KRS ganda
        $query = "SELECT k.id_krs, m.nim, m.nama, k.kode_mk, k.tahun_akademik
                  FROM tb_krs k
                  JOIN tb_mahasiswa m ON k.nim = m.nim
                  WHERE (k.nim, k.kode_mk, k.tahun_akademik) IN (
                      SELECT nim, kode_mk, tahun_akademik
                      FROM tb_krs
                      GROUP BY nim, kode_mk, tahun_akademik
                      HAVING COUNT(*) > 1
                  )
                  ORDER BY m.nim, k.kode_mk, k.tahun_akademik";
        $stmt = $this->db->prepare($query);
        $stmt->execute();
        $duplicates = $stmt->fetchAll(PDO::FETCH_ASSOC);
    
        // Lempar ke view
        require_once __DIR__ . '/../Views/admin/validasi_krs.php';
    }

}
