Notes
![]() ![]() Notes - notes.io |
"use client"
import React from 'react'
import { useState, useEffect } from "react";
import Link from 'next/link';
import { toast } from "react-toastify";
import "react-toastify/dist/ReactToastify.css";
import { FcCheckmark } from "react-icons/fc";
import { apiUrl } from '@/app/constant/constant';
import { useTranslation } from 'react-i18next';
import { useRouter } from "next/navigation";
import moment from "moment/moment";
import axios from "axios";
const Section1 = () => {
const [headerData, setHeaderData] = useState();
const [isLoading, setIsLoading] = useState(false);
const [attributeData, setAttributeData] = useState({});
const [data, setdata] = useState([]);
const [filteredDat, setFilterData]= useState([]);
const { t } = useTranslation();
const [selectedCategories, setSelectedCategories] = useState([]);
const [selectedCount, setSelectedCount] = useState(0);
const [userSubscription, setUserSubscription] = useState([]);
//important!!!
// to show button of subscription only for user id 2 or 3
// and sub_end date < today date
const [showSubsButton, setShowSubsButton] = useState(true);
const current_date = moment().format("Y-m-d H:mm:ss");
useEffect(() => {
const fetchData = async () => {
const session = JSON.parse(sessionStorage.getItem("token"));
let token = "";
if (session != null) {
token = session.access_token;
}
try {
const response = await axios.get(
`${apiUrl}api/user/subscription/details`,
{
headers: {
Authorization: "Bearer " + token,
},
}
);
let result = response?.data.data;
if(result && result.length > 0){
let sortedData = result.filter((x)=>x.payment_status==="COMPLETED").sort(
(a, b) => (a.subs_end_date - b.subs_end_date)
);
if (
sortedData[0].payment_status === "COMPLETED" &&
new Date(sortedData[0].subs_end_date).getTime() > new Date().getTime() &&
(sortedData[0]?.user_type === 2 || sortedData[0]?.user_type === 3)
) {
setShowSubsButton(false);
} else {
setShowSubsButton(true);
}
}
setUserSubscription(result);
} catch (error) {
console.error("Error fetching user data:", error);
}
};
fetchData();
}, []);
const router = useRouter(); //router Initialization
const handleCategoryClick = (selectedCategoryId) => {
const updatedCategories = selectedCategories.map((item) =>
item.id === selectedCategoryId
? { ...item, isSelected: !item.isSelected }
: item
);
//event handler for category click, it updates the state based selected category
const selectedCat = updatedCategories.filter((item) => item.isSelected);
const selectedCatIds = selectedCat.map((item) => item.id);
if (selectedCount < 3) {
localStorage.setItem("selectedCatIds", JSON.stringify(selectedCatIds));
}
setSelectedCount(selectedCat.length);
if(showSubsButton){
if (selectedCat.length === 2) {
toast.warning("You can select one more category");
} else if (selectedCat.length > 3) {
toast.error("You need a premium subscription");
return;
}
}
setSelectedCategories(updatedCategories);
};
const handleSubscriptionClick = () => {
//event handler for category click, it updates the state based selected category
if (selectedCount === 0) {
toast.error("Please select at least one category");
return;
}
const selectedCat = selectedCategories.filter((item) => item.isSelected);
const selectedCatIds = selectedCat.map((item) => item.id);
localStorage.setItem("selectedCatIds", JSON.stringify(selectedCatIds));
//event handler for subscription click,
const token = sessionStorage.getItem("token");
const role = sessionStorage.getItem("role");
let userType = Number(role);
if (token !== null) {
//console.log("tokenrole,", role);
//router.push("/subscription");
if (userType === 4) {
router.push("/subscription");
} else if (userType === 2) {
router.push("/Pricing");
} else if (userType === 3) {
router.push("/Pricing");
}
} else {
router.push("/login");
}
};
const getCategoriesInfo = async () => {
try {
const response = await fetch(`${apiUrl}api/category`, {
method: "POST",
headers: {
Accept: "application/json",
"Content-Type": "application/x-www-form-urlencoded",
},
// body: formBody
});
const responseJson = await response.json();
if (responseJson.success === "true") {
const res = responseJson.category.map((item) => ({
...item,
isSelected: false,
}));
setSelectedCategories(res);
setIsLoading(false);
}
} catch (error) {
//console.error(error);
}
};
useEffect(() => {
setIsLoading(true);
getCategoriesInfo();
}, []);
useEffect(() => {}, [selectedCount]);
function getHeaderInfo(){
fetch( `${apiUrl}api/home/header/image`, {
method: 'POST',
headers: {
'Accept': 'application/json',
'Content-Type': 'application/x-www-form-urlencoded'
},
// body: formBody
})
.then((response) => response.json())
.then((responseJson) => {
//console.log(responseJson);
if (responseJson.success == "true") {
setHeaderData(responseJson.header_image[0]);
setIsLoading(false);
//console.log(headerData.home_page_image)
}
})
.catch((error) => {
console.error(error);
});
}
useEffect(() => {
setIsLoading(true);
getHeaderInfo();
getProductAttributes();
}, [])
function getProductAttributes() {
fetch(`${apiUrl}api/product/attributes`)
.then((response) => response.json())
.then((responseJson) => {
if (responseJson.success === "true") {
console.log(responseJson.product_attr_value);
setAttributeData(responseJson.product_attr_value);
}
})
.catch((error) => {
console.error(error);
});
}
function getValue(eventt, ind) {
console.log(ind, data);
const name = eventt.target.name;
const value = eventt.target.value;
const dataIndex = data.findIndex(item => item.name === name);
if (dataIndex === -1) {
data.push({
name: name,
value: value
});
} else {
data[dataIndex].value = value;
}
setdata(data);
console.log(data);
}
function handleButtonClick() {
console.log("sa");
let filter_values = {
"system_choice": "",
"industrial_area": "",
"building_type": "",
"number_of_rooms": "",
"availability_country": ""
};
data.forEach(item => {
switch (item.name) {
case "system_choice":
filter_values.system_choice = item.value;
break;
case "industrial_area":
filter_values.industrial_area = item.value;
break;
case "building_type":
filter_values.building_type = item.value;
break;
case "number_of_rooms":
filter_values.number_of_rooms = item.value;
break;
case "availability_country":
filter_values.availability_country = item.value;
break;
default:
break;
}
});
fetch(`${apiUrl}api/product/attributes/categories`, {
method: 'POST',
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json'
},
body: JSON.stringify({
"filter_values": filter_values, // This will be replaced with your filter_values object
"lang": null // You may replace null with a language value if needed
})
})
.then(response => response.json())
.then(responseJson => {
if (responseJson.success === "true") {
const res = responseJson.filter_category.map((item) => ({
...item,
isSelected: false,
}));
setSelectedCategories(res);
setIsLoading(false);
}
setFilterData(responseJson); //responseJson
console.log("responseJson handleButtonClick:-", responseJson);
})
.catch(error => {
console.error('Error:', error);
});
}
return (
<>
{isLoading ? <p>Loading...</p> : null}
<section id="hero-1" className="bg--scroll hero-section">
{
headerData?<img
src={`${apiUrl}storage/home_images/${headerData?.home_page_image}`}
alt="header image"
className="img-fluid banner-img"
/>:''
}
<div className="container container-content">
<div className="row d-flex align-items-center">
<div className="col-lg-6">
<div className="hero-1-txt color--white wow fadeInRight">
<h2 className="s-47">
{headerData?.img_header_1}
</h2>
<p className="p-xl">
{headerData?.img_para_1}
</p>
<Link
href="#banner-3"
className="btn r-04 btn--theme hover--tra-white"
>
{headerData?.img_h_text}
</Link>
</div>
</div>
<div className="col-md-12">
<div className="select_section wow fadeInUp">
{/ Product attribute dropdowns /}
{Object.keys(attributeData).map((key, index) => (
<select key={index} name={key} id={key} onChange={(event) => getValue(event, index)} className="form-control">
<option value="">{key}</option>
{attributeData[key].map((item, itemIndex) => (
<option key={itemIndex} value={item[key]}>
{item[key]}
</option>
))}
</select>
))}
<button className="btn btn-submit" onClick={handleButtonClick}>
Ich habe schon etwas
</button>
</div>
</div>
</div>
</div>
</section>
<section className='pt-100 features-section division'>
<div className='container'>
<div className="row justify-content-center">
<div className="col-md-10 col-lg-9">
<div className="section-title">
<h2 className="s-50">
{t(headerData?.below_image_text)}
</h2>
</div>
</div>
</div>
</div>
</section>
<section
id="features-6"
className="pt-100 pb-50 features-section division"
>
<div className="container">
<div className="fbox-wrapper text-center">
<div className="row row-cols-1 row-cols-md-2 row-cols-lg-4">
{selectedCategories.map((category) => (
<div className="col" key={category.id}>
<div
className={`fbox-6 fb-1 wow fadeInUp ${
category.isSelected ? "active" : ""
}`}
onClick={() => handleCategoryClick(category.id)}
>
<div className="img-style">
<img
src={`${apiUrl}storage/category/${category?.cat_image}`}
alt=""
className="img-fluid"
/>
</div>
<div className="check-icon">
<FcCheckmark />
</div>
<div className="fbox-txt">
<h6 className="s-20">{category?.cat_name}</h6>
</div>
</div>
</div>
))}
</div>
<div className="d-flex align-items-center justify-content-center mt-4">
{selectedCount > 0 ? (
<Link
href="/product/FilterProduct"
state={{ selectedCategories }}
className="btn btn-success me-4"
>
{" "}
{t("View Product")}
</Link>
) : (
<Link
href="/product"
state={{ selectedCategories }}
className="btn btn-success"
>
{t("View All Products")}
</Link>
)}
{(() => {
//if ((userSubscription?.payment_status === "Completed" && userSubscription?.subs_end_date > current_date) && (userSubscription?.user_type === 2 || userSubscription?.user_type === 3))
if (!showSubsButton) {
return "";
} else {
return (
<button
className="btn btn-success ms-4"
onClick={handleSubscriptionClick}
>
{t("Subscription")}
</button>
);
}
})()}
</div>
</div>
</div>
</section>
</>
)
}
export default Section1
![]() |
Notes is a web-based application for online taking notes. You can take your notes and share with others people. If you like taking long notes, notes.io is designed for you. To date, over 8,000,000,000+ notes created and continuing...
With notes.io;
- * You can take a note from anywhere and any device with internet connection.
- * You can share the notes in social platforms (YouTube, Facebook, Twitter, instagram etc.).
- * You can quickly share your contents without website, blog and e-mail.
- * You don't need to create any Account to share a note. As you wish you can use quick, easy and best shortened notes with sms, websites, e-mail, or messaging services (WhatsApp, iMessage, Telegram, Signal).
- * Notes.io has fabulous infrastructure design for a short link and allows you to share the note as an easy and understandable link.
Fast: Notes.io is built for speed and performance. You can take a notes quickly and browse your archive.
Easy: Notes.io doesn’t require installation. Just write and share note!
Short: Notes.io’s url just 8 character. You’ll get shorten link of your note when you want to share. (Ex: notes.io/q )
Free: Notes.io works for 14 years and has been free since the day it was started.
You immediately create your first note and start sharing with the ones you wish. If you want to contact us, you can use the following communication channels;
Email: [email protected]
Twitter: http://twitter.com/notesio
Instagram: http://instagram.com/notes.io
Facebook: http://facebook.com/notesio
Regards;
Notes.io Team