// ============================================================
// frontend/assets/js/api.js  — Centralized API client
// ============================================================

// ⚠️ WAMP: use http://localhost/healthagency/backend
// ⚠️ cPanel: use https://yourdomain.com/backend  (or /api if you rename)
const API_BASE = 'http://localhost/healthagency/backend';

/**
 * Core fetch wrapper — attaches JWT token automatically
 */
async function apiRequest(endpoint, method = 'GET', body = null) {
  const token = localStorage.getItem('ha_token');
  const headers = { 'Content-Type': 'application/json' };
  if (token) headers['Authorization'] = `Bearer ${token}`;

  const options = { method, headers };
  if (body && method !== 'GET') options.body = JSON.stringify(body);

  try {
    const res  = await fetch(`${API_BASE}${endpoint}`, options);
    const data = await res.json();
    return { ok: res.ok, status: res.status, ...data };
  } catch (err) {
    return { ok: false, success: false, message: 'Network error. Please check your connection.' };
  }
}

// ---- Auth ----
const Auth = {
  register: (body)  => apiRequest('/auth/register', 'POST', body),
  login:    (body)  => apiRequest('/auth/login',    'POST', body),
  me:       ()      => apiRequest('/auth/me'),
  logout:   ()      => { localStorage.removeItem('ha_token'); localStorage.removeItem('ha_user'); },
  saveSession: (token, user) => {
    localStorage.setItem('ha_token', token);
    localStorage.setItem('ha_user', JSON.stringify(user));
  },
  getUser: () => {
    try { return JSON.parse(localStorage.getItem('ha_user')); } catch { return null; }
  },
  isLoggedIn: () => !!localStorage.getItem('ha_token'),
  isAdmin:    () => { const u = Auth.getUser(); return u && u.role === 'admin'; },
};

// ---- Events ----
const Events = {
  all:      (status = '') => apiRequest(`/events${status ? '?status=' + status : ''}`),
  single:   (id)          => apiRequest(`/events/${id}`),
};

// ---- Classes ----
const Classes = {
  all:      ()     => apiRequest('/classes'),
  single:   (id)   => apiRequest(`/classes/${id}`),
  enroll:   (body) => apiRequest('/classes/enroll', 'POST', body),
  mine:     ()     => apiRequest('/classes/mine'),
};

// ---- Products ----
const Products = {
  all:    (params = {}) => {
    const q = new URLSearchParams(params).toString();
    return apiRequest(`/products${q ? '?' + q : ''}`);
  },
  single: (id) => apiRequest(`/products/${id}`),
};

// ---- Uploads ----
const Uploads = {
  upload: async (file) => {
    const token = localStorage.getItem('ha_token');
    const form  = new FormData();
    form.append('image', file);
    try {
      const res = await fetch(`${API_BASE}/uploads`, {
        method:  'POST',
        headers: { 'Authorization': `Bearer ${token}` },
        body:    form,
      });
      return await res.json();
    } catch {
      return { success: false, message: 'Network error during upload' };
    }
  },
  list:   ()         => apiRequest('/uploads'),
  show:   (id)       => apiRequest(`/uploads/${id}`),
  delete: (filename) => apiRequest(`/uploads/${filename}`, 'DELETE'),
};

// ---- Orders ----
const Orders = {
  create:   (body) => apiRequest('/orders', 'POST', body),
  mine:     ()     => apiRequest('/orders/mine'),
  single:   (id)   => apiRequest(`/orders/${id}`),
};

// ---- Payments ----
const Payments = {
  verify: (reference) => apiRequest('/payments/verify', 'POST', { reference }),
};

// ---- Admin ----
const Admin = {
  stats:          ()       => apiRequest('/admin/stats'),
  // classes
  classes:        ()       => apiRequest('/admin/classes'),
  createClass:    (b)      => apiRequest('/admin/classes', 'POST', b),
  updateClass:    (id, b)  => apiRequest(`/admin/classes/${id}`, 'PUT', b),
  deleteClass:    (id)     => apiRequest(`/admin/classes/${id}`, 'DELETE'),
  // products
  products:       ()       => apiRequest('/admin/products'),
  createProduct:  (b)      => apiRequest('/admin/products', 'POST', b),
  updateProduct:  (id, b)  => apiRequest(`/admin/products/${id}`, 'PUT', b),
  deleteProduct:  (id)     => apiRequest(`/admin/products/${id}`, 'DELETE'),
  // events
  events:         ()       => apiRequest('/admin/events'),
  createEvent:    (b)      => apiRequest('/admin/events', 'POST', b),
  updateEvent:    (id, b)  => apiRequest(`/admin/events/${id}`, 'PUT', b),
  deleteEvent:    (id)     => apiRequest(`/admin/events/${id}`, 'DELETE'),
  // orders
  orders:         ()       => apiRequest('/admin/orders'),
  updateOrder:    (id, b)  => apiRequest(`/admin/orders/${id}`, 'PUT', b),
  // users
  users:          ()       => apiRequest('/admin/users'),
};

// ============================================================
// Cart (stored in localStorage, synced at checkout)
// ============================================================
const Cart = {
  _key: 'ha_cart',

  get: () => {
    try { return JSON.parse(localStorage.getItem(Cart._key)) || []; } catch { return []; }
  },

  save: (items) => localStorage.setItem(Cart._key, JSON.stringify(items)),

  add: (product, qty = 1) => {
    const items = Cart.get();
    const idx   = items.findIndex(i => i.product_id === product.id);
    if (idx > -1) {
      items[idx].quantity += qty;
    } else {
      items.push({
        product_id: product.id,
        name:       product.name,
        price:      product.price,
        image:      product.image,
        quantity:   qty,
      });
    }
    Cart.save(items);
    Cart.updateBadge();
  },

  remove: (productId) => {
    Cart.save(Cart.get().filter(i => i.product_id !== productId));
    Cart.updateBadge();
  },

  updateQty: (productId, qty) => {
    const items = Cart.get().map(i =>
      i.product_id === productId ? { ...i, quantity: Math.max(1, qty) } : i
    );
    Cart.save(items);
    Cart.updateBadge();
  },

  clear: () => { localStorage.removeItem(Cart._key); Cart.updateBadge(); },

  total: () => Cart.get().reduce((sum, i) => sum + i.price * i.quantity, 0),

  count: () => Cart.get().reduce((sum, i) => sum + i.quantity, 0),

  updateBadge: () => {
    const badge = document.getElementById('cart-badge');
    if (badge) {
      const count = Cart.count();
      badge.textContent = count;
      badge.style.display = count > 0 ? 'inline-flex' : 'none';
    }
  },
};

// ============================================================
// Utility helpers
// ============================================================
const Utils = {
  formatCurrency: (n) => '₦' + Number(n).toLocaleString('en-NG', { minimumFractionDigits: 2 }),
  formatDate:     (d) => new Date(d).toLocaleDateString('en-NG', { year:'numeric', month:'long', day:'numeric' }),
  formatDateTime: (d) => new Date(d).toLocaleString('en-NG', { year:'numeric', month:'long', day:'numeric', hour:'2-digit', minute:'2-digit' }),

  toast: (message, type = 'success') => {
    const t = document.createElement('div');
    t.className = `ha-toast ha-toast--${type}`;
    t.innerHTML = `<span>${message}</span>`;
    document.body.appendChild(t);
    setTimeout(() => t.classList.add('show'), 10);
    setTimeout(() => { t.classList.remove('show'); setTimeout(() => t.remove(), 400); }, 3500);
  },

  spinner: (el, show) => {
    if (show) {
      el.disabled = true;
      el.dataset.original = el.innerHTML;
      el.innerHTML = '<span class="spinner-border spinner-border-sm me-2"></span>Loading...';
    } else {
      el.disabled = false;
      el.innerHTML = el.dataset.original || el.innerHTML;
    }
  },

  redirectIfNotLoggedIn: () => {
    if (!Auth.isLoggedIn()) {
      window.location.href = '/healthagency/frontend/pages/login.html';
    }
  },

  redirectIfNotAdmin: () => {
    if (!Auth.isAdmin()) {
      window.location.href = '/healthagency/frontend/pages/login.html';
    }
  },
};

// Init cart badge on every page load
document.addEventListener('DOMContentLoaded', () => Cart.updateBadge());
