<?php
include("koneksi.php");

if ($_SERVER["REQUEST_METHOD"] == "POST") {
    
    $user_id = $_POST['id'];
    $username = $_POST['username'];
    $nama_lengkap = $_POST['nama'];
    $role_id = $_POST['role'];
    
    if (!empty($_POST['password'])) {
        $password_hash = password_hash($_POST['password'], PASSWORD_DEFAULT);
        
        $sql = "UPDATE users SET 
                username = ?, 
                nama_lengkap = ?, 
                password = ?,
                role_id = ?
                WHERE user_id = ?";
        
        $stmt = mysqli_prepare($cnn, $sql);
        
        if ($stmt) {
            mysqli_stmt_bind_param($stmt, "ssssi", 
                $username, 
                $nama_lengkap, 
                $password_hash,
                $role_id,
                $user_id);
                
            $query = mysqli_stmt_execute($stmt);
            
            if ($query) {
                header("Location: member.php?status=success");
                exit();
            } else {
                $error = "Error updating with password: " . mysqli_error($cnn);
            }
            
            mysqli_stmt_close($stmt);
        } else {
            $error = "Error preparing password statement: " . mysqli_error($cnn);
        }
    }
    else {
        $sql = "UPDATE users SET 
                username = ?, 
                nama_lengkap = ?, 
                role_id = ?
                WHERE user_id = ?";
        
        $stmt = mysqli_prepare($conn, $sql);
        
        if ($stmt) {
            mysqli_stmt_bind_param($stmt, "ssii", 
                $username, 
                $nama_lengkap, 
                $role_id,
                $user_id);
                
            $query = mysqli_stmt_execute($stmt);
            
            if ($query) {
                header("Location: ../admin.php?status=success");
                exit();
            } else {
                $error = "Error updating without password: " . mysqli_error($cnn);
            }
            
            mysqli_stmt_close($stmt);
        } else {
            $error = "Error preparing no-password statement: " . mysqli_error($cnn);
        }
    }
    
    echo $error ?? "Unknown error occurred";
    mysqli_close($cnn);
} else {
    header("Location: ../Admin/admin.php");
    exit();
}   