async function request(url, options = {}) {
  const isFormData = options.body instanceof FormData;
  const response = await fetch(url, {
    credentials: "same-origin",
    headers: isFormData
      ? { ...(options.headers || {}) }
      : {
          "Content-Type": "application/json",
          ...(options.headers || {})
        },
    ...options
  });

  const data = await response.json().catch(() => ({}));

  if (!response.ok || data.ok === false) {
    throw new Error(data.message || "Bir istek hatasi olustu.");
  }

  return data;
}

export function getSession() {
  return request("/api/session.php");
}

export function login(username, password) {
  return request("/api/login.php", {
    method: "POST",
    body: JSON.stringify({ username, password })
  });
}

export function logout() {
  return request("/api/logout.php", {
    method: "POST",
    body: JSON.stringify({})
  });
}

export async function getPatients() {
  const data = await request("/api/patients.php");
  return data.patients;
}

export async function getPatientBySlug(slug) {
  const data = await request(`/api/patient.php?slug=${encodeURIComponent(slug)}`);
  return {
    ...data.patient,
    orderForms: data.orderForms || [],
    filesCount: Array.isArray(data.files) ? data.files.length : 0
  };
}

export async function getPatientFilesBySlug(slug) {
  return request(`/api/patient-files.php?slug=${encodeURIComponent(slug)}`);
}

export function getOrdersBySlug(slug, formId = 0) {
  const query = new URLSearchParams({ slug });
  if (formId) query.set("formId", String(formId));
  return request(`/api/orders.php?${query.toString()}`);
}

export async function updatePatient(patient) {
  const data = await request("/api/update-patient.php", {
    method: "POST",
    body: patient instanceof FormData ? patient : JSON.stringify(patient)
  });
  return data.patient;
}

export async function createPatient(patient) {
  const data = await request("/api/create-patient.php", {
    method: "POST",
    body: patient instanceof FormData ? patient : JSON.stringify(patient)
  });
  return data.patient;
}

export async function getUsers() {
  const data = await request("/api/users.php");
  return data.users;
}

export function sendNotification(userId, message) {
  return request("/api/send-notification.php", {
    method: "POST",
    body: JSON.stringify({ userId, message })
  });
}

export async function getUnreadNotifications() {
  const data = await request("/api/notifications.php");
  return data.notifications || [];
}

export async function getMessages() {
  const data = await request("/api/messages.php");
  return data.messages || [];
}

export async function getCheckedMessages() {
  const data = await request("/api/checked-messages.php");
  return data.messages || [];
}

export async function getUnreadMessageCount() {
  const data = await request("/api/unread-messages.php");
  return Number(data.count || 0);
}

export function postMessage(message) {
  return request("/api/post-message.php", {
    method: "POST",
    body: JSON.stringify({ message })
  });
}

export function checkMessage(id) {
  return request("/api/check-message.php", {
    method: "POST",
    body: JSON.stringify({ id })
  });
}

export function deleteMessage(id) {
  return request("/api/delete-message.php", {
    method: "POST",
    body: JSON.stringify({ id })
  });
}

export function markNotificationRead(id) {
  return request("/api/mark-notification-read.php", {
    method: "POST",
    body: JSON.stringify({ id })
  });
}

export async function saveUser(user) {
  return request("/api/save-user.php", {
    method: "POST",
    body: JSON.stringify(user)
  });
}

export function deleteUser(id) {
  return request("/api/delete-user.php", {
    method: "POST",
    body: JSON.stringify({ id })
  });
}

export function deletePatient(id) {
  return request("/api/delete-patient.php", {
    method: "POST",
    body: JSON.stringify({ id })
  });
}

export function archivePatient(id) {
  return request("/api/archive-patient.php", {
    method: "POST",
    body: JSON.stringify({ id })
  });
}

export function unarchivePatient(id) {
  return request("/api/unarchive-patient.php", {
    method: "POST",
    body: JSON.stringify({ id })
  });
}

export function uploadPatientFile(formData) {
  return request("/api/upload-patient-file.php", {
    method: "POST",
    body: formData
  });
}

export function updatePatientFile(id, displayName) {
  return request("/api/update-patient-file.php", {
    method: "POST",
    body: JSON.stringify({ id, displayName })
  });
}

export function deletePatientFile(id) {
  return request("/api/delete-patient-file.php", {
    method: "POST",
    body: JSON.stringify({ id })
  });
}

export function updatePatientCategoryNote(patientId, category, note) {
  return request("/api/update-patient-category-note.php", {
    method: "POST",
    body: JSON.stringify({ patientId, category, note })
  });
}

export function saveOrders(patientId, items, formId = 0) {
  return request("/api/save-orders.php", {
    method: "POST",
    body: JSON.stringify({ patientId, formId, items })
  });
}

export function deleteOrder(patientId, formId) {
  return request("/api/delete-order.php", {
    method: "POST",
    body: JSON.stringify({ patientId, formId })
  });
}

export async function getVisitReports() {
  const data = await request("/api/visits.php");
  return data.reports || [];
}

export async function getVisitReport(reportId) {
  const data = await request(`/api/visit-report.php?id=${encodeURIComponent(reportId)}`);
  return {
    report: data.report || null,
    items: data.items || [],
    patientNames: data.patientNames || []
  };
}

export function getSummary(month, year) {
  const query = new URLSearchParams({
    month: String(month),
    year: String(year)
  });
  return request(`/api/summary.php?${query.toString()}`);
}

export function saveVisitReport(reportId, items) {
  return request("/api/save-visit-report.php", {
    method: "POST",
    body: JSON.stringify({ reportId, items })
  });
}

export function deleteVisitReport(reportId) {
  return request("/api/delete-visit-report.php", {
    method: "POST",
    body: JSON.stringify({ reportId })
  });
}

export async function getLogs({ q = "", from = "", to = "", page = 1 } = {}) {
  const query = new URLSearchParams();
  if (q) query.set("q", q);
  if (from) query.set("from", from);
  if (to) query.set("to", to);
  query.set("page", String(page));

  const url = query.toString() ? `/api/logs.php?${query.toString()}` : "/api/logs.php";
  const data = await request(url);
  return {
    logs: data.logs || [],
    onlineUsers: data.onlineUsers || [],
    page: Number(data.page || 1),
    perPage: Number(data.perPage || 30),
    total: Number(data.total || 0),
    totalPages: Number(data.totalPages || 1)
  };
}

export function downloadBackup() {
  window.location.href = "/api/backup-export.php";
}

export function uploadBackup(formData) {
  return request("/api/backup-import.php", {
    method: "POST",
    body: formData
  });
}
