<?php
namespace App\Controller;
use App\Repository\BucketsRepository;
use App\Repository\InfoRepository;
use App\Repository\IssuesRepository;
use App\Repository\NFHSRepository;
use App\Repository\UpdatesRepository;
use App\Repository\CreateRepository;
use App\Repository\BannerRepository;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Component\HttpFoundation\Session\SessionInterface;
use Symfony\Contracts\Translation\TranslatorInterface;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\HttpFoundation\JsonResponse;
use Symfony\Component\Routing\Annotation\Route;
use App\Entity\ChatUser;
use Doctrine\ORM\EntityManagerInterface;
use Psr\Log\LoggerInterface;
use App\Repository\SubscriberRepository;
use App\Entity\Subscriber;
class WebController extends AbstractController
{
private $entityManager;
private $translator;
private $logger;
private $otpValidityDuration;
public function __construct(
EntityManagerInterface $entityManager,
TranslatorInterface $translator,
LoggerInterface $logger
) {
$this->entityManager = $entityManager;
$this->translator = $translator;
$this->logger = $logger;
}
#[Route('/', name: 'web_index')]
public function index(
Request $req,
BucketsRepository $bucketsRepository,
InfoRepository $infoRepository,
UpdatesRepository $updatesRepository,
BannerRepository $bannerRepository,
TranslatorInterface $translator
): Response {
return $this->render('index.twig', [
'title' => $translator->trans('home.title'),
'page' => 'home',
'data' => [
'buckets' => $bucketsRepository->findBy([
'locale' => $req->getLocale()
]),
'intro' => $infoRepository->findBy(['locale' => $req->getLocale()]),
'updates' => $updatesRepository->findBy(['locale' => $req->getLocale()]),
'banners' => $bannerRepository->findBy(['locale' => $req->getLocale()])
]
]);
}
#[Route('/{_locale<en|hi>}/', name: 'web_index_locale')]
public function indexLocale(
Request $req,
BucketsRepository $bucketsRepository,
InfoRepository $infoRepository,
UpdatesRepository $updatesRepository,
TranslatorInterface $translator
): Response {
return $this->render('index.twig', [
'title' => $translator->trans('home.title'),
'page' => 'home',
'data' => [
'buckets' => $bucketsRepository->findBy([
'locale' => $req->getLocale()
]),
'intro' => $infoRepository->findBy(['locale' => $req->getLocale()]),
'updates' => $updatesRepository->findBy(['locale' => $req->getLocale()])
]
]);
}
#[
Route(
'/dashboard/{statecode}',
name: 'web_dashboard',
options: ['expose' => true]
)
]
public function dashboard(
Request $req,
BucketsRepository $bucketsRepository,
NFHSRepository $nfhsRepository,
TranslatorInterface $translator,
string $statecode
): Response {
$nfhs = $nfhsRepository->findOneBy(['code' => $statecode]);
return $this->render('dashboard.twig', [
'title' =>
$translator->trans('dashboard.title') .
' - ' .
$translator->trans($nfhs->getState()),
'page' => 'dashboard',
'data' => [
'buckets' => $bucketsRepository->findBy([
'locale' => $req->getLocale()
]),
'state' => $nfhs
]
]);
}
#[
Route(
'/bucket/{id}/{category}',
name: 'web_bucket',
options: ['expose' => true]
)
]
public function bucket(
Request $req,
BucketsRepository $bucketsRepository,
IssuesRepository $issuesRepository,
string $id,
string $category = null
): Response {
$issues = [];
$results = $issuesRepository->findBy([
'bucket' => $id,
'locale' => $req->getLocale()
],['date' => 'DESC']);
if (!empty($results)) {
foreach ($results as $issue) {
if ($category) {
if (in_array($category, $issue->getCategory())) {
array_push($issues, $issue);
}
} else {
array_push($issues, $issue);
}
}
} else {
return $this->redirectToRoute('web_index');
}
return $this->render('bucket.twig', [
'title' => $bucketsRepository->findOneBy(['_id' => $id])->getTitle(),
'description' => $bucketsRepository->findOneBy(['_id' => $id])->getDescription(),
'data' => [
'bucket' => $id,
'category' => $category,
'buckets' => $bucketsRepository->findBy([
'locale' => $req->getLocale()
]),
'issues' => $issues
]
]);
}
#[
Route(
'/search/{query}/{category}',
name: 'web_search',
options: ['expose' => true]
)
]
public function search(
Request $req,
BucketsRepository $bucketsRepository,
IssuesRepository $issuesRepository,
TranslatorInterface $translator,
string $query,
string $category = null
): Response {
$search = [];
$results = $issuesRepository->search($query, $req->getDefaultLocale());
if (!empty($results)) {
foreach ($results as $result) {
if ($category) {
if (in_array($category, $result['category'])) {
array_push($search, $result);
}
} else {
array_push($search, $result);
}
}
} else {
return $this->redirectToRoute('web_index');
}
return $this->render('search.twig', [
'title' => $translator->trans('search.title'),
'page' => 'search',
'data' => [
'category' => $category,
'buckets' => $bucketsRepository->findBy([
'locale' => $req->getLocale()
]),
'query' => $query,
'results' => $search
]
]);
}
#[Route('/contact', name: 'web_contact')]
public function contact(
Request $req,
BucketsRepository $bucketsRepository,
TranslatorInterface $translator
): Response {
return $this->render('contact.twig', [
'title' => $translator->trans('contact.title'),
'data' => [
'buckets' => $bucketsRepository->findBy([
'locale' => $req->getLocale()
])
]
]);
}
#[Route('/introduction', name: 'web_introduction')]
public function introduction(
Request $req,
BucketsRepository $bucketsRepository,
InfoRepository $infoRepository,
UpdatesRepository $updatesRepository,
TranslatorInterface $translator): Response {
return $this->render('introduction.twig', [
'data' => [
'buckets' => $bucketsRepository->findBy([
'locale' => $req->getLocale()
]),
'intro' => $infoRepository->findBy(['locale' => $req->getLocale()]),
'updates' => $updatesRepository->findBy(['locale' => $req->getLocale()])
]
]);
}
#[Route('/updates', name: 'web_updates')]
public function updates(
Request $req,
BucketsRepository $bucketsRepository,
InfoRepository $infoRepository,
UpdatesRepository $updatesRepository,
TranslatorInterface $translator): Response {
return $this->render('updates.twig', [
'data' => [
'buckets' => $bucketsRepository->findBy([
'locale' => $req->getLocale()
]),
'intro' => $infoRepository->findBy(['locale' => $req->getLocale()]),
'updates' => $updatesRepository->findBy(['locale' => $req->getLocale()])
]
]);
}
#[Route('/chatbot', name: 'web_chatbot')]
public function chatbot(Request $request,BucketsRepository $bucketsRepository,
InfoRepository $infoRepository,
UpdatesRepository $updatesRepository,
TranslatorInterface $translator): Response {
if (isset($_SESSION['user_email'])) {
$user_email = $_SESSION['user_email'];
$user_name = $_SESSION['user_name'];
}else{
$user_email = '';
$user_name = '';
}
$query = $request->query->get('q');
$curl = curl_init();
curl_setopt_array($curl, array(
// CURLOPT_URL => 'http://89.116.20.47:8000/chat_history/[email protected]',
CURLOPT_URL => 'http://89.116.20.47:8000/unique_dates/'. urlencode($user_email),
CURLOPT_RETURNTRANSFER => true,
CURLOPT_ENCODING => '',
CURLOPT_MAXREDIRS => 10,
CURLOPT_TIMEOUT => 0,
CURLOPT_FOLLOWLOCATION => true,
CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
CURLOPT_CUSTOMREQUEST => 'GET',
));
$response = curl_exec($curl);
curl_close($curl);
// $chatHistory = json_decode($response, true)['chat_history'];
$chatHistory = [];
$responseData = json_decode($response, true);
//echo "<pre>";print_r($responseData);echo "</pre>";
/*if (isset($responseData['chat_history'])) {
$chatHistory = $responseData['unique_dates'];
} else {
// Handle case where 'chat_history' key is not present in the response
$chatHistory= '';
}*/
$uniqueDates = $responseData['unique_dates'] ?? [];
return $this->render('chatbot.twig', [
'uniqueDates' => $uniqueDates,
'user_Email' => $user_email,
'user_Name' => $user_name,
'query' => $query,
'data' => [
'buckets' => $bucketsRepository->findBy([
'locale' => $request->getLocale()
]),]
]);
}
#[Route('/chathistory', name: 'web_chathistory')]
public function chathistory(Request $request,BucketsRepository $bucketsRepository,
InfoRepository $infoRepository,
UpdatesRepository $updatesRepository,
TranslatorInterface $translator): Response {
if (isset($_SESSION['user_email'])) {
$user_email = $_SESSION['user_email'];
$user_name = $_SESSION['user_name'];
} else {
$user_email = '';
$user_name = '';
}
if(!empty($request->query->get('date', ''))){
$date = $request->query->get('date', '');
$dateval = "?date=".urlencode($date)."";
}else{
$date = '';
$dateval = '';
}
$curl = curl_init();
curl_setopt_array($curl, array(
CURLOPT_URL => 'http://89.116.20.47:8000/chat_history/' . urlencode($user_email).$dateval,
CURLOPT_RETURNTRANSFER => true,
CURLOPT_ENCODING => '',
CURLOPT_MAXREDIRS => 10,
CURLOPT_TIMEOUT => 0,
CURLOPT_FOLLOWLOCATION => true,
CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
CURLOPT_CUSTOMREQUEST => 'GET',
));
$response = curl_exec($curl);
curl_close($curl);
$chatHistory = [];
$responseData = json_decode($response, true);
if (isset($responseData['chat_history'])) {
$chatHistory = $responseData['chat_history'];
} else {
// Handle case where 'chat_history' key is not present in the response
$chatHistory = 'Invalid API response: Missing "chat_history" key';
}
$curl1 = curl_init();
curl_setopt_array($curl1, array(
// CURLOPT_URL => 'http://89.116.20.47:8000/chat_history/[email protected]',
CURLOPT_URL => 'http://89.116.20.47:8000/unique_dates/'. urlencode($user_email),
CURLOPT_RETURNTRANSFER => true,
CURLOPT_ENCODING => '',
CURLOPT_MAXREDIRS => 10,
CURLOPT_TIMEOUT => 0,
CURLOPT_FOLLOWLOCATION => true,
CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
CURLOPT_CUSTOMREQUEST => 'GET',
));
$response1 = curl_exec($curl1);
curl_close($curl1);
$uniqueDates = [];
$responseData1 = json_decode($response1, true);
$uniqueDates = $responseData1['unique_dates'] ?? [];
return $this->render('chathistory.twig', [
'uniqueDates' => $uniqueDates,
'chatHistory' => $chatHistory,
'user_Email' => $user_email,
'user_Name' => $user_name,
'data' => [
'buckets' => $bucketsRepository->findBy([
'locale' => $request->getLocale()
]),]
]);
}
#[Route('/destroysession', name: 'destroy_session', methods: ['POST'])]
public function destroySession(Request $request): Response
{
// Use core PHP to destroy the session
if (session_status() === PHP_SESSION_NONE) {
session_start();
}
session_destroy();
// Redirect to the homepage or any other page
return $this->redirectToRoute('web_chatbot');
}
#[Route('/sendOTP', name: 'send_otp', methods: ['POST'])]
public function sendOTP(Request $request): JsonResponse
{
$data = json_decode($request->getContent(), true);
$email = $data['email'] ?? null;
if (!$email) {
return new JsonResponse(['success' => false, 'message' => 'Email is required.'], 400);
}
$query = $this->entityManager->createQuery('SELECT c FROM App\Entity\ChatUser c WHERE c.email = :email'
)->setParameter('email', $email);
$emailverify = $query->getOneOrNullResult();
if($emailverify){
//$otpSent = $this->sendOtpToEmail($emailverify->getId());
$otpSent = $this->sendOtpToEmail($emailverify->getId(), $email);
//$this->sendOtpToEmail1($emailverify->getId());
}
else{
return new JsonResponse(['success' => false, 'message' => 'User does not exist.']);
}
if ($otpSent) {
return new JsonResponse(['success' => true, 'message' => 'OTP Sent Succesfully.']);
} else {
return new JsonResponse(['success' => false, 'message' => 'Failed to send OTP.']);
}
}
/* private function sendOtpToEmail(int $userId, string $email): bool
{
// Generate a 6-digit OTP
$otp = random_int(100000, 999999);
// Save OTP and timestamp to database or session for verification later
// ...
// Prepare email content
$to = $email;
$subject = "Your OTP Code";
$message = "Your OTP code is: $otp";
$headers = "From: [email protected]";
// Send the email
if (mail($to, $subject, $message, $headers)) {
$this->logger->info("OTP email sent successfully to user ID: $userId");
return true;
} else {
$this->logger->error("Failed to send OTP email to user ID: $userId");
return false;
}
}*/
private function sendOtpToEmail(int $id, string $email): bool
{
$otp = rand(123456, 999999);
$chatUser = $this->entityManager->getRepository(ChatUser::class)->find($id);
if (!$chatUser) {
return false;
}
$otpExpiresAt = new \DateTime('+300 seconds');
$chatUser->setOtp($otp);
$chatUser->setOtpExpiresAt($otpExpiresAt);
$this->entityManager->persist($chatUser);
$this->entityManager->flush();
$to = $email;
$subject = "Your OTP Code";
// $message = "Your OTP code is: $otp";
$message = "Your OTP code is: $otp\n\nThanks and Regards,\n PFI";
$headers = [
'From' => '[email protected]',
'Reply-To' => '[email protected]',
'X-Mailer' => 'PHP/' . phpversion()
];
// Send the email
if (mail($to, $subject, $message, $headers)) {
$this->logger->info("OTP email sent successfully ");
return true;
} else {
$this->logger->error("Failed to send OTP email");
return false;
}
return true;
}
#[Route('/verifyOTP', name: 'verify_otp', methods: ['POST'])]
public function verifyOTP(Request $request): JsonResponse
{
if (session_status() == PHP_SESSION_NONE) {
session_start();
}
$data = json_decode($request->getContent(), true);
$otp = $data['otp'] ?? null;
$email = $data['email'] ?? null;
if (!$email || !$otp) {
return new JsonResponse(['success' => false, 'message' => 'Email and OTP are required.'], 400);
}
// Get current time
$currentTime = new \DateTime();
$query = $this->entityManager->createQuery(
'SELECT c FROM App\Entity\ChatUser c
WHERE c.email = :email AND c.otp = :otp AND c.otp_expires_at > :currentTime'
)->setParameter('email', $email)
->setParameter('otp', $otp)
->setParameter('currentTime', $currentTime);
$otpverify = $query->getOneOrNullResult();
if ($otpverify) {
$_SESSION['user_email'] = $otpverify->getEmail();
$_SESSION['user_name'] = $otpverify->getName();
// Clear OTP and expiration time after successful verification
$otpverify->setOtp(0);
$otpverify->setOtpExpiresAt(null);
$this->entityManager->persist($otpverify);
$this->entityManager->flush();
return new JsonResponse(['success' => true, 'message' => 'OTP Verified Successfully']);
} else {
// Check if the email exists to give a more specific error message
$user = $this->entityManager->getRepository(ChatUser::class)->findOneBy(['email' => $email]);
if ($user && $user->getOtpExpiresAt() <= $currentTime) {
return new JsonResponse(['success' => false, 'message' => 'OTP has expired.'], 400);
}
return new JsonResponse(['success' => false, 'message' => 'Invalid OTP.'], 400);
}
}
#[Route('/saveUser', name: 'save_user', methods: ['POST'])]
public function saveUser(Request $request, EntityManagerInterface $entityManager): JsonResponse
{
$data = json_decode($request->getContent(), true);
$email = $data['email'] ?? null;
$name = $data['name'] ?? null;
if (!$email || !$name) {
return new JsonResponse(['success' => false, 'message' => 'Email and Name are required.'], 400);
}
$query = $this->entityManager->createQuery(
'SELECT c FROM App\Entity\ChatUser c WHERE c.email = :email '
)->setParameter('email', $email);
$chatUser = $query->getOneOrNullResult();
if ($chatUser !='') {
return new JsonResponse(['success' => false, 'message' => 'User already exist.'], 200);
}
else{
try {
$otp = rand(123456, 999999);
$otpExpiresAt = new \DateTime('+300 seconds');
$chatUser = new ChatUser();
$chatUser->setEmail($email);
$chatUser->setName($name);
$chatUser->setOtp($otp);
$chatUser->setOtpExpiresAt($otpExpiresAt);
$this->entityManager->persist($chatUser);
$this->entityManager->flush();
} catch (\Exception $e) {
return new JsonResponse(['success' => false, 'message' => 'Failed to save user. Error: ' . $e->getMessage()]);
}
}
// $email = $chatUser->setEmail();
$otpSent = $this->sendOtpToEmailReg($otp,$data['email']);
return new JsonResponse(['success' => true, 'message' => 'User saved successfully.']);
}
private function sendOtpToEmailReg(int $otp,string $email): bool
{
//$otp = rand(123456, 999999);
$to = $email;
$subject = "Your OTP Code";
$message = "Your OTP code is: $otp\n\nThanks and Regards,\n PFI";
$headers = [
'From' => '[email protected]',
'Reply-To' => '[email protected]',
'X-Mailer' => 'PHP/' . phpversion()
];
// Send the email
if (mail($to, $subject, $message, $headers)) {
$this->logger->info("OTP email sent successfully ");
return true;
} else {
$this->logger->error("Failed to send OTP email");
return false;
}
return true;
}
#[Route('/chatbot/query', name: 'web_chatbot_query', methods: ['POST'])]
public function chatbotQuery(Request $request): JsonResponse
{
$data = json_decode($request->getContent(), true);
$question = $data['question'];
// $email ="[email protected]";
if (isset($_SESSION['user_email'])) {
$email = $_SESSION['user_email'];
}else{
$email = '';
}
// Make API call using cURL
$curl = curl_init();
curl_setopt_array($curl, array(
CURLOPT_URL => 'http://89.116.20.47:8000/query',
CURLOPT_RETURNTRANSFER => true,
CURLOPT_ENCODING => '',
CURLOPT_MAXREDIRS => 10,
CURLOPT_TIMEOUT => 0,
CURLOPT_FOLLOWLOCATION => true,
CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
CURLOPT_CUSTOMREQUEST => 'POST',
CURLOPT_POSTFIELDS => json_encode(['question' => $question,'email' =>$email]),
CURLOPT_HTTPHEADER => array(
'Content-Type: application/json'
),
));
$response = curl_exec($curl);
curl_close($curl);
$responseData = json_decode($response, true);
return new JsonResponse($responseData);
}
#[Route('/viewDistrict', name: 'web_district', options: ['expose' => true])]
public function viewDistrict(NFHSRepository $nfhsRepository,CreateRepository $createRepository, Request $request,BucketsRepository $bucketsRepository,
InfoRepository $infoRepository,
UpdatesRepository $updatesRepository,
TranslatorInterface $translator): Response
{
$ts = $request->query->get('ts', '');
$states = $nfhsRepository->findAllStates();
$searchQuery = $request->query->get('search', '');
if ($searchQuery) {
$districts = $nfhsRepository->searchDistrictsWithStateNames($searchQuery);
} else {
$districts = $nfhsRepository->findAllWithStateNames();
}
$districtslink = $createRepository->findByStateFieldyind(794);
//print_r($districtslink);
$districtLink = '';
if (!empty($districtslink) && isset($districtslink[0])) {
$districtLink = $districtslink[0]->getLink();
}
return $this->render('DistrictDashboard.twig', [
'title' => 'District Dashboard',
'states' => $states,
'districts' => $districts,
'search' => $searchQuery,
'ts' => $ts,
'districtLink' => $districtLink,
'data' => [
'buckets' => $bucketsRepository->findBy([
'locale' => $request->getLocale()
]),]
]);
}
#[Route('/mail_subscribe', name: 'mail_save', methods: ['POST'])]
public function mail_subscribe(Request $request): JsonResponse
{
$data = json_decode($request->getContent(), true);
$email = $data['email'] ?? null;
if (!$email) {
return new JsonResponse(['success' => false, 'message' => 'Email is required.'], 400);
}
$query = $this->entityManager->createQuery(
'SELECT c FROM App\Entity\Subscriber c WHERE c.email = :email'
)->setParameter('email', $email);
$emailverify = $query->getOneOrNullResult();
if ($emailverify) {
if ($emailverify->getIsSubscribe() == 1) {
$emailverify->setIsSubscribe(0);
$emailverify->setUpdatedBy(new \DateTime());
$this->entityManager->flush();
return new JsonResponse(['success' => true, 'message' => 'Thank you for signing up! We’ll keep you posted on the latest updates.']);
}
return new JsonResponse(['success' => false, 'message' => 'Email is already subscribed.']);
} else {
$details = new Subscriber();
$details->setEmail($email);
$details->setIsSubscribe(0);
$details->setCreatedBy(0);
$details->setCreatedAt(new \DateTime());
$this->entityManager->persist($details);
$this->entityManager->flush();
return new JsonResponse(['success' => true, 'message' => 'Thank you for signing up! We’ll keep you posted on the latest updates.']);
}
}
}