async function apiRequest(url, options = {}) { const config = { credentials: "same-origin", headers: { ...(options.body instanceof FormData ? {} : { "Content-Type": "application/json" }), ...options.headers }, ...options }; try { const response = await fetch(url, config); let data = null; const contentType = response.headers.get("content-type"); if (contentType && contentType.includes("application/json")) { data = await response.json(); } if (data?.message && data?.category) { showToast(data.category, data.message); } if (!response.ok) { if (response.status === 401) { showToast("error", "Session expired. Redirecting..."); setTimeout(() => window.location.href = "/login", 1500); } else if (response.status === 403) { showToast("error", "You don't have permission."); } else if (response.status >= 500) { showToast("error", "Server error. Please try again."); } throw data || { message: "Request failed" }; } return response; } catch (error) { console.error("API Error:", error); if (!error?.message) { showToast("error", "Network error. Please check connection."); } throw error; } }