<?php
require_once __DIR__ . '/includes/layout.php';
require_login();
require_roles(['Pengguna Biasa', 'Admin Audit', 'Pentadbir Sistem']);
require_department_access($conn, 'senarai_pengguna', 'update');

$userId = (int) ($_GET['id'] ?? 0);
if ($userId <= 0) {
    header('Location: senarai_pengguna.php');
    exit();
}

$bahagianList = audit_bahagian_list();
$currentManagerRole = current_user_role();
$allowedRoles = $currentManagerRole === 'Pentadbir Sistem'
    ? ['Pengguna Biasa', 'Admin Audit', 'Pentadbir Sistem']
    : ['Pengguna Biasa', 'Admin Audit'];

$stmt = $conn->prepare("
    SELECT id, nama, ic, emel, role, jabatan
    FROM users
    WHERE id = ?
    LIMIT 1
");
$stmt->bind_param('i', $userId);
$stmt->execute();
$selectedUser = $stmt->get_result()->fetch_assoc();

if (!$selectedUser) {
    header('Location: senarai_pengguna.php');
    exit();
}

if ($currentManagerRole === 'Admin Audit' && ($selectedUser['role'] ?? '') === 'Pentadbir Sistem') {
    header('Location: senarai_pengguna.php?error=protected_system_admin');
    exit();
}

add_current_user_log($conn, 'Membuka halaman edit pengguna ' . ($selectedUser['nama'] ?? 'Tidak Diketahui'));

$extraJs = <<<HTML
<script>
function togglePasswordVisibility(fieldId, icon) {
    const input = document.getElementById(fieldId);
    input.type = input.type === 'password' ? 'text' : 'password';
    icon.classList.toggle('fa-eye');
    icon.classList.toggle('fa-eye-slash');
}
</script>
HTML;

render_layout_start('Edit Pengguna - Dashboard Audit MAINPP');
?>
<?php if (isset($_GET['success']) && $_GET['success'] === 'updated'): ?>
    <div class="status-message status-success">Maklumat pengguna berjaya dikemaskini.</div>
<?php elseif (isset($_GET['success']) && $_GET['success'] === 'password_updated'): ?>
    <div class="status-message status-success">Kata laluan pengguna berjaya dikemaskini.</div>
<?php elseif (isset($_GET['error']) && $_GET['error'] === 'duplicate'): ?>
    <div class="status-message status-danger">Emel telah digunakan oleh pengguna lain.</div>
<?php elseif (isset($_GET['error']) && $_GET['error'] === 'invalid_role'): ?>
    <div class="status-message status-danger">Role yang dipilih tidak dibenarkan.</div>
<?php elseif (isset($_GET['error']) && $_GET['error'] === 'password_mismatch'): ?>
    <div class="status-message status-danger">Kata laluan baru tidak sepadan.</div>
<?php endif; ?>

<div class="content-card">
    <h3><i class="fa-solid fa-user-pen"></i> Edit Maklumat Pengguna</h3>
    <form action="proses_edit_pengguna.php" method="POST">
        <input type="hidden" name="action_type" value="profile">
        <input type="hidden" name="user_id" value="<?= (int) $selectedUser['id'] ?>">
        <div class="form-grid">
            <div class="full-width">
                <label for="nama">Nama</label>
                <input type="text" id="nama" name="nama" value="<?= htmlspecialchars($selectedUser['nama']) ?>" required>
            </div>
            <div>
                <label>No. Kad Pengenalan</label>
                <input type="text" value="<?= htmlspecialchars($selectedUser['ic']) ?>" readonly>
            </div>
            <div>
                <label for="emel">Emel</label>
                <input type="email" id="emel" name="emel" value="<?= htmlspecialchars($selectedUser['emel']) ?>" required>
            </div>
            <div>
                <label for="role">Role</label>
                <select id="role" name="role" required>
                    <?php foreach ($allowedRoles as $role): ?>
                        <option value="<?= htmlspecialchars($role) ?>" <?= $selectedUser['role'] === $role ? 'selected' : '' ?>><?= htmlspecialchars($role) ?></option>
                    <?php endforeach; ?>
                </select>
            </div>
            <div>
                <label for="jabatan">Bahagian / Unit</label>
                <select id="jabatan" name="jabatan" required>
                    <?php foreach ($bahagianList as $bahagian): ?>
                        <option value="<?= htmlspecialchars($bahagian) ?>" <?= $selectedUser['jabatan'] === $bahagian ? 'selected' : '' ?>><?= htmlspecialchars($bahagian) ?></option>
                    <?php endforeach; ?>
                </select>
            </div>
        </div>
        <div class="button-row">
            <button type="submit" class="primary-btn">Simpan Maklumat</button>
        </div>
    </form>
</div>

<div class="content-card">
    <h3><i class="fa-solid fa-key"></i> Keselamatan Akaun</h3>
    <form action="proses_edit_pengguna.php" method="POST">
        <input type="hidden" name="action_type" value="password">
        <input type="hidden" name="user_id" value="<?= (int) $selectedUser['id'] ?>">
        <div class="form-grid">
            <div>
                <label for="new_password">Kata Laluan Baru</label>
                <div class="password-container">
                    <input type="password" id="new_password" name="new_password" required>
                    <i class="fa-solid fa-eye-slash toggle-password" onclick="togglePasswordVisibility('new_password', this)"></i>
                </div>
            </div>
            <div>
                <label for="confirm_password">Sahkan Kata Laluan Baru</label>
                <div class="password-container">
                    <input type="password" id="confirm_password" name="confirm_password" required>
                    <i class="fa-solid fa-eye-slash toggle-password" onclick="togglePasswordVisibility('confirm_password', this)"></i>
                </div>
            </div>
        </div>
        <div class="button-row">
            <button type="submit" class="primary-btn">Kemaskini Kata Laluan</button>
        </div>
    </form>
</div>
<?php render_layout_end($extraJs); ?>
