<?php
include('db_connect.php');
$meta = [];

if (isset($_GET['id']) && !empty($_GET['id'])) {
    $stmt = $conn->prepare("SELECT * FROM users WHERE id = ?");
    $stmt->bind_param("i", $_GET['id']);
    $stmt->execute();
    $result = $stmt->get_result()->fetch_assoc();
    if ($result) {
        foreach ($result as $k => $val) {
            $meta[$k] = $val;
        }
    }
}
?>

<div class="container-fluid">
    <form id="manage_user">
        <div class="col-md-12">
            <div class="form-group mb-2">
                <label for="name" class="control-label">Name</label>
                <input type="hidden" name="id" value="<?php echo isset($meta['id']) ? $meta['id'] : '' ?>">
                <input type="text" class="form-control" id="name" name="name" required value="<?php echo isset($meta['name']) ? $meta['name'] : '' ?>">
            </div>
            <div class="form-group mb-2">
                <label for="username" class="control-label">Username</label>
                <input type="text" class="form-control" id="username" name="username" required value="<?php echo isset($meta['username']) ? $meta['username'] : '' ?>">
            </div>
            <div class="form-group mb-2">
                <label for="password" class="control-label">Password</label>
                <input type="password" class="form-control" id="password" name="password" placeholder="<?php echo isset($meta['id']) ? 'Leave blank to keep current password' : 'Enter password' ?>">
            </div>
        </div>
        <button type="submit" class="btn btn-primary">Save</button>
    </form>
</div>

<script>
$('#manage_user').submit(function(e){
    e.preventDefault();
    start_load();
    $.ajax({
        url: './save_user.php',
        method: 'POST',
        data: $(this).serialize(),
        error: err => {
            console.log(err);
            end_load();
            alert_toast('An error occurred', 'danger');
        },
        success: function(resp){
            if(resp == 1){
                end_load();
                $('.modal').modal('hide');
                alert_toast('Data successfully saved', 'success');
                load_user();
            } else {
                end_load();
                alert_toast(resp, 'warning'); // Shows server response if not 1
            }
        }
    });
});
</script>
