import axios from 'axios';
import { OpenToast } from 'components/third-party/OpenToast';
import dayjs from 'dayjs';
const userid = localStorage.getItem('userid');

// ==============================|| getRiderPeriodicLogs ||============================== //
// Returns the rider's latest periodic log entry — battery, GPS, status, current
// order. Used by the Rider Info modal on the Dispatch page.
export const getRiderPeriodicLogs = async (userid) => {
  const url = `${process.env.REACT_APP_URL}/utils/getriderperiodiclogs${userid ? `?userid=${userid}` : ''}`;
  const response = await axios.get(url);
  if (response.data && response.data.status) return response.data.data;
  return null;
};

// ==============================|| fetchAppLocations||============================== //

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

  return updatedLocations;
};

// ==============================|| fetchPercentageData (orders) ||============================== //

export const fetchPercentageData = async (appId) => {
  const response = await axios.get(`${process.env.REACT_APP_URL}/orders/getordersummary/?applocationid=${appId}`);
  const details = response.data.details;

  return {
    created: details.created.toString(),
    uncoveredOrders: details.pending.toString(),
    coveredOrders: details.delivered.toString(),
    cancelled: details.cancelled.toString(),
    percentage1: (Math.round((details.created / details.total) * 100) || 0).toString(),
    percentage2: (Math.round((details.pending / details.total) * 100) || 0).toString(),
    percentage3: (Math.round((details.delivered / details.total) * 100) || 0).toString(),
    percentage4: (Math.round((details.cancelled / details.total) * 100) || 0).toString()
  };
};
// ===================================================== || getTenants || =====================================================

export const getTenants = async (appId) => {
  const response = await axios.get(`${process.env.REACT_APP_URL}/tenants/gettenants/?applocationid=${appId}&status=active`);
  if (response.data.status) {
    let arr = [];
    response.data.details.map((val) => {
      arr.push({
        ...val,
        label: `${val.tenantname}`
      });
    });
    return arr;
  }
};
// ============================================= || gettenantlocations (branches) || =============================================
export const gettenantlocations = async (appId) => {
  try {
    const res = await axios.get(`${process.env.REACT_APP_URL}/tenants/gettenantlocations/?tenantid=${appId}`);
    return res.data.details;
  } catch (err) {
    console.log('gettenantlocations', err);
  }
};
// ==============================|| fetchorderscount (orders) ||============================== //

export const fetchorderscount = async ({ queryKey }) => {
  const [, appId, startdate, enddate, currentStatus, tenantid, locationid] = queryKey;

  const url = `${process.env.REACT_APP_URL}/orders/getordersummary/?applocationid=${appId}&tenantid=${tenantid}&locationid=${locationid}&fromdate=${startdate}&todate=${enddate}&status=${currentStatus}`;

  const response = await axios.get(url);

  return response.data.details;
};

// ==============================|| fetchOrders (orders) ||============================== //

// export const fetchOrders = async ({ queryKey }) => {
//   const [, appId, currentStatus, searchword, startdate, enddate, page, rowsPerPage, tenantid, locationid] = queryKey;
//   const url = `${
//     process.env.REACT_APP_URL
//   }/orders/getorders/?applocationid=${appId}&tenantid=${tenantid}&locationid=${locationid}&status=${currentStatus}&fromdate=${startdate}&todate=${enddate}&pageno=${
//     page + 1
//   }&pagesize=${rowsPerPage}&keyword=${searchword}`;
//   const response = await axios.get(url);
//   return response.data.details.map((val, i) => ({ ...val, sno: i + 1 }));
// };
export const fetchOrders = async ({ pageParam = 1, queryKey }) => {
  const [, appId, currentStatus, debouncedSearch, startdate, enddate, rowsPerPage, tenantid, locationid] = queryKey;

  const url = `${process.env.REACT_APP_URL}/orders/tenant/getorders/?applocationid=${appId}&tenantid=${tenantid}&locationid=${locationid}&status=${currentStatus}&fromdate=${startdate}&todate=${enddate}&keyword=${debouncedSearch}&pageno=${pageParam}&pagesize=${rowsPerPage}`;

  const response = await axios.get(url);

  return {
    rows: response.data.details,
    nextPage: response.data.details.length === Number(rowsPerPage) ? pageParam + 1 : undefined
  };
};

// ==============================|| 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
  }));
};

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

export const fetchRidersList = async ({ queryKey }) => {
  try {
    const [, appId] = queryKey; // Extract appId from queryKey
    const { data } = await axios.get(`${process.env.REACT_APP_URL}/partners/getriders/?applocationid=${appId}`);
    console.log('data', data);
    const response = data?.details
      ? data?.details.map((val) => ({
        ...val,
        label: `${val.firstname} ${val.lastname} | ${val.contactno}`
      }))
      : [];
    return response;
  } catch (err) {
    OpenToast(err.message, 'error', 2000);
    throw err; // 🔥 REQUIRED
  }
};

// ==============================|| createOptimisationDeliveries (orders) Arrange  the order ||============================== //

export const createOptimisationDeliveries = async (deliveryData) => {
  // optimse the orders
  const response = await axios.post(`https://routes.workolik.com/api/v1/optimization/createdeliveries`, deliveryData.deliveries);
  return response.data;
};
// ==============================|| reconcileSteps (Preview - validate rider/order step assignments) ||============================== //

export const reconcileSteps = async ({ riders }) => {
  const response = await axios.post(
    `https://routes.workolik.com/api/v1/optimization/reconcile-steps`,
    { riders }
  );
  return response.data;
};

// ==============================|| fetchBatchEfficiency (Dispatch - Analysis view) ||============================== //
// Calls POST /api/v1/batch/efficiency with a JSON body { batch, tenant_id }.
// `batch` is one of: 'morning' | 'afternoon' | 'evening'.

export const fetchBatchEfficiency = async ({ batch, tenantId }) => {
  const response = await axios.post(
    `https://routes.workolik.com/api/v1/batch/efficiency`,
    {
      batch,
      tenant_id: tenantId
    },
    {
      headers: { 'Content-Type': 'application/json' },
      // Let success:false envelopes flow through so the UI can surface the
      // server's own error message (instead of axios throwing on 4xx/5xx).
      validateStatus: () => true
    }
  );
  return response.data;
};
// ==============================|| finalCreatedeliveries (orders) ||============================== //

export const finalCreatedeliveries = async (deliveryData) => {
  // Go backend types Deliveries.userid (and rider_id) as int. Coerce at the
  // boundary so any upstream string — including ones that only surface in the
  // deployed build's data flow — can't cause a 500 unmarshal error.
  const toInt = (v) => {
    const n = Number(v);
    return Number.isFinite(n) ? n : v;
  };
  const deliveries = (deliveryData.deliveries || []).map((d) => ({
    ...d,
    userid: toInt(d.userid),
    rider_id: toInt(d.rider_id)
  }));
  console.log('deliveryData', deliveries);
  const response = await axios.post(`https://jupiter.nearle.app/live/api/v1/deliveries/createdeliveries`, deliveries);
  return response.data;
};
// ==============================|| createAutomationDeliveries (orders)  Auto rider Assign ||============================== //

export const createAutomationDeliveries = async (variables) => {
  console.log('variables', variables);

  const absentRiders = Array.isArray(variables.absent_riders) ? variables.absent_riders : [];

  // Bike mode (routes.workolik) historically accepted just the deliveries
  // array as the body. To carry the operator's "Absent Riders" picks
  // through to the AI assignment, we now wrap the body as
  //   { deliveries: [...], absent_riders: [...] }
  // for that endpoint. Auto mode (routemate) already uses a structured
  // body via `variables.data`, so we just merge absent_riders into it.
  const url =
    variables.selectedMode.value == 1
      ? `https://routes.workolik.com/api/v1/optimization/riderassign?hypertuning_params=${variables.hypertuning_params}`
      : `https://routemate.workolik.com/api/v1/optimization/riderassign?strategy=multi_trip`;

  const body =
    variables.selectedMode.value == 1
      ? { deliveries: variables.deliveries, absent_riders: absentRiders }
      : { ...(variables.data || {}), absent_riders: absentRiders };

  console.log('createAutomationDeliveries body', body);

  const response = await axios.post(url, body);
  return response.data;
};

// ==============================|| notifyRider (orders / deliveries) ||============================== //

export const notifyRider = async (riderToken) => {
  if (!riderToken) {
    throw new Error('Invalid rider token');
  }
  console.log('notify rider called');
  console.log('riderToken', riderToken);
  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;
};

// ==============================|| 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;
};
// ==============================|| cancelMultipleOrder (orders) ||============================== //

export const cancelMultipleOrder = async (orderlist) => {
  console.log('data', orderlist);

  const data = orderlist?.map((e) => ({
    orderheaderid: e.orderheaderid,
    orderstatus: 'cancelled',
    cancelled: dayjs().format('YYYY-MM-DD HH:mm:ss')
  }));

  // Send request if needed
  const response = await axios.put(`${process.env.REACT_APP_URL}/orders/updatemultipleorders`, data);
  return response.data;
};
// ==============================|| fetchDeliveries (deliveries) ||============================== //

export const fetchDeliveries = async ({ pageParam = 1, queryKey }) => {
  let [, appId, userid, currentStatus, startdate, enddate, rowsPerPage, searchword, tenantid, locationid, riderid] = queryKey;
  currentStatus = currentStatus == 'All' ? 'all' : currentStatus;
  const url =
    appId === 0
      ? `${process.env.REACT_APP_URL}/deliveries/getdeliveries/?appuserid=${userid}&status=${currentStatus}&fromdate=${startdate}&todate=${enddate}&pageno=${pageParam}&pagesize=${rowsPerPage}&keyword=${searchword}&tenantid=${tenantid}&locationid=${locationid}&userid=${riderid}`
      : `${process.env.REACT_APP_URL}/deliveries/getdeliveries/?applocationid=${appId}&status=${currentStatus}&fromdate=${startdate}&todate=${enddate}&pageno=${pageParam}&pagesize=${rowsPerPage}&keyword=${searchword}&tenantid=${tenantid}&locationid=${locationid}&userid=${riderid}`;
  const response = await axios.get(url);

  return {
    rows: response.data.details,
    nextPage: response.data.details.length === Number(rowsPerPage) ? pageParam + 1 : undefined
  };
};

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

export const fetchPercentageAPI = async (appId) => {
  const url = `${process.env.REACT_APP_URL}/deliveries/deliverysummary/?applocationid=${appId}`;
  const response = await axios.get(url);

  const data = response.data.details;

  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, userid, startdate, enddate, rowsPerPage, debouncedSearch, tenantid, locationid, riderid) => {
  const url =
    appId == 0
      ? `${process.env.REACT_APP_URL}/deliveries/deliverysummary/?appuserid=${userid}&fromdate=${startdate}&todate=${enddate}`
      : `${process.env.REACT_APP_URL}/deliveries/deliverysummary/?applocationid=${appId}&fromdate=${startdate}&todate=${enddate}&tenantid=${tenantid}&locationid=${locationid}&userid=${riderid}`;
  const response = await axios.get(url);
  const data = response.data.details;
  return {
    total: data.total,
    uncoveredLength: data.pending,
    assignedLength: data.accepted,
    arrivedLength: data.arrived,
    pickedLength: data.picked,
    activeLength: data.active,
    coveredLength: data.delivered,
    cancelLength: data.cancelled,
    skippedLength: data.skipped
  };
};

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

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

export const changeRiderAPI = async (selectedRider, selectedRow) => {
  console.log('selectedRider', selectedRider);
  console.log('selectedRow', 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')
  });
};
// ==============================|| updateDeliveryAPI (deliveries) ||============================== //

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

// ==============================|| getalltenants (tenants) ||============================== //

export const getalltenants = async ({ queryKey }) => {
  const [, appId, debouncedSearch, status, page, rowsPerPage] = queryKey;
  try {
    let url = `${process.env.REACT_APP_URL
      }/tenants/getalltenants/?status=${status}&applocationid=${appId}&keyword=${debouncedSearch}&pageno=${page + 1
      }&pagesize=${rowsPerPage}&moduleid=6`;
    const response = await axios.get(url);
    return response.data.details; // return only data, keep it clean
  } catch (err) {
    const message = err.response?.data?.message || err.message || 'Something went wrong';
    OpenToast(message);
    return null; // return null for failure
  }
};
// ==============================|| gettenantsummary (tenants) ||============================== //

export const gettenantsummary = async ({ queryKey }) => {
  const [, appId] = queryKey;
  try {
    const response = await axios.get(`${process.env.REACT_APP_URL}/tenants/gettenantsummary/?moduleid=6&applocationid=${appId}`);
    return response.data.summary; // return only data, keep it clean
  } catch (err) {
    const message = err.response?.data?.message || err.message || 'Something went wrong';
    OpenToast(message);
    return null; // return null for failure
  }
};
// ==============================|| getpricinglist (tenants) ||============================== //

export const getpricinglist = async ({ queryKey }) => {
  const [, appId] = queryKey;
  try {
    const response = await axios.get(`${process.env.REACT_APP_URL}/tenants/getpricinglist/?moduleid=6&applocationid=${appId}`);
    return response.data.summary; // return only data, keep it clean
  } catch (err) {
    const message = err.response?.data?.message || err.message || 'Something went wrong';
    OpenToast(message);
    return null; // return null for failure
  }
};
// ==============================|| getallpricing (clientPricing) ||============================== //

export const getallpricing = async ({ queryKey }) => {
  const [, appId] = queryKey;
  try {
    const response = await axios.get(`${process.env.REACT_APP_URL}/utils/getallpricing/?applocationid=${appId}`);
    return response.data.details || [];
  } catch (err) {
    const message = err.response?.data?.message || err.message || 'Something went wrong';
    OpenToast(message);
    return [];
  }
};

// ==============================|| getcustomersummary (customers) ||============================== //

export const getcustomersummary = async ({ queryKey }) => {
  const [, appId] = queryKey;
  try {
    const response = await axios.get(`${process.env.REACT_APP_URL}/customers/getcustomersummary?applocationid=${appId}`);
    return response.data.summary;
  } catch (err) {
    const message = err.response?.data?.message || err.message || 'Something went wrong';
    OpenToast(message);
    return null; // return null for failure
  }
};

// ==============================|| getallcustomers (customers) ||============================== //

export const getallcustomers = async ({ pageParam = 1, queryKey }) => {
  const [, appId, debouncedSearch, rowsPerPage] = queryKey;

  try {
    const response = await axios.get(`${process.env.REACT_APP_URL}/customers/getallcustomers/`, {
      params: {
        applocationid: appId,
        keyword: debouncedSearch,
        pageno: pageParam,
        pagesize: rowsPerPage
      }
    });

    return {
      data: response.data.details || [],
      nextPage: response.data.details?.length === rowsPerPage ? pageParam + 1 : undefined
    };
  } catch (err) {
    const message = err.response?.data?.message || err.message || 'Something went wrong';

    OpenToast(message);
    throw err; // IMPORTANT for React Query
  }
};

// ==============================|| fetchAllRiders (riders)  ||============================== //
export const fetchAllRiders = async ({ pageParam = 1, queryKey }) => {
  try {
    const [, appId, debouncedSearch, tabvalue] = queryKey;

    const url = `${process.env.REACT_APP_URL
      }/partners/getallriders/?applocationid=${appId}&pageno=${pageParam}&pagesize=${20}&keyword=${debouncedSearch}&status=${tabvalue == 0 ? '' : 'Active'
      }`;
    const res = await axios.get(url);
    return {
      details: res.data.details,
      nextPage: res.data.details.length === 20 ? pageParam + 1 : undefined
    };
  } catch (err) {
    console.log('fetchAllRiders err', err.message);
    return [];
  }
};
// ==============================|| getallridersummary (riders)  ||============================== //
export const getallridersummary = async ({ queryKey }) => {
  try {
    const [, appId, tabvalue] = queryKey;
    const response = await axios.get(
      `${process.env.REACT_APP_URL}/partners/getallridersummary/?applocationid=${appId}&status=${tabvalue == 0 ? '' : 'Active'}`
    );
    return response.data.details;
  } catch (err) {
    console.log('getallridersummary err', err.message);
    return [];
  }
};

// ==============================|| fetchRiders (riders), active riders ||============================== //

export const fetchRiders = async ({ pageParam = 1, queryKey }) => {
  try {
    const [, appId, debouncedSearch] = queryKey;

    const url = `${process.env.REACT_APP_URL
      }/partners/getriders/?applocationid=${appId}&pageno=${pageParam}&pagesize=${20}&keyword=${debouncedSearch}`;

    const res = await axios.get(url);
    return {
      details: res.data.details,
      nextPage: res.data.details.length === 20 ? pageParam + 1 : undefined
    };
  } catch (err) {
    console.log('fetchRiders err', err.message);
    return [];
  }
};

// ==============================|| getriderstatus (riders)||============================== //
export const getriderstatus = async () => {
  const response = await axios.get(`${process.env.REACT_APP_URL}/utils/getriderstatus`);
  return response.data.data;
};

// ==============================|| getreportsummary (orders summary)||============================== //
export const getreportsummary = async ({ queryKey }) => {
  console.log('queryKey for getreportsummary', queryKey);
  const [appId, tenantid, locationid, startdate, enddate] = queryKey;
  const response = await axios.get(
    `${process.env.REACT_APP_URL}/deliveries/getreportsummary/?applocationid=${appId}&tenantid=${tenantid}&locationid=${locationid}&fromdate=${startdate}&todate=${enddate}`
  );
  console.log('getreportsummary', response.data.details);

  return response.data.details;
};

// ==============================|| getreportlocationsummary (orders summary)||============================== //
export const getreportlocationsummary = async ({ queryKey }) => {
  console.log('queryKey for getreportlocationsummary', queryKey);
  const [appId, tenantid, locationid, startdate, enddate] = queryKey;
  const response = await axios.get(
    `${process.env.REACT_APP_URL}/deliveries/getreportlocationsummary/?applocationid=${appId}&tenantid=${tenantid}&locationid=${locationid}&fromdate=${startdate}&todate=${enddate}`
  );
  console.log('getreportlocationsummary', 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, page, rowsPerPage] = queryKey;

  const response = await axios.get(
    appId == 0
      ? `${process.env.REACT_APP_URL2}/orders/getorders/?appuserid=${userid}&fromdate=${startdate}&todate=${enddate}&pageno=${page + 1
      }&pagesize=${rowsPerPage}`
      : `${process.env.REACT_APP_URL2}/orders/getorders/?fromdate=${startdate}&todate=${enddate}&applocationid=${appId}&pageno=${page}&pagesize=${rowsPerPage}`
  );
  const detailsWithSNo = response.data.details.map((item, index) => ({
    ...item,
    sno: index + 1
  }));
  console.log('fetchorderdetails', detailsWithSNo);
  return detailsWithSNo;
};

// ==============================|| getriderbydelivery (orders detail)||============================== //

export const getriderbydelivery = async (startdate, enddate, appId = 0, tenantid = 0, locationid = 0) => {
  // const [, startdate, enddate] = queryKey;

  try {
    const response = await axios.get(
      `${process.env.REACT_APP_URL}/deliveries/getriderbydelivery/?applocationid=${appId}&tenantid=${tenantid}&locationid=${locationid}&fromdate=${startdate}&todate=${enddate}`
    );
    return response.data.details || [];
  } catch (err) {
    console.log('getriderbydelivery', err.message);
    return [];
  }
};

// ==============================|| fetchCount (orders detail)||============================== //

export const fetchCount = async ({ queryKey }) => {
  console.log('queryKey of fetchCount', queryKey);
  const [appId, startdate, enddate] = queryKey;
  let url =
    appId == 0
      ? `${process.env.REACT_APP_URL}/deliveries/deliverysummary/?fromdate=${startdate}&todate=${enddate}`
      : `${process.env.REACT_APP_URL}/deliveries/deliverysummary/?applocationid=${appId}&fromdate=${startdate}&todate=${enddate}`;

  const response = await axios.get(url);
  return response.data.details;
};

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

export const fetchRidersSummary = async ({ queryKey }) => {
  console.log('queryKey for fetchRidersSummary', queryKey);
  const [, appId, startdate, enddate] = queryKey;
  const response = await axios.get(
    `${process.env.REACT_APP_URL}/deliveries/getridersummary/?applocationid=${appId}&fromdate=${startdate}&todate=${enddate}`
  );
  console.log('fetchRidersSummary', 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;
};

// ==============================|| fetchinvoiceinsight (Invoice)||============================== //

export const fetchinvoiceinsight = async () => {
  const insightResponse = await axios.get(`${process.env.REACT_APP_URL}/invoice/getinvoiceinsight`);
  return insightResponse.data.details;
};

// ==============================|| fetchdeliverylist (Invoice)||============================== //

export const fetchdeliverylist = async ({ queryKey }) => {
  const [billStatus] = queryKey;
  const deliveyResponse = await axios.get(`${process.env.REACT_APP_URL}/invoice/getallinvoice/?billstatus=${billStatus}`);
  console.log('fetchdeliverylist', deliveyResponse.data.details);
  return deliveyResponse.data.details;
};
// ==============================|| fetchRidersLogs (RiderLogs)||============================== //

export const fetchRidersLogs = async ({ queryKey }) => {
  const [appId, startdate, riderSearch = ''] = queryKey;
  const riderLogsResponse = await axios.get(
    `${process.env.REACT_APP_URL2}/partners/getriderlogs/?applocationid=${appId}&fromdate=${startdate || ''}&todate=${startdate}&keyword=${riderSearch || ''
    } `
  );
  console.log('fetchRidersLogs', riderLogsResponse.data.details);
  return riderLogsResponse.data.details;
};

// ==============================|| getorders (Locations)||============================== //
// fetchOrders.js

export const fetchOrders1 = async ({ pageParam = 1, queryKey }) => {
  const [, tenantid, locationid, status, startdate, enddate, searchword, rowsPerPage] = queryKey;

  const res = await axios.get(
    `${process.env.REACT_APP_URL}/orders/tenant/getorders/?tenantid=${tenantid}&locationid=${locationid}&status=${status}&fromdate=${startdate}&todate=${enddate}&pageno=${pageParam}&pagesize=${rowsPerPage}&keyword=${searchword}`
  );

  return {
    details: res.data.details,
    nextPage: res.data.details.length === rowsPerPage ? pageParam + 1 : undefined
  };
};
// ==============================|| getusers (viewProfile)||============================== //

export const getusers = async () => {
  try {
    const res = await axios.get(`${process.env.REACT_APP_URL}/users/getusers/?configid=9&userid=${userid}`);
    return res.data.details;
  } catch (err) {
    console.log('getusers', err.message);
  }
};
// ==============================|| getallriders (order)||============================== //

export const getallriders = async () => {
  try {
    const res = await axios.get(`${process.env.REACT_APP_URL}/partners/getallriders?partnerid=64`);
    return res.data.details;
  } catch (err) {
    console.log('getallriders', err.message);
  }
};
