/* ============================================================
   API Client — talks to /api/admin/*.php endpoints
   ============================================================ */

const API = {
  base: '../api/admin',

  getToken() {
    return localStorage.getItem('admin_token') || '';
  },

  setToken(token) {
    if (token) localStorage.setItem('admin_token', token);
    else localStorage.removeItem('admin_token');
  },

  async request(method, path, body = null, isMultipart = false) {
    const headers = {};
    const token = this.getToken();
    if (token) headers['Authorization'] = 'Bearer ' + token;

    const options = { method, headers };

    if (body && isMultipart) {
      options.body = body; // FormData — browser sets multipart boundary
    } else if (body) {
      headers['Content-Type'] = 'application/json';
      options.body = JSON.stringify(body);
    }

    let response;
    try {
      response = await fetch(this.base + path, options);
    } catch (err) {
      throw new Error('Network error — check your connection or server status.');
    }

    let json;
    try {
      json = await response.json();
    } catch (err) {
      throw new Error('Server returned an invalid response.');
    }

    if (response.status === 401) {
      this.setToken(null);
      if (!path.includes('login')) {
        window.location.reload();
      }
    }

    if (!json.success) {
      throw new Error(json.message || 'Request failed.');
    }

    return json.data;
  },

  get(path) { return this.request('GET', path); },
  post(path, body, isMultipart = false) { return this.request('POST', path, body, isMultipart); },
  put(path, body, isMultipart = false) { return this.request('PUT', path, body, isMultipart); },
  patch(path, body) { return this.request('PATCH', path, body); },
  del(path) { return this.request('DELETE', path); },
};
