import "nes.css/css/nes.min.css";
import { useState, useContext } from 'react';
import { Button, Modal } from 'react-bootstrap';
import UserContext from "../UserContext.js";
import Swal from "sweetalert2";
const AddToCartModal = ({ productId, addToCart }) => {
const { user } = useContext(UserContext);
const [quantity, setQuantity] = useState(1);
const [isOpen, setIsOpen] = useState(false);
const openModal = () => {
setIsOpen(true);
}
const closeModal = () => {
setIsOpen(false);
}
const decrementQuantity = () => {
if (quantity > 1) {
setQuantity(quantity - 1);
}
};
const incrementQuantity = () => {
setQuantity(quantity + 1);
};
const AddtoCart = () => {
if (!user || user.isAdmin == null) {
Swal.fire({
title: "Authentication error",
icon: "error",
text: "Please log in to add to cart."
});
return;
} else if (user.isAdmin) {
Swal.fire({
title: "Action forbidden",
icon: "error",
text: "Only non-admin users can add to cart."
})
return;
}
fetch(`${process.env.REACT_APP_API_BASE_URL}/products/add-to-cart`, {
method : "POST",
headers: {
Authorization: `Bearer ${localStorage.getItem("token")}`,
"Content-Type" : "application/json"
},
body: JSON.stringify({
productId: productId,
quantity: quantity
})
}).then(result => result.json())
.then(data => {
if (data) {
Swal.fire({
title: "Add to cart succesful!",
icon: "success",
text: "Product successfully added to cart."
})
closeModal();
setQuantity(0);
}else{
Swal.fire({
title: "Something went wrong",
icon: "error",
text: "Please try again"
})
}
})
}
return (
<>
Add to Cart
Quantity:
{quantity}
>
);
};
export default AddToCartModal;