<?php
// manajemen_user.php (Hanya bisa diakses oleh Admin)
include_once 'header.php'; // Menggunakan header seragam

// Cek hak akses admin (Perlindungan ini harus tetap ada)
if ($_SESSION['is_admin'] == 0) {
    header("Location: dashboard.php");
    exit();
}

// Inisialisasi pesan
if (!isset($_SESSION['msg'])) {
    $_SESSION['msg'] = ['type' => '', 'text' => ''];
}


// --- FUNGSI CREATE (Tambah User Baru) ---
if (isset($_POST['add_user'])) {
    $username = $conn->real_escape_string($_POST['username']);
    $password = password_hash($_POST['password'], PASSWORD_DEFAULT);
    $nama_lengkap = $conn->real_escape_string($_POST['nama_lengkap']);
    $is_admin = isset($_POST['is_admin']) ? 1 : 0;

    $sql = "INSERT INTO users (username, password, nama_lengkap, is_admin) VALUES (?, ?, ?, ?)";
    $stmt = $conn->prepare($sql);
    $stmt->bind_param("sssi", $username, $password, $nama_lengkap, $is_admin);
    
    if ($stmt->execute()) {
        $_SESSION['msg'] = ['type' => 'success', 'text' => "User **$username** berhasil ditambahkan."];
    } else {
        // Cek error untuk duplikasi username
        $error_text = (strpos($stmt->error, 'Duplicate entry') !== false) ? 
                      "Username sudah digunakan." : 
                      "Gagal menambahkan user: " . $stmt->error;
        $_SESSION['msg'] = ['type' => 'danger', 'text' => $error_text];
    }
    $stmt->close();
    header("Location: manajemen_user.php");
    exit();
}

// --- FUNGSI DELETE (Hapus User) ---
if (isset($_GET['action']) && $_GET['action'] == 'delete' && isset($_GET['id'])) {
    $id = intval($_GET['id']);
    
    if ($id == $_SESSION['user_id']) {
        $_SESSION['msg'] = ['type' => 'danger', 'text' => "Anda tidak bisa menghapus akun Anda sendiri."];
    } else {
        $sql = "DELETE FROM users WHERE id = ?";
        $stmt = $conn->prepare($sql);
        $stmt->bind_param("i", $id);
        if ($stmt->execute()) {
            $_SESSION['msg'] = ['type' => 'success', 'text' => "User berhasil dihapus."];
        } else {
            $_SESSION['msg'] = ['type' => 'danger', 'text' => "Gagal menghapus user: " . $stmt->error];
        }
        $stmt->close();
    }
    header("Location: manajemen_user.php");
    exit();
}

// --- FUNGSI READ (Ambil Data User) ---
$user_data = [];
$sql_read = "SELECT id, username, nama_lengkap, is_admin FROM users ORDER BY id ASC";
$result_read = $conn->query($sql_read);
if ($result_read) {
    while ($row = $result_read->fetch_assoc()) {
        $user_data[] = $row;
    }
}

// Ambil pesan dari session dan hapus
$msg_type = $_SESSION['msg']['type'] ?? '';
$msg_content = $_SESSION['msg']['text'] ?? '';
unset($_SESSION['msg']); // Hapus pesan setelah ditampilkan

?>

    <h2><i class="bi bi-person-gear"></i> Manajemen User (Admin Only)</h2>
    <hr>

    <?php if ($msg_content): ?>
        <div class="alert alert-<?php echo ($msg_type == 'success' ? 'success' : 'danger'); ?> alert-dismissible fade show" role="alert">
            <?php echo $msg_content; ?>
            <button type="button" class="btn-close" data-bs-dismiss="alert" aria-label="Close"></button>
        </div>
    <?php endif; ?>

    <button class="btn btn-primary mb-3" data-bs-toggle="modal" data-bs-target="#addUserModal">
        <i class="bi bi-plus-circle"></i> Tambah User Baru
    </button>

    <div class="table-responsive">
        <table class="table table-striped table-bordered">
            <thead>
                <tr>
                    <th>ID</th>
                    <th>Nama Lengkap</th>
                    <th>Username</th>
                    <th>Hak Akses</th>
                    <th>Aksi</th>
                </tr>
            </thead>
            <tbody>
                <?php if (empty($user_data)): ?>
                    <tr><td colspan="5" class="text-center">Belum ada data User.</td></tr>
                <?php else: ?>
                    <?php foreach ($user_data as $user): ?>
                        <tr>
                            <td><?php echo $user['id']; ?></td>
                            <td><?php echo htmlspecialchars($user['nama_lengkap']); ?></td>
                            <td><?php echo htmlspecialchars($user['username']); ?></td>
                            <td>
                                <?php echo $user['is_admin'] ? '<span class="badge bg-danger">Admin</span>' : '<span class="badge bg-success">User Biasa</span>'; ?>
                            </td>
                            <td>
                                <?php if ($user['id'] != $_SESSION['user_id']): ?>
                                    <a href="manajemen_user.php?action=delete&id=<?php echo $user['id']; ?>" 
                                       onclick="return confirm('Yakin ingin menghapus user <?php echo $user['username']; ?>?')" 
                                       class="btn btn-sm btn-danger"><i class="bi bi-trash"></i> Hapus</a>
                                <?php else: ?>
                                    <button class="btn btn-sm btn-secondary" disabled>Akun Anda</button>
                                <?php endif; ?>
                            </td>
                        </tr>
                    <?php endforeach; ?>
                <?php endif; ?>
            </tbody>
        </table>
    </div>

<div class="modal fade" id="addUserModal" tabindex="-1" aria-labelledby="addUserModalLabel" aria-hidden="true">
    <div class="modal-dialog">
        <div class="modal-content">
            <form method="POST" action="manajemen_user.php">
                <div class="modal-header">
                    <h5 class="modal-title" id="addUserModalLabel">Tambah User Baru</h5>
                    <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
                </div>
                <div class="modal-body">
                    <div class="mb-3">
                        <label for="nama_lengkap" class="form-label">Nama Lengkap</label>
                        <input type="text" class="form-control" id="nama_lengkap" name="nama_lengkap" required>
                    </div>
                    <div class="mb-3">
                        <label for="username" class="form-label">Username</label>
                        <input type="text" class="form-control" id="username" name="username" required>
                    </div>
                    <div class="mb-3">
                        <label for="password" class="form-label">Password</label>
                        <input type="password" class="form-control" id="password" name="password" required>
                    </div>
                    <div class="form-check mb-3">
                        <input class="form-check-input" type="checkbox" value="1" id="is_admin" name="is_admin">
                        <label class="form-check-label" for="is_admin">
                            Berikan Hak Akses **Admin**
                        </label>
                    </div>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Tutup</button>
                    <button type="submit" name="add_user" class="btn btn-primary">Simpan User</button>
                </div>
            </form>
        </div>
    </div>
</div>

<?php 
include_once 'footer.php'; 
?>