<?php
namespace App\Controllers;

use Core\Database;
use PDO;

class ManagePegKKNController
{
    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']) : '';
        $param = [];
        $sqlWhere = '';
    
        if ($search !== '') {
            $sqlWhere = "WHERE nim LIKE :search OR nama LIKE :search";
            $param[':search'] = "%$search%";
        }
    
        // Hitung total data (untuk paginasi)
        $stmtTotal = $this->db->prepare("SELECT COUNT(*) FROM tb_kkn $sqlWhere");
        $stmtTotal->execute($param);
        $totalData = $stmtTotal->fetchColumn();
        $totalPages = ceil($totalData / $perPage);
    
        // Ambil data sesuai halaman
        $stmt = $this->db->prepare("SELECT * FROM tb_kkn $sqlWhere ORDER BY tanggal_daftar DESC LIMIT :offset, :perPage");
    
        // Bind semua parameter search jika ada
        foreach ($param as $key => $val) {
            $stmt->bindValue($key, $val, PDO::PARAM_STR);
        }
    
        $stmt->bindValue(':offset', $offset, PDO::PARAM_INT);
        $stmt->bindValue(':perPage', $perPage, PDO::PARAM_INT);
        $stmt->execute();
    
        $data_kkn = $stmt->fetchAll(PDO::FETCH_ASSOC);
    
        // Untuk view pagination dan search
        include __DIR__ . '/../Views/pegawai/data_kkn.php';
    }

    public function update($data)
    {
        $sql = "UPDATE tb_kkn SET 
                    nim = :nim,
                    nama = :nama,
                    tmpt_lahir = :tmpt_lahir,
                    tgl_lahir = :tgl_lahir,
                    prodi = :prodi,
                    semester = :semester,
                    jenis_kelamin = :jenis_kelamin,
                    no_hp = :no_hp,
                    alamat = :alamat,
                    status_perkawinan = :status_perkawinan,
                    status_pekerjaan = :status_pekerjaan,
                    token = :token
                WHERE id_kkn = :id_kkn";
        $stmt = $this->db->prepare($sql);
        return $stmt->execute($data);
    }

    public function destroy($id_kkn)
    {
        $stmt = $this->db->prepare("DELETE FROM tb_kkn WHERE id_kkn = :id");
        $stmt->bindParam(':id', $id_kkn, PDO::PARAM_INT);
        return $stmt->execute();
    }
}
