import axios from 'axios';

// Untuk PHP backend, API URL relatif ke domain yang sama
// Jika di localhost: http://localhost/rhelektronik.com/api
// Jika di production: https://rhelektronik.com/api
const API = process.env.REACT_APP_BACKEND_URL 
  ? `${process.env.REACT_APP_BACKEND_URL}/api` 
  : '/api';

export const api = axios.create({
  baseURL: API,
});

// Add token to requests if exists
api.interceptors.request.use((config) => {
  const token = localStorage.getItem('admin_token');
  if (token) {
    config.headers.Authorization = `Bearer ${token}`;
  }
  return config;
});

// Handle errors
api.interceptors.response.use(
  (response) => response,
  (error) => {
    if (error.response?.status === 401) {
      localStorage.removeItem('admin_token');
      // Redirect to login if on admin page
      if (window.location.pathname.includes('/admin') && !window.location.pathname.includes('/login')) {
        window.location.href = '/admin/login';
      }
    }
    return Promise.reject(error);
  }
);

// Auth
export const adminLogin = (credentials) => api.post('/admin/login', credentials);

// Blog - PHP uses query params for ID
export const getBlogPosts = (status = null) => {
  const params = status ? { status } : {};
  return api.get('/blog', { params });
};
export const getBlogPost = (id) => api.get('/blog', { params: { id } });
export const createBlogPost = (data) => api.post('/blog', data);
export const updateBlogPost = (id, data) => api.put('/blog', data, { params: { id } });
export const deleteBlogPost = (id) => api.delete('/blog', { params: { id } });

// Services
export const getServices = () => api.get('/services');
export const createService = (data) => api.post('/services', data);
export const updateService = (id, data) => api.put('/services', data, { params: { id } });
export const deleteService = (id) => api.delete('/services', { params: { id } });

// Brands
export const getBrands = () => api.get('/brands');
export const createBrand = (data) => api.post('/brands', data);
export const updateBrand = (id, data) => api.put('/brands', data, { params: { id } });
export const deleteBrand = (id) => api.delete('/brands', { params: { id } });

// Areas
export const getAreas = () => api.get('/areas');
export const createArea = (data) => api.post('/areas', data);
export const updateArea = (id, data) => api.put('/areas', data, { params: { id } });
export const deleteArea = (id) => api.delete('/areas', { params: { id } });

// Contact
export const getContact = () => api.get('/contact');
export const updateContact = (data) => api.put('/contact', data);

// About
export const getAboutCards = () => api.get('/about');
export const createAboutCard = (data) => api.post('/about', data);
export const updateAboutCard = (id, data) => api.put('/about', data, { params: { id } });
export const deleteAboutCard = (id) => api.delete('/about', { params: { id } });

// Stats
export const getStats = () => api.get('/stats', { params: { type: 'admin' } });
export const getPublicStats = () => api.get('/stats', { params: { type: 'public' } });

// Products
export const getProducts = (category = null, featured = null) => {
  const params = {};
  if (category) params.category = category;
  if (featured !== null) params.featured = featured;
  return api.get('/products', { params });
};
export const getProduct = (id) => api.get('/products', { params: { id } });
export const createProduct = (data) => api.post('/products', data);
export const updateProduct = (id, data) => api.put('/products', data, { params: { id } });
export const deleteProduct = (id) => api.delete('/products', { params: { id } });

// Upload
export const uploadImage = (file) => {
  const formData = new FormData();
  formData.append('file', file);
  return api.post('/upload-image', formData, {
    headers: { 'Content-Type': 'multipart/form-data' }
  });
};
