<?php
namespace App\Controller;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\Routing\Annotation\Route;
use Symfony\Component\HttpFoundation\JsonResponse;
use Symfony\Bridge\Twig\Mime\BodyRenderer;
use Symfony\Bridge\Twig\Mime\TemplatedEmail;
use Symfony\Component\EventDispatcher\EventDispatcher;
use Symfony\Component\Mailer\EventListener\MessageListener;
use Symfony\Component\Mailer\Mailer;
use Symfony\Component\Mailer\Transport;
use Twig\Environment as TwigEnvironment;
use Twig\Loader\FilesystemLoader;
use Doctrine\ODM\MongoDB\DocumentManager;
use Symfony\Component\Mime\Address;
use App\Document\Notification;
use App\Controller\SmsIRController;
use Symfony\Component\HttpFoundation\File\UploadedFile;
use Symfony\Component\String\Slugger\SluggerInterface;
use Symfony\Component\HttpFoundation\Request;
class NotificationController extends AbstractController
{
private $slugger;
private $slug;
public function __construct( SluggerInterface $slugger )
{
$this->slug = $slugger ;
}
private function saveFile(UploadedFile $file ): string
{
$directory = 'notifications'; // Specify the directory to save the file
try {
$safeFilename = $this->slug->slug($file);
$newFilename = $safeFilename.'-'.uniqid().'.'.$file->guessExtension();
$file->move($directory,$newFilename);
return $newFilename;
} catch (Exception $e) {
throw new \RuntimeException('Failed to save file: ' . $e->getMessage());
}
}
#[Route('/api/admin/sendNotification', methods: ['POST'], name: 'send_notification')]
public function sendNotification(DocumentManager $doctrine, Request $request): JsonResponse
{
// Handle JSON fields
$title = $request->get('title');
$message = $request->get('message');
$backgroundColor = $request->get('backgroundColor');
$titleColor = $request->get('titleColor');
$textColor = $request->get('textColor');
$recipients = json_decode($request->get('recipients'), true);
$status = $request->get('status');
$user = $this->getUser(); // Current logged-in user
$user_id = $user->getId();
// Handle image file upload
$image = null;
/** @var UploadedFile $uploadedFile */
$uploadedFile = $request->files->get('image');
if ($uploadedFile) {
$image = $this->saveFile($uploadedFile);
}
// Create new notification document
$notification = new Notification();
$notification->setUserid($user_id);
$notification->setTitle($title);
$notification->setMessage($message);
$notification->setBackgroundColor($backgroundColor);
$notification->setTitleColor($titleColor);
$notification->setTextColor($textColor);
$notification->setRecipients($recipients);
$notification->setCreateTime(date('Y-m-d H:i:s'));
$notification->setStatus($status); // 0 for unread
if ($image) {
$notification->setImage($image);
}
// Persist the notification document
$doctrine->persist($notification);
$doctrine->flush();
return new JsonResponse(['status' => 200, 'msg' => 'Notification sent']);
}
#[Route('/api/admin/updateNotification/{id}', methods: ['POST'], name: 'update_notification')]
public function updateNotification(DocumentManager $doctrine, Request $request, string $id): JsonResponse
{
// Get the current user (assuming you have a user system)
$user = $this->getUser();
$userId = $user->getId();
// Find the notification by its ID
$notification = $doctrine->getRepository(Notification::class)->findOneBy(['_id' => new \MongoDB\BSON\ObjectId($id)]);
// If the notification doesn't exist, return an error
if (!$notification) {
return new JsonResponse(['status' => '404', 'msg' => 'Notification not found'], 404);
}
// Retrieve form data
$title = $request->request->get('title');
$message = $request->request->get('message');
$status = $request->request->get('status');
$backgroundColor = $request->request->get('backgroundColor');
$titleColor = $request->request->get('titleColor');
$textColor = $request->request->get('textColor');
$recipientsJson = $request->request->get('recipients'); // Get the recipients as a JSON string
// Decode the recipients JSON into an array
$recipients = json_decode($recipientsJson, true);
// Update the notification fields based on input
if ($title) {
$notification->setTitle($title);
}
if ($message) {
$notification->setMessage($message);
}
if ($status) {
$notification->setStatus($status);
}
if ($backgroundColor) {
$notification->setBackgroundColor($backgroundColor);
}
if ($titleColor) {
$notification->setTitleColor($titleColor);
}
if ($textColor) {
$notification->setTextColor($textColor);
}
// Handle file upload (if an image is uploaded)
if ($request->files->has('image')) {
$imageFile = $request->files->get('image');
if ($imageFile) {
$imagePath = $this->saveFile($imageFile);
$notification->setImage($imagePath);
}
}
// If recipients are provided, update them (assuming you have a way to store recipients)
if (is_array($recipients)) {
$notification->setRecipients($recipients); // Assuming you have a `setRecipients()` method in the Notification entity
}
// Persist changes to the database
$doctrine->persist($notification);
$doctrine->flush();
// Return a success response
return new JsonResponse(['status' => '200', 'msg' => 'Notification updated successfully']);
}
#[Route('/api/admin/delete/notifications/{id}', methods: ['DELETE'], name: 'delete_notification')]
public function delete_notification(string $id, DocumentManager $doctrine): JsonResponse
{
// Fetch the notification by ID
$notification = $doctrine->getRepository(Notification::class)->find($id);
// If the notification does not exist, return a 404 error
if (!$notification) {
return new JsonResponse(['status' => '404', 'msg' => 'Notification not found'], 404);
}
// Remove the notification from the database
$doctrine->remove($notification);
$doctrine->flush();
// Return a success response
return new JsonResponse(['status' => '200', 'msg' => 'Notification deleted successfully']);
}
#[Route('/api/admin/notifications',methods: ['POST'], name: 'admin_get_notifications')]
public function admin_get_notifications(DocumentManager $doctrine , Request $request ): JsonResponse
{
$data = json_decode($request->getContent(), false);
$notifications = $doctrine->createQueryBuilder(Notification::class)
->hydrate(false)
->getQuery()
->execute()
->toArray();
$res = ["status" => "200" , "msg" => "OK" , "notifications" => $notifications ] ;
return new JsonResponse($res);
}
#[Route('/api/notifications/get', methods: ['POST'], name: 'get_notifications')]
public function get_notifications(DocumentManager $doctrine, Request $request): JsonResponse
{
// Get the current user (assuming you have a user system)
$user = $this->getUser();
$user_id = $user->getId();
// Fetch notifications where the user's ID exists in the recipients array
$notifications = $doctrine->createQueryBuilder(Notification::class)
->field('recipients')->in([$user_id]) // Check if user_id exists in the recipients array
->hydrate(false)
->getQuery()
->execute()
->toArray();
// Prepare the response
$res = [
"status" => "200",
"msg" => "OK",
"notifications" => $notifications
];
return new JsonResponse($res);
}
public function sms_send_deposit(String $amount , String $pair , String $number ): Response
{
$curl = curl_init();
curl_setopt_array($curl, array(
CURLOPT_URL => 'https://api.kavenegar.com/v1/69434D6E304943427752544A587755343546775650334452444C4D46522F5A4F32516B4B75634A6A6E75413D/verify/lookup.json',
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 => 'receptor='.$number.'&template=deposit&token='.$pair.'&token2='.$amount,
CURLOPT_HTTPHEADER => array(
'Content-Type: application/x-www-form-urlencoded',
'Cookie: cookiesession1=678A8C31QRSTUVXZBEGIKMOQSUWY60AF'
),
));
$response = curl_exec($curl);
curl_close($curl);
return new Response($response);
}
public function sms_send_withdraw(String $amount , String $pair , String $number ): Response
{
$curl = curl_init();
curl_setopt_array($curl, array(
CURLOPT_URL => 'https://api.kavenegar.com/v1/69434D6E304943427752544A587755343546775650334452444C4D46522F5A4F32516B4B75634A6A6E75413D/verify/lookup.json',
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 => 'receptor='.$number.'&template=withdraw&token='.$pair.'&token2='.$amount,
CURLOPT_HTTPHEADER => array(
'Content-Type: application/x-www-form-urlencoded',
'Cookie: cookiesession1=678A8C31QRSTUVXZBEGIKMOQSUWY60AF'
),
));
$response = curl_exec($curl);
curl_close($curl);
return new Response($response);
}
public function sms_send_kyc(String $name , String $number ): Response
{
$curl = curl_init();
curl_setopt_array($curl, array(
CURLOPT_URL => 'https://api.kavenegar.com/v1/69434D6E304943427752544A587755343546775650334452444C4D46522F5A4F32516B4B75634A6A6E75413D/verify/lookup.json',
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 => 'receptor='.$number.'&template=kyc&token20='.$name,
CURLOPT_HTTPHEADER => array(
'Content-Type: application/x-www-form-urlencoded',
'Cookie: cookiesession1=678A8C31QRSTUVXZBEGIKMOQSUWY60AF'
),
));
$response = curl_exec($curl);
curl_close($curl);
return new Response($response);
}
public function get_token(){
$curl = curl_init();
curl_setopt_array($curl, array(
CURLOPT_URL => 'http://RestfulSms.com/api/Token',
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 =>'{
"UserApiKey": "d35f3ad2c7d6b1a0ea753ad3",
"SecretKey": "4xG3WYwR1lt"
}',
CURLOPT_HTTPHEADER => array(
'Content-Type: application/json'
),
));
$response = curl_exec($curl);
curl_close($curl);
return $response;
}
public function sms_send_otp(String $msg , String $number ): JsonResponse
{
$curl = curl_init();
curl_setopt_array($curl, array(
CURLOPT_URL => 'https://api.sms.ir/v1/send/verify',
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 =>'{
"mobile": "'.$number.'",
"templateId": 9012,
"parameters": [
{
"name": "VERIFICATIONCODE",
"value": "'.$msg.'"
}
]
}',
CURLOPT_HTTPHEADER => array(
'Content-Type: application/json',
'Accept: text/plain',
'x-api-key: 5otSfVo5m8yWhzYafPGmulSxM7dUbxoNeSZVnx0VzHb6tpsb'
),
));
$response = curl_exec($curl);
curl_close($curl);
$res = ["status" => "200" , "msg" => "sms sent"] ;
return new JsonResponse($res);
}
public function sendemail(string $subject , string $text , string $html ): JsonResponse
{
$loader = new FilesystemLoader(dirname(__DIR__, 2).'/templates');
$twig = new TwigEnvironment($loader);
$messageListener = new MessageListener(null, new BodyRenderer($twig));
$eventDispatcher = new EventDispatcher();
$eventDispatcher->addSubscriber($messageListener);
$transport = Transport::fromDsn('gmail+smtp://h68ablog:xgjnvzkhevapoliu@default', $eventDispatcher);
$mailer = new Mailer($transport, null, $eventDispatcher);
$email = (new TemplatedEmail())
->from('h68ablog@gmail.com')
->to(new Address('h6688a@gmail.com'))
->subject('Thanks for signing up!')
->htmlTemplate('emails/main.html.twig')
->context([
'expiration_date' => new \DateTime('+7 days'),
'username' => 'foo',
])
;
$mailer->send($email);
$res = ["status" => "200" , "msg" => "Email sent"] ;
return new JsonResponse($res);
}
}