<?php

namespace App\Controllers;

use Core\Controller;
use Core\Database;

class DataPegGelMhsController extends Controller
{
    public function __construct()
    {
        // Cek login
        if (!isset($_SESSION['user'])) {
            header('Location: /login');
            exit;
        }
    }

    public function index()
    {
        // === Koneksi DB ===
        try {
            $db = Database::getConnection();
        } catch (\PDOException $e) {
            die("Koneksi database gagal: " . $e->getMessage());
        }

        // === Tangani POST Update Gelombang & Tanggal ===
        if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['id'], $_POST['gelombang'], $_POST['tanggal'])) {
            $id        = $_POST['id'];
            $gelombang = $_POST['gelombang'];
            $tanggal   = $_POST['tanggal'];

            $stmt = $db->prepare("UPDATE tb_pmb SET gelombang = :gelombang, tanggal = :tanggal WHERE id_pmb = :id");
            $updated = $stmt->execute([
                ':gelombang' => $gelombang,
                ':tanggal'   => $tanggal,
                ':id'        => $id
            ]);

            if ($updated) {
                $_SESSION['pesan'] = "Data gelombang dan tanggal berhasil diperbarui!";
                $_SESSION['status_alert'] = "success";
            } else {
                $_SESSION['pesan'] = "Gagal memperbarui data.";
                $_SESSION['status_alert'] = "danger";
            }

            header("Location: /dashboard/pegawai-ubah_gel_mhs");
            exit;
        }

        // === Ambil Data List Mahasiswa + Paging & Search ===
        $search = $_GET['search'] ?? '';
        $page   = isset($_GET['page_no']) && is_numeric($_GET['page_no']) ? (int)$_GET['page_no'] : 1;
        $limit  = 25;
        $offset = ($page - 1) * $limit;

        $params = [];
        $where = '';

        if (!empty($search)) {
            // ✅ Sesuaikan kolom dengan tabel sebenarnya
            $where = "WHERE nama_camaba LIKE :search OR nisn LIKE :search";
            $params[':search'] = "%$search%";
        }

        // Hitung total baris
        $sqlCount = "SELECT COUNT(*) FROM tb_pmb $where";
        $stmtCount = $db->prepare($sqlCount);
        $stmtCount->execute($params);
        $totalRows = $stmtCount->fetchColumn();
        $totalPages = ceil($totalRows / $limit);

        // Ambil data mahasiswa
        $sqlData = "SELECT * FROM tb_pmb $where ORDER BY id_pmb DESC LIMIT :limit OFFSET :offset";
        $stmtData = $db->prepare($sqlData);

        if (!empty($search)) {
            $stmtData->bindValue(':search', "%$search%", \PDO::PARAM_STR);
        }
        $stmtData->bindValue(':limit', $limit, \PDO::PARAM_INT);
        $stmtData->bindValue(':offset', $offset, \PDO::PARAM_INT);
        $stmtData->execute();

        $data = $stmtData->fetchAll(\PDO::FETCH_ASSOC);

        // === Tampilkan ke View ===
        $this->view('pegawai/pegawai_gel_pmb', [
            'data_pmb' => $data,            // ✅ sudah cocok dengan view
            'search' => $search,
            'page_no' => $page,
            'totalPages' => $totalPages,
            'offset' => $offset,
            'pesan' => $_SESSION['pesan'] ?? '',
            'status_alert' => $_SESSION['status_alert'] ?? '',
        ]);

        // Reset pesan session
        unset($_SESSION['pesan'], $_SESSION['status_alert']);
    }
}
