<?php
include 'koneksi.php';

if (isset($_POST['edit'])) {
    $id_user = $_POST['id_user'];
    $username = $_POST['username'];
    $email = $_POST['email'];
    $nohp = $_POST['nohp'];
    $role = $_POST['role'];

    // Cek username sudah digunakan oleh pengguna lain
    $cek_username = "SELECT * FROM users WHERE username = '$username' AND id_user != '$id_user'";
    $result_username = mysqli_query($conn, $cek_username);

    // Cek email sudah digunakan oleh pengguna lain
    $cek_email = "SELECT * FROM users WHERE email = '$email' AND id_user != '$id_user'";
    $result_email = mysqli_query($conn, $cek_email);

    // Cek no hp sudah digunakan oleh pengguna lain
    $cek_nohp = "SELECT * FROM users WHERE nohp = '$nohp' AND id_user != '$id_user'";
    $result_nohp = mysqli_query($conn, $cek_nohp);

    if (mysqli_num_rows($result_username) > 0) {
        echo "<script>alert('Username sudah digunakan oleh pengguna lain!'); window.location='pengguna.php';</script>";
    } elseif (mysqli_num_rows($result_email) > 0) {
        echo "<script>alert('Email sudah digunakan oleh pengguna lain!'); window.location='pengguna.php';</script>";
    } elseif (mysqli_num_rows($result_nohp) > 0) {
        echo "<script>alert('Nomor HP sudah digunakan oleh pengguna lain!'); window.location='pengguna.php';</script>";
    } elseif (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
        echo "<script>alert('Format email tidak valid!'); window.location='pengguna.php';</script>";
    } else {
        // Password tidak diubah saat edit
        $query = "UPDATE users SET 
                  username = '$username',
                  email = '$email',
                  nohp = '$nohp',
                  role = '$role'
                  WHERE id_user = '$id_user'";
        
        if (mysqli_query($conn, $query)) {
            echo "<script>alert('Data pengguna berhasil diperbarui!'); window.location='pengguna.php';</script>";
        } else {
            echo "<script>alert('Gagal memperbarui data pengguna.'); window.location='pengguna.php';</script>";
        }
    }
}
?>