import { useState, useRef } from 'react'; import { Button } from "./ui/button"; import { Input } from "./ui/input"; import { Label } from "./ui/label"; import { X } from "lucide-react"; import PocketBase from 'pocketbase'; const PUBLIC_USER_API_URL = import.meta.env.PUBLIC_USER_API_URL; const PUBLIC_POCKETBASE_URL = import.meta.env.PUBLIC_POCKETBASE_URL; const pb = new PocketBase(PUBLIC_POCKETBASE_URL); export function AvatarUpload({ userId }: { userId: string }) { const [selectedFile, setSelectedFile] = useState(null); const [isUploading, setIsUploading] = useState(false); const fileInputRef = useRef(null); const handleFileChange = (e: React.ChangeEvent) => { if (e.target.files && e.target.files.length > 0) { setSelectedFile(e.target.files[0]); } }; const handleRemoveFile = () => { setSelectedFile(null); if (fileInputRef.current) { fileInputRef.current.value = ''; } }; const handleUpload = async () => { if (!selectedFile || !userId) return; setIsUploading(true); try { // 1. Upload to PocketBase const formData = new FormData(); formData.append('avatar', selectedFile); // Update PocketBase user record const pbRecord = await pb.collection('users').update(userId, formData); // Get the avatar URL from PocketBase const avatarUrl = pb.getFileUrl(pbRecord, pbRecord.avatar, { thumb: '100x100' }); // 2. Update PHP backend session const response = await fetch(`${PUBLIC_USER_API_URL}?query=login`, { method: 'POST', credentials: 'include', // Important for sessions to work headers: { 'Content-Type': 'application/json', }, body: JSON.stringify({ avatar: avatarUrl, query: 'avatar_update' }) }); if (!response.ok) { throw new Error('Failed to update session'); } // Success - you might want to refresh the user data or show a success message window.location.reload(); } catch (error) { console.error('Error uploading avatar:', error); alert('Failed to update avatar'); } finally { setIsUploading(false); } }; return (
{!selectedFile ? (

JPG, GIF or PNG. 1MB max.

) : (

{selectedFile.name}

{(selectedFile.size / 1024).toFixed(2)} KB

)}
); }