<?php
$page_title = 'จัดการผู้ใช้';
require_once __DIR__ . '/../includes/functions.php';
requireAdmin();
require_once __DIR__ . '/../includes/header.php';

$db = getDB();
$users = $db->query("SELECT u.*, c.name_th AS curriculum_name FROM users u LEFT JOIN curricula c ON u.curriculum_id = c.id ORDER BY u.staff_code")->fetchAll();

if (isset($_GET['deleted'])): ?>
<div class="alert alert-success alert-dismissible fade show">ลบผู้ใช้เรียบร้อยแล้ว<button type="button" class="btn-close" data-bs-dismiss="alert"></button></div>
<?php endif; ?>

<div class="page-heading">
    <div>
        <h4>จัดการผู้ใช้</h4>
        <div class="text-muted small">ทั้งหมด <?= count($users) ?> บัญชี</div>
    </div>
    <a href="add.php" class="btn btn-primary"><i class="bi bi-plus-lg"></i> เพิ่มผู้ใช้</a>
</div>

<div class="card">
    <div class="card-body p-0">
        <div class="table-responsive">
        <table class="table table-striped mb-0">
            <thead>
                <tr>
                    <th>รหัสบุคลากร</th>
                    <th>ชื่อ-สกุล</th>
                    <th>อีเมล</th>
                    <th>สาขาวิชา</th>
                    <th>บทบาท</th>
                    <th style="width:140px">จัดการ</th>
                </tr>
            </thead>
            <tbody>
                <?php foreach ($users as $u): ?>
                <tr>
                    <td><?= htmlspecialchars($u['staff_code']) ?></td>
                    <td><?= htmlspecialchars($u['name']) ?></td>
                    <td><?= htmlspecialchars($u['email']) ?></td>
                    <td><?= htmlspecialchars($u['curriculum_name'] ?? '-') ?></td>
                    <td><?= $u['role'] == 'admin' ? 'ผู้ดูแลระบบ' : 'อาจารย์ที่ปรึกษา' ?></td>
                    <td>
                        <div class="action-buttons">
                        <a href="edit.php?id=<?= $u['id'] ?>" class="btn btn-sm btn-warning"><i class="bi bi-pencil"></i></a>
                        <a href="delete.php?id=<?= $u['id'] ?>" class="btn btn-sm btn-danger" onclick="return confirm('ยืนยันลบผู้ใช้ <?= htmlspecialchars($u['name']) ?>?')"><i class="bi bi-trash"></i></a>
                        </div>
                    </td>
                </tr>
                <?php endforeach; ?>
            </tbody>
        </table>
        </div>
    </div>
</div>

<?php require_once __DIR__ . '/../includes/footer.php'; ?>
