// api.js
import axios from 'axios';
import { getLoginUser } from 'supportFuctions/getLoginUser';

const userdata = getLoginUser();

const baseapi = axios.create({
  baseURL: 'https://api.workolik.com/api/rest',
  headers: {
    'Content-Type': 'application/json',
    'x-hasura-admin-secret': 'nearle-admin-secret'
  }
});

export const getusers = async ({ tenantid, limit, offset, roleid }) => {
  const res = await baseapi.get('/getusers', {
    params: { roleid, tenantid, limit, offset }
  });

  return res.data.app_users || [];
};

export const getapproles = async () => {
  const res = await baseapi.get('/getapproles?configid=15');
  return res.data.app_roles || [];
};

// ==============================|| tenantgetorders (orders)||============================== //
export const tenantgetorders = async ({ queryKey }) => {
  const [, currentStatus, startdate, enddate, page, rowsPerPage, debouncedSearchword] = queryKey;
  const response = await axios.get(
    `${process.env.REACT_APP_URL}/orders/tenant/getorders/?tenantid=${
      userdata?.tenantid
    }&status=${currentStatus}&fromdate=${startdate}&todate=${enddate}&pageno=${
      page + 1
    }&pagesize=${rowsPerPage}&keyword=${debouncedSearchword}`
  );
  console.log('tenantgetorders', response.data.details);
  return response.data.details;
};

// ==============================|| getOrdersSummary (orders)||============================== //
export const getOrdersSummary = async ({ queryKey }) => {
  const [, startdate = '', enddate = ''] = queryKey;
  const response = await axios.get(
    `${process.env.REACT_APP_URL}/orders/getordersummary/?tenantid=${userdata?.tenantid}&fromdate=${startdate}&todate=${enddate}`
  );
  console.log('getOrdersSummary', response.data.details);
  return response.data.details;
};
// ==============================|| fetchOrderSummary (orders)||============================== //
export const fetchOrderSummary = async () => {
  const response = await axios.get(`${process.env.REACT_APP_URL2}/orders/getordersummary?tenantid=${userdata?.tenantid}`);
  console.log('fetchOrderSummary', response.data.details[0]);
  return response.data.details[0];
};
// ==============================|| fetchLocationSummary (orders)||============================== //
export const fetchLocationSummary = async () => {
  const response = await axios.get(`${process.env.REACT_APP_URL2}/orders/getlocationsummary?tenantid=${userdata?.tenantid}`);
  console.log('fetchLocationSummary', response.data.details);

  return response.data.details;
};

// ==============================|| fetchOrderInsight (orders)||============================== //
export const fetchOrderInsight = async () => {
  const response = await axios.get(`${process.env.REACT_APP_URL2}/orders/getorderinsight?tenantid=${userdata?.tenantid}`);
  console.log('fetchOrderInsight', response.data.details);
  return response.data.details;
};

// ==============================|| getorderdetails (orders) ||============================== //
export const getorderdetails = async (orderHeaderid) => {
  const response = await axios.get(`${process.env.REACT_APP_URL}/orders/getorderdetails?orderheaderid=${orderHeaderid}`);
  return response.data;
};

// ==============================|| cancelOrder (orders) ||============================== //

export const cancelOrder = async (orderHeaderid) => {
  const response = await axios.put(`${process.env.REACT_APP_URL}/orders/updateorder`, {
    orderheaderid: orderHeaderid,
    orderstatus: 'cancelled',
    cancelled: dayjs().format('YYYY-MM-DD HH:mm:ss')
  });
  return response.data;
};

// ==============================|| fetchPaymentType (orders) ||============================== //

export const fetchPaymentType = async () => {
  const { data } = await axios.get(`${process.env.REACT_APP_URL}/utils/getapptypes/?tag=paymentmode`);
  return data.details.map((val) => ({
    ...val,
    label: val.typename
  }));
};

// ==============================|| createDeliveries (orders) ||============================== //

export const createDeliveries = async (deliveryData) => {
  try {
    const response = await axios.post(`${process.env.REACT_APP_URL}/deliveries/createdeliveries`, deliveryData.deliveries);
    console.log(response.data);
    return response.data;
  } catch (err) {
    console.log('createDeliveries', err.message);
    throw err;
  }
};

// ==============================|| cancelDeliveryAPI (deliveries) ||============================== //

export const cancelDeliveryAPI = async (selectedRow, cancelFeed) => {
  const payload = {
    deliveryid: selectedRow.deliveryid,
    orderheaderid: selectedRow.orderheaderid,
    orderstatus: 'cancelled',
    canceltime: dayjs().format('YYYY-MM-DD HH:mm:ss'),
    feedback: cancelFeed
  };
  const response = await axios.put(`${process.env.REACT_APP_URL}/deliveries/updatedelivery`, payload);
  return response.data;
};

// ==============================|| fetchDeliveries (deliveries) ||============================== //

export const fetchDeliveries = async (appId, userid, currentStatus, startdate, enddate, page, rowsPerPage, searchword) => {
  const url = `${process.env.REACT_APP_URL}/deliveries/getdeliveries/?tenantid=${
    userdata?.tenantid
  }&status=${currentStatus}&fromdate=${startdate}&todate=${enddate}&pageno=${page + 1}&pagesize=${rowsPerPage}&keyword=${searchword}`;
  const response = await axios.get(url);
  // Add serial numbers to each row
  return response.data.details.map((val, i) => ({ ...val, sno: i + 1 }));
};

// ==============================|| fetchPercentageAPI (deliveries) ||============================== //

export const fetchPercentageAPI = async () => {
  const url = `${process.env.REACT_APP_URL}/deliveries/deliverysummary/?tenantid=${userdata?.tenantid}`;
  const response = await axios.get(url);
  console.log('response', response);
  const data = response.data.details;
  console.log('data', data);

  return {
    coveredOrders: data.delivered.toString(),
    cancelledOrders: data.cancelled.toString(),
    uncoveredOrders: data.pending.toString(),
    assignedOrders: data.accepted.toString(),
    createdOrders: data.created.toString(),
    closedOrders: data.delivered.toString(),
    pickedOrders: data.picked.toString(),
    percentage1: (Math.round((data.pending / data.total) * 100) || 0).toString(),
    percentage2: (Math.round((data.accepted / data.total) * 100) || 0).toString(),
    percentage3: (Math.round((data.picked / data.total) * 100) || 0).toString(),
    percentage4: (Math.round((data.delivered / data.total) * 100) || 0).toString()
  };
};

// ==============================|| fetchCountAPI (deliveries) ||============================== //

export const fetchCountAPI = async (appId, startdate, enddate) => {
  const url = `${process.env.REACT_APP_URL}/deliveries/deliverysummary/?tenantid=${userdata?.tenantid}&fromdate=${startdate}&todate=${enddate}`;
  const response = await axios.get(url);
  const data = response.data.details;
  return {
    uncoveredLength: data.pending,
    assignedLength: data.accepted,
    arrivedLength: data.arrived,
    pickedLength: data.picked,
    activeLength: data.active,
    coveredLength: data.delivered,
    cancelLength: data.cancelled
  };
};

// ==============================|| fetchRidersList (orders) ||============================== //

export const fetchRidersList = async ({ queryKey }) => {
  const [, appId] = queryKey; // Extract appId from queryKey
  const { data } = await axios.get(`${process.env.REACT_APP_URL}/partners/getriders/?applocationid=${appId}`);
  return data.details.map((val) => ({
    ...val,
    label: `${val.firstname} ${val.lastname} | ${val.contactno}`
  }));
};

// ==============================|| changeRiderAPI (deliveries) ||============================== //

export const changeRiderAPI = async (selectedRider, selectedRow) => {
  return axios.put(`${process.env.REACT_APP_URL}/deliveries/updatedelivery`, {
    userid: selectedRider.userid,
    deliveryid: selectedRow.deliveryid,
    orderheaderid: selectedRow.orderheaderid,
    orderstatus: 'pending',
    assigntime: dayjs().format('YYYY-MM-DD HH:mm:ss')
  });
};
// ==============================|| notifyRider (orders / deliveries) ||============================== //

export const notifyRider = async (riderToken) => {
  try {
    const response = await axios.post(`${process.env.REACT_APP_URL}/utils/notifyuser`, {
      token: riderToken,
      notification: {
        title: 'NearleXpress',
        body: 'Orders have been placed for delivery. Kindly accept and process deliveries',
        sound: 'ring',
        image: ''
      }
    });
    return response.data; // ✅ If success, return the data
  } catch (error) {
    console.error('Notification failed:', error.message);
    throw error; // ✅ Re-throw so calling function (e.g. mutation) can catch it
  }
};

// ==============================|| updateDeliveryAPI (deliveries) ||============================== //

export const updateDeliveryAPI = async (orderData) => {
  return axios.put(`${process.env.REACT_APP_URL}/deliveries/updatedelivery`, orderData);
};

// ==============================|| fetchDeliverySummary (delivery)||============================== //
export const fetchDeliverySummary = async () => {
  const response = await axios.get(`${process.env.REACT_APP_URL}/deliveries/deliverysummary?tenantid=${userdata?.tenantid}`);
  console.log('fetchDeliverySummary', response.data.details);
  return response.data.details;
};

// ==============================|| fetchDeliveryInsight (delivery)||============================== //
export const fetchDeliveryInsight = async () => {
  const response = await axios.get(`${process.env.REACT_APP_URL2}/deliveries/getdeliveryinsight?tenantid=${userdata?.tenantid}`);
  console.log('fetchDeliveryInsight', response.data.details);

  return response.data.details;
};
// ==============================|| fetchDeliveryLocationSummary (delivery)||============================== //
export const fetchDeliveryLocationSummary = async () => {
  const response = await axios.get(`${process.env.REACT_APP_URL2}/deliveries/getlocationsummary?tenantid=${userdata?.tenantid}`);
  console.log('fetchDeliveryLocationSummary', response.data.details);

  return response.data.details;
};

// ==============================|| fetchAllTenants (clients)||============================== //

export const fetchAllTenants = async ({ queryKey }) => {
  const [size, status, pageno, search, rough] = queryKey;
  console.log('fetchAllTenants', size, status, pageno, search, rough);
  let url = '';
  if (search) {
    // url = `${process.env.REACT_APP_URL}/tenants/search/?keyword=${search}`;
    url = `${process.env.REACT_APP_URL}/tenants/search/?keyword=${search}`;
  } else {
    // url = `${process.env.REACT_APP_URL}/tenants/getalltenants?pageno=${pageno}&pagesize=${size}`;
    url = `${process.env.REACT_APP_URL}/tenants/getalltenants?pageno=${pageno}&pagesize=${size}`;
  }
  const response = await axios.get(url);

  // tenants/search/?keyword=${search}
  console.log('fetchAllTenants', response.data.details);

  return response.data.details;
};
// ==============================|| fetchCustomersList (customers)||============================== //
export const fetchCustomersList = async ({ queryKey }) => {
  const [pages] = queryKey;
  const response = await axios.get(`${process.env.REACT_APP_URL}/customers/getallcustomers/?pageno=${pages}&pagesize=10`);
  console.log('fetchCustomersList', response.data.details);
  return response.data.details;
};
// ==============================|| fetchCustomersListBySearch (customers)||============================== //
export const fetchCustomersListBySearch = async ({ queryKey }) => {
  const [search] = queryKey;
  const response = await axios.get(search.lenght > 3 && `${process.env.REACT_APP_URL}/customers/search/?keyword=${search}`);
  console.log('fetchCustomersListBySearch', response.data.details);
  return response.data.details;
};
// ==============================|| fetchOrdersSummary (orders summary)||============================== //
export const fetchOrdersSummary = async ({ queryKey }) => {
  console.log('queryKey for fetchOrdersSummary', queryKey);
  const [id, startdate, enddate] = queryKey;
  const response = await axios.get(
    id == -1
      ? `${process.env.REACT_APP_URL}/deliveries/getreportsummary/?&fromdate=${startdate}&todate=${enddate}`
      : `${process.env.REACT_APP_URL}/deliveries/getreportsummary/?partnerid=${id}&fromdate=${startdate}&todate=${enddate}`
  );
  console.log('fetchOrdersSummary', response.data.details);

  return response.data.details;
};
// ==============================|| fetchLocations (orders summary))||============================== //

export const fetchLocations = async () => {
  const response = await axios.get(`${process.env.REACT_APP_URL}/partners/getpartners`);
  const updatedLocations = [
    ...response.data.details,
    { partnername: 'All', partnerid: -1 } // Add your new object here
  ];
  console.log('fetchLocations', updatedLocations);
  return updatedLocations;
};

// ==============================|| fetchRidersSummary (riders summary)||============================== //

export const fetchRidersSummary = async ({ queryKey }) => {
  console.log('queryKey for fetchRidersSummary', queryKey);
  const [id, startdate, enddate] = queryKey;
  const response = await axios.get(
    id == -1
      ? `${process.env.REACT_APP_URL}/deliveries/getridersummary/?&fromdate=${startdate}&todate=${enddate}`
      : `${process.env.REACT_APP_URL}/deliveries/getridersummary/?applocationid=${id}&fromdate=${startdate}&todate=${enddate}`
  );
  console.log('fetchRidersSummary', response.data.details);

  return response.data.details;
};

// ==============================|| fetchorderdetails (orders detail)||============================== //
export const fetchorderdetails = async ({ queryKey }) => {
  console.log('queryKey of fetchorderdetails', queryKey);
  const [, appId, startdate, enddate] = queryKey;
  const partnerParam = appId === -1 ? '' : `&partnerid=${appId}`;
  const response = await axios.get(
    `${process.env.REACT_APP_URL}/deliveries/getdeliveries/?tenantid=${userdata?.tenantid}${partnerParam}&fromdate=${startdate}&todate=${enddate}`
  );
  console.log('fetchorderdetails', response.data.details);

  return response.data.details || [];
};
// ==============================|| fetchCount (orders detail)||============================== //
export const fetchCount = async ({ queryKey }) => {
  console.log('queryKey of fetchCount', queryKey);
  const [startdate, enddate] = queryKey;
  const response = await axios.get(`${process.env.REACT_APP_URL}/orders/getorders/?fromdate=${startdate}&todate=${enddate}`);
  const calculateOrderCounts = () => {
    let deliveredCount = 0;
    let pendingCount = 0;
    let cancelledCount = 0;

    response.data.details.forEach((order) => {
      const status = order.orderstatus;
      if (status === 'delivered') {
        deliveredCount++;
      } else if (status === 'pending') {
        pendingCount++;
      } else if (status === 'cancelled') {
        cancelledCount++;
      }
    });

    return { deliveredCount, pendingCount, cancelledCount };
  };
  console.log('fetchCount', calculateOrderCounts());

  return calculateOrderCounts();
};

// ==============================|| getproductsubcategories (products)||============================== //

export const getproductsubcategories = async () => {
  try {
    const response = await axios.get(`${process.env.REACT_APP_URL}/products/getproductsubcategories?categoryid=${userdata?.categoryid}`);
    console.log('getproductsubcategories', response.data.details);
    return response.data.details;
  } catch (err) {
    console.log('getproductsubcategories', err);
    return err;
  }
};
// ==============================|| getproductscount (products)||============================== //

export const getproductscount = async (subcatid) => {
  console.log('getproductscount subcat', subcatid);
  try {
    const response = await axios.get(
      `${process.env.REACT_APP_URL}/products/getproductscount?categoryid=${userdata?.categoryid}&subcategoryid=${subcatid}&tenantid=${userdata?.tenantid}`
    );
    console.log('getproductscount', response.data.details[0]);
    return response.data.details[0];
  } catch (err) {
    console.log('getproductscount', err);
    return err;
  }
};
// ==============================|| productsDelete (products)||============================== //

export const productsDelete = async (props) => {
  try {
    const response = await axios.delete(`${process.env.REACT_APP_URL}/products/delete?productid=${props.productid}`, props);
    console.log('productsDelete', response.data.data);
    return response.data.data;
  } catch (err) {
    console.log('productsDelete', err);
    return err;
  }
};

// ==============================|| productsUpdate (products)||============================== //

export const productsUpdate = async (props) => {
  try {
    const response = await axios.put(`${process.env.REACT_APP_URL}/products/update`, props);
    console.log('productsUpdate', response.data.data);
    return response.data.data;
  } catch (err) {
    console.log('productsUpdate', err);
    return err;
  }
};

// ==============================|| getallproducts (products)||============================== //

export const getallproducts = async (subcatid, page, rowsPerPage, search) => {
  console.log(subcatid, page, rowsPerPage, search);
  try {
    const response = await axios.get(
      `${process.env.REACT_APP_URL}/products/getallproducts?categoryid=${userdata?.categoryid}&subcategoryid=${subcatid}&pageno=${
        page + 1
      }&pagesize=${rowsPerPage}&keyword=${search}&tenantid=${userdata?.tenantid}`
    );
    return response.data.data[0]?.products || [];
  } catch (err) {
    console.log('getallproducts', err);
    return [];
  }
};
// ==============================|| getallinfiniteproducts (products)||============================== //

export const getallinfiniteproducts = async ({ pageParam = 0, subcatid, rowsPerPage, search }) => {
  console.log(subcatid, pageParam, rowsPerPage, search);
  try {
    const response = await axios.get(
      `${process.env.REACT_APP_URL}/products/getallproducts?categoryid=${userdata?.categoryid}&subcategoryid=${subcatid}&pageno=${
        pageParam + 1
      }&pagesize=${rowsPerPage}&keyword=${search}&tenantid=${userdata?.tenantid}`
    );
    console.log('again getallinfiniteproducts', response.data.data[0]?.products);
    return response?.data?.data[0]?.products || [];
  } catch (err) {
    console.log('getallinfiniteproducts', err);
    return err;
  }
};

// ==============================|| getproductcategories (products)||============================== //
export const getproductcategories = async () => {
  try {
    const response = await axios.get(`${process.env.REACT_APP_URL}/products/getproductcategories`);
    console.log('getproductcategories', response.data.details);
    return response.data.details;
  } catch (err) {
    console.log('getproductcategories', err);
    return err;
  }
};

// ==============================|| getsubcategories (products)||============================== //
export const getsubcategories = async () => {
  try {
    const response = await axios.get(
      `${process.env.REACT_APP_URL}/utils/getsubcategories/?categoryid=${userdata?.categoryid}&moduleid=${moduleid}`
    );
    console.log('getsubcategories', response.data.details);
    return response.data.details;
  } catch (err) {
    console.log('getsubcategories', err);
    return err;
  }
};
// ==============================|| getProductUnits (products)||============================== //

export const getProductUnits = async () => {
  try {
    const response = await axios.get(`${process.env.REACT_APP_URL}/utils/getapptypes/?tag=uom`);
    console.log('productUnits', response.data.details);
    return response.data.details;
  } catch (err) {
    console.log('productUnits', err);
    return err;
  }
};

// ==============================|| getproductvariants (products)||============================== //

export const getproductvariants = async ({ queryKey }) => {
  const [, subcategoryid] = queryKey;
  try {
    const response = await axios.get(
      `${process.env.REACT_APP_URL}/products/getproductvariants?tenantid=${userdata?.tenantid}&subcategoryid=${subcategoryid}`
    );
    console.log('getproductvariants', response.data.details);
    return response.data.details;
  } catch (err) {
    console.log('getproductvariants', err);
    throw err;
  }
};
// ==============================|| productCreate (products)||============================== //

export const productCreate = async (props) => {
  try {
    const response = await axios.post(
      `${process.env.REACT_APP_URL}/products/create`,
      // props
      { ...props, tenantid: userdata?.tenantid }
    );
    console.log('productCreate', response.data.data);
    return response.data.data;
  } catch (err) {
    console.log('productCreate', err);
    // return err;
    throw err; // ✅ this tells React Query it's a failed mutation
  }
};

// ==============================|| fetchAppLocations (report summary))||============================== //

export const fetchAppLocations = async () => {
  // const response = await axios.get(`${process.env.REACT_APP_URL}/partners/getpartners`);
  const response = await axios.get(`${process.env.REACT_APP_URL}/utils/getapplocations`);
  const updatedLocations = [
    ...response.data.details,
    { locationname: 'All', applocationid: 0 } // Add your new object here
  ];
  console.log('fetchAppLocations', updatedLocations);

  return updatedLocations;
};

// ==============================|| getAllUsers (report summary))||============================== //

export const getAllUsers = async (queryKey) => {
  const [_key, roleId, page, rowsPerPage, debouncedSearchword] = queryKey;
  console.log(_key, roleId);
  const response = await axios.get(
    `${process.env.REACT_APP_URL}/users/getallusers?tenantid=${userdata?.tenantid}&roleid=${roleId}&pageno=${
      page + 1
    }&pagesize=${rowsPerPage}&keyword=${debouncedSearchword}`
  );
  return response.data.details;
};

// ==============================|| getridershifts (users ))||============================== //

export const getRiderShifts = async () => {
  const res = await axios.get(`${process.env.REACT_APP_URL}/partners/getridershifts/?applocationid=${appId}`);
  return res.data.details;
};

// ============================================= || gettenantlocations (locations) || =============================================
export const gettenantlocations = async () => {
  try {
    const res = await axios.get(`${process.env.REACT_APP_URL}/tenants/gettenantlocations/?tenantid=${userdata?.tenantid}`);
    console.log('gettenantlocations response', res.data.details);

    if (res.data.status) {
      return res.data.details;
    } else {
      console.warn('gettenantlocations failed', res.data);
      return [];
    }
  } catch (err) {
    console.error('gettenantlocations error', err);
    return [];
  }
};
