<?php
$page_title = 'แก้ไขผู้ใช้';
require_once __DIR__ . '/../includes/functions.php';
requireAdmin();
require_once __DIR__ . '/../includes/header.php';

$id = intval($_GET['id'] ?? 0);
$user = getUser($id);
if (!$user) {
    echo '<div class="alert alert-danger">ไม่พบผู้ใช้</div>';
    require_once __DIR__ . '/../includes/footer.php';
    exit;
}

$curricula = getCurricula();
$error = '';
$message = '';

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $staff_code = trim($_POST['staff_code'] ?? '');
    $name = trim($_POST['name'] ?? '');
    $email = trim($_POST['email'] ?? '');
    $curriculum_id = !empty($_POST['curriculum_id']) ? intval($_POST['curriculum_id']) : null;
    $role = $_POST['role'] ?? 'advisor';
    $password = trim($_POST['password'] ?? '');

    if (empty($staff_code) || empty($name) || empty($email)) {
        $error = 'กรุณากรอกข้อมูลให้ครบถ้วน';
    } else {
        try {
            $db = getDB();
            $stmt = $db->prepare("SELECT COUNT(*) FROM users WHERE staff_code = ? AND id != ?");
            $stmt->execute([$staff_code, $id]);
            if ($stmt->fetchColumn() > 0) {
                $error = 'รหัสบุคลากรนี้มีผู้ใช้อื่นใช้อยู่แล้ว';
            } else {
                if (!empty($password)) {
                    $stmt = $db->prepare("UPDATE users SET staff_code=?, name=?, email=?, curriculum_id=?, role=?, password=? WHERE id=?");
                    $stmt->execute([$staff_code, $name, $email, $curriculum_id, $role, password_hash($password, PASSWORD_DEFAULT), $id]);
                } else {
                    $stmt = $db->prepare("UPDATE users SET staff_code=?, name=?, email=?, curriculum_id=?, role=? WHERE id=?");
                    $stmt->execute([$staff_code, $name, $email, $curriculum_id, $role, $id]);
                }
                $message = 'บันทึกการแก้ไขเรียบร้อย';
                $user = getUser($id);
            }
        } catch (PDOException $e) {
            $error = 'เกิดข้อผิดพลาด: ' . $e->getMessage();
        }
    }
}
?>
<h4 class="mb-3">แก้ไขผู้ใช้: <?= htmlspecialchars($user['name']) ?></h4>
<?php if ($error): ?><div class="alert alert-danger"><?= htmlspecialchars($error) ?></div><?php endif; ?>
<?php if ($message): ?><div class="alert alert-success"><?= htmlspecialchars($message) ?></div><?php endif; ?>
<div class="card">
    <div class="card-body">
        <form method="POST">
            <div class="mb-3">
                <label class="form-label">รหัสบุคลากร <span class="text-danger">*</span></label>
                <input type="text" name="staff_code" class="form-control" value="<?= htmlspecialchars($user['staff_code']) ?>" required>
            </div>
            <div class="mb-3">
                <label class="form-label">ชื่อ-สกุล <span class="text-danger">*</span></label>
                <input type="text" name="name" class="form-control" value="<?= htmlspecialchars($user['name']) ?>" required>
            </div>
            <div class="mb-3">
                <label class="form-label">อีเมล <span class="text-danger">*</span></label>
                <input type="email" name="email" class="form-control" value="<?= htmlspecialchars($user['email']) ?>" required>
            </div>
            <div class="mb-3">
                <label class="form-label">สาขาวิชา</label>
                <select name="curriculum_id" class="form-select">
                    <option value="">-- ไม่ระบุ --</option>
                    <?php foreach ($curricula as $c): ?>
                    <option value="<?= $c['id'] ?>" <?= $user['curriculum_id'] == $c['id'] ? 'selected' : '' ?>><?= htmlspecialchars($c['code']) ?> - <?= htmlspecialchars($c['name_th']) ?></option>
                    <?php endforeach; ?>
                </select>
            </div>
            <div class="mb-3">
                <label class="form-label">บทบาท</label>
                <select name="role" class="form-select">
                    <option value="advisor" <?= $user['role'] == 'advisor' ? 'selected' : '' ?>>อาจารย์ที่ปรึกษา</option>
                    <option value="admin" <?= $user['role'] == 'admin' ? 'selected' : '' ?>>ผู้ดูแลระบบ</option>
                </select>
            </div>
            <div class="mb-3">
                <label class="form-label">รหัสผ่านใหม่ <small class="text-muted">(เว้นว่างไว้ถ้าไม่ต้องการเปลี่ยน)</small></label>
                <input type="password" name="password" class="form-control">
            </div>
            <button type="submit" class="btn btn-primary"><i class="bi bi-save"></i> บันทึก</button>
            <a href="list.php" class="btn btn-secondary">ยกเลิก</a>
        </form>
    </div>
</div>
<?php require_once __DIR__ . '/../includes/footer.php'; ?>
