<?php
namespace App\Controller;
use App\Entity\Create;
use App\Entity\Banner;
use App\Entity\Issues;
use App\Repository\BannerRepository;
use App\Repository\BucketsRepository;
use App\Repository\IssuesRepository;
use App\Repository\NFHSRepository;
use App\Repository\CreateRepository;
use App\Repository\UpdatesRepository;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\HttpFoundation\JsonResponse;
use Symfony\Component\Routing\Annotation\Route;
use Doctrine\ORM\EntityManagerInterface;
use Symfony\Component\Uid\Uuid as SymfonyUUID;
use Imagick;
use ImagickPixel;
class AdminController extends AbstractController
{
#[
Route(
'/admin/dashboard',
name: 'admin_dashboard',
options: ['expose' => true]
)
]
public function dashboard(
Request $req,
UpdatesRepository $updatesRepository,
NFHSRepository $nfhsRepository,
CreateRepository $createRepository,
BucketsRepository $bucketsRepository
): Response {
return $this->render('admin/dashboard.twig', [
'title' => 'Dashboard',
'data' => [
'totalUpdates' => $updatesRepository->count([
'locale' => $req->getLocale()
]),
'totalStates' => $nfhsRepository->count([]),
'totalDistrict' => $createRepository->count([]),
'totalBuckets' => $bucketsRepository->count([
'locale' => $req->getLocale()
])
]
]);
}
#[Route('/admin/updates', name: 'admin_updates', options: ['expose' => true])]
public function updates(): Response
{
return $this->render('admin/updates.twig', [
'title' => 'Updates - Dashboard'
]);
}
#[Route('/admin/nfhs', name: 'admin_nfhs', options: ['expose' => true])]
public function nfhs(): Response
{
return $this->render('admin/nfhs.twig', [
'title' => 'NFHS - Dashboard'
]);
}
#[Route('/admin/create', name: 'admin_create', options: ['expose' => true])]
public function create(NFHSRepository $nfhsRepository, CreateRepository $createRepository, Request $request): Response
{
$states = $nfhsRepository->findAllStates();
//$districts = $createRepository->findAll();
$districts = $nfhsRepository->findAllWithStateNames();
$states = $nfhsRepository->findAllStates();
$searchQuery = $request->query->get('search', '');
if ($searchQuery) {
$districts = $nfhsRepository->searchDistrictsWithStateNames($searchQuery);
} else {
$districts = $nfhsRepository->findAllWithStateNames();
}
return $this->render('admin/create.twig', [
'title' => 'Create - Dashboard',
'states' => $states,
'districts' => $districts,
'search' => $searchQuery
]);
}
#[Route('/admin/add', name: 'admin_add', methods: ['POST'], options: ['expose' => true])]
public function add(Request $request, EntityManagerInterface $entityManager, CreateRepository $createRepository): JsonResponse
{
$data = json_decode($request->getContent(), true);
$stateID = $data['state'];
$districtName = $data['district'];
$link = $data['link'];
// Check for uniqueness
$existingRecord = $createRepository->findOneBy([
'stateID' => $stateID,
'districtName' => $districtName,
]);
if ($existingRecord) {
return new JsonResponse(['status' => 'error', 'message' => 'This state and district combination already exists!'], JsonResponse::HTTP_CONFLICT);
}
$create = new Create();
$create->setStateID($stateID);
$create->setDistrictName($districtName);
$create->setLink($link);
// Set createdOn and updatedOn to the current datetime
$create->setCreatedOn(new \DateTimeImmutable());
$create->setUpdatedOn(new \DateTimeImmutable());
$entityManager->persist($create);
$entityManager->flush();
return new JsonResponse(['status' => 'success', 'message' => 'Data added successfully!']);
}
#[Route('/admin/edit/{id}', name: 'admin_edit', methods: ['POST'])]
public function edit(string $id, Request $request, EntityManagerInterface $entityManager): JsonResponse
{
$data = json_decode($request->getContent(), true);
$create = $entityManager->getRepository(Create::class)->find($id);
if (!$create) {
return new JsonResponse(['status' => 'error', 'message' => 'Record not found.'], 404);
}
//$create->setStateID($data['stateID']);
//$create->setDistrictName($data['districtName']);
$create->setLink($data['link']);
$create->setUpdatedOn(new \DateTimeImmutable()); // Update the timestamp
// Assuming you have an updatedBy field in your entity
// Replace 'updatedBy' with your actual field name if it differs
$create->setUpdatedBy($data['updatedBy']);
$entityManager->flush();
return new JsonResponse(['status' => 'success', 'message' => 'Data updated successfully!']);
}
#[Route('/admin/gptsearch', name: 'admin_gptsearch', options: ['expose' => true])]
public function chatbot(): Response
{
$curl = curl_init();
curl_setopt_array($curl, array(
CURLOPT_URL => 'http://89.116.20.47:8000/chat_history/admin_login',
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);
$email = '';
$chatHistory = [];
$responseData = json_decode($response, true);
if (isset($responseData['chat_history'])) {
$chatHistory = $responseData['chat_history'];
$email = $responseData['chat_history'][0]['email']; // Assuming the email is consistent across chat history entries
} else {
$chatHistory = 'Invalid API response: Missing "chat_history" key';
}
return $this->render('admin/gpt_search.twig', [
'chatHistory' => $chatHistory,
'email' => $email
]);
}
#[Route('/admin/gptguestuser', name: 'admin_gptguestuser', options: ['expose' => true])]
public function chatbothistory(): Response
{
$curl = curl_init();
curl_setopt_array($curl, array(
CURLOPT_URL => 'http://89.116.20.47:8000/guest_chat_history',
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);
//print_r($responseData);exit();
if (isset($responseData['guest_chat_history'])) {
$chatHistory = $responseData['guest_chat_history'];
} else {
// Handle case where 'chat_history' key is not present in the response
$chatHistory = 'Invalid API response: Missing "chat_history" key';
}
return $this->render('admin/gpt_usersearch.twig',[
'chatHistory' => $chatHistory
]);
}
#[Route('/admin/chatbot/query', name: 'admin_chatbot_query', methods: ['POST'])]
public function chatbotQuery(Request $request): JsonResponse
{
$data = json_decode($request->getContent(), true);
$question = $data['question'];
// 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]),
CURLOPT_HTTPHEADER => array(
'Content-Type: application/json'
),
));
$response = curl_exec($curl);
curl_close($curl);
$responseData = json_decode($response, true);
return new JsonResponse($responseData);
}
#[Route('/get-districts/{stateId}', name: 'get_districts', methods: ['GET'])]
public function getDistricts(CreateRepository $createRepository, string $stateId): JsonResponse
{
$districts = $createRepository->findByStateField($stateId);
$districtArray = [];
foreach ($districts as $district) {
$districtArray[] = [
'id' => $district->getId(),
'link' => $district->getLink(),
'name' => $district->getDistrictName()
];
}
return new JsonResponse($districtArray);
}
#[Route('/admin/buckets', name: 'admin_buckets', options: ['expose' => true])]
public function buckets(): Response
{
return $this->render('admin/buckets.twig', [
'title' => 'Buckets - Dashboard'
]);
}
#[Route('/buckets/copy/{id}', name: 'buckets_copy')]
public function copyBuckets(Request $request, IssuesRepository $issuesRepository, string $id = null): Response
{
// Step 1: Fetch the existing bucket by ID
$existingData = $issuesRepository->find(['_id' => $id]);
// dump($existingData);
if (!$existingData) {
throw $this->createNotFoundException('Bucket not found');
}
if ($request->isMethod('POST')) {
// Retrieve form data
$submittedData = [
'type' => $request->request->get('type'),
'title' => $request->request->get('title'),
'bucket' => $request->request->get('bucket'), // Ensure this is retrieved correctly
'cover' => $existingData->getCover(),
'type' => $existingData->getType(),
'link' => $existingData->getLink(),
'category' => $existingData->getCategory(),
'locale' => $request->request->get('locale'),
'description' => $request->request->get('description'),
'date' => new \DateTimeImmutable($request->request->get('date')),
'pdf_ytlink' => $request->request->get('pdf_ytlink'),
];
// Handle file uploads
$uploadedFile = $request->files->get('file');
$uploadedCover = $request->files->get('cover');
// Define the directory to store uploaded files
$uploadsDirectory = $this->getParameter('uploads');
// Create a new instance of your entity for the new bucket
$newData = new Issues(); // Replace Issues with your actual entity class
// Save PDF file if uploaded
if ($uploadedFile) {
$originalFilename = pathinfo($uploadedFile->getClientOriginalName(), PATHINFO_FILENAME);
$newFilename = uniqid() . '-' . $originalFilename . '.' . $uploadedFile->guessExtension();
$uploadedFile->move($uploadsDirectory, $newFilename);
$newData->setPdf($newFilename); // Ensure you have a method to set the filename in your entity
}
// Save cover image if uploaded
if ($uploadedCover) {
$originalCoverFilename = pathinfo($uploadedCover->getClientOriginalName(), PATHINFO_FILENAME);
$newCoverFilename = uniqid() . '-' . $originalCoverFilename . '.' . $uploadedCover->guessExtension();
$uploadedCover->move($uploadsDirectory, $newCoverFilename);
$newData->setCover($newCoverFilename); // Ensure you have a method to set the cover filename in your entity
}
// Update new data object with new values
$newData->setType($submittedData['type']);
$newData->setTitle($submittedData['title']);
$newData->setBucket($submittedData['bucket']); // Set bucket correctly here
$newData->setDescription($submittedData['description']);
$newData->setDate($submittedData['date']);
$newData->setLink($submittedData['link']);
$newData->setPdfYtlink($submittedData['pdf_ytlink']);
$newData->setCover($submittedData['cover']);
$newData->setLocale($submittedData['locale']);
$newData->setCategory($submittedData['category']);
//dump($newData);exit();
// Ensure bucket is not null before saving
if (empty($submittedData['bucket'])) {
// Handle the error case, maybe add a flash message
$this->addFlash('error', 'Bucket cannot be empty.');
return $this->render('admin/bucketscopy.twig', [
'data' => $existingData,
'id' => $id,
'submittedData' => $submittedData, // Pass the submitted data back for user to see
]);
}
//dump($newData);exit;
// Save the new data and flush
$issuesRepository->save($newData, true);
return $this->redirectToRoute('admin_buckets');
}
// Render the Twig template
return $this->render('admin/bucketscopy.twig', [
'data' => $existingData,
'id' => $id
]);
}
#[Route('/admin/banner', name: 'admin_banner', options: ['expose' => true])]
public function banner(Request $request, EntityManagerInterface $entityManager,BannerRepository $bannerRepository): Response
{
$requestr = $request->getLocale();
$banners = $bannerRepository->findBy(['locale' => $requestr]);
//$banners = $bannerRepository->findAll();
if ($request->isMethod('POST')) {
$title = $request->request->get('title');
$description = $request->request->get('description');
$languageId = $request->request->get('locale');
// Handle file upload
/** @var UploadedFile $cover */
$cover = $request->files->get('cover');
$coverFilename = '';
if ($cover) {
$coverFilename = uniqid() . '.' . $cover->guessExtension();
$cover->move(
$this->getParameter('uploads') . '/banners', // Define this in config
$coverFilename
);
}
// Create new Banner entity
$banner = new Banner();
$banner->setTitle($title);
$banner->setDescription($description);
$banner->setlocale($languageId);
$banner->setCover($coverFilename);
// Save to database
$entityManager->persist($banner);
$entityManager->flush();
$this->addFlash('success', 'Banner saved successfully!');
return $this->redirectToRoute('admin_banner');
}
return $this->render('admin/banner.twig', [
'title' => 'Banner - Dashboard',
'banners' => $banners
]);
}
#[Route('/admin/banner/edit/{id}', name: 'admin_banner_edit')]
public function editBanner(Request $request, EntityManagerInterface $entityManager, BannerRepository $bannerRepository, int $id): Response
{
$banner = $bannerRepository->find($id);
if (!$banner) {
throw $this->createNotFoundException('Banner not found.');
}
if ($request->isMethod('POST')) {
$title = $request->request->get('title');
$description = $request->request->get('description');
$languageId = $request->request->get('locale');
/** @var UploadedFile $cover */
$cover = $request->files->get('cover');
if ($cover) {
$coverFilename = uniqid() . '.' . $cover->guessExtension();
$cover->move(
$this->getParameter('uploads') . '/banners',
$coverFilename
);
$banner->setCover($coverFilename); // Update the cover if a new one is provided
}
// Update existing Banner entity
$banner->setTitle($title);
$banner->setDescription($description);
$banner->setLocale($languageId);
// Save updated data to database
$entityManager->flush();
$this->addFlash('success', 'Banner updated successfully!');
return $this->redirectToRoute('admin_banner');
}
return $this->render('admin/edit_banner.twig', [
'title' => 'Edit Banner',
'banner' => $banner,
]);
}
#[Route('/admin/banner/delete/{id}', name: 'admin_banner_delete')]
public function deleteBanner(EntityManagerInterface $entityManager, BannerRepository $bannerRepository, int $id): Response
{
$banner = $bannerRepository->find($id);
if (!$banner) {
throw $this->createNotFoundException('Banner not found.');
}
// Remove the banner from the database
$entityManager->remove($banner);
$entityManager->flush();
$this->addFlash('success', 'Banner deleted successfully!');
return $this->redirectToRoute('admin_banner');
}
#[
Route('/admin/issue/{id}', name: 'admin_issue', options: ['expose' => true])
]
public function issues(
BucketsRepository $bucketsRepository,
string $id
): Response {
$bucket = $bucketsRepository->findOneBy(['_id' => $id]);
return $this->render('admin/issue.twig', [
'title' => 'Manage Issue - Dashboard',
'data' => [
'bucket' => [
'id' => $id,
'title' => $bucket->getTitle()
]
]
]);
}
#[Route('/admin/contact', name: 'admin_contact', options: ['expose' => true])]
public function contact(): Response
{
return $this->render('admin/contact.twig', [
'title' => 'Contact - Dashboard'
]);
}
#[Route('/admin/info', name: 'admin_info', options: ['expose' => true])]
public function info(): Response
{
return $this->render('admin/info.twig', [
'title' => 'Info - Dashboard'
]);
}
}