import moment from "moment";
export async function GetUserSubsriptionDetails(user) {
if (user) {
try {
const apiResponse = await fetch("/api/data/read", {
method: "POST",
headers: {
"Content-Type": "application/json",
},
body: JSON.stringify({
email: user.email,
}),
});
if (apiResponse.ok) {
const res = await apiResponse.json();
const processed = checkLatestSubscription(res, user.email);
return processed;
}
} catch (error) {
return error;
}
}
}
const checkLatestSubscription = (user, email) => {
const currentDate = moment();
const targetService = "COLORINGPAGESPRO";
const targetPaid = true;
user.sort(
(a, b) =>
moment(b.createdDate, "DD/MM/YYYY, HH:mm:ss").valueOf() -
moment(a.createdDate, "DD/MM/YYYY, HH:mm:ss").valueOf(),
);
const userData = user.find(
(user) => user.email === email && user.service === targetService,
);
const inactiveSubscription = {
leftTime: "Access Finished",
active: "false",
};
if (isAdmin(email)) {
return {
leftTime: `Admin Access`,
active: "true",
};
}
if (
userData &&
userData.service === targetService &&
userData.paid === targetPaid
) {
const oneDayInMillis = 24 * 60 * 60 * 1000;
const userCreatedDate = moment(
userData.createdDate,
"DD/MM/YYYY, HH:mm:ss",
);
const hoursLeft = Math.round(
(userCreatedDate.valueOf() + oneDayInMillis - currentDate.valueOf()) /
(60 * 60 * 1000),
);
if (hoursLeft <= 0) {
return inactiveSubscription;
}
return {
leftTime: `${hoursLeft} Hours Remaining`,
active: "true",
};
} else {
return inactiveSubscription;
}
};
const isAdmin = (email) => email === "youremail@email.com";
export const isActiveSubscription = (userSubscription) =>
userSubscription && userSubscription.active === "true";
export const MembershipBadge = ({ userSubscription }) => {
return (
<>
{userSubscription && (
<div
className={`hidden p-1 text-xs font-medium text-dark-text-color md:block`}
>
Membership Active: {userSubscription.active}
<div className="flex">Time Left: {userSubscription.leftTime}</div>
</div>
)}
</>
);
};