// export const base_url = 'http://127.0.0.1:8000/api/';
// export const base_url = 'http://192.168.1.17:5151/api/';
// export const base_url ="https://stadmin.rowellness.care/public/api/";
export const base_url ="https://admin.rowellness.care/public/api/";



export const fetchRolesAPI = async () => {
    try {
        const response = await fetch(`${base_url}admin/roles/view`, {
            method: 'POST',
            headers: {
                Accept: 'application/json',
                'Content-Type': 'application/json',
            },
        });

        const data = await response.json();
        return data;
    } catch (error) {
        throw new Error('An error occurred while fetching roles.');
    }
};

export const CreateRole = async (payload) => {
    try {
        const response = await fetch(`${base_url}admin/roles/create`, {
            method: 'POST',
            headers: {
                Accept: 'application/json',
                'Content-Type': 'application/json',
            },

            body: JSON.stringify(payload),
        });

        if (!response.ok) {
            const errorData = await response.json();
            throw new Error(errorData.message || 'Failed to create role');
        }

        return await response.json();
    } catch (error) {
        throw new Error(error.message || 'An error occurred while creating role');
    }
};

export const ViewEditRolse = async (id) => {
    try {
        const response = await fetch(`${base_url}admin/roles/show`, {
            method: 'POST',
            headers: {
                Accept: 'application/json',
                'Content-Type': 'application/json',
            },

            body: JSON.stringify(id),
        });

        if (!response.ok) {
            const errorData = await response.json();
            throw new Error(errorData.message || 'Failed to create role');
        }

        return await response.json();
    } catch (error) {
        throw new Error(error.message || 'An error occurred while creating role');
    }
};

export const UpdateRoles = async (payload) => {
    try {
        const response = await fetch(`${base_url}admin/roles/update`, {
            method: 'POST',
            headers: {
                Accept: 'application/json',
                'Content-Type': 'application/json',
            },

            body: JSON.stringify(payload),
        });

        if (!response.ok) {
            const errorData = await response.json();
            throw new Error(errorData.message || 'Failed to create role');
        }

        return await response.json();
    } catch (error) {
        throw new Error(error.message || 'An error occurred while creating role');
    }
};

export const deleteRoleAPI = async (id) => {
    try {
        const response = await fetch(`${base_url}admin/roles/delete`, {
            method: 'POST',
            headers: {
                Accept: 'application/json',
                'Content-Type': 'application/json',
            },
            body: JSON.stringify({ id }),
        });

        const data = await response.json();
        return data;
    } catch (error) {
        throw new Error('An error occurred while fetching roles.');
    }
};

export const viewUser = async () => {
    try {
        const response = await fetch(`${base_url}view_user`, {
            method: 'POST',
            headers: {
                Accept: 'application/json',
                'Content-Type': 'application/json',
            },
        });

        const data = await response.json();
        return data;
    } catch (error) {
        console.log('view user error', error);
        throw new Error('An error occurred while fetching users ');
    }
};

export const createUser = async (payload) => {
    try {
        const response = await fetch(`${base_url}create_user`, {
            method: 'POST',
            headers: {
                Accept: 'application/json',
                'Content-Type': 'application/json',
            },
            body: JSON.stringify(payload),
        });
        const data = response.json();
        return data;
    } catch (error) {
        console.log('create user error', error);
        throw new Error('An error occurred while creating user.');
    }
};

export const editUser = async (userid) => {
    try {
        const response = await fetch(`${base_url}edit_user`, {
            method: 'POST',
            headers: {
                Accept: 'application/json',
                'Content-Type': 'application/json',
            },
            body: JSON.stringify({ id: userid }),
        });

        const data = response.json();
        return data;
    } catch (error) {
        console.log('error fetch edit data', error);
        throw new Error('An error occurred while edit user');
    }
};

export const updateUser = async (payload) => {
    try {
        const response = await fetch(`${base_url}update_user`, {
            method: 'POST',
            headers: {
                Accept: 'application/json',
                'Content-Type': 'application/json',
            },
            body: JSON.stringify(payload),
        });
        const data = response.json();
        return data;
    } catch (error) {
        console.log('update user error', error);
        throw new Error('An error occurred while update user ');
    }
};

export const deleteUser = async (id) => {
    try {
        const response = await fetch(`${base_url}delete_user`, {
            method: 'POST',
            headers: {
                Accept: 'application/json',
                'Content-Type': 'application/json',
            },
            body: JSON.stringify({ id }),
        });

        const data = await response.json();
        return data;
    } catch (error) {
        throw new Error('An error occurred while fetching roles.');
    }
};

export const updatePassword = async (payload) => {
    try {
        const response = await fetch(`${base_url}password_change_user`, {
            method: 'POST',
            headers: {
                Accept: 'application/json',
                'Content-Type': 'application/json',
            },
            body: JSON.stringify(payload),
        });

        const data = response.json();
        return data;
    } catch (error) {
        console.log('error passowd update', error);
        throw new Error('An error occurred while update password.');
    }
};

export const AddInsurance = async (payload) => {
    try {
        const response = await fetch(`${base_url}admin/insurance_create`, {
            method: 'POST',
            headers: {
                Accept: 'application/json',
                'Content-Type': 'application/json',
            },
            body: JSON.stringify(payload),
        });

        const data = response.json();
        return data;
    } catch (error) {
        console.log('error insurance create', error);
        throw new Error('An error occurred while create insurance.');
    }
};

export const viewInsurasnce = async () => {
    try {
        const response = await fetch(`${base_url}admin/insurance_view`, {
            method: 'POST',
            headers: {
                Accept: 'application/json',
                'Content-Type': 'application/json',
            },
        });

        const data = response.json();
        return data;
    } catch (error) {
        console.log('error insurance create', error);
        throw new Error('An error occurred while create insurance.');
    }
};

export const editInsurasnce = async (id) => {
    try {
        const response = await fetch(`${base_url}admin/insurance_edit`, {
            method: 'POST',
            headers: {
                Accept: 'application/json',
                'Content-Type': 'application/json',
            },
            body: JSON.stringify({ id }),
        });

        const data = response.json();
        return data;
    } catch (error) {
        console.log('error insurance create', error);
        throw new Error('An error occurred while create insurance.');
    }
};

export const updateInsurance = async (payload) => {
    try {
        const response = await fetch(`${base_url}admin/insurance_update`, {
            method: 'POST',
            headers: {
                Accept: 'application/json',
                'Content-Type': 'application/json',
            },
            body: JSON.stringify(payload),
        });

        const data = response.json();
        return data;
    } catch (error) {
        console.log('error insurance create', error);
        throw new Error('An error occurred while create insurance.');
    }
};

export const deleteInsuranceAPI = async (id: number) => {
    try {
        const response = await fetch(`${base_url}admin/insurance_delete`, {
            method: 'POST',
            headers: {
                Accept: 'application/json',
                'Content-Type': 'application/json',
            },
            body: JSON.stringify({ id }),
        });

        if (!response.ok) {
            throw new Error(`HTTP error! status: ${response.status}`);
        }

        return await response.json();
    } catch (error) {
        console.error('Error deleting insurance:', error);
        throw new Error('Failed to delete insurance company. Please try again.');
    }
};

export const viewInvoices = async (email) => {
    try {
        const response = await fetch(`${base_url}admin/getbookingdetails`, {
            method: 'POST',
            headers: {
                Accept: 'application/json',
                'Content-Type': 'application/json',
            },
            body: JSON.stringify({email})
        });

        const data = response.json();
        return data;
    } catch (error) {
        console.log('error insurance create', error);
        throw new Error('An error occurred while create insurance.');
    }
};

export const PreviewInvoices = async (booking_id) => {
    try {
        const response = await fetch(`${base_url}admin/single/booking/details`, {
            method: 'POST',
            headers: {
                Accept: 'application/json',
                'Content-Type': 'application/json',
            },
            body: JSON.stringify({ booking_id }),
        });

        const data = response.json();
        return data;
    } catch (error) {
        console.log('error insurance create', error);
        throw new Error('An error occurred while create insurance.');
    }
};

export const updateAppointmentStatus = async (payload) => {
    try {
        const response = await fetch(`${base_url}update/process/status`, {
            method: 'POST',
            headers: {
                Accept: 'application/json',
                'Content-Type': 'application/json',
            },
            body: JSON.stringify(payload),
        });

        const data = await response.json();
        return data;
    } catch (error) {
        console.log('Error while updating the appointment status ', error);
        throw new Error('An error occurred while update appointment status');
    }
};

export const addAddressWithProfile = async (payload) => {
    try {
        const response = await fetch(`${base_url}update_profiledata_company_admin`, {
            method: 'POST',
            headers: {
                Accept: 'application/json',
                'Content-Type': 'application/json',
            },
            body: JSON.stringify(payload),
        });
        const data = await response.json();
        return data;
    } catch (error) {
        console.log('Error while updating the appointment status ', error);
        throw new Error('An error occurred while update appointment status');
    }
};

export const getDoctorsList = async (payload ) => {
    try {
        const response = await fetch(`${base_url}admin/get/doctor/list`, {
            method: 'POST',
            headers: {
                Aceept: 'application/json',
                'Content-Type': 'application/json',
            },
                  body: JSON.stringify(payload),
        });

        const data = response.json();
        return data;
    } catch (error) {
        console.log('error whlie fetching doctors list', error);
        throw new Error('An error occured whlie fetching doctor list');
    }
};

export const assignDoctor = async (payload) => {
    try {
        const response = await fetch(`${base_url}booking/add/doctor`, {
            method: 'POST',
            headers: {
                Accept: 'application/json',
                'Content-Type': 'application/json',
            },
            body: JSON.stringify(payload),
        });

        const data = response.json();
        return data;
    } catch (error) {
        console.log('error while assigm the doctor ', error);
        throw new Error('An error occured while assign the doctor');
    }
};

export const generateOrder = async (id, key = []) => {
    try {
        const response = await fetch(`${base_url}webhooks/extending/order`, {
            method: 'POST',
            headers: {
                Accept: 'application/json',
                'Content-Type': 'application/json',
            },
            body: JSON.stringify({ cust_id: id, value: key }),
        });

        const data = await response.json();
        return data;
    } catch (error) {
        console.log('error while generating the order ', error);
        throw new Error('An error occured while generating the order');
    }
};

export const CustomerHistoryDetails = async (id) => {
    try {
        const response = await fetch(`${base_url}getCustomerdetailswithbooking`, {
            method: 'POST',
            headers: {
                Accept: 'application/json',
                'Content-Type': 'application/json',
            },
            body: JSON.stringify({ cust_id: id }),
        });

        const data = await response.json();
        return data;
    } catch (error) {
        console.log('error while fetch an customer history', error);
        throw new Error('An error occured while fetching the customer history data');
    }
};

export const EditBooking = async (id) => {
    try {
        const response = await fetch(`${base_url}edit_booking`, {
            method: 'POST',
            headers: {
                Accept: 'application/json',
                'Content-Type': 'application/json',
            },
            body: JSON.stringify({ booking_id: id }),
        });

        const data = await response.json();
        return data;
    } catch (error) {
        console.log('getting error when fetching edit booking', error);
        throw new Error('An error occured while fetching the booking data');
    }
};

export const viewAPIKEY = async () => {
    try {
        const response = await fetch(`${base_url}view_apikey`, {
            method: 'POST',
            headers: {
                Accept: 'application/json',
                'Content-Type': 'application/json',
            },
        });

        const data = response.json();
        return data;
    } catch (error) {
        console.log('error while fetching the api keys', error);
        throw new Error('An error occured while fetching the api keys');
    }
};

export const CreateAPIKEY = async (payload) => {
    try {
        const response = await fetch(`${base_url}create_apikey`, {
            method: "POST",
            headers: {
                "Accept": "application/json",
                "Content-Type": "application/json"
            },
            body: JSON.stringify(payload)
        })

        const data = response.json()
        return data

    } catch (error) {
        console.log("error while fetching the api keys", error)
        throw new Error("An error occured while fetching the api keys")


    }
}
export const editAPIKEY = async (id) => {
    try {
        const response = await fetch(`${base_url}edit_apikey`, {
            method: "POST",
            headers: {
                "Accept": "application/json",
                "Content-Type": "application/json"
            },
            body: JSON.stringify({ id })
        })
        const data = await response.json()
        return data

    } catch (error) {
        console.log("error while fetching the api keys", error)
        throw new Error("An error occured while fetching the api keys")


    }
}
export const deleteAPIKEY = async (id) => {
    try {
        const response = await fetch(`${base_url}delete_apikey`, {
            method: "POST",
            headers: {
                "Accept": "application/json",
                "Content-Type": "application/json"
            },
            body: JSON.stringify({ id })
        })
        const data = await response.json()
        return data

    } catch (error) {
        console.log("error while fetching the api keys", error)
        throw new Error("An error occured while fetching the api keys")


    }
}
export const updateAPIKEY = async (payload) => {
    try {
        const response = await fetch(`${base_url}update_apikey`, {
            method: "POST",
            headers: {
                "Accept": "application/json",
                "Content-Type": "application/json"
            },
            body: JSON.stringify(payload)
        })
        const data = await response.json()
        return data

    } catch (error) {
        console.log("error while fetching the api keys", error)
        throw new Error("An error occured while fetching the api keys")


    }
}


export const getPackagesList = async (company_id) => {
    try {
        const response = await fetch(`${base_url}view_newpackage`, {
            method: "POST",
            headers: {
                "Accept": "application/json",
                "Content-Type": "application/json"
            },
            body: JSON.stringify({ company_id })
        })

        const data = response.json()
        return data

    } catch (error) {
        console.log("error while fetching the api keys", error)
        throw new Error("An error occured while fetching the api keys")


    }
}
export const getAddOnList = async (company_id) => {
    try {
        const response = await fetch(`${base_url}view_Addon`, {
            method: "POST",
            headers: {
                "Accept": "application/json",
                "Content-Type": "application/json"
            },
            body: JSON.stringify({ company_id })
        })

        const data = response.json()
        return data

    } catch (error) {
        console.log("error while fetching the api keys", error)
        throw new Error("An error occured while fetching the api keys")


    }
}


// export const getPackagesList = async (company_id) => {
//     try {
//         const response = await fetch(`${base_url}get_package`, {
//             method: "POST",
//             headers: {
//                 "Accept": "application/json",
//                 "Content-Type": "application/json"
//             },
//             body: JSON.stringify({ company_id })
//         })

//         const data = response.json()
//         return data

//     } catch (error) {
//         console.log("error while fetching the api keys", error)
//         throw new Error("An error occured while fetching the api keys")


//     }
// }


export const createPackages = async (payload) => {
    try {
        const response = await fetch(`${base_url}add_newpackage`, {
            method: "POST",
            headers: {
                "Accept": "application/json",
                "Content-Type": "application/json"
            },
            body: JSON.stringify(payload)
        })

        const data = response.json()
        return data

    } catch (error) {
        console.log("error while fetching the api keys", error)
        throw new Error("An error occured while fetching the api keys")


    }
}


export const createAddOn = async (payload) => {
    try {
        const response = await fetch(`${base_url}add_Addon`, {
            method: "POST",
            headers: {
                "Accept": "application/json",
                "Content-Type": "application/json"
            },
            body: JSON.stringify(payload)
        })

        const data = response.json()
        return data

    } catch (error) {
        console.log("error while fetching the api keys", error)
        throw new Error("An error occured while fetching the api keys")


    }
}


// export const createPackages = async (payload) => {
//     try {
//         const response = await fetch(`${base_url}create_package`, {
//             method: "POST",
//             headers: {
//                 "Accept": "application/json",
//                 "Content-Type": "application/json"
//             },
//             body: JSON.stringify(payload)
//         })

//         const data = response.json()
//         return data

//     } catch (error) {
//         console.log("error while fetching the api keys", error)
//         throw new Error("An error occured while fetching the api keys")


//     }
// }

export const updatePackages = async (payload) => {
    try {
        const response = await fetch(`${base_url}update_newpackage`, {
            method: "POST",
            headers: {
                "Accept": "application/json",
                "Content-Type": "application/json"
            },
            body: JSON.stringify(payload)
        })

        const data = response.json()
        return data

    } catch (error) {
        console.log("error while fetching the api keys", error)
        throw new Error("An error occured while fetching the api keys")


    }
}




export const updateAddOn = async (payload) => {
    try {
        const response = await fetch(`${base_url}update_Addon`, {
            method: "POST",
            headers: {
                "Accept": "application/json",
                "Content-Type": "application/json"
            },
            body: JSON.stringify(payload)
        })

        const data = response.json()
        return data

    } catch (error) {
        console.log("error while fetching the api keys", error)
        throw new Error("An error occured while fetching the api keys")


    }
}



// export const updatePackages = async (payload) => {
//     try {
//         const response = await fetch(`${base_url}update_package`, {
//             method: "POST",
//             headers: {
//                 "Accept": "application/json",
//                 "Content-Type": "application/json"
//             },
//             body: JSON.stringify(payload)
//         })

//         const data = response.json()
//         return data

//     } catch (error) {
//         console.log("error while fetching the api keys", error)
//         throw new Error("An error occured while fetching the api keys")


//     }
// }
export const editPackages = async (id) => {
    try {
        const response = await fetch(`${base_url}show_newpackage`, {
            method: "POST",
            headers: {
                "Accept": "application/json",
                "Content-Type": "application/json"
            },
            body: JSON.stringify({ id })
        })

        const data = response.json()
        return data

    } catch (error) {
        console.log("error while fetching the api keys", error)
        throw new Error("An error occured while fetching the api keys")


    }
}




export const editAddOn = async (id) => {
    try {
        const response = await fetch(`${base_url}show_Addon`, {
            method: "POST",
            headers: {
                "Accept": "application/json",
                "Content-Type": "application/json"
            },
            body: JSON.stringify({ id })
        })

        const data = response.json()
        return data

    } catch (error) {
        console.log("error while fetching the api keys", error)
        throw new Error("An error occured while fetching the api keys")


    }
}



// export const editPackages = async (package_id) => {
//     try {
//         const response = await fetch(`${base_url}edit_package`, {
//             method: "POST",
//             headers: {
//                 "Accept": "application/json",
//                 "Content-Type": "application/json"
//             },
//             body: JSON.stringify({ package_id })
//         })

//         const data = response.json()
//         return data

//     } catch (error) {
//         console.log("error while fetching the api keys", error)
//         throw new Error("An error occured while fetching the api keys")


//     }
// }
export const deletePackages = async (id) => {
    try {
        const response = await fetch(`${base_url}destroy_newpackage`, {
            method: "POST",
            headers: {
                "Accept": "application/json",
                "Content-Type": "application/json"
            },
            body: JSON.stringify({id })
        })

        const data = response.json()
        return data

    } catch (error) {
        console.log("error while fetching the api keys", error)
        throw new Error("An error occured while fetching the api keys")


    }
}
export const deleteAddon = async (id) => {
    try {
        const response = await fetch(`${base_url}delete_Addon`, {
            method: "POST",
            headers: {
                "Accept": "application/json",
                "Content-Type": "application/json"
            },
            body: JSON.stringify({id })
        })

        const data = response.json()
        return data

    } catch (error) {
        console.log("error while fetching the api keys", error)
        throw new Error("An error occured while fetching the api keys")


    }
}
// export const deletePackages = async (package_id) => {
//     try {
//         const response = await fetch(`${base_url}delete_package`, {
//             method: "POST",
//             headers: {
//                 "Accept": "application/json",
//                 "Content-Type": "application/json"
//             },
//             body: JSON.stringify({ package_id })
//         })

//         const data = response.json()
//         return data

//     } catch (error) {
//         console.log("error while fetching the api keys", error)
//         throw new Error("An error occured while fetching the api keys")


//     }
// }

export const CustomReport = async (booking_id: number, files: File[]) => {
    try {
        const formData = new FormData();
        formData.append("booking_id", String(booking_id));
        formData.append("value", "Admin_Panel");

        // Append multiple files
        files.forEach((file) => {
            formData.append("file[]", file);
        });

        const response = await fetch(`${base_url}webhooks/custom/report`, {
            method: "POST",
            body: formData, // ✅ do not stringify, do not set Content-Type manually
        });

        if (!response.ok) {
            throw new Error(`HTTP error! status: ${response.status}`);
        }

        const data = await response.json();
        return data;
    } catch (error) {
        console.error("Error while uploading files:", error);
        throw new Error("An error occurred while uploading files");
    }
};



export const filterCompletedBookings = async (payload) => {
    try {
        const res = await fetch(`${base_url}get_booking_completed`, {
            method: "POST",
            headers: {
                "Accept": "application/json",
                "Content-Type": "application/json"
            },
            body: JSON.stringify(payload)
        })
        const data = res.json()
        return data
    } catch (error) {
        console.error("Error while filtered completed bookings:", error);
        throw new Error("An error occurred while filtered completed bookings");
    }
}


export const getReports = async (payload) => {
    try {
        const res = await fetch(`${base_url}admin/getAllReports`, {
            method: "POST",
            headers: {
                "Accept": "application/json",
                "Content-Type": "application/json"
            },
            body: JSON.stringify(payload)
        })
        const data = res.json()
        return data
    } catch (error) {
        console.error("Error while filtered completed bookings:", error);
        throw new Error("An error occurred while filtered completed bookings");
    }
}


export const getCompletedBooking = async (payload) => {
    try {
        const res = await fetch(`${base_url}view_completed_booking`, {
            method: "POST",
            headers: {
                "Accept": "application/json",
                "Content-Type": "application/json"
            },
            body: JSON.stringify(payload)
        })
        const data = res.json()
        return data
    } catch (error) {
        console.error("Error while filtered completed bookings:", error);
        throw new Error("An error occurred while filtered completed bookings");
    }
}


export const getDashboardChartData = async (payload) => {
    try {
        const res = await fetch(`${base_url}revenue-chart-data`, {
            method: "POST",
            headers: {
                "Accept": "application/json",
                "Content-Type": "application/json"
            },
            body: JSON.stringify(payload)
        })
        const data = res.json()
        return data
    } catch (error) {
        console.error("Error while filtered completed bookings:", error);
        throw new Error("An error occurred while filtered completed bookings");
    }
}
export const getRevenueChartData = async (payload) => {
    try {
        const res = await fetch(`${base_url}admin/revenueReport`, {
            method: "POST",
            headers: {
                "Accept": "application/json",
                "Content-Type": "application/json"
            },
            body: JSON.stringify(payload)
        })
        const data = res.json()
        return data
    } catch (error) {
        console.error("Error while filtered completed bookings:", error);
        throw new Error("An error occurred while filtered completed bookings");
    }
}
export const getDashboardCustomerChartData = async (email) => {
    try {
        const res = await fetch(`${base_url}customerChartData`, {
            method: "POST",
            headers: {
                "Accept": "application/json",
                "Content-Type": "application/json"
            },
             body: JSON.stringify({email})
        })
        const data = res.json()
        return data
    } catch (error) {
        console.error("Error while filtered completed bookings:", error);
        throw new Error("An error occurred while filtered completed bookings");
    }
}


export const getDashboardBookingsProcessCount = async (email) => {
    try {
        const res = await fetch(`${base_url}bookingProcessStatusSummary`, {
            method: "POST",
            headers: {
                "Accept": "application/json",
                "Content-Type": "application/json"
            },
            body:JSON.stringify({email})
        })
        const data = res.json()
        return data
    } catch (error) {
        console.error("Error while filtered completed bookings:", error);
        throw new Error("An error occurred while filtered completed bookings");
    }
}


export const getRecentBookings = async (email ) => {
    try {
        const res = await fetch(`${base_url}bookings/last-eight-days`, {
            method: "POST",
            headers: {
                "Accept": "application/json",
                "Content-Type": "application/json"
            },
            body: JSON.stringify({email})
        })
        const data = res.json()
        return data
    } catch (error) {
        console.error("Error while filtered completed bookings:", error);
        throw new Error("An error occurred while filtered completed bookings");
    }
}

export const toggleActiveInActivePackages = async (payload ) => {
    try {
        const res = await fetch(`${base_url}toggleActiveInActive`, {
            method: "POST",
            headers: {
                "Accept": "application/json",
                "Content-Type": "application/json"
            },
               body: JSON.stringify(payload)
        })
        const data = res.json()
        return data
    } catch (error) {
        console.error("Error while filtered completed bookings:", error);
        throw new Error("An error occurred while filtered completed bookings");
    }
}


export const createHeadings = async (payload ) => {
    try {
        const res = await fetch(`${base_url}heading/create`, {
            method: "POST",
            headers: {
                "Accept": "application/json",
                "Content-Type": "application/json"
            },
               body: JSON.stringify(payload)
        })
        const data = res.json()
        return data
    } catch (error) {
        console.error("Error while filtered completed bookings:", error);
        throw new Error("An error occurred while filtered completed bookings");
    }
}

export const editHeadings = async (id) => {
    try {
        const res = await fetch(`${base_url}heading/show`, {
            method: "POST",
            headers: {
                "Accept": "application/json",
                "Content-Type": "application/json"
            },
               body: JSON.stringify({id})
        })
        const data = res.json()
        return data
    } catch (error) {
        console.error("Error while filtered completed bookings:", error);
        throw new Error("An error occurred while filtered completed bookings");
    }
}
export const updateHeadings = async (payload) => {
    try {
        const res = await fetch(`${base_url}heading/update`, {
            method: "POST",
            headers: {
                "Accept": "application/json",
                "Content-Type": "application/json"
            },
               body: JSON.stringify(payload)
        })
        const data = res.json()
        return data
    } catch (error) {
        console.error("Error while filtered completed bookings:", error);
        throw new Error("An error occurred while filtered completed bookings");
    }
}

export const deleteHeadings = async (id) => {
    try {
        const res = await fetch(`${base_url}heading/delete`, {
            method: "POST",
            headers: {
                "Accept": "application/json",
                "Content-Type": "application/json"
            },
               body: JSON.stringify({id})
        })
        const data = res.json()
        return data
    } catch (error) {
        console.error("Error while filtered completed bookings:", error);
        throw new Error("An error occurred while filtered completed bookings");
    }
}
export const getHeadingsList = async () => {
    try {
        const res = await fetch(`${base_url}heading/list`, {
            method: "POST",
            headers: {
                "Accept": "application/json",
                "Content-Type": "application/json"
            },

        })
        const data = res.json()
        return data
    } catch (error) {
        console.error("Error while filtered completed bookings:", error);
        throw new Error("An error occurred while filtered completed bookings");
    }
}
export const getCustomersByInsurance = async (id) => {
    try {
        const res = await fetch(`${base_url}admin/get_customers_by_insurance`, {
            method: "POST",
            headers: {
                "Accept": "application/json",
                "Content-Type": "application/json"
            },
              body: JSON.stringify({insurance_id:id})

        })
        const data = res.json()
        return data
    } catch (error) {
        console.error("Error while filtered completed bookings:", error);
        throw new Error("An error occurred while filtered completed bookings");
    }
}

// AI Agent Settings APIs
export const getAIAgentSettings = async (companyId: string) => {
    try {
        const response = await fetch(`${base_url}ai-agent-settings?company_id=${companyId}`, {
            method: 'GET',
            headers: {
                'Accept': 'application/json',
                'Content-Type': 'application/json',
            }
        });

        const data = await response.json();
        return data;
    } catch (error) {
        console.error('Error fetching AI agent settings:', error);
        throw new Error('An error occurred while fetching AI agent settings');
    }
};

export const saveAIAgentSettings = async (payload) => {
    try {
        const response = await fetch(`${base_url}ai-agent-settings`, {
            method: 'POST',
            headers: {
                'Accept': 'application/json',
                'Content-Type': 'application/json',
            },
            body: JSON.stringify(payload)
        });

        const data = await response.json();
        return data;
    } catch (error) {
        console.error('Error saving AI agent settings:', error);
        throw new Error('An error occurred while saving AI agent settings');
    }
};

export const deleteAIAgentSettings = async (companyId: string) => {
    try {
        const response = await fetch(`${base_url}ai-agent-settings`, {
            method: 'DELETE',
            headers: {
                'Accept': 'application/json',
                'Content-Type': 'application/json',
            },
            body: JSON.stringify({ company_id: companyId })
        });

        const data = await response.json();
        return data;
    } catch (error) {
        console.error('Error deleting AI agent settings:', error);
        throw new Error('An error occurred while deleting AI agent settings');
    }
};

// Customer Management API Functions
export const getCustomers = async (payload: {
    email: string;
    page: number;
    per_page: number;
    search: string;
    sort_by: string;
    sort_dir: string;
}) => {
    try {
        const response = await fetch(`${base_url}get_customers`, {
            method: 'POST',
            headers: {
                'Accept': 'application/json',
                'Content-Type': 'application/json',
            },
            body: JSON.stringify(payload),
        });
        const data = await response.json();
        return data;
    } catch (error) {
        console.error('Error fetching customers:', error);
        throw new Error('Failed to load customer data. Please try again later.');
    }
};

export const deleteCustomer = async (customerId: string) => {
    try {
        const response = await fetch(`${base_url}delete_customer`, {
            method: 'POST',
            headers: {
                'Accept': 'application/json',
                'Content-Type': 'application/json',
            },
            body: JSON.stringify({ customer_id: customerId }),
        });
        const data = await response.json();
        return data;
    } catch (error) {
        console.error('Error deleting customer:', error);
        throw new Error('An error occurred while deleting the customer.');
    }
};

export const exportCustomers = async (payload: {
    email: string;
    search: string;
    sort_by: string;
    sort_dir: string;
}) => {
    try {
        const response = await fetch(`${base_url}export_customers`, {
            method: 'POST',
            headers: {
                'Accept': 'text/csv',
                'Content-Type': 'application/json',
            },
            body: JSON.stringify(payload),
        });
        
        if (!response.ok) {
            throw new Error('Export failed');
        }
        
        return await response.blob();
    } catch (error) {
        console.error('Export error:', error);
        throw new Error('Failed to export customers. Please try again.');
    }
};

export const getCustomerNotes = async (customerId: string, email: string) => {
    try {
        const response = await fetch(`${base_url}get_customer_notes`, {
            method: 'POST',
            headers: {
                'Accept': 'application/json',
                'Content-Type': 'application/json',
            },
            body: JSON.stringify({ customer_id: customerId, email }),
        });
        const data = await response.json();
        return data;
    } catch (error) {
        console.error('Error fetching notes:', error);
        throw new Error('Failed to fetch customer notes.');
    }
};

export const getCustomerNotesCount = async (customerIds: string[], email: string) => {
    try {
        const response = await fetch(`${base_url}get_customer_notes_count`, {
            method: 'POST',
            headers: {
                'Accept': 'application/json',
                'Content-Type': 'application/json',
            },
            body: JSON.stringify({ customer_ids: customerIds, email }),
        });
        const data = await response.json();
        return data;
    } catch (error) {
        console.error('Error fetching note counts:', error);
        throw new Error('Failed to fetch note counts.');
    }
};

export const addCustomerNote = async (customerId: string, note: string, email: string) => {
    try {
        const response = await fetch(`${base_url}add_customer_note`, {
            method: 'POST',
            headers: {
                'Accept': 'application/json',
                'Content-Type': 'application/json',
            },
            body: JSON.stringify({ customer_id: customerId, note, email }),
        });
        const data = await response.json();
        return data;
    } catch (error) {
        console.error('Error saving note:', error);
        throw new Error('Failed to save note');
    }
};

export const updateCustomerNote = async (noteId: string, note: string, customerId: string, email: string) => {
    try {
        const response = await fetch(`${base_url}update_customer_note`, {
            method: 'POST',
            headers: {
                'Accept': 'application/json',
                'Content-Type': 'application/json',
            },
            body: JSON.stringify({ note_id: noteId, note, customer_id: customerId, email }),
        });
        const data = await response.json();
        return data;
    } catch (error) {
        console.error('Error updating note:', error);
        throw new Error('Failed to update note');
    }
};

export const deleteCustomerNote = async (noteId: string, email: string) => {
    try {
        const response = await fetch(`${base_url}delete_customer_note`, {
            method: 'POST',
            headers: {
                'Accept': 'application/json',
                'Content-Type': 'application/json',
            },
            body: JSON.stringify({ note_id: noteId, email }),
        });
        const data = await response.json();
        return data;
    } catch (error) {
        console.error('Error deleting note:', error);
        throw new Error('Failed to delete note');
    }
};
