<?php

namespace App\Controllers;

use Core\Database;
use PDO;

class PWMahasiswaController
{
    private $db;

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

    public function index()
    {
        $recordsPerPage = 10;
        $currentPage = isset($_GET['page']) && is_numeric($_GET['page']) ? (int)$_GET['page'] : 1;
        $search = isset($_GET['search']) ? $_GET['search'] : '';

        $where = "WHERE level = 'Mahasiswa'";
        $params = [];

        if (!empty($search)) {
            $where .= " AND (nama LIKE :search OR username LIKE :search)";
            $params[':search'] = '%' . $search . '%';
        }

        $offset = ($currentPage - 1) * $recordsPerPage;

        $sql = "SELECT * FROM tb_user $where LIMIT :offset, :recordsPerPage";
        $stmt = $this->db->prepare($sql);
        foreach ($params as $key => $val) {
            $stmt->bindValue($key, $val);
        }
        $stmt->bindValue(':offset', $offset, PDO::PARAM_INT);
        $stmt->bindValue(':recordsPerPage', $recordsPerPage, PDO::PARAM_INT);
        $stmt->execute();
        $mahasiswas = $stmt->fetchAll(PDO::FETCH_ASSOC);

        $countSql = "SELECT COUNT(*) AS total FROM tb_user $where";
        $countStmt = $this->db->prepare($countSql);
        foreach ($params as $key => $val) {
            $countStmt->bindValue($key, $val);
        }
        $countStmt->execute();
        $total = $countStmt->fetch(PDO::FETCH_ASSOC)['total'];

        $totalPages = ceil($total / $recordsPerPage);
        $maxPagesToShow = 5;
        $startPage = max(1, $currentPage - floor($maxPagesToShow / 2));
        $endPage = min($totalPages, $startPage + $maxPagesToShow - 1);

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

    public function updatePassword()
    {
        if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['id_user'], $_POST['password'])) {
            $id_user = $_POST['id_user'];
            $password = md5($_POST['password']);

            $sql = "UPDATE tb_user SET password = :password WHERE id_user = :id_user";
            $stmt = $this->db->prepare($sql);
            $stmt->bindParam(':password', $password);
            $stmt->bindParam(':id_user', $id_user);
            $stmt->execute();

            $_SESSION['pesan'] = "Password berhasil direset.";
            header("Location: /dashboard/admin-ubah_pw_mahasiswa");
            exit;
        }
    }
}
