src/Controller/AdminController.php line 396

Open in your IDE?
  1. <?php
  2. namespace App\Controller;
  3. use App\Entity\Create;
  4. use App\Entity\Banner;
  5. use App\Entity\Issues;
  6. use App\Repository\BannerRepository;
  7. use App\Repository\BucketsRepository;
  8. use App\Repository\IssuesRepository;
  9. use App\Repository\NFHSRepository;
  10. use App\Repository\CreateRepository;
  11. use App\Repository\UpdatesRepository;
  12. use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
  13. use Symfony\Component\HttpFoundation\Request;
  14. use Symfony\Component\HttpFoundation\Response;
  15. use Symfony\Component\HttpFoundation\JsonResponse;
  16. use Symfony\Component\Routing\Annotation\Route;
  17. use Doctrine\ORM\EntityManagerInterface;
  18. use Symfony\Component\Uid\Uuid as SymfonyUUID;
  19. use Imagick;
  20. use ImagickPixel;
  21. class AdminController extends AbstractController
  22. {
  23.   #[
  24.     Route(
  25.       '/admin/dashboard',
  26.       name'admin_dashboard',
  27.       options: ['expose' => true]
  28.     )
  29.   ]
  30.   public function dashboard(
  31.     Request $req,
  32.     UpdatesRepository $updatesRepository,
  33.     NFHSRepository $nfhsRepository,
  34.     CreateRepository $createRepository,
  35.     BucketsRepository $bucketsRepository
  36.   ): Response {
  37.     return $this->render('admin/dashboard.twig', [
  38.       'title' => 'Dashboard',
  39.       'data' => [
  40.         'totalUpdates' => $updatesRepository->count([
  41.           'locale' => $req->getLocale()
  42.         ]),
  43.         'totalStates' => $nfhsRepository->count([]),
  44.         'totalDistrict' => $createRepository->count([]),
  45.         'totalBuckets' => $bucketsRepository->count([
  46.           'locale' => $req->getLocale()
  47.         ])
  48.       ]
  49.     ]);
  50.   }
  51.   #[Route('/admin/updates'name'admin_updates'options: ['expose' => true])]
  52.   public function updates(): Response
  53.   {
  54.     return $this->render('admin/updates.twig', [
  55.       'title' => 'Updates - Dashboard'
  56.     ]);
  57.   }
  58.   #[Route('/admin/nfhs'name'admin_nfhs'options: ['expose' => true])]
  59.   public function nfhs(): Response
  60.   {
  61.     return $this->render('admin/nfhs.twig', [
  62.       'title' => 'NFHS - Dashboard'
  63.     ]);
  64.   
  65. }
  66. #[Route('/admin/create'name'admin_create'options: ['expose' => true])]
  67. public function create(NFHSRepository $nfhsRepositoryCreateRepository $createRepositoryRequest $request): Response
  68. {
  69.         $states $nfhsRepository->findAllStates();
  70.         //$districts = $createRepository->findAll();
  71.          $districts $nfhsRepository->findAllWithStateNames();
  72.     $states $nfhsRepository->findAllStates();
  73.     $searchQuery $request->query->get('search''');
  74.     if ($searchQuery) {
  75.         $districts $nfhsRepository->searchDistrictsWithStateNames($searchQuery);
  76.     } else {
  77.         $districts $nfhsRepository->findAllWithStateNames();
  78.     }
  79.         return $this->render('admin/create.twig', [
  80.             'title' => 'Create - Dashboard',
  81.             'states' => $states,
  82.             'districts' => $districts,
  83.              'search' => $searchQuery
  84.         ]);
  85.     }
  86.    #[Route('/admin/add'name'admin_add'methods: ['POST'], options: ['expose' => true])]
  87. public function add(Request $requestEntityManagerInterface $entityManagerCreateRepository $createRepository): JsonResponse
  88. {
  89.     $data json_decode($request->getContent(), true);
  90.     $stateID $data['state'];
  91.     $districtName $data['district'];
  92.     $link $data['link'];
  93.     // Check for uniqueness
  94.     $existingRecord $createRepository->findOneBy([
  95.         'stateID' => $stateID,
  96.         'districtName' => $districtName,
  97.     ]);
  98.     if ($existingRecord) {
  99.         return new JsonResponse(['status' => 'error''message' => 'This state and district combination already exists!'], JsonResponse::HTTP_CONFLICT);
  100.     }
  101.     $create = new Create();
  102.     $create->setStateID($stateID);
  103.     $create->setDistrictName($districtName);
  104.     $create->setLink($link);
  105.    
  106.     // Set createdOn and updatedOn to the current datetime
  107.     $create->setCreatedOn(new \DateTimeImmutable());
  108.     $create->setUpdatedOn(new \DateTimeImmutable());
  109.     $entityManager->persist($create);
  110.     $entityManager->flush();
  111.     return new JsonResponse(['status' => 'success''message' => 'Data added successfully!']);
  112. }
  113. #[Route('/admin/edit/{id}'name'admin_edit'methods: ['POST'])]
  114. public function edit(string $idRequest $requestEntityManagerInterface $entityManager): JsonResponse
  115. {
  116.     $data json_decode($request->getContent(), true);
  117.     $create $entityManager->getRepository(Create::class)->find($id);
  118.     if (!$create) {
  119.         return new JsonResponse(['status' => 'error''message' => 'Record not found.'], 404);
  120.     }
  121.     //$create->setStateID($data['stateID']);
  122.     //$create->setDistrictName($data['districtName']);
  123.     $create->setLink($data['link']);
  124.     $create->setUpdatedOn(new \DateTimeImmutable()); // Update the timestamp
  125.     // Assuming you have an updatedBy field in your entity
  126.     // Replace 'updatedBy' with your actual field name if it differs
  127.     $create->setUpdatedBy($data['updatedBy']);
  128.     $entityManager->flush();
  129.     return new JsonResponse(['status' => 'success''message' => 'Data updated successfully!']);
  130. }
  131.  #[Route('/admin/gptsearch'name'admin_gptsearch'options: ['expose' => true])]
  132.     public function chatbot(): Response
  133.     {
  134.       $curl curl_init();
  135.     curl_setopt_array($curl, array(
  136.         CURLOPT_URL => 'http://89.116.20.47:8000/chat_history/admin_login',
  137.         CURLOPT_RETURNTRANSFER => true,
  138.         CURLOPT_ENCODING => '',
  139.         CURLOPT_MAXREDIRS => 10,
  140.         CURLOPT_TIMEOUT => 0,
  141.         CURLOPT_FOLLOWLOCATION => true,
  142.         CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
  143.         CURLOPT_CUSTOMREQUEST => 'GET',
  144.     ));
  145.     $response curl_exec($curl);
  146.     curl_close($curl);
  147.     $email '';
  148.     $chatHistory = [];
  149.     $responseData json_decode($responsetrue);
  150.     if (isset($responseData['chat_history'])) {
  151.         $chatHistory $responseData['chat_history'];
  152.         $email $responseData['chat_history'][0]['email']; // Assuming the email is consistent across chat history entries
  153.     } else {
  154.         $chatHistory 'Invalid API response: Missing "chat_history" key';
  155.     }
  156.     return $this->render('admin/gpt_search.twig', [
  157.         'chatHistory' => $chatHistory,
  158.         'email' => $email
  159.     ]);
  160.     }
  161.     #[Route('/admin/gptguestuser'name'admin_gptguestuser'options: ['expose' => true])]
  162.     public function chatbothistory(): Response
  163.     {
  164.       $curl curl_init();
  165.     curl_setopt_array($curl, array(
  166.         CURLOPT_URL => 'http://89.116.20.47:8000/guest_chat_history',
  167.         CURLOPT_RETURNTRANSFER => true,
  168.         CURLOPT_ENCODING => '',
  169.         CURLOPT_MAXREDIRS => 10,
  170.         CURLOPT_TIMEOUT => 0,
  171.         CURLOPT_FOLLOWLOCATION => true,
  172.         CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
  173.         CURLOPT_CUSTOMREQUEST => 'GET',
  174.     ));
  175.     $response curl_exec($curl);
  176.     curl_close($curl);
  177.     $chatHistory = [];
  178.     $responseData json_decode($responsetrue);
  179. //print_r($responseData);exit();
  180.    if (isset($responseData['guest_chat_history'])) {
  181.             $chatHistory $responseData['guest_chat_history'];
  182.         } else {
  183.             // Handle case where 'chat_history' key is not present in the response
  184.             $chatHistory 'Invalid API response: Missing "chat_history" key';
  185.         }
  186.         return $this->render('admin/gpt_usersearch.twig',[
  187.         'chatHistory' => $chatHistory
  188.     ]);
  189.     }
  190.     #[Route('/admin/chatbot/query'name'admin_chatbot_query'methods: ['POST'])]
  191.     public function chatbotQuery(Request $request): JsonResponse
  192.     {
  193.         $data json_decode($request->getContent(), true);
  194.         $question $data['question'];
  195.         // Make API call using cURL
  196.         $curl curl_init();
  197.         curl_setopt_array($curl, array(
  198.             CURLOPT_URL => 'http://89.116.20.47:8000/query',
  199.             CURLOPT_RETURNTRANSFER => true,
  200.             CURLOPT_ENCODING => '',
  201.             CURLOPT_MAXREDIRS => 10,
  202.             CURLOPT_TIMEOUT => 0,
  203.             CURLOPT_FOLLOWLOCATION => true,
  204.             CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
  205.             CURLOPT_CUSTOMREQUEST => 'POST',
  206.             CURLOPT_POSTFIELDS => json_encode(['question' => $question]),
  207.             CURLOPT_HTTPHEADER => array(
  208.                 'Content-Type: application/json'
  209.             ),
  210.         ));
  211.         $response curl_exec($curl);
  212.         curl_close($curl);
  213.         $responseData json_decode($responsetrue);
  214.         return new JsonResponse($responseData);
  215.     }
  216. #[Route('/get-districts/{stateId}'name'get_districts'methods: ['GET'])]
  217.     public function getDistricts(CreateRepository $createRepositorystring $stateId): JsonResponse
  218.     {
  219.        $districts $createRepository->findByStateField($stateId);
  220.         $districtArray = [];
  221.         foreach ($districts as $district) {
  222.             $districtArray[] = [
  223.                 'id' => $district->getId(),
  224.                 'link' => $district->getLink(),
  225.                 'name' => $district->getDistrictName()
  226.             ];
  227.         }
  228.         return new JsonResponse($districtArray);
  229.     }
  230.   #[Route('/admin/buckets'name'admin_buckets'options: ['expose' => true])]
  231.   public function buckets(): Response
  232.   {
  233.     return $this->render('admin/buckets.twig', [
  234.       'title' => 'Buckets - Dashboard'
  235.     ]);
  236.   }
  237.  #[Route('/buckets/copy/{id}'name'buckets_copy')]
  238. public function copyBuckets(Request $requestIssuesRepository $issuesRepositorystring $id null): Response
  239. {
  240.     // Step 1: Fetch the existing bucket by ID
  241.     $existingData $issuesRepository->find(['_id' => $id]);
  242.    // dump($existingData);
  243.     
  244.     if (!$existingData) {
  245.         throw $this->createNotFoundException('Bucket not found');
  246.     }
  247.     if ($request->isMethod('POST')) {
  248.         // Retrieve form data
  249.         $submittedData = [
  250.             'type' => $request->request->get('type'),
  251.             'title' => $request->request->get('title'),
  252.             'bucket' => $request->request->get('bucket'), // Ensure this is retrieved correctly
  253.             'cover' => $existingData->getCover(),
  254.             'type' => $existingData->getType(),
  255.             'link' => $existingData->getLink(),
  256.             'category' => $existingData->getCategory(),
  257.             'locale' => $request->request->get('locale'),
  258.             'description' => $request->request->get('description'),
  259.             'date' => new \DateTimeImmutable($request->request->get('date')),
  260.             'pdf_ytlink' => $request->request->get('pdf_ytlink'),
  261.         ];
  262.         // Handle file uploads
  263.         $uploadedFile $request->files->get('file');
  264.         $uploadedCover $request->files->get('cover');
  265.         // Define the directory to store uploaded files
  266.         $uploadsDirectory $this->getParameter('uploads');
  267.         // Create a new instance of your entity for the new bucket
  268.         $newData = new Issues(); // Replace Issues with your actual entity class
  269.         // Save PDF file if uploaded
  270.         if ($uploadedFile) {
  271.             $originalFilename pathinfo($uploadedFile->getClientOriginalName(), PATHINFO_FILENAME);
  272.             $newFilename uniqid() . '-' $originalFilename '.' $uploadedFile->guessExtension();
  273.             $uploadedFile->move($uploadsDirectory$newFilename);
  274.             $newData->setPdf($newFilename); // Ensure you have a method to set the filename in your entity
  275.         }
  276.         // Save cover image if uploaded
  277.         if ($uploadedCover) {
  278.             $originalCoverFilename pathinfo($uploadedCover->getClientOriginalName(), PATHINFO_FILENAME);
  279.             $newCoverFilename uniqid() . '-' $originalCoverFilename '.' $uploadedCover->guessExtension();
  280.             $uploadedCover->move($uploadsDirectory$newCoverFilename);
  281.             $newData->setCover($newCoverFilename); // Ensure you have a method to set the cover filename in your entity
  282.         }
  283.         // Update new data object with new values
  284.         $newData->setType($submittedData['type']);
  285.         $newData->setTitle($submittedData['title']);
  286.         $newData->setBucket($submittedData['bucket']); // Set bucket correctly here
  287.         $newData->setDescription($submittedData['description']);
  288.         $newData->setDate($submittedData['date']);
  289.         $newData->setLink($submittedData['link']);
  290.         $newData->setPdfYtlink($submittedData['pdf_ytlink']);
  291.         $newData->setCover($submittedData['cover']); 
  292.         $newData->setLocale($submittedData['locale']);
  293.         $newData->setCategory($submittedData['category']);
  294.         
  295. //dump($newData);exit();
  296.         // Ensure bucket is not null before saving
  297.         if (empty($submittedData['bucket'])) {
  298.             // Handle the error case, maybe add a flash message
  299.             $this->addFlash('error''Bucket cannot be empty.');
  300.             return $this->render('admin/bucketscopy.twig', [
  301.                 'data' => $existingData,
  302.                 'id' => $id,
  303.                 'submittedData' => $submittedData// Pass the submitted data back for user to see
  304.             ]);
  305.         }
  306. //dump($newData);exit;
  307.         // Save the new data and flush
  308.         $issuesRepository->save($newDatatrue);
  309.         return $this->redirectToRoute('admin_buckets');
  310.     }
  311.     // Render the Twig template
  312.     return $this->render('admin/bucketscopy.twig', [
  313.         'data' => $existingData,
  314.         'id' => $id
  315.     ]);
  316. }
  317.    #[Route('/admin/banner'name'admin_banner'options: ['expose' => true])]
  318.     public function banner(Request $requestEntityManagerInterface $entityManager,BannerRepository $bannerRepository): Response
  319.     {
  320.       $requestr $request->getLocale();
  321.       $banners $bannerRepository->findBy(['locale' => $requestr]);
  322.       //$banners = $bannerRepository->findAll();
  323.         if ($request->isMethod('POST')) {
  324.             $title $request->request->get('title');
  325.             $description $request->request->get('description');
  326.             $languageId $request->request->get('locale');
  327.             // Handle file upload
  328.             /** @var UploadedFile $cover */
  329.             $cover $request->files->get('cover');
  330.             $coverFilename '';
  331.             if ($cover) {
  332.                 $coverFilename uniqid() . '.' $cover->guessExtension();
  333.                 $cover->move(
  334.                     $this->getParameter('uploads') . '/banners'// Define this in config
  335.                     $coverFilename
  336.                 );
  337.             }
  338.             // Create new Banner entity
  339.             $banner = new Banner();
  340.             $banner->setTitle($title);
  341.             $banner->setDescription($description);
  342.             $banner->setlocale($languageId);
  343.             $banner->setCover($coverFilename);
  344.             // Save to database
  345.             $entityManager->persist($banner);
  346.             $entityManager->flush();
  347.             $this->addFlash('success''Banner saved successfully!');
  348.             return $this->redirectToRoute('admin_banner');
  349.         }
  350.         return $this->render('admin/banner.twig', [
  351.             'title' => 'Banner - Dashboard',
  352.             'banners' => $banners
  353.         ]);
  354.     }
  355.     #[Route('/admin/banner/edit/{id}'name'admin_banner_edit')]
  356. public function editBanner(Request $requestEntityManagerInterface $entityManagerBannerRepository $bannerRepositoryint $id): Response
  357. {
  358.     $banner $bannerRepository->find($id);
  359.     if (!$banner) {
  360.         throw $this->createNotFoundException('Banner not found.');
  361.     }
  362.     if ($request->isMethod('POST')) {
  363.         $title $request->request->get('title');
  364.         $description $request->request->get('description');
  365.         $languageId $request->request->get('locale');
  366.         /** @var UploadedFile $cover */
  367.         $cover $request->files->get('cover');
  368.         if ($cover) {
  369.             $coverFilename uniqid() . '.' $cover->guessExtension();
  370.             $cover->move(
  371.                 $this->getParameter('uploads') . '/banners',
  372.                 $coverFilename
  373.             );
  374.             $banner->setCover($coverFilename); // Update the cover if a new one is provided
  375.         }
  376.         // Update existing Banner entity
  377.         $banner->setTitle($title);
  378.         $banner->setDescription($description);
  379.         $banner->setLocale($languageId);
  380.         // Save updated data to database
  381.         $entityManager->flush();
  382.         $this->addFlash('success''Banner updated successfully!');
  383.         return $this->redirectToRoute('admin_banner');
  384.     }
  385.     return $this->render('admin/edit_banner.twig', [
  386.         'title' => 'Edit Banner',
  387.         'banner' => $banner,
  388.     ]);
  389. }
  390. #[Route('/admin/banner/delete/{id}'name'admin_banner_delete')]
  391. public function deleteBanner(EntityManagerInterface $entityManagerBannerRepository $bannerRepositoryint $id): Response
  392. {
  393.     $banner $bannerRepository->find($id);
  394.     if (!$banner) {
  395.         throw $this->createNotFoundException('Banner not found.');
  396.     }
  397.     // Remove the banner from the database
  398.     $entityManager->remove($banner);
  399.     $entityManager->flush();
  400.     $this->addFlash('success''Banner deleted successfully!');
  401.     return $this->redirectToRoute('admin_banner');
  402. }
  403.   #[
  404.     Route('/admin/issue/{id}'name'admin_issue'options: ['expose' => true])
  405.   ]
  406.   public function issues(
  407.     BucketsRepository $bucketsRepository,
  408.     string $id
  409.   ): Response {
  410.     $bucket $bucketsRepository->findOneBy(['_id' => $id]);
  411.     return $this->render('admin/issue.twig', [
  412.       'title' => 'Manage Issue - Dashboard',
  413.       'data' => [
  414.         'bucket' => [
  415.           'id' => $id,
  416.           'title' => $bucket->getTitle()
  417.         ]
  418.       ]
  419.     ]);
  420.   }
  421.   #[Route('/admin/contact'name'admin_contact'options: ['expose' => true])]
  422.   public function contact(): Response
  423.   {
  424.     return $this->render('admin/contact.twig', [
  425.       'title' => 'Contact - Dashboard'
  426.     ]);
  427.   }
  428.   #[Route('/admin/info'name'admin_info'options: ['expose' => true])]
  429.   public function info(): Response
  430.   {
  431.     return $this->render('admin/info.twig', [
  432.       'title' => 'Info - Dashboard'
  433.     ]);
  434.   }
  435. }