import axios from 'axios';

// In dev, Vite proxies /api -> your local PHP server (see vite.config.js).
// In production on cPanel, /api resolves relative to wherever you deploy
// the frontend, so keep the api/ folder alongside the built frontend files
// (see README.md for the exact layout).
const client = axios.create({
  baseURL: '/api',
  withCredentials: true, // send the PHP session cookie
});

client.interceptors.response.use(
  (res) => res,
  (err) => {
    if (err.response && err.response.status === 401) {
      // Session expired or not logged in — bounce to login.
      if (window.location.hash !== '#/login') {
        window.location.hash = '#/login';
      }
    }
    return Promise.reject(err);
  }
);

export default {
  login: (username, password) => client.post('/auth/login.php', { username, password }),
  logout: () => client.post('/auth/logout.php'),
  me: () => client.get('/auth/me.php'),

  getProductGroups: () => client.get('/product_groups.php'),
  createProductGroup: (data) => client.post('/product_groups.php', data),
  updateProductGroup: (data) => client.put('/product_groups.php', data),
  deleteProductGroup: (id) => client.delete(`/product_groups.php?id=${id}`),

  getStyles: (params) => client.get('/styles.php', { params }),

  getCostings: (params) => client.get('/costings.php', { params }),
  createCosting: (data) => client.post('/costings.php', data),
  editPrice: (data) => client.post('/pricing_edit.php', data),

  getSuppliers: () => client.get('/suppliers.php'),
  getImports: () => client.get('/imports.php'),
  createImport: (data) => client.post('/imports.php', data),
  getImportDetail: (id) => client.get(`/import_detail.php?id=${id}`),
  importAction: (data) => client.post('/import_action.php', data),

  getStock: (params) => client.get('/stock.php', { params }),
};
