<?php 
include 'koneksi.php';
cek_akses(['Super Admin']);

// Proses Tambah User
if(isset($_POST['simpan'])) {
    $username = mysqli_real_escape_string($conn, $_POST['username']);
    $password = md5($_POST['password']);
    $full_name = mysqli_real_escape_string($conn, $_POST['full_name']);
    $role = $_POST['role'];
    $unit = $_POST['unit'];
    
    // Cek username sudah ada atau belum
    $cek = mysqli_query($conn, "SELECT * FROM users WHERE username='$username'");
    if(mysqli_num_rows($cek) > 0) {
        echo "<script>alert('Username sudah digunakan!'); window.location='kelola_user.php';</script>";
        exit();
    }
    
    $query = "INSERT INTO users (username, password, full_name, role, unit) VALUES ('$username', '$password', '$full_name', '$role', '$unit')";
    if(mysqli_query($conn, $query)) {
        echo "<script>alert('User berhasil ditambahkan!'); window.location='kelola_user.php';</script>";
    } else {
        echo "<script>alert('Gagal menambahkan user: " . mysqli_error($conn) . "');</script>";
    }
}

// Proses Edit User
if(isset($_POST['update'])) {
    $id = $_POST['id'];
    $full_name = mysqli_real_escape_string($conn, $_POST['full_name']);
    $role = $_POST['role'];
    $unit = $_POST['unit'];
    
    $query = "UPDATE users SET full_name='$full_name', role='$role', unit='$unit' WHERE id=$id";
    mysqli_query($conn, $query);
    echo "<script>alert('User berhasil diupdate!'); window.location='kelola_user.php';</script>";
}

// Proses Hapus User
if(isset($_GET['hapus'])) {
    $id = $_GET['hapus'];
    if($id != $_SESSION['user_id']) { // Cegah hapus sendiri
        mysqli_query($conn, "DELETE FROM users WHERE id=$id");
        echo "<script>alert('User berhasil dihapus!'); window.location='kelola_user.php';</script>";
    } else {
        echo "<script>alert('Tidak bisa menghapus akun sendiri!'); window.location='kelola_user.php';</script>";
    }
}

// Proses Reset Password
if(isset($_GET['reset'])) {
    $id = $_GET['reset'];
    $new_password = md5('123456');
    mysqli_query($conn, "UPDATE users SET password='$new_password' WHERE id=$id");
    echo "<script>alert('Password berhasil direset menjadi 123456'); window.location='kelola_user.php';</script>";
}

// Ambil data user
$users = mysqli_query($conn, "SELECT * FROM users ORDER BY id DESC");
?>

<!DOCTYPE html>
<html>
<head>
    <title>Kelola User - Sistem Administrasi Guru</title>
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/admin-lte@3.2/dist/css/adminlte.min.css">
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css" rel="stylesheet">
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.0.0/css/all.min.css">
    <link rel="stylesheet" href="assets/css/theme-istiqlal-green.css">
    <style>
        .modal-header {
            background: linear-gradient(135deg, #0de01f 0%, #0b4e29 100%);
            color: white;
        }
        .btn-modal-close {
            color: white;
            opacity: 1;
        }
        .user-avatar {
            width: 40px;
            height: 40px;
            border-radius: 50%;
            background: #055a33;
            display: flex;
            align-items: center;
            justify-content: center;
            color: white;
            font-weight: bold;
        }
    </style>
</head>
<body class="hold-transition sidebar-mini layout-fixed">
<div class="wrapper">
    <?php include 'sidebar.php'; ?>
    
    <div class="content-wrapper">
        <!-- Header -->
        <div class="content-header">
            <div class="container-fluid">
                <div class="row mb-2">
                    <div class="col-sm-6">
                        <h1 class="m-0">
                            <i class="fas fa-users-cog text-primary"></i> Kelola User
                        </h1>
                    </div>
                    <div class="col-sm-6">
                        <ol class="breadcrumb float-sm-right">
                            <li class="breadcrumb-item"><a href="dashboard.php">Home</a></li>
                            <li class="breadcrumb-item active">Kelola User</li>
                        </ol>
                    </div>
                </div>
            </div>
        </div>

        <!-- Main Content -->
        <div class="content">
            <div class="container-fluid">
                
                <!-- Tombol Tambah User -->
                <div class="row mb-3">
                    <div class="col-12">
                        <button type="button" class="btn btn-primary" data-bs-toggle="modal" data-bs-target="#modalTambahUser" id="btnTambahUser">
                            <i class="fas fa-plus"></i> Tambah User Baru
                        </button>
                        <button type="button" class="btn btn-success" onclick="window.location.reload()">
                            <i class="fas fa-sync-alt"></i> Refresh
                        </button>
                    </div>
                </div>

                <!-- Tabel User -->
                <div class="card">
                    <div class="card-header">
                        <h3 class="card-title">
                            <i class="fas fa-list"></i> Daftar Pengguna
                        </h3>
                        <div class="card-tools">
                            <span class="badge badge-primary">Total: <?= mysqli_num_rows($users) ?> User</span>
                        </div>
                    </div>
                    <div class="card-body">
                        <div class="table-responsive">
                            <table class="table table-bordered table-striped table-hover" id="tabelUser">
                                <thead class="thead-dark">
                                    <tr>
                                        <th width="5%">No</th>
                                        <th width="10%">Username</th>
                                        <th width="20%">Nama Lengkap</th>
                                        <th width="10%">Role</th>
                                        <th width="20%">Unit</th>
                                        <th width="15%">Status</th>
                                        <th width="20%">Aksi</th>
                                    </tr>
                                </thead>
                                <tbody>
                                    <?php 
                                    $no = 1;
                                    if(mysqli_num_rows($users) > 0):
                                        while($row = mysqli_fetch_assoc($users)): 
                                    ?>
                                    <tr>
                                        <td><?= $no++ ?></td>
                                        <td>
                                            <div class="d-flex align-items-center">
                                                <div class="user-avatar mr-2">
                                                    <?= strtoupper(substr($row['username'], 0, 1)) ?>
                                                </div>
                                                <?= $row['username'] ?>
                                            </div>
                                         </td>
                                        <td><?= $row['full_name'] ?></td>
                                        <td>
                                            <?php 
                                            $role_badge = [
                                                'Super Admin' => 'danger',
                                                'Pimpinan' => 'primary',
                                                'Kepala' => 'warning',
                                                'Guru' => 'info'
                                            ];
                                            ?>
                                            <span class="badge badge-<?= $role_badge[$row['role']] ?>">
                                                <?= $row['role'] ?>
                                            </span>
                                         </td>
                                        <td>
                                            <span class="badge badge-secondary"><?= $row['unit'] ?></span>
                                         </td>
                                        <td>
                                            <?php if($row['id'] == $_SESSION['user_id']): ?>
                                                <span class="badge badge-success"><i class="fas fa-check-circle"></i> Aktif (Anda)</span>
                                            <?php else: ?>
                                                <span class="badge badge-info">Aktif</span>
                                            <?php endif; ?>
                                         </td>
                                        <td>
                                            <div class="btn-group" role="group">
                                                <button class="btn btn-sm btn-info" onclick="editUser(<?= $row['id'] ?>, '<?= $row['full_name'] ?>', '<?= $row['role'] ?>', '<?= $row['unit'] ?>')">
                                                    <i class="fas fa-edit"></i> Edit
                                                </button>
                                                <?php if($row['id'] != $_SESSION['user_id']): ?>
                                                    <a href="kelola_user.php?reset=<?= $row['id'] ?>" class="btn btn-sm btn-warning" onclick="return confirm('Reset password user ini menjadi 123456?')">
                                                        <i class="fas fa-key"></i> Reset
                                                    </a>
                                                    <a href="kelola_user.php?hapus=<?= $row['id'] ?>" class="btn btn-sm btn-danger" onclick="return confirm('Yakin ingin menghapus user <?= $row['username'] ?>?')">
                                                        <i class="fas fa-trash"></i> Hapus
                                                    </a>
                                                <?php endif; ?>
                                            </div>
                                         </td>
                                     </tr>
                                    <?php endwhile; 
                                    else: ?>
                                    <tr>
                                        <td colspan="7" class="text-center text-muted">
                                            <i class="fas fa-users fa-3x"></i>
                                            <br>Belum ada user
                                        </td>
                                    </tr>
                                    <?php endif; ?>
                                </tbody>
                            </table>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>

    <footer class="main-footer">
        <strong>&copy; <?= date('Y') ?> Sistem Administrasi Guru.</strong>
        All rights reserved.
    </footer>
</div>

<!-- MODAL TAMBAH USER -->
<div class="modal fade" id="modalTambahUser" tabindex="-1" aria-labelledby="modalTambahUserLabel" aria-hidden="true">
    <div class="modal-dialog modal-dialog-centered">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title" id="modalTambahUserLabel">
                    <i class="fas fa-user-plus"></i> Tambah User Baru
                </h5>
                <button type="button" class="btn-close btn-modal-close" data-bs-dismiss="modal" aria-label="Close">&times;</button>
            </div>
            <form method="POST" action="">
                <div class="modal-body">
                    <div class="form-group">
                        <label><i class="fas fa-user"></i> Username</label>
                        <input type="text" name="username" class="form-control" placeholder="Masukkan username" required>
                        <small class="text-muted">Username harus unik</small>
                    </div>
                    <div class="form-group">
                        <label><i class="fas fa-lock"></i> Password</label>
                        <input type="password" name="password" class="form-control" placeholder="Masukkan password" required>
                        <small class="text-muted">Minimal 6 karakter</small>
                    </div>
                    <div class="form-group">
                        <label><i class="fas fa-user-circle"></i> Nama Lengkap</label>
                        <input type="text" name="full_name" class="form-control" placeholder="Masukkan nama lengkap" required>
                    </div>
                    <div class="form-group">
                        <label><i class="fas fa-tag"></i> Role / Jabatan</label>
                        <select name="role" class="form-control" required>
                            <option value="">-- Pilih Role --</option>
                            <option value="Super Admin">👑 Super Admin</option>
                            <option value="Pimpinan">👔 Pimpinan</option>
                            <option value="Kepala">📋 Kepala</option>
                            <option value="Guru">👨‍🏫 Guru</option>
                        </select>
                    </div>
                    <div class="form-group">
                        <label><i class="fas fa-building"></i> Unit / Satuan Pendidikan</label>
                        <select name="unit" class="form-control" required>
                            <option value="">-- Pilih Unit --</option>
                            <option>MIJ</option>
                            <option>Kelompok Bermain</option>
                            <option>Raudhatul Athfal</option>
                            <option>Madrasah Ibtidaiyah</option>
                            <option>Madrasah Tsanawiyah</option>
                            <option>Madrasah Aliyah</option>
                            <option>Istiqlal Boarding School</option>
                        </select>
                    </div>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">
                        <i class="fas fa-times"></i> Batal
                    </button>
                    <button type="submit" name="simpan" class="btn btn-primary">
                        <i class="fas fa-save"></i> Simpan User
                    </button>
                </div>
            </form>
        </div>
    </div>
</div>

<!-- MODAL EDIT USER -->
<div class="modal fade" id="modalEditUser" tabindex="-1" aria-labelledby="modalEditUserLabel" aria-hidden="true">
    <div class="modal-dialog modal-dialog-centered">
        <div class="modal-content">
            <div class="modal-header bg-warning">
                <h5 class="modal-title" id="modalEditUserLabel">
                    <i class="fas fa-edit"></i> Edit User
                </h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close">&times;</button>
            </div>
            <form method="POST" action="">
                <div class="modal-body">
                    <input type="hidden" name="id" id="edit_id">
                    <div class="form-group">
                        <label><i class="fas fa-user-circle"></i> Nama Lengkap</label>
                        <input type="text" name="full_name" id="edit_full_name" class="form-control" required>
                    </div>
                    <div class="form-group">
                        <label><i class="fas fa-tag"></i> Role</label>
                        <select name="role" id="edit_role" class="form-control" required>
                            <option value="Super Admin">Super Admin</option>
                            <option value="Pimpinan">Pimpinan</option>
                            <option value="Kepala">Kepala</option>
                            <option value="Guru">Guru</option>
                        </select>
                    </div>
                    <div class="form-group">
                        <label><i class="fas fa-building"></i> Unit</label>
                        <select name="unit" id="edit_unit" class="form-control" required>
                            <option>MIJ</option>
                            <option>Kelompok Bermain</option>
                            <option>Raudhatul Athfal</option>
                            <option>Madrasah Ibtidaiyah</option>
                            <option>Madrasah Tsanawiyah</option>
                            <option>Madrasah Aliyah</option>
                            <option>Istiqlal Boarding School</option>
                        </select>
                    </div>
                    <div class="alert alert-info">
                        <i class="fas fa-info-circle"></i> Password tidak diubah di sini. Gunakan fitur "Reset Password" untuk mengubah password.
                    </div>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Batal</button>
                    <button type="submit" name="update" class="btn btn-warning">Update User</button>
                </div>
            </form>
        </div>
    </div>
</div>

<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/js/bootstrap.bundle.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/admin-lte@3.2/dist/js/adminlte.min.js"></script>

<script>
// Fungsi untuk edit user
function editUser(id, full_name, role, unit) {
    document.getElementById('edit_id').value = id;
    document.getElementById('edit_full_name').value = full_name;
    document.getElementById('edit_role').value = role;
    document.getElementById('edit_unit').value = unit;
    
    // Tampilkan modal edit
    var editModal = new bootstrap.Modal(document.getElementById('modalEditUser'));
    editModal.show();
}

// Pastikan modal tambah berfungsi
$(document).ready(function() {
    // Jika tombol tambah user diklik
    $('#btnTambahUser').click(function() {
        $('#modalTambahUser').modal('show');
    });
    
    // Inisialisasi semua modal
    var modals = document.querySelectorAll('.modal');
    modals.forEach(function(modal) {
        new bootstrap.Modal(modal);
    });
});

// Notifikasi sukses
<?php if(isset($_GET['success'])): ?>
$(document).ready(function() {
    Swal.fire('Berhasil!', 'User telah ditambahkan', 'success');
});
<?php endif; ?>
</script>

<!-- SweetAlert (opsional untuk notifikasi lebih bagus) -->
<script src="https://cdn.jsdelivr.net/npm/sweetalert2@11"></script>

</body>
</html>