<?php
namespace App\Controllers;

use Core\Database;
use PDO;

class ManageKHSController
{
    private $db;

    public function __construct()
    {
        $this->db = Database::getConnection();
        try {
            $this->db->exec("SET NAMES 'utf8mb4'");
        } catch (\Exception $e) {}
    }

    public function index()
    {
        $limit = 15;
        $page = isset($_GET['page']) && (int)$_GET['page'] > 0 ? (int)$_GET['page'] : 1;
        $offset = ($page - 1) * $limit;
    
        $search = isset($_GET['search']) ? trim($_GET['search']) : '';
    
        $where = '';
        $params = [];
        if ($search !== '') {
            $where = "WHERE (
                CONVERT(t.nim USING utf8mb4) LIKE :search 
                OR CONVERT(m.nama USING utf8mb4) LIKE :search
                OR CONVERT(t.token USING utf8mb4) LIKE :search
            )";
            $params[':search'] = "%{$search}%";
        }
    
        // hitung total
        $sqlCount = "
            SELECT COUNT(*) AS total
            FROM tb_token_khs t
            INNER JOIN tb_mahasiswa m ON CONVERT(t.nim USING utf8mb4) = CONVERT(m.nim USING utf8mb4)
            $where
        ";
        $stmtCount = $this->db->prepare($sqlCount);
        $stmtCount->execute($params);
        $row = $stmtCount->fetch(PDO::FETCH_ASSOC);
        $totalRows = isset($row['total']) ? (int)$row['total'] : 0;
        $totalPages = $totalRows > 0 ? (int)ceil($totalRows / $limit) : 1;
    
        // ambil data
        $sql = "
            SELECT t.id_token_khs, t.token, t.nim, t.status, t.smt, m.nama
            FROM tb_token_khs t
            INNER JOIN tb_mahasiswa m ON CONVERT(t.nim USING utf8mb4) = CONVERT(m.nim USING utf8mb4)
            $where
            ORDER BY t.id_token_khs DESC
            LIMIT :limit OFFSET :offset
        ";
        $stmt = $this->db->prepare($sql);
    
        foreach ($params as $k => $v) {
            $stmt->bindValue($k, $v);
        }
        $stmt->bindValue(':limit', (int)$limit, PDO::PARAM_INT);
        $stmt->bindValue(':offset', (int)$offset, PDO::PARAM_INT);
    
        $stmt->execute();
        $data = $stmt->fetchAll(PDO::FETCH_ASSOC);
    
        require_once __DIR__ . '/../Views/admin/manage_khs.php';
    }

    public function update()
    {
        if ($_SERVER['REQUEST_METHOD'] === 'POST') {
            $id = $_POST['id_token_khs'] ?? null;
            $smt = $_POST['smt'] ?? null;
            $nim = $_POST['nim'] ?? null;

            if (!$id) {
                header("Location: /dashboard/admin-khs");
                exit;
            }

            $sql = "UPDATE tb_token_khs SET smt = :smt WHERE id_token_khs = :id";
            $stmt = $this->db->prepare($sql);
            $stmt->execute([':smt' => $smt, ':id' => $id]);

             header("Location: /dashboard/admin-khs?search=" . urlencode($nim));
            exit;
        }
    }

    public function delete()
    {
        if (isset($_GET['id'])) {
            $id = $_GET['id'];
            $sql = "DELETE FROM tb_token_khs WHERE id_token_khs = :id";
            $stmt = $this->db->prepare($sql);
            $stmt->execute([':id' => $id]);
        }

        header("Location: /dashboard/admin-khs");
        exit;
    }
}
