<?php
require '../db.php';
require '../auth.php';
require_login();
require_admin();

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $id = (int)($_POST['id'] ?? 0);
    $username = trim($_POST['username'] ?? '');
    $nama_lengkap = trim($_POST['nama_lengkap'] ?? '');
    $password = $_POST['password'] ?? '';
    $role = $_POST['role'] ?? '';
    
    // Validate required fields
    if ($id <= 0 || empty($username) || empty($nama_lengkap) || empty($role)) {
        header('Location: users.php?error=Data tidak lengkap');
        exit;
    }
    
    // Validate role
    if (!in_array($role, ['admin', 'petugas'])) {
        header('Location: users.php?error=Role tidak valid');
        exit;
    }
    
    // Check if user exists
    $check = $db->prepare('SELECT id FROM users WHERE id = ?');
    $check->execute([$id]);
    if (!$check->fetch()) {
        header('Location: users.php?error=User tidak ditemukan');
        exit;
    }
    
    // Check if username is taken by other user
    $check_username = $db->prepare('SELECT id FROM users WHERE username = ? AND id != ?');
    $check_username->execute([$username, $id]);
    if ($check_username->fetch()) {
        header('Location: users.php?error=Username sudah digunakan oleh user lain');
        exit;
    }
    
    try {
        if (!empty($password)) {
            // Update with new password
            if (strlen($password) < 6) {
                header('Location: users.php?error=Password minimal 6 karakter');
                exit;
            }
            $stmt = $db->prepare('UPDATE users SET username = ?, nama_lengkap = ?, password_hash = ?, role = ? WHERE id = ?');
            $result = $stmt->execute([$username, $nama_lengkap, password_hash($password, PASSWORD_DEFAULT), $role, $id]);
        } else {
            // Update without changing password
            $stmt = $db->prepare('UPDATE users SET username = ?, nama_lengkap = ?, role = ? WHERE id = ?');
            $result = $stmt->execute([$username, $nama_lengkap, $role, $id]);
        }
        
        if ($result) {
            header('Location: users.php?success=updated');
        } else {
            header('Location: users.php?error=Gagal mengupdate akun');
        }
    } catch (PDOException $e) {
        header('Location: users.php?error=Error: ' . $e->getMessage());
    }
} else {
    header('Location: users.php');
}
exit;
?>
