<?php
session_start();

// Guard Session Login
if (empty($_SESSION['namauser']) && empty($_SESSION['passuser'])) {
    echo "<script>alert('Silahkan login terlebih dahulu!'); window.location='../../index.php';</script>";
    exit();
}

include "../../../config/koneksi.php";

$module = $_GET['module'] ?? '';
$act    = $_GET['act'] ?? '';

if ($module == 'user' && $act == 'update') {
    $id       = mysqli_real_escape_string($konek, $_POST['id']);
    $username = mysqli_real_escape_string($konek, $_POST['username']);
    $password = $_POST['password'];

    // Validasi Cek User Exists
    $cek_user = mysqli_query($konek, "SELECT username FROM users WHERE id_session='$id'");
    if (mysqli_num_rows($cek_user) == 0) {
        echo "<script>alert('Data user tidak ditemukan!'); window.location='../../media.php?module=user';</script>";
        exit();
    }

    $data_user = mysqli_fetch_array($cek_user);

    // Keamanan: Cek Otorisasi (Hanya Admin atau Pemilik Akun Sendiri yang boleh Ubah Data)
    if ($_SESSION['leveluser'] != 'admin' && $data_user['username'] != $_SESSION['namauser']) {
        echo "<script>alert('Anda tidak memiliki akses untuk mengubah data ini!'); window.location='../../media.php?module=user';</script>";
        exit();
    }

    // Apabila Password Tidak Diubah (Kosong)
    if (empty($password)) {
        $update = "UPDATE users SET username = '$username' WHERE id_session = '$id'";
        mysqli_query($konek, $update);
    } 
    // Apabila Password Diubah
    else {
        $pass_hash = md5($password);
        $update = "UPDATE users SET username = '$username', password = '$pass_hash' WHERE id_session = '$id'";
        mysqli_query($konek, $update);

        // Jika user yang sedang login mengubah passwordnya sendiri, perbarui session password-nya
        if ($data_user['username'] == $_SESSION['namauser']) {
            $_SESSION['passuser'] = $pass_hash;
        }
    }

    // Jika username disesuaikan, update juga session-nya
    if ($data_user['username'] == $_SESSION['namauser']) {
        $_SESSION['namauser'] = $username;
    }

    header("location:../../media.php?module=" . $module);
}
?>