if (isset($_FILES['upload']) && $_FILES['upload']['error'] === UPLOAD_ERR_OK) {
    $allowedTypes = ['image/jpeg', 'image/jpg', 'image/png'];
    $maxSize = 800 * 1024; // 800KB
    $fileTmpPath = $_FILES['upload']['tmp_name'];
    $fileName = basename($_FILES['upload']['name']);
    $fileSize = $_FILES['upload']['size'];
    $fileType = mime_content_type($fileTmpPath);
    $ext = pathinfo($fileName, PATHINFO_EXTENSION);

    if (in_array($fileType, $allowedTypes) && $fileSize <= $maxSize) {
        $uploadDir = 'uploads/';
        if (!file_exists($uploadDir)) {
            mkdir($uploadDir, 0755, true);
        }

        $newFileName = uniqid('avatar_') . '.' . $ext;
        $destPath = $uploadDir . $newFileName;

        if (move_uploaded_file($fileTmpPath, $destPath)) {
            $user_image = $newFileName;
        } else {
            echo "<script>alert('Gagal memuat naik gambar.'); window.history.back();</script>";
            exit;
        }
    } else {
        echo "<script>alert('Jenis atau saiz gambar tidak sah.'); window.history.back();</script>";
        exit;
    }
}
