<?php

namespace App\Controllers;

use Core\Database;
use PDO;

class ValidasiKHSController
{
    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_khs'])) {
                $ids = $_POST['id_khs'];
                $placeholders = implode(',', array_fill(0, count($ids), '?'));
                $queryDelete = "DELETE FROM tb_khs WHERE id_khs 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!";
            }

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

        // Ambil data KHS ganda
        $query = "SELECT k.id_khs, m.nim, m.nama, k.kode_mk, k.smt, k.nilai
                  FROM tb_khs k
                  JOIN tb_mahasiswa m ON k.nim = m.nim
                  WHERE (k.nim, k.kode_mk) IN (
                      SELECT nim, kode_mk
                      FROM tb_khs
                      GROUP BY nim, kode_mk
                      HAVING COUNT(*) > 1
                  )
                  ORDER BY m.nim, k.kode_mk, k.smt";
        $stmt = $this->db->prepare($query);
        $stmt->execute();
        $duplicates = $stmt->fetchAll(PDO::FETCH_ASSOC);

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