<?php
// File: superadmin/superadmin_edit_user.php

require_once('../db.php'); 
include 'auth_check.php';
require_role(['superadmin']);

$message = "";

// 1. Ambil ID dari URL (GET parameter)
if (!isset($_GET['id']) || !is_numeric($_GET['id'])) {
    header("Location: superadmin_list_user.php");
    exit();
}
$user_id = $_GET['id'];

$user_data = [];

// --- Logika GET: Ambil Data User Saat Ini ---
$select_stmt = mysqli_prepare($conn, "SELECT username, role FROM users WHERE id = ?");
mysqli_stmt_bind_param($select_stmt, "i", $user_id); 
mysqli_stmt_execute($select_stmt);
$result = mysqli_stmt_get_result($select_stmt);

if (mysqli_num_rows($result) === 0) {
    die("User tidak ditemukan.");
}

$user_data = mysqli_fetch_assoc($result);
mysqli_stmt_close($select_stmt);


// --- Logika POST: Simpan Perubahan (Update) ---
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    
    $new_username = trim($_POST['username']);
    $new_role = $_POST['role'];
    $new_password = $_POST['password']; 
    
    if (empty($new_username) || empty($new_role)) {
        $message = "Username dan Role harus diisi!";
    } elseif (!in_array($new_role, ['superadmin', 'employer', 'member'])) {
        $message = "Role tidak valid.";
    } elseif (strlen($new_username) < 4) {
        $message = "Username minimal 4 karakter.";
    } else {
        // Logika UPDATE
        $sql = "UPDATE users SET username = ?, role = ? WHERE id = ?";
        $types = "ssi"; 
        $params = [&$new_username, &$new_role, &$user_id];
        
        if (!empty($new_password)) {
            if (strlen($new_password) < 6) {
                $message = "Password baru minimal 6 karakter. Pembaharuan dibatalkan.";
            } else {
                $hashed_password = password_hash($new_password, PASSWORD_DEFAULT);
                $sql = "UPDATE users SET username = ?, password = ?, role = ? WHERE id = ?";
                $types = "sssi";
                $params = [&$new_username, &$hashed_password, &$new_role, &$user_id];
            }
        }
        
        if ($message == "") {
            $update_stmt = mysqli_prepare($conn, $sql);
            // Menggunakan call_user_func_array untuk bind_param dinamis
            $bind_names[] = $types;
            for ($i=0; $i<count($params);$i++) {
                $bind_name = 'bind' . $i;
                $$bind_name = $params[$i];
                $bind_names[] = &$$bind_name;
            }
            call_user_func_array(array($update_stmt, 'bind_param'), $bind_names);

            if (mysqli_stmt_execute($update_stmt)) {
                $message = "✅ User **berhasil diperbarui**!";
                $user_data['username'] = $new_username;
                $user_data['role'] = $new_role;
            } else {
                $message = "❌ Gagal memperbarui user! Error: " . mysqli_error($conn);
            }
            mysqli_stmt_close($update_stmt);
        }
    }
}
?>

<!DOCTYPE html>
<html lang="id">
<head>
    <title>Edit User</title>
    <link href="https://fonts.googleapis.com/css2?family=Poppins:wght@300;400;600;700&display=swap" rel="stylesheet">
    <style>
        /* --- GLOBAL STYLES --- */
        :root { --primary: #2196F3; --bg: #f4f6f9; --text: #333; }
        * { margin: 0; padding: 0; box-sizing: border-box; font-family: 'Poppins', sans-serif; }
        
        body { 
            background-color: var(--bg); 
            color: var(--text); 
            display: flex; 
            justify-content: center; 
            align-items: center; 
            min-height: 100vh; /* Tengah Vertikal */
            padding: 20px;
        }

        /* --- CARD CONTAINER --- */
        .card {
            background: white;
            padding: 40px;
            width: 100%;
            max-width: 500px;
            border-radius: 16px;
            box-shadow: 0 10px 30px rgba(0,0,0,0.05);
            border-top: 5px solid var(--primary); /* Aksen Biru di Atas */
        }

        /* --- HEADER --- */
        .header { text-align: center; margin-bottom: 30px; }
        .header h2 { font-size: 24px; font-weight: 700; color: #111; margin-bottom: 5px; }
        .header p { color: #666; font-size: 14px; }
        .user-badge { 
            background: #e3f2fd; color: #1976D2; padding: 2px 10px; border-radius: 20px; font-size: 12px; font-weight: 600; text-transform: uppercase;
        }

        /* --- FORM ELEMENTS --- */
        .form-group { margin-bottom: 20px; }
        label { display: block; margin-bottom: 8px; font-size: 14px; font-weight: 600; color: #555; }
        
        input, select {
            width: 100%;
            padding: 12px 15px;
            border: 1px solid #ddd;
            border-radius: 8px;
            font-size: 14px;
            font-family: 'Poppins';
            transition: 0.2s;
            background-color: #fafafa;
        }

        input:focus, select:focus {
            outline: none;
            border-color: var(--primary);
            background-color: #fff;
            box-shadow: 0 0 0 3px rgba(33, 150, 243, 0.1);
        }

        /* --- ALERTS --- */
        .alert { padding: 12px; border-radius: 8px; margin-bottom: 20px; font-size: 14px; text-align: center; font-weight: 500; }
        .success { background: #dcfce7; color: #166534; border: 1px solid #bbf7d0; }
        .error { background: #fee2e2; color: #991b1b; border: 1px solid #fecaca; }

        /* --- BUTTONS --- */
        .btn-submit {
            width: 100%;
            background-color: var(--primary);
            color: white;
            padding: 14px;
            border: none;
            border-radius: 8px;
            font-size: 16px;
            font-weight: 700;
            cursor: pointer;
            transition: 0.2s;
            box-shadow: 0 4px 10px rgba(33, 150, 243, 0.3);
        }
        .btn-submit:hover { background-color: #1976D2; transform: translateY(-2px); }

        .btn-back {
            display: block;
            text-align: center;
            margin-top: 20px;
            text-decoration: none;
            color: #777;
            font-size: 13px;
            font-weight: 500;
            transition: 0.2s;
        }
        .btn-back:hover { color: #333; }

    </style>
</head>
<body>

<div class="card">
    <div class="header">
        <h2>✏️ Edit User</h2>
        <p>Mengubah data untuk: <span class="user-badge"><?php echo htmlspecialchars($user_data['username']); ?></span></p>
    </div>

    <?php 
    if ($message != "") {
        $class = (strpos($message, 'berhasil') !== false) ? 'success' : 'error';
        echo "<div class='alert {$class}'>{$message}</div>";
    }
    ?>

    <form method="POST">
        <div class="form-group">
            <label>Username</label>
            <input type="text" name="username" required minlength="4" value="<?php echo htmlspecialchars($user_data['username']); ?>">
        </div>

        <div class="form-group">
            <label>Ganti Password <span style="font-weight:400; color:#888; font-size:12px;">(Kosongkan jika tidak ganti)</span></label>
            <input type="password" name="password" minlength="6" placeholder="Masukkan password baru...">
        </div>

        <div class="form-group">
            <label>Role / Jabatan</label>
            <select name="role" required>
                <option value="superadmin" <?php echo ($user_data['role'] == 'superadmin') ? 'selected' : ''; ?>>Superadmin</option>
                <option value="employer" <?php echo ($user_data['role'] == 'employer') ? 'selected' : ''; ?>>Employer</option>
                <option value="member" <?php echo ($user_data['role'] == 'member') ? 'selected' : ''; ?>>Member</option>
            </select>
        </div>

        <button type="submit" class="btn-submit">💾 SIMPAN PERUBAHAN</button>
    </form>

    <a href="superadmin_list_user.php" class="btn-back">← Kembali ke Daftar User</a>
</div>

</body>
</html>