import axios from 'axios';
import AsyncStorage from '@react-native-async-storage/async-storage';

// ----------------------------------------------------------------
// Change BASE_URL to your PHP server address
// e.g. 'http://192.168.1.10/stile-lpg/backend' for local network
// ----------------------------------------------------------------
export const BASE_URL = 'http://192.168.1.10/stile-lpg/backend';

const api = axios.create({ baseURL: BASE_URL });

// Attach Bearer token to every request
api.interceptors.request.use(async (config) => {
  const token = await AsyncStorage.getItem('token');
  if (token) config.headers.Authorization = `Bearer ${token}`;
  return config;
});

// ============================================================
// Auth
// ============================================================
export const login = async (email: string, password: string) => {
  const { data } = await api.post('/api/auth/login', { email, password });
  await AsyncStorage.setItem('token', data.token);
  await AsyncStorage.setItem('user', JSON.stringify(data.user));
  return data;
};

export const register = async (
  name: string,
  email: string,
  phone: string,
  password: string,
) => {
  const { data } = await api.post('/api/auth/register', { name, email, phone, password });
  return data;
};

export const logout = async () => {
  await AsyncStorage.removeItem('token');
  await AsyncStorage.removeItem('user');
};

export const getStoredUser = async () => {
  const raw = await AsyncStorage.getItem('user');
  return raw ? JSON.parse(raw) : null;
};

// ============================================================
// Products (customer — public list)
// ============================================================
export const fetchProducts = async (category?: string) => {
  const { data } = await api.get('/api/customer/products', {
    params: category ? { category } : {},
  });
  return data;
};

// ============================================================
// Orders (customer)
// ============================================================
export const fetchMyOrders = async () => {
  const { data } = await api.get('/api/customer/orders');
  return data;
};

export const placeOrder = async (payload: {
  items: { productId: string | null; productName?: string; category?: string; quantity: number; price: number }[];
  fulfillment: 'delivery' | 'pickup';
  address?: string;
  notes?: string;
}) => {
  const { data } = await api.post('/api/customer/orders/place', payload);
  return data;
};

// ============================================================
// Profile
// ============================================================
export const fetchProfile = async () => {
  const { data } = await api.get('/api/customer/profile');
  return data;
};

export const updateProfile = async (payload: {
  name: string;
  phone?: string;
  address?: string;
}) => {
  const { data } = await api.patch('/api/customer/profile', payload);
  return data;
};

// ============================================================
// Admin — Products
// ============================================================
export const adminFetchProducts = async () => {
  const { data } = await api.get('/api/admin/products');
  return data;
};

export const adminAddProduct = async (payload: object) => {
  const { data } = await api.post('/api/admin/products', payload);
  return data;
};

export const adminUpdateProduct = async (payload: object) => {
  const { data } = await api.patch('/api/admin/products', payload);
  return data;
};

export const adminDeleteProduct = async (id: string) => {
  const { data } = await api.delete('/api/admin/products', { data: { id } });
  return data;
};

// ============================================================
// Admin — Orders
// ============================================================
export const adminFetchOrders = async () => {
  const { data } = await api.get('/api/admin/orders');
  return data;
};

export const adminUpdateOrderStatus = async (orderId: string, status: string) => {
  const { data } = await api.patch('/api/admin/orders', { orderId, status });
  return data;
};

// ============================================================
// Admin — Users
// ============================================================
export const adminFetchUsers = async () => {
  const { data } = await api.get('/api/admin/users');
  return data;
};

// ============================================================
// Admin — Stats
// ============================================================
export const adminFetchStats = async () => {
  const { data } = await api.get('/api/admin/stats');
  return data;
};

// ============================================================
// Admin — Gallery
// ============================================================
export const adminFetchGallery = async () => {
  const { data } = await api.get('/api/admin/gallery');
  return data;
};

export const adminAddGallery = async (payload: object) => {
  const { data } = await api.post('/api/admin/gallery', payload);
  return data;
};

export const adminDeleteGallery = async (id: string) => {
  const { data } = await api.delete('/api/admin/gallery', { data: { id } });
  return data;
};

// ============================================================
// Admin — Messages
// ============================================================
export const adminFetchMessages = async () => {
  const { data } = await api.get('/api/admin/messages');
  return data;
};

export const adminMarkMessageRead = async (id: string) => {
  const { data } = await api.patch('/api/admin/messages', { id });
  return data;
};

// ============================================================
// Public
// ============================================================
export const fetchGallery = async () => {
  const { data } = await api.get('/api/gallery');
  return data;
};

export const sendContactMessage = async (payload: {
  name: string;
  phone: string;
  service?: string;
  message: string;
}) => {
  const { data } = await api.post('/api/contact', payload);
  return data;
};

export default api;
