<?php
namespace App\Controllers;

use Core\Database;
use PDO;

class ManagePegSkripsiController
{
    private $db;

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

    public function index()
    {
        $perPage = 15;
        $page = isset($_GET['page']) && is_numeric($_GET['page']) ? (int) $_GET['page'] : 1;
        $offset = ($page - 1) * $perPage;

        $search = isset($_GET['search']) ? trim($_GET['search']) : '';
        $query = "SELECT * FROM tb_sidang_skripsi";
        $params = [];

        if ($search) {
            $query .= " WHERE nim LIKE :search OR nama LIKE :search";
            $params['search'] = "%$search%";
        }

        $stmtTotal = $this->db->prepare(str_replace('*', 'COUNT(*)', $query));
        $stmtTotal->execute($params);
        $totalData = $stmtTotal->fetchColumn();
        $totalPages = ceil($totalData / $perPage);

        $query .= " ORDER BY tanggal_daftar DESC LIMIT :offset, :perPage";
        $stmt = $this->db->prepare($query);

        foreach ($params as $k => $v) {
            $stmt->bindValue(":$k", $v);
        }
        $stmt->bindValue(':offset', $offset, PDO::PARAM_INT);
        $stmt->bindValue(':perPage', $perPage, PDO::PARAM_INT);

        $stmt->execute();
        $data_skripsi = $stmt->fetchAll(PDO::FETCH_ASSOC);

        include __DIR__ . '/../Views/pegawai/data_skripsi.php';
    }
}
