NotesWhat is notes.io?

Notes brand slogan

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 { fetchWithAuth } from "@/app/utils/api";
import AdvanceSearch from "./AdvanceSearch";
import { useAuth } from "@/app/components/AuthProvider/useAuth";
import { MultiSelect } from "react-multi-select-component";

const Section1 = () => {
const { t } = useTranslation();

const { isLoggedIn } = useAuth();

const [headerData, setHeaderData] = useState();
const [isLoading, setIsLoading] = useState(false);
const [attributeData, setAttributeData] = useState({});
const [data, setdata] = useState([]);
const [filteredData, setFilterData] = useState([]);
const [selectedAttributes, setSelectedAttributes] = useState([]);
console.log("selectedAttributes:-", selectedAttributes)

const [displayFurtherButton, setDisplayFurtherButton] = useState(true);
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 [already, setAlready] = useState(false);
const current_date = moment().format("Y-m-d H:mm:ss");
const [displayAdditionalSearch, setDisplayAdditionalSearch] = useState(false);
let filter_values = {
system_choice: [],
industrial_area: [],
building_type: [],
number_of_rooms: [],
availability_country: [],
};

useEffect(() => {
const fetchData = async () => {
const session = JSON.parse(sessionStorage.getItem("token"));

let token = "";
if (session != null) {
token = session.access_token;

try {
let options = {
headers: {
Authorization: "bearer " + token,
},
};
const response = await fetchWithAuth(
`${apiUrl}api/user/subscription/details`,
options
);
const responseJson = await response.json();

let result = responseJson?.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 != null &&
sortedData.length > 0 &&
sortedData[0].payment_status === "COMPLETED" &&
new Date(sortedData[0].subs_end_date).getTime() >
new Date().getTime()
) {
setUserSubscription(sortedData[0]);
setShowSubsButton(false);
} else {
setShowSubsButton(true);
}
}
} 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 (userSubscription != null && userSubscription.id > 0) {
// if (userSubscription.user_type === 4) {
// if (selectedCat.length === 3) {
// toast.warning(t("You can select one more category"));
// } else if (selectedCat.length > 4) {
// toast.error(t("You can't choose more category"));
// return;
// }
// } else if (
// userSubscription.user_type === 2 ||
// userSubscription.user_type === 3
// ) {
// // if (selectedCat.length === 3) {
// // toast.warning(t("You can select one more category"));
// // } else if (selectedCat.length > 4) {
// // toast.error(t("You can't choose more category"));
// // return;
// // }
// }
// } else {
// if (selectedCat.length === 2) {
// toast.warning(t("You can select one more category"));
// } else if (selectedCat.length > 3) {
// toast.error(t("You need a premium subscription"));
// return;
// }
// }
// } else {
// if (selectedCat.length === 2) {
// toast.warning(t("You can select one more category"));
// } else if (selectedCat.length > 3) {
// toast.error(t("You need a premium subscription"));
// return;
// }
// }

// setSelectedCategories(updatedCategories);
// };

const handleCategoryClick = (selectedCategoryId) => {
const updatedCategories = selectedCategories.map((item) =>
item.id === selectedCategoryId
? { ...item, isSelected: !item.isSelected }
: item
);

const selectedCat = updatedCategories.filter((item) => item.isSelected);

setSelectedCategories(updatedCategories);
setSelectedCount(selectedCat.length);

if (!showSubsButton) {
if (userSubscription != null && userSubscription.id > 0) {
if (userSubscription.user_type === 4) {
if (selectedCat.length === 3) {
toast.warning(t("You can select one more category"));
} else if (selectedCat.length > 4) {
toast.error(t("You can't choose more category"));
return;
}
} else if (
userSubscription.user_type === 2 ||
userSubscription.user_type === 3
) {
// if (selectedCat.length === 3) {
// toast.warning(t("You can select one more category"));
// } else if (selectedCat.length > 4) {
// toast.error(t("You can't choose more category"));
// return;
// }
}
} else {
if (selectedCat.length === 2) {
toast.warning(t("You can select one more category"));
} else if (selectedCat.length > 3) {
toast.error(t("You need a premium subscription"));
return;
}
}
}
// else {
// if (selectedCat.length === 2) {
// toast.warning(t("You can select one more category"));
// } else if (selectedCat.length > 3) {
// toast.error(t("You need a premium subscription"));
// return;
// }
// }
};

const handleLink = () => {
localStorage.removeItem("filter_values");
const selectedCat = selectedCategories.filter((item) => item.isSelected);
const selectedCatIds = selectedCat.map((item) => item.id);
localStorage.setItem("selectedCatIds", JSON.stringify(selectedCatIds));

if (selectedCount > 0 && selectedCount < 4) {
router.push("/product/FilterProduct");
} else {
if (
userSubscription?.payment_status === "COMPLETED" &&
(userSubscription?.user_type === 2 || userSubscription?.user_type === 3)
) {
const todayDate = new Date().toJSON().slice(0, 10);
const subcriptionDate = new Date(userSubscription.subs_end_date);
const subsEndDate = subcriptionDate.toISOString().substring(0, 10);

if (subsEndDate >= todayDate) {
router.push("/product/FilterProduct");
} else {
router.push("/Pricing");
}
} else {
router.push("/Pricing");
}
}
};

// userSubscription?.user_type === 4

const handleSubscriptionClick = () => {
//event handler for category click, it updates the state based selected category
clearLocalStorage();
if (selectedCount === 0) {
toast.error(t("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) {
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 {
let options = {
method: "POST",
headers: {
Accept: "application/json",
"Content-Type": "application/x-www-form-urlencoded",
},
// body: formBody
};
const response = await fetchWithAuth(`${apiUrl}api/category`, options);
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(() => {
// fetchData();
setIsLoading(true);
getCategoriesInfo();
getHeaderInfo();
getProductAttributes();
}, []);

// useEffect(() => {}, [selectedCount]);

async function getHeaderInfo() {
let options = {
method: "POST",
headers: {
Accept: "application/json",
"Content-Type": "application/x-www-form-urlencoded",
},
// body: formBody
};
const response = await fetchWithAuth(
`${apiUrl}api/home/header/image`,
options
);
const responseJson = await response.json();
if (responseJson.success == "true") {
setHeaderData(responseJson.header_image[0]);
setIsLoading(false);
}
}

async function getProductAttributes() {
let options = {};
const response = await fetchWithAuth(
`${apiUrl}api/product/attributes`,
options
);
const responseJson = await response.json();
if (responseJson.success === "true") {
console.log(responseJson.product_attr_value)
setAttributeData(responseJson.product_attr_value);
}
}
// function getValue(eventt, ind) {
// const name = eventt.target.name;
// const value = eventt.target.value;
// let obj = { name: eventt.target.name, 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);
// }

function getValue(arrayOfObjects, ind, key) {
console.log(key);
const selectedItems = arrayOfObjects.map(obj => obj.value);
switch (key) {
case "Sytemwahl":
filter_values.system_choice = [...new Set(selectedItems)];
break;
case "IndustrieBereich":
filter_values.industrial_area = [...new Set(selectedItems)];
break;
case "Gebäudeart":
filter_values.building_type = [...new Set(selectedItems)];
break;
case "Raumanzahl":
filter_values.number_of_rooms = [...new Set(selectedItems)];
break;
case "VerfügbarkeitLand":
filter_values.availability_country = [...new Set(selectedItems)];
break;
default:
break;
}
// const dataIndex = data.findIndex((item) => item.name === name);
// if (dataIndex === -1) {
// data.push({
// name: name,
// value: value,
// });
// } else {
// data[dataIndex].value = value;
// }
// (data);
// setSelectedAttributes(prevState => {
// const newState = [...prevState];
// // Ensure selectedItems is always an array
// const itemsArray = Array.isArray(selectedItems) ? selectedItems : [selectedItems];
// newState[ind] = itemsArray.map(item => typeof item === 'object' ? item.value : item);
// return newState;
// });
}


const clearLocalStorage = () => {
localStorage.removeItem("selectedCatIds");
};

const displayAdditional = (val) => {
data.forEach((item) => {
switch (item.name) {
case "Sytemwahl":
filter_values.system_choice.push(item.value);
break;
case "IndustrieBereich":
filter_values.industrial_area.push(item.value);
break;
case "Gebäudeart":
filter_values.building_type.push(item.value);
break;
case "Raumanzahl":
filter_values.number_of_rooms.push(item.value);
break;
case "VerfügbarkeitLand":
filter_values.availability_country.push(item.value);
break;
default:
break;
}
});

if (
filter_values.availability_country.length === 0 &&
filter_values.building_type.length === 0 &&
filter_values.industrial_area.length === 0 &&
filter_values.number_of_rooms.length === 0 &&
filter_values.system_choice.length === 0
) {
toast.warning(t("Please choose any one filter"));
setDisplayAdditionalSearch(false);
setDisplayFurtherButton(true);
} else {
setDisplayAdditionalSearch(!displayAdditionalSearch);
setDisplayFurtherButton(!displayFurtherButton);
clearLocalStorage();
}
};

async function handleButtonClick() {
data.forEach((item) => {
switch (item.name) {
case "Sytemwahl":
filter_values.system_choice.push(item.value);
break;
case "IndustrieBereich":
filter_values.industrial_area.push(item.value);
break;
case "Gebäudeart":
filter_values.building_type.push(item.value);
break;
case "Raumanzahl":
filter_values.number_of_rooms.push(item.value);
break;
case "VerfügbarkeitLand":
filter_values.availability_country.push(item.value);
break;
default:
break;
}
});

if (
filter_values.availability_country.length === 0 &&
filter_values.building_type.length === 0 &&
filter_values.industrial_area.length === 0 &&
filter_values.number_of_rooms.length === 0 &&
filter_values.system_choice.length === 0
) {
toast.warning(t("Please choose any one filter"));
} else {
let options = {
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
}),
};
const response = await fetchWithAuth(
`${apiUrl}api/product/attributes/categories`,
options
);
const responseJson = await response.json();
if (responseJson.success === "true") {
if (responseJson.filter_category.length == 0) {
toast.warning("No categories found for selected choice ");
} else {
const res = responseJson.filter_category.map((item) => ({
...item,
isSelected: false,
}));
setSelectedCategories(res);
setIsLoading(false);
const section = document.querySelector("#features-6");
section.scrollIntoView({ behavior: "smooth", block: "start" });
}
}
setFilterData(responseJson);
}
}

return (
<>
{isLoading ? <p> {t("Loading...")}</p> : null}
<section id="hero-1" className="bg--scroll hero-section">
{headerData?.home_page_image == "undefined" ? (
<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">
<div className="hero-1-img mobile__img">
<img
src="http://165.232.130.162/infotechdesign/trisfusa/assets/img/slider/img1.png"
alt="header image"
className="img-fluid"
/>
</div>

<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>

{isLoading ? <p> {t("Loading...")}</p> : null}
<div className="col-md-12">
<div className="new_search_section select_section wow fadeInUp">
{isLoading ? <p> {t("Loading...")}</p> : null}
{/* {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}>
{item}
</option>
))}
</select>
))} */}

{/* {isLoggedIn && parseInt(userRole) !== 4 && ( */}

{Object.keys(attributeData).map((key, index) => (
<MultiSelect
key={`${key}-${index}`}
disableSearch="true"
options={attributeData[key].map((item) => ({ label: item, value: item }))}
onChange={(selectedItems) => getValue(selectedItems, index, key)}
className="form-control dark"
/>
))}



<button
className="btn btn-submit"
onClick={() => {
displayAdditional();
}}
>
{t("I already have something")}
</button>
{/* )} */}
</div>
<br />

{displayFurtherButton && (
<div className="text-center">
<button
className="btn r-04 btn--theme hover--tra-white last-link"
onClick={handleButtonClick}
>
{t("Further")}
</button>
</div>
)}
</div>
{displayAdditionalSearch && <AdvanceSearch />}
</div>
</div>
</section>

{/* <section id="select" className="mobile_select">
<div className="container">
<div className="row">
<div className="col-md-6">
<AdvanceSearch />
</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, index) => (
<div className="col" key={index}>
<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 ? (
selectedCount > 3 ? (
<button
onClick={handleLink}
state={{ selectedCategories }}
className="btn btn-success me-4"
>
{t("Pricing")}
</button>
) : (
<button
onClick={handleLink}
state={{ selectedCategories }}
className="btn btn-success"
>
{t("View Product")}
</button>
)
) : null}

{/* {(() => {
//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;
     
 
what is notes.io
 

Notes.io is a web-based application for 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 12 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

     
 
Shortened Note Link
 
 
Looding Image
 
     
 
Long File
 
 

For written notes was greater than 18KB Unable to shorten.

To be smaller than 18KB, please organize your notes, or sign in.