<?php 
include 'template/header.php';
check_user_access('admin'); // Only admin can access this page
?>

<br>

<?php
if(isset($_POST['tambahUser']))
{
    $username = htmlspecialchars($_POST['username']);
    $password = password_hash($_POST['password'], PASSWORD_DEFAULT);
    $role = htmlspecialchars($_POST['role']);
    $name = htmlspecialchars($_POST['name']);

    // Check if username already exists
    $checkUser = mysqli_query($conn, "SELECT * FROM users WHERE username='$username'");
    if(mysqli_num_rows($checkUser) > 0) {
        echo '<script>alert("Username sudah digunakan!");</script>';
    } else {
        $tambahUser = mysqli_query($conn,"INSERT INTO users (username, password, role, name) VALUES ('$username', '$password', '$role', '$name')");
        if ($tambahUser){
            echo '<script>alert("Berhasil Menambahkan User");window.location="users.php"</script>';
        } else {
            echo '<script>alert("Gagal Menambahkan User");history.go(-1);</script>';
        }
    }
}

if(isset($_POST['updateUser'])){
    $id = htmlspecialchars($_POST['id']);
    $username = htmlspecialchars($_POST['username']);
    $role = htmlspecialchars($_POST['role']);
    $name = htmlspecialchars($_POST['name']);
    $password = $_POST['password'] ?? '';
    
    // Check if username already exists for other users
    $checkUser = mysqli_query($conn, "SELECT * FROM users WHERE username='$username' AND id!='$id'");
    if(mysqli_num_rows($checkUser) > 0) {
        echo '<script>alert("Username sudah digunakan oleh user lain!");</script>';
    } else {
        if(!empty($password)) {
            // Update with new password
            $password = password_hash($password, PASSWORD_DEFAULT);
            $updateQuery = "UPDATE users SET username='$username', role='$role', name='$name', password='$password' WHERE id='$id'";
        } else {
            // Update without changing password
            $updateQuery = "UPDATE users SET username='$username', role='$role', name='$name' WHERE id='$id'";
        }
        
        mysqli_query($conn, $updateQuery);
        echo '<script>alert("Berhasil Update User");window.location="users.php"</script>';
    }
};
?>

<div class="card">
    <div class="card-header">
        <div class="card-tittle"><i class="fa fa-users me-2"></i> Manajemen User 
        <button type="button" class="btn btn-primary btn-sm p-1 float-right" data-toggle="modal" data-target="#addUser">
            <i class="fa fa-plus fa-sm mr-1"></i> Tambah User</button></div>
    </div>
        <div class="card-body">
            <div class="table-responsive">
            <table class="table table-striped table-sm table-bordered dt-responsive nowrap" id="table" width="100%">
                        <thead>
                        <tr>
                            <th>No.</th>
                            <th>Nama Lengkap</th>
                            <th>Username</th>
                            <th>Role</th>
                            <th>Tanggal Dibuat</th>
                            <th>Aksi</th>
                        </tr>
                        </thead>
                        <tbody>
                            <?php
                                $no=1;
                                $data_users = mysqli_query($conn,"SELECT * FROM users ORDER BY id ASC");
                                while($d=mysqli_fetch_array($data_users)){
                                    $id = $d['id'];
                                    ?>
                                    
                                    <tr>
                                        <td><?php echo $no++ ?></td>
                                        <td><?php echo $d['name'] ?></td>
                                        <td><?php echo $d['username'] ?></td>
                                        <td>
                                            <?php 
                                            if($d['role'] == 'admin') {
                                                echo '<span class="badge badge-primary">Admin</span>';
                                            } else {
                                                echo '<span class="badge badge-success">Kasir</span>';
                                            }
                                            ?>
                                        </td>
                                        <td><?php echo $d['created_at'] ?></td>
                                        <td>
                                            <button type="button" class="btn btn-primary btn-sm"
                                             data-toggle="modal" data-target="#editU<?php echo $id ?>">
                                             <i class="fa fa-edit fa-sm mr-1"></i>Edit</button>
                                            <?php if($d['id'] != $_SESSION['id_login']): // Don't allow deleting own account ?>
                                            <a class="btn btn-danger btn-sm" href="?hapus=<?php echo $id ?>" 
                                            onclick="javascript:return confirm('Hapus User - <?php echo $d['username'] ?> ?');">
                                            <i class="fa fa-trash fa-sm mr-1"></i>Hapus</a>
                                            <?php else: ?>
                                            <span class="text-muted">Tidak bisa hapus akun sendiri</span>
                                            <?php endif; ?>
                                        </td>
                                    </tr>
                                    
                                    <!-- modal edit -->
                                    <div class="modal fade" id="editU<?php echo $id ?>" tabindex="-1" role="dialog" aria-labelledby="ModalTittle2" aria-hidden="true">
                                        <div class="modal-dialog" role="document">
                                            <div class="modal-content">
                                            <form method="post">
                                            <div class="modal-header">
                                                <h5 class="modal-title" id="ModalTittle2"><i class="fa fa-user mr-1 text-muted"></i> Edit User</h5>
                                                <button type="button" class="close" data-dismiss="modal" aria-label="Close">
                                                <span aria-hidden="true">&times;</span>
                                                </button>
                                            </div>
                                            <div class="modal-body">
                                                <div class="form-group mb-2">
                                                    <label>Nama Lengkap:</label>
                                                    <input type="hidden" name="id" class="form-control" value="<?php echo $d['id'] ?>">
                                                    <input type="text" name="name" class="form-control" value="<?php echo $d['name'] ?>" required>
                                                </div>
                                                <div class="form-group mb-2">
                                                    <label>Username:</label>
                                                    <input type="text" name="username" class="form-control" value="<?php echo $d['username'] ?>" required>
                                                </div>
                                                <div class="form-group mb-2">
                                                    <label>Role:</label>
                                                    <select name="role" class="form-control" required>
                                                        <option value="admin" <?php echo $d['role'] == 'admin' ? 'selected' : ''; ?>>Admin</option>
                                                        <option value="kasir" <?php echo $d['role'] == 'kasir' ? 'selected' : ''; ?>>Kasir</option>
                                                    </select>
                                                </div>
                                                <div class="form-group mb-2">
                                                    <label>Password (Kosongkan jika tidak ingin diubah):</label>
                                                    <input type="password" name="password" class="form-control" placeholder="Masukkan password baru...">
                                                </div>
                                            </div>
                                            <div class="modal-footer">
                                                <button type="button" class="btn btn-secondary btn-sm" data-dismiss="modal">
                                                    <i class="fa fa-times mr-1"></i> Batal</button>
                                                <button type="submit" class="btn btn-primary btn-sm" name="updateUser">
                                                <i class="fa fa-save mr-1"></i> Simpan Perubahan</button>
                                            </div>
                                            </form>
                                            </div>
                                        </div>
                                        </div>
                                    <!-- end modal edit -->
                        <?php }?>
					</tbody>
                </table>
            </div>
        </div>
</div>
<?php 
	if(!empty($_GET['hapus'])){
		$id = $_GET['hapus'];
		if($id != $_SESSION['id_login']) { // Prevent deleting own account
            $hapus_data = mysqli_query($conn, "DELETE FROM users WHERE id='$id'");
            if($hapus_data){
                echo '<script>alert("Berhasil Hapus User");window.location="users.php"</script>';
            } else {
                echo '<script>alert("Gagal Hapus User");history.go(-1);</script>';
            }
        } else {
            echo '<script>alert("Tidak bisa menghapus akun sendiri");history.go(-1);</script>';
        }
	};
?>

<!-- Modal Tambah User -->
<div class="modal fade" id="addUser" tabindex="-1" role="dialog" aria-labelledby="ModalTittle" aria-hidden="true">
  <div class="modal-dialog" role="document">
    <div class="modal-content">
    <form method="post">
      <div class="modal-header">
        <h5 class="modal-title" id="ModalTittle"><i class="fa fa-user-plus mr-1 text-muted"></i> Tambah User Baru</h5>
        <button type="button" class="close" data-dismiss="modal" aria-label="Close">
          <span aria-hidden="true">&times;</span>
        </button>
      </div>
      <div class="modal-body">
          <div class="form-group mb-2">
              <label>Nama Lengkap:</label>
              <input type="text" name="name" class="form-control" placeholder="Nama lengkap user..." required>
          </div>
          <div class="form-group mb-2">
              <label>Username:</label>
              <input type="text" name="username" class="form-control" placeholder="Username untuk login..." required>
          </div>
          <div class="form-group mb-2">
              <label>Role:</label>
              <select name="role" class="form-control" required>
                  <option value="admin">Admin</option>
                  <option value="kasir" selected>Kasir</option>
              </select>
          </div>
          <div class="form-group mb-2">
              <label>Password:</label>
              <input type="password" name="password" class="form-control" placeholder="Password untuk user..." required>
          </div>
          <div class="alert alert-info small">
              <i class="fas fa-info-circle"></i> <strong>Info:</strong> 
              <ul class="mb-0">
                  <li>Role <strong>Admin</strong> memiliki akses penuh ke semua fitur</li>
                  <li>Role <strong>Kasir</strong> hanya bisa mengakses halaman transaksi</li>
                  <li>Gunakan username yang unik untuk setiap user</li>
              </ul>
          </div>
      </div>
      <div class="modal-footer">
        <button type="button" class="btn btn-secondary btn-sm" data-dismiss="modal">
            <i class="fa fa-times mr-1"></i> Batal</button>
        <button type="reset" class="btn btn-warning btn-sm">
        <i class="fa fa-undo mr-1"></i> Reset</button>
        <button type="submit" class="btn btn-primary btn-sm" name="tambahUser">
        <i class="fa fa-plus mr-1"></i> Tambahkan User</button>
      </div>
      </form>
    </div>
  </div>
</div>

<?php include 'template/footer.php';?>