<?php
session_start();
require_once "../config/db.php";

// Hanya superadmin boleh edit user
if (!isset($_SESSION['user']) || $_SESSION['user']['role'] !== 'superadmin') {
    header("Location: ../pages/users.php?error=unauthorized");
    exit;
}

$id       = $_POST['id'];
$nama     = trim($_POST['nama']);
$username = trim($_POST['username']);
$role     = trim($_POST['role']);
$password = trim($_POST['password']); // opsional

if ($nama === '' || $username === '' || $role === '') {
    header("Location: ../pages/users.php?error=empty");
    exit;
}

// Jika password kosong → tidak diubah
if ($password === '') {
    $stmt = $pdo->prepare("UPDATE users 
                           SET nama=:nama, username=:username, role=:role 
                           WHERE id=:id");
    $stmt->execute([
        ':nama'     => $nama,
        ':username' => $username,
        ':role'     => $role,
        ':id'       => $id
    ]);
} else {
    $hashed = password_hash($password, PASSWORD_BCRYPT);

    $stmt = $pdo->prepare("UPDATE users 
                           SET nama=:nama, username=:username, role=:role, password=:password
                           WHERE id=:id");
    $stmt->execute([
        ':nama'     => $nama,
        ':username' => $username,
        ':role'     => $role,
        ':password' => $hashed,
        ':id'       => $id
    ]);
}

header("Location: ../pages/users.php?edit=1");
exit;
