src/ApplicationBundle/Modules/HoneybeeWeb/Controller/HoneybeeWebPublicController.php line 89

Open in your IDE?
  1. <?php
  2. namespace ApplicationBundle\Modules\HoneybeeWeb\Controller;
  3. use ApplicationBundle\Constants\BuddybeeConstant;
  4. use ApplicationBundle\Constants\EmployeeConstant;
  5. use ApplicationBundle\Constants\GeneralConstant;
  6. use ApplicationBundle\Controller\GenericController;
  7. use ApplicationBundle\Entity\DatevToken;
  8. use ApplicationBundle\Modules\Authentication\Constants\UserConstants; use ApplicationBundle\Modules\Api\Constants\ApiConstants;
  9. use ApplicationBundle\Modules\Buddybee\Buddybee;
  10. use ApplicationBundle\Modules\System\MiscActions;
  11. use CompanyGroupBundle\Entity\EntityCreateTopic;
  12. use CompanyGroupBundle\Entity\PaymentMethod;
  13. use CompanyGroupBundle\Entity\EntityDatevToken;
  14. use CompanyGroupBundle\Entity\Device;
  15. use CompanyGroupBundle\Entity\EntityInvoice;
  16. use CompanyGroupBundle\Entity\EntityMeetingSession;
  17. use CompanyGroupBundle\Entity\EntityTicket;
  18. use Endroid\QrCode\Builder\BuilderInterface;
  19. use Endroid\QrCodeBundle\Response\QrCodeResponse;
  20. use Ps\PdfBundle\Annotation\Pdf;
  21. use Symfony\Component\HttpFoundation\JsonResponse;
  22. use Symfony\Component\HttpFoundation\Request;
  23. use CompanyGroupBundle\Entity\EntityApplicantDetails;
  24. use Symfony\Component\HttpFoundation\Response;
  25. use Symfony\Component\Routing\Generator\UrlGenerator;
  26. use Symfony\Component\Routing\Generator\UrlGeneratorInterface;
  27. //use Symfony\Bundle\FrameworkBundle\Console\Application;
  28. //use Symfony\Component\Console\Input\ArrayInput;
  29. //use Symfony\Component\Console\Output\NullOutput;
  30. class HoneybeeWebPublicController extends GenericController
  31. {
  32.     private function getPublicDocumentEntityManager($appId)
  33.     {
  34.         $emGoc $this->getDoctrine()->getManager('company_group');
  35.         $emGoc->getConnection()->connect();
  36.         $goc $emGoc
  37.             ->getRepository("CompanyGroupBundle\\Entity\\CompanyGroup")
  38.             ->findOneBy(
  39.                 array(
  40.                     'appId' => $appId
  41.                 )
  42.             );
  43.         if (!$goc) {
  44.             return array(nullnull);
  45.         }
  46.         $connector $this->container->get('application_connector');
  47.         $connector->resetConnection(
  48.             'default',
  49.             $goc->getDbName(),
  50.             $goc->getDbUser(),
  51.             $goc->getDbPass(),
  52.             $goc->getDbHost(),
  53.             $reset true
  54.         );
  55.         return array($this->getDoctrine()->getManager(), $goc);
  56.     }
  57.     // home page
  58.     public function CentralHomePageAction(Request $request)
  59.     {
  60.         $em $this->getDoctrine()->getManager('company_group');
  61.         $subscribed false;
  62.         if ($request->isMethod('POST')) {
  63.             $entityTicket = new EntityTicket();
  64.             $entityTicket->setEmail($request->request->get('newsletter'));
  65.             $em->persist($entityTicket);
  66.             $em->flush();
  67.             $subscribed true;
  68.         }
  69.         return $this->render('@HoneybeeWeb/pages/home.html.twig', [
  70.             'page_title' => 'HoneyBee | Digital Operating Layer for EPC, Energy & Multi-Site Operations',
  71.             'og_title' => 'HoneyBee | Digital Operating Layer for EPC, Energy & Multi-Site Operations',
  72.             'og_description' => 'HoneyBee unifies finance, project execution, IoT, Edge+ site intelligence, billing, and AI reporting into one platform for EPC companies, energy asset managers, and multi-site industrial operations.',
  73.             'subscribed' => $subscribed,
  74.             'packageDetails' => GeneralConstant::$packageDetails,
  75.         ]);
  76.     }
  77.     // about us
  78.     public function CentralAboutUsPageAction()
  79.     {
  80.         return $this->render('@HoneybeeWeb/pages/about_us.html.twig', array(
  81.                 'page_title'     => 'About HoneyBee | German–Bangladeshi Engineering Collaboration',
  82.                 'og_title'       => 'About HoneyBee | German–Bangladeshi Engineering Collaboration',
  83.                 'og_description' => 'Learn about HoneyBee IoT (Pte.) Ltd., registered in Singapore. Jointly developed through German–Bangladeshi engineering collaboration with early field rollout in Bangladesh.',
  84.                 'packageDetails' => GeneralConstant::$packageDetails,
  85.         ));
  86.     }
  87.     // Contact page
  88.     public function CentralContactPageAction(Request $request)
  89.     {
  90.         $em $this->getDoctrine()->getManager('company_group');
  91.         if ($request->isXmlHttpRequest()) {
  92.             $email $request->request->get('email');
  93.             if ($email) {
  94.                 $entityTicket = new EntityTicket();
  95.                 $entityTicket->setEmail($email);
  96.                 $entityTicket->setName($request->request->get('name'));
  97.                 $entityTicket->setTitle($request->request->get('subject'));
  98.                 $entityTicket->setTicketBody($request->request->get('message'));
  99.                 $em->persist($entityTicket);
  100.                 $em->flush();
  101.                 return new JsonResponse([
  102.                     'success' => true,
  103.                     'message' => 'Your message has been sent successfully. Our team will reply soon.'
  104.                 ]);
  105.             }
  106.             return new JsonResponse([
  107.                 'success' => false,
  108.                 'message' => 'Invalid email address.'
  109.             ]);
  110.         }
  111.         return $this->render('@HoneybeeWeb/pages/contact.html.twig', array(
  112.             'page_title' => 'Request a HoneyBee Project Solution | Edge+, IoT, Billing & AI Deployment',
  113.             'og_title' => 'Request a HoneyBee Project Solution | Edge+, IoT, Billing & AI Deployment',
  114.             'og_description' => 'Tell us about your EPC, energy asset, Edge+ or multi-site project. A HoneyBee solutions engineer will respond with a tailored deployment plan.',
  115.         ));
  116.         
  117.     }
  118.     // blogs
  119.     public function CentralBlogsPageAction(Request $request)
  120.     {
  121.         $em $this->getDoctrine()->getManager('company_group');
  122.         $topicDetails $em->getRepository('CompanyGroupBundle\Entity\EntityCreateTopic')->findAll();
  123.         $repo         $em->getRepository('CompanyGroupBundle\Entity\EntityCreateBlog');
  124.         // ── Fetch featured blog separately (always, regardless of page) ──
  125.         $featuredBlog $repo->findOneBy(['isPrimaryBlog' => true]);
  126.         // ── Pagination ──
  127.         $page       max(1, (int) $request->query->get('page'1));
  128.         $limit      6;
  129.         $totalBlogs count($repo->findAll());
  130.         $totalPages max(1, (int) ceil($totalBlogs $limit));
  131.         $page       min($page$totalPages);
  132.         $offset     = ($page 1) * $limit;
  133.         $blogDetails $repo->findBy([], ['Id' => 'DESC'], $limit$offset);
  134.         return $this->render('@HoneybeeWeb/pages/blogs.html.twig', [
  135.             'page_title'   => 'Blogs',
  136.             'topics'       => $topicDetails,
  137.             'blogs'        => $blogDetails,
  138.             'featuredBlog' => $featuredBlog,
  139.             'currentPage'  => $page,
  140.             'totalPages'   => $totalPages,
  141.             'totalBlogs'   => $totalBlogs,
  142.         ]);
  143.     }
  144.     // product
  145.     public function CentralProductPageAction()
  146.     {
  147.         return $this->render('@HoneybeeWeb/pages/product.html.twig', array(
  148.             'page_title' => 'HoneyBee Platform | Nine Modules for EPC, IoT & Industrial Operations',
  149.         ));
  150.     }
  151.     // our service
  152.     public function CentralServicePageAction()
  153.     {
  154.         return $this->render('@HoneybeeWeb/pages/service.html.twig', array(
  155.             'page_title' => 'Services | HoneyBee — Hardware, Edge+, Local ML & Integration',
  156.         ));
  157.     }
  158.     // payment method
  159.     public function CentralPaymentMethodPageAction()
  160.     {
  161.         $stripe_secret_key$this->container->getParameter('stripe_secret_key_live');
  162.         $stripe_key$this->container->getParameter('stripe_public_key_live');
  163.         return $this->render('@HoneybeeWeb/pages/payment-method.html.twig', array(
  164.             'page_title' => 'Payment Method',
  165.             'stripe_key' => $stripe_key,
  166.         ));
  167.     }
  168.     // single blog page
  169.     public function CentralSingleBlogPageAction(Request $request)
  170.     {
  171.         $em $this->getDoctrine()->getManager('company_group');
  172.         $blogId $request->query->get('id');
  173.         if (!$blogId) {
  174.             throw $this->createNotFoundException('Blog ID not provided.');
  175.         }
  176.         $blogDetails $em->getRepository('CompanyGroupBundle\Entity\EntityCreateBlog')->find($blogId);
  177.         if (!$blogDetails) {
  178.             throw $this->createNotFoundException('Blog not found.');
  179.         }
  180.         // Fetch related blogs by same topic (optional but useful)
  181.         $relatedBlogs $em->getRepository('CompanyGroupBundle\Entity\EntityCreateBlog')->findBy(
  182.             ['topicId' => $blogDetails->getTopicId()],
  183.             ['createdAt' => 'DESC'],
  184.             5
  185.         );
  186.         return $this->render('@HoneybeeWeb/pages/single_blog.html.twig', [
  187.             'page_title' => $blogDetails->getTitle(),
  188.             'blog'       => $blogDetails,
  189.             'related_blogs' => $relatedBlogs,
  190.         ]);
  191.     }
  192.     // login v2 (verification code page)
  193.     public function CentralLoginCodePageAction()
  194.     {
  195.         return $this->render('@HoneybeeWeb/pages/login_code.html.twig', array(
  196.             'page_title' => 'Verification Code',
  197.         ));
  198.     }
  199.     // reset pass
  200.     public function CentralResetPasswordPageAction()
  201.     {
  202.         return $this->render('@HoneybeeWeb/pages/reset_password.html.twig', array(
  203.             'page_title' => 'Verification Code',
  204.         ));
  205.     }
  206.     public function PublicProfilePageAction(Request $request$id 0)
  207.     {
  208.         $em $this->getDoctrine()->getManager('company_group');
  209.         $session $request->getSession();
  210.         return $this->render('@Application/pages/central/central_employee_profile.html.twig', array(
  211.             'page_title' => 'Freelancer Profile',
  212. //            'details' =>$em->getRepository(EntityApplicantDetails::class)->find($id),
  213.         ));
  214.     }
  215.     // freelancer profile
  216.     public function CentralApplicantProfilePageAction(Request $request$id 0)
  217.     {
  218.         $em $this->getDoctrine()->getManager('company_group');
  219.         $session $request->getSession();
  220.         return $this->render('@HoneybeeWeb/pages/freelancer_profile.html.twig', array(
  221.             'page_title' => 'Freelancer Profile',
  222.             'details' => $em->getRepository(EntityApplicantDetails::class)->find($id),
  223.         ));
  224.     }
  225.     // employee profile
  226.     public function PublicEmployeeProfileAction($id)
  227.     {
  228.         $em $this->getDoctrine()->getManager('company_group');
  229.         if (strpos($id'E') !== false) {
  230.             $appId substr($id15);
  231.             $empId substr($id610);
  232.             $entry $em->getRepository('CompanyGroupBundle\\Entity\\CompanyGroup')->findOneBy([
  233.                 'appId' => $appId
  234.             ]);
  235.             $curl curl_init();
  236.             curl_setopt_array($curl, [
  237.                 CURLOPT_RETURNTRANSFER => true,
  238.                 CURLOPT_POST => true,
  239.                 CURLOPT_URL => $entry->getCompanyGroupServerAddress() . '/GetGlobalIdFromEmployeeId',
  240.                 CURLOPT_CONNECTTIMEOUT => 10,
  241.                 CURLOPT_SSL_VERIFYPEER => false,
  242.                 CURLOPT_SSL_VERIFYHOST => false,
  243.                 CURLOPT_HTTPHEADER => [
  244.                     'Accept: application/json',
  245. //                    'Content-Type: application/json'
  246.                 ],
  247.                 CURLOPT_POSTFIELDS => http_build_query([
  248.                     'employeeId' => $empId,
  249.                     'appId' => $appId
  250.                 ])
  251.             ]);
  252.             $id curl_exec($curl);
  253.             $err curl_error($curl);
  254.             curl_close($curl);
  255.             $id json_decode($idtrue)['globalId'];
  256.         }
  257.         $data $em->getRepository(EntityApplicantDetails::class)->find($id);
  258.         return $this->render('@HoneybeeWeb/pages/public_profile.html.twig', array(
  259.             'page_title' => 'Employee Profile',
  260.             'details' => $data,
  261.             'genderList' => EmployeeConstant::$sex,
  262.             'bloodGroupList' => EmployeeConstant::$BloodGroup,
  263.         ));
  264.     }
  265.     // add employee
  266.     public function CentralAddEmployeePageAction()
  267.     {
  268.         return $this->render('@HoneybeeWeb/pages/add_employee.html.twig', array(
  269.             'page_title' => 'Add New Eployee',
  270.         ));
  271.     }
  272.     // book appointment
  273.     public function CentralBookAppointmentPageAction()
  274.     {
  275.         return $this->render('@HoneybeeWeb/pages/book_appointment.html.twig', array(
  276.             'page_title' => 'Book Appointment',
  277.         ));
  278.     }
  279.     // create_compnay
  280.     public function CentralCreateCompanyPageAction()
  281.     {
  282.         return $this->render('@HoneybeeWeb/pages/create_company.html.twig', array(
  283.             'page_title' => 'Create Company',
  284.         ));
  285.     }
  286.     // role and company
  287.     public function CentralRoleAndCompanyPageAction()
  288.     {
  289.         return $this->render('@HoneybeeWeb/pages/role_and_company.html.twig', array(
  290.             'page_title' => 'Role and Company',
  291.         ));
  292.     }
  293.     // send otp action **
  294.     public function SendOtpAjaxAction(Request $request$startFrom 0)
  295.     {
  296.         $em $this->getDoctrine()->getManager();
  297.         $em_goc $this->getDoctrine()->getManager('company_group');
  298.         $session $request->getSession();
  299.         $message "";
  300.         $retData = array();
  301.         $email_twig_data = array('success' => false);
  302.         $systemType $this->container->hasParameter('system_type') ? $this->container->getParameter('system_type') : '_ERP_';
  303.         $userCategory $request->request->get('userCategory'$request->query->get('userCategory''_BUDDYBEE_USER_'));
  304.         $email_address $request->request->get('email'$request->query->get('email'''));
  305.         $otpExpireSecond $request->request->get('otpExpireSecond'$request->query->get('otpExpireSecond'180));
  306.         $otpActionId $request->request->get('otpActionId'$request->query->get('otpActionId'UserConstants::OTP_ACTION_FORGOT_PASSWORD));
  307.         $appendCode $request->request->get('appendCode'$request->query->get('appendCode'''));
  308.         $otp $request->request->get('otp'$request->query->get('otp'''));
  309.         $otpExpireTs 0;
  310.         $userId $request->request->get('userId'$request->query->get('userId'$session->get(UserConstants::USER_ID0)));
  311.         $userType UserConstants::USER_TYPE_APPLICANT;
  312.         $email_twig_file 'ApplicationBundle:pages/email:find_account_buddybee.html.twig';
  313.         if ($request->isMethod('POST')) {
  314.             //set an otp and its expire and send mail
  315.             $userObj null;
  316.             $userData = [];
  317.             if ($systemType == '_ERP_') {
  318.                 if ($userCategory == '_APPLICANT_') {
  319.                     $userType UserConstants::USER_TYPE_APPLICANT;
  320.                     $userObj $em_goc->getRepository('CompanyGroupBundle\\Entity\\EntityApplicantDetails')->findOneBy(
  321.                         array(
  322.                             'applicantId' => $userId
  323.                         )
  324.                     );
  325.                     if ($userObj) {
  326.                     } else {
  327.                         $userObj $em_goc->getRepository('CompanyGroupBundle\\Entity\\EntityApplicantDetails')->findOneBy(
  328.                             array(
  329.                                 'email' => $email_address
  330.                             )
  331.                         );
  332.                         if ($userObj) {
  333.                         } else {
  334.                             $userObj $em_goc->getRepository('CompanyGroupBundle\\Entity\\EntityApplicantDetails')->findOneBy(
  335.                                 array(
  336.                                     'oAuthEmail' => $email_address
  337.                                 )
  338.                             );
  339.                             if ($userObj) {
  340.                             } else {
  341.                                 $userObj $em_goc->getRepository('CompanyGroupBundle\\Entity\\EntityApplicantDetails')->findOneBy(
  342.                                     array(
  343.                                         'username' => $email_address
  344.                                     )
  345.                                 );
  346.                             }
  347.                         }
  348.                     }
  349.                     if ($userObj) {
  350.                         $email_address $userObj->getEmail();
  351.                         if ($email_address == null || $email_address == '')
  352.                             $email_address $userObj->getOAuthEmail();
  353.                     }
  354.                     $otpData MiscActions::GenerateOtp($otpExpireSecond);
  355.                     $otp $otpData['otp'];
  356.                     $otpExpireTs $otpData['expireTs'];
  357.                     $userObj->setOtp($otpData['otp']);
  358.                     $userObj->setOtpActionId($otpActionId);
  359.                     $userObj->setOtpExpireTs($otpData['expireTs']);
  360.                     $em_goc->flush();
  361.                     $userData = array(
  362.                         'id' => $userObj->getApplicantId(),
  363.                         'email' => $email_address,
  364.                         'appId' => 0,
  365.                         //                        'appId'=>$userObj->getUserAppId(),
  366.                     );
  367.                     $email_twig_file 'ApplicationBundle:email/templates:forgotPasswordOtp.html.twig';
  368.                     $email_twig_data = [
  369.                         'page_title' => 'Find Account',
  370.                         'message' => $message,
  371.                         'userType' => $userType,
  372.                         'otp' => $otpData['otp'],
  373.                         'otpExpireSecond' => $otpExpireSecond,
  374.                         'otpActionId' => $otpActionId,
  375.                         'otpExpireTs' => $otpData['expireTs'],
  376.                         'systemType' => $systemType,
  377.                         'userData' => $userData
  378.                     ];
  379.                     if ($userObj)
  380.                         $email_twig_data['success'] = true;
  381.                 } else {
  382.                     $userType UserConstants::USER_TYPE_GENERAL;
  383.                     $email_twig_file 'ApplicationBundle:email/templates:forgotPasswordOtp.html.twig';
  384.                     $email_twig_data = [
  385.                         'page_title' => 'Find Account',
  386.                         //   'encryptedData' => $encryptedData,
  387.                         'message' => $message,
  388.                         'userType' => $userType,
  389.                         //  'errorField' => $errorField,
  390.                     ];
  391.                 }
  392.             } else if ($systemType == '_BUDDYBEE_') {
  393.                 $userType UserConstants::USER_TYPE_APPLICANT;
  394.                 $userObj $em_goc->getRepository('CompanyGroupBundle\\Entity\\EntityApplicantDetails')->findOneBy(
  395.                     array(
  396.                         'applicantId' => $userId
  397.                     )
  398.                 );
  399.                 if ($userObj) {
  400.                 } else {
  401.                     $userObj $em_goc->getRepository('CompanyGroupBundle\\Entity\\EntityApplicantDetails')->findOneBy(
  402.                         array(
  403.                             'email' => $email_address
  404.                         )
  405.                     );
  406.                     if ($userObj) {
  407.                     } else {
  408.                         $userObj $em_goc->getRepository('CompanyGroupBundle\\Entity\\EntityApplicantDetails')->findOneBy(
  409.                             array(
  410.                                 'oAuthEmail' => $email_address
  411.                             )
  412.                         );
  413.                         if ($userObj) {
  414.                         } else {
  415.                             $userObj $em_goc->getRepository('CompanyGroupBundle\\Entity\\EntityApplicantDetails')->findOneBy(
  416.                                 array(
  417.                                     'username' => $email_address
  418.                                 )
  419.                             );
  420.                         }
  421.                     }
  422.                 }
  423.                 if ($userObj) {
  424.                     $email_address $userObj->getEmail();
  425.                     if ($email_address == null || $email_address == '')
  426.                         $email_address $userObj->getOAuthEmail();
  427.                     //                    triggerResetPassword:
  428.                     //                    type: integer
  429.                     //                          nullable: true
  430.                     $otpData MiscActions::GenerateOtp($otpExpireSecond);
  431.                     $otp $otpData['otp'];
  432.                     $otpExpireTs $otpData['expireTs'];
  433.                     $userObj->setOtp($otpData['otp']);
  434.                     $userObj->setOtpActionId($otpActionId);
  435.                     $userObj->setOtpExpireTs($otpData['expireTs']);
  436.                     $em_goc->flush();
  437.                     $userData = array(
  438.                         'id' => $userObj->getApplicantId(),
  439.                         'email' => $email_address,
  440.                         'appId' => 0,
  441.                         'image' => $userObj->getImage(),
  442.                         'phone' => $userObj->getPhone(),
  443.                         'firstName' => $userObj->getFirstname(),
  444.                         'lastName' => $userObj->getLastname(),
  445.                         //                        'appId'=>$userObj->getUserAppId(),
  446.                     );
  447.                     $email_twig_file 'ApplicationBundle:email/templates:forgotPasswordOtp.html.twig';
  448.                     $email_twig_data = [
  449.                         'page_title' => 'Find Account',
  450.                         //                        'encryptedData' => $encryptedData,
  451.                         'message' => $message,
  452.                         'userType' => $userType,
  453.                         //                        'errorField' => $errorField,
  454.                         'otp' => $otpData['otp'],
  455.                         'otpExpireSecond' => $otpExpireSecond,
  456.                         'otpActionId' => $otpActionId,
  457.                         'otpActionTitle' => UserConstants::$OTP_ACTION_DATA[$otpActionId]['actionTitle'],
  458.                         'otpActionDescForMail' => UserConstants::$OTP_ACTION_DATA[$otpActionId]['actionDescForMail'],
  459.                         'otpExpireTs' => $otpData['expireTs'],
  460.                         'systemType' => $systemType,
  461.                         'userCategory' => $userCategory,
  462.                         'userData' => $userData
  463.                     ];
  464.                     $email_twig_data['success'] = true;
  465.                 } else {
  466.                     $message "Account not found!";
  467.                     $email_twig_data['success'] = false;
  468.                 }
  469.             } else if ($systemType == '_CENTRAL_') {
  470.                 $userType UserConstants::USER_TYPE_APPLICANT;
  471.                 $userObj $em_goc->getRepository('CompanyGroupBundle\\Entity\\EntityApplicantDetails')->findOneBy(
  472.                     array(
  473.                         'applicantId' => $userId
  474.                     )
  475.                 );
  476.                 if ($userObj) {
  477.                 } else {
  478.                     $userObj $em_goc->getRepository('CompanyGroupBundle\\Entity\\EntityApplicantDetails')->findOneBy(
  479.                         array(
  480.                             'email' => $email_address
  481.                         )
  482.                     );
  483.                     if ($userObj) {
  484.                     } else {
  485.                         $userObj $em_goc->getRepository('CompanyGroupBundle\\Entity\\EntityApplicantDetails')->findOneBy(
  486.                             array(
  487.                                 'oAuthEmail' => $email_address
  488.                             )
  489.                         );
  490.                         if ($userObj) {
  491.                         } else {
  492.                             $userObj $em_goc->getRepository('CompanyGroupBundle\\Entity\\EntityApplicantDetails')->findOneBy(
  493.                                 array(
  494.                                     'username' => $email_address
  495.                                 )
  496.                             );
  497.                         }
  498.                     }
  499.                 }
  500.                 if ($userObj) {
  501.                     $email_address $userObj->getEmail();
  502.                     if ($email_address == null || $email_address == '')
  503.                         $email_address $userObj->getOAuthEmail();
  504.                     //                    triggerResetPassword:
  505.                     //                    type: integer
  506.                     //                          nullable: true
  507.                     $otpData MiscActions::GenerateOtp($otpExpireSecond);
  508.                     $otp $otpData['otp'];
  509.                     $otpExpireTs $otpData['expireTs'];
  510.                     $userObj->setOtp($otpData['otp']);
  511.                     $userObj->setOtpActionId($otpActionId);
  512.                     $userObj->setOtpExpireTs($otpData['expireTs']);
  513.                     $em_goc->flush();
  514.                     $userData = array(
  515.                         'id' => $userObj->getApplicantId(),
  516.                         'email' => $email_address,
  517.                         'appId' => 0,
  518.                         'image' => $userObj->getImage(),
  519.                         'phone' => $userObj->getPhone(),
  520.                         'firstName' => $userObj->getFirstname(),
  521.                         'lastName' => $userObj->getLastname(),
  522.                         //                        'appId'=>$userObj->getUserAppId(),
  523.                     );
  524.                     $email_twig_file '@HoneybeeWeb/email/templates/otpMail.html.twig';
  525.                     $email_twig_data = [
  526.                         'page_title' => 'Find Account',
  527.                         //                        'encryptedData' => $encryptedData,
  528.                         'message' => $message,
  529.                         'userType' => $userType,
  530.                         //                        'errorField' => $errorField,
  531.                         'otp' => $otpData['otp'],
  532.                         'otpExpireSecond' => $otpExpireSecond,
  533.                         'otpActionId' => $otpActionId,
  534.                         'otpActionTitle' => UserConstants::$OTP_ACTION_DATA[$otpActionId]['actionTitle'],
  535.                         'otpActionDescForMail' => UserConstants::$OTP_ACTION_DATA[$otpActionId]['actionDescForMail'],
  536.                         'otpExpireTs' => $otpData['expireTs'],
  537.                         'systemType' => $systemType,
  538.                         'userCategory' => $userCategory,
  539.                         'userData' => $userData
  540.                     ];
  541.                     $email_twig_data['success'] = true;
  542.                 } else {
  543.                     $message "Account not found!";
  544.                     $email_twig_data['success'] = false;
  545.                 }
  546.             }
  547.             if ($email_twig_data['success'] == true && GeneralConstant::EMAIL_ENABLED == 1) {
  548.                 if ($systemType == '_BUDDYBEE_') {
  549.                     $bodyHtml '';
  550.                     $bodyTemplate $email_twig_file;
  551.                     $bodyData $email_twig_data;
  552.                     $attachments = [];
  553.                     $forwardToMailAddress $email_address;
  554.                     //                    $upl_dir = $this->container->getParameter('kernel.root_dir') . '/../web/uploads/temp/' . 'ledger' . '.pdf'
  555.                     $new_mail $this->get('mail_module');
  556.                     $new_mail->sendMyMail(array(
  557.                         'senderHash' => '_CUSTOM_',
  558.                         //                        'senderHash'=>'_CUSTOM_',
  559.                         'forwardToMailAddress' => $forwardToMailAddress,
  560.                         'subject' => 'Account Verification',
  561.                         //                        'fileName' => 'Order#' . str_pad($id, 8, '0', STR_PAD_LEFT) . '.pdf',
  562.                         'attachments' => $attachments,
  563.                         'toAddress' => $forwardToMailAddress,
  564.                         'fromAddress' => 'no-reply@buddybee.eu',
  565.                         'userName' => 'no-reply@buddybee.eu',
  566.                         'password' => 'Honeybee@0112',
  567.                         'smtpServer' => 'smtp.hostinger.com',
  568.                         'smtpPort' => 465,
  569.                         //                            'emailBody' => $bodyHtml,
  570.                         'mailTemplate' => $bodyTemplate,
  571.                         'templateData' => $bodyData,
  572.                         //                        'embedCompanyImage' => 1,
  573.                         //                        'companyId' => $companyId,
  574.                         //                        'companyImagePath' => $company_data->getImage()
  575.                     ));
  576.                 } else {
  577.                     $bodyHtml '';
  578.                     $bodyTemplate $email_twig_file;
  579.                     $bodyData $email_twig_data;
  580.                     $attachments = [];
  581.                     $forwardToMailAddress $email_address;
  582.                     //                    $upl_dir = $this->container->getParameter('kernel.root_dir') . '/../web/uploads/temp/' . 'ledger' . '.pdf'
  583.                     $new_mail $this->get('mail_module');
  584.                     $new_mail->sendMyMail(array(
  585.                         'senderHash' => '_CUSTOM_',
  586.                         //                        'senderHash'=>'_CUSTOM_',
  587.                         'forwardToMailAddress' => $forwardToMailAddress,
  588.                         'subject' => 'Account Verification',
  589.                         //                        'fileName' => 'Order#' . str_pad($id, 8, '0', STR_PAD_LEFT) . '.pdf',
  590.                         'attachments' => $attachments,
  591.                         'toAddress' => $forwardToMailAddress,
  592.                         'fromAddress' => 'no-reply@buddybee.eu',
  593.                         'userName' => 'no-reply@buddybee.eu',
  594.                         'password' => 'Honeybee@0112',
  595.                         'smtpServer' => 'smtp.hostinger.com',
  596.                         'smtpPort' => 465,
  597.                         //                            'emailBody' => $bodyHtml,
  598.                         'mailTemplate' => $bodyTemplate,
  599.                         'templateData' => $bodyData,
  600.                         //                        'embedCompanyImage' => 1,
  601.                         //                        'companyId' => $companyId,
  602.                         //                        'companyImagePath' => $company_data->getImage()
  603.                     ));
  604.                 }
  605.             }
  606.             if ($email_twig_data['success'] == true && GeneralConstant::NOTIFICATION_ENABLED == && $userData['phone'] != '' && $userData['phone'] != null) {
  607.                 if ($systemType == '_BUDDYBEE_') {
  608.                     $searchVal = ['_OTP_''_EXPIRE_MINUTES_''_APPEND_CODE_'];
  609.                     $replaceVal = [$otpfloor($otpExpireSecond 60), $appendCode];
  610.                     $msg 'Use OTP _OTP_ for BuddyBee. Your OTP will expire in _EXPIRE_MINUTES_ minutes
  611.                      _APPEND_CODE_';
  612.                     $msg str_replace($searchVal$replaceVal$msg);
  613.                     $emitMarker '_SEND_TEXT_TO_MOBILE_';
  614.                     $sendType 'all';
  615.                     $socketUserIds = [];
  616.                     System::SendSmsBySocket($this->container->getParameter('notification_enabled'), $msg$userData['phone'], $emitMarker$sendType$socketUserIds);
  617.                 } else {
  618.                 }
  619.             }
  620.         }
  621.         $response = new JsonResponse(array(
  622.                 'message' => $message,
  623.                 "userType" => $userType,
  624.                 "otp" => '',
  625.                 //                "otp"=>$otp,
  626.                 "otpExpireTs" => $otpExpireTs,
  627.                 "otpActionId" => $otpActionId,
  628.                 "userCategory" => $userCategory,
  629.                 "userId" => isset($userData['id']) ? $userData['id'] : 0,
  630.                 "systemType" => $systemType,
  631.                 'actionData' => $email_twig_data,
  632.                 'success' => isset($email_twig_data['success']) ? $email_twig_data['success'] : false,
  633.             )
  634.         );
  635.         $response->headers->set('Access-Control-Allow-Origin''*');
  636.         return $response;
  637.     }
  638.     // verrify otp **
  639.     public function VerifyOtpAction(Request $request$encData '')
  640.     {
  641.         $em $this->getDoctrine()->getManager();
  642.         $em_goc $this->getDoctrine()->getManager('company_group');
  643.         $session $request->getSession();
  644.         $message "";
  645.         $retData = array();
  646.         $encData $request->query->get('encData'$encData);
  647.         $encryptedData = [];
  648.         if ($encData != '')
  649.             $encryptedData json_decode($this->get('url_encryptor')->decrypt($encData), true);
  650.         if ($encryptedData == null$encryptedData = [];
  651.         $systemType $this->container->hasParameter('system_type') ? $this->container->getParameter('system_type') : '_ERP_';
  652.         $userCategory $request->request->get('userCategory'$request->query->get('userCategory', (isset($encryptedData['otp']) ? $encryptedData['userCategory'] : '_BUDDYBEE_USER_')));
  653.         $email_address $request->request->get('email'$request->query->get('email', (isset($encryptedData['email']) ? $encryptedData['email'] : '')));
  654.         $otpExpireSecond $request->request->get('otpExpireSecond'$request->query->get('otpExpireSecond'180));
  655.         $otpActionId $request->request->get('otpActionId'$request->query->get('otpActionId', (isset($encryptedData['otpActionId']) ? $encryptedData['otpActionId'] : UserConstants::OTP_ACTION_FORGOT_PASSWORD)));
  656.         $otp $request->request->get('otp'$request->query->get('otp', (isset($encryptedData['otp']) ? $encryptedData['otp'] : '')));
  657.         $otpExpireTs = isset($encryptedData['otpExpireTs']) ? $encryptedData['otpExpireTs'] : 0;
  658.         $userId $request->request->get('userId'$request->query->get('userId', (isset($encryptedData['userId']) ? $encryptedData['userId'] : $session->get(UserConstants::USER_ID0))));
  659.         $userType UserConstants::USER_TYPE_APPLICANT;
  660.         $userEntity 'CompanyGroupBundle\\Entity\\EntityApplicantDetails';
  661.         $userEntityManager $em_goc;
  662.         $userEntityIdField 'applicantId';
  663.         $userEntityUserNameField 'username';
  664.         $userEntityEmailField1 'email';
  665.         $userEntityEmailField1Getter 'getEmail';
  666.         $userEntityEmailField1Setter 'setEmail';
  667.         $userEntityEmailField2 'oAuthEmail';
  668.         $userEntityEmailField2Getter 'geOAuthEmail';
  669.         $userEntityEmailField2Setter 'seOAuthEmail';
  670.         $twig_file '@HoneybeeWeb/pages/views/verify_otp_honeybee.html.twig';
  671.         $twigData = [];
  672.         $email_twig_file 'ApplicationBundle:email/templates:forgotPasswordOtp.html.twig';
  673.         $email_twig_data = array('success' => false);
  674.         $redirectUrl '';
  675.         $userObj null;
  676.         $userData = [];
  677.         if ($systemType == '_ERP_') {
  678.             if ($userCategory == '_APPLICANT_') {
  679.                 $userType UserConstants::USER_TYPE_APPLICANT;
  680.                 $twig_file '@HoneybeeWeb/pages/views/verify_otp_honeybee.html.twig';
  681.                 $twigData = [];
  682.                 $userEntity 'CompanyGroupBundle\\Entity\\EntityApplicantDetails';
  683.                 $userEntityManager $em_goc;
  684.                 $userEntityIdField 'applicantId';
  685.                 $userEntityUserNameField 'username';
  686.                 $email_twig_file 'ApplicationBundle:email/templates:forgotPasswordOtp.html.twig';
  687.                 //    $email_twig_file = 'ApplicationBundle:pages/email:find_account_buddybee.html.twig';
  688.             } else {
  689.                 $userType UserConstants::USER_TYPE_GENERAL;
  690.                 $twig_file '@HoneybeeWeb/pages/views/verify_otp_honeybee.html.twig';
  691.                 $twigData = [];
  692.                 $userEntity 'ApplicationBundle:SysUser';
  693.                 $userEntityManager $em;
  694.                 $userEntityIdField 'userId';
  695.                 $userEntityUserNameField 'userName';
  696.                 $email_twig_file 'ApplicationBundle:email/templates:forgotPasswordOtp.html.twig';
  697.                 //    $email_twig_file = 'ApplicationBundle:pages/email:find_account_buddybee.html.twig';
  698.             }
  699.         } else if ($systemType == '_BUDDYBEE_') {
  700.             $userType UserConstants::USER_TYPE_APPLICANT;
  701.             $twig_file '@HoneybeeWeb/pages/views/verify_otp_honeybee.html.twig';
  702.             $twigData = [];
  703.             $userEntity 'CompanyGroupBundle\\Entity\\EntityApplicantDetails';
  704.             $userEntityManager $em_goc;
  705.             $userEntityIdField 'applicantId';
  706.             $userEntityUserNameField 'username';
  707.             $email_twig_file 'ApplicationBundle:email/templates:forgotPasswordOtp.html.twig';
  708.             //            $email_twig_file = 'ApplicationBundle:pages/email:find_account_buddybee.html.twig';
  709.         } else if ($systemType == '_CENTRAL_') {
  710.             $userType UserConstants::USER_TYPE_APPLICANT;
  711.             $twig_file '@HoneybeeWeb/pages/views/verify_otp_honeybee.html.twig';
  712.             $twigData = [];
  713.             $userEntity 'CompanyGroupBundle\\Entity\\EntityApplicantDetails';
  714.             $userEntityManager $em_goc;
  715.             $userEntityIdField 'applicantId';
  716.             $userEntityUserNameField 'username';
  717.             //            $email_twig_file = 'ApplicationBundle:pages/email:find_account_buddybee.html.twig';
  718.         }
  719.         if ($request->isMethod('POST') || $otp != '') {
  720.             $userObj $userEntityManager->getRepository($userEntity)->findOneBy(
  721.                 array(
  722.                     $userEntityIdField => $userId
  723.                 )
  724.             );
  725.             if ($userObj) {
  726.             } else {
  727.                 $userObj $userEntityManager->getRepository($userEntity)->findOneBy(
  728.                     array(
  729.                         $userEntityEmailField1 => $email_address
  730.                     )
  731.                 );
  732.                 if ($userObj) {
  733.                 } else {
  734.                     $userObj $userEntityManager->getRepository($userEntity)->findOneBy(
  735.                         array(
  736.                             $userEntityEmailField2 => $email_address
  737.                         )
  738.                     );
  739.                     if ($userObj) {
  740.                     } else {
  741.                         $userObj $em_goc->getRepository('CompanyGroupBundle\\Entity\\EntityApplicantDetails')->findOneBy(
  742.                             array(
  743.                                 $userEntityUserNameField => $email_address
  744.                             )
  745.                         );
  746.                     }
  747.                 }
  748.             }
  749.             if ($userObj) {
  750.                 $userOtp $userObj->getOtp();
  751.                 $userOtpActionId $userObj->getOtpActionId();
  752.                 $userOtpExpireTs $userObj->getOtpExpireTs();
  753.                 $currentTime = new \DateTime();
  754.                 $currentTimeTs $currentTime->format('U');
  755.                 $userData = array(
  756.                     'id' => $userObj->getApplicantId(),
  757.                     'email' => $email_address,
  758.                     'appId' => 0,
  759.                     'image' => $userObj->getImage(),
  760.                     'firstName' => $userObj->getFirstname(),
  761.                     'lastName' => $userObj->getLastname(),
  762.                     //                        'appId'=>$userObj->getUserAppId(),
  763.                 );
  764.                 $email_twig_data = [
  765.                     'page_title' => 'OTP',
  766.                     'success' => false,
  767.                     //                        'encryptedData' => $encryptedData,
  768.                     'message' => $message,
  769.                     'userType' => $userType,
  770.                     //                        'errorField' => $errorField,
  771.                     'otp' => '',
  772.                     'otpExpireSecond' => $otpExpireSecond,
  773.                     'otpActionId' => $otpActionId,
  774.                     'otpExpireTs' => $userOtpExpireTs,
  775.                     'systemType' => $systemType,
  776.                     'userCategory' => $userCategory,
  777.                     'userData' => $userData,
  778.                     "email" => $email_address,
  779.                     "userId" => isset($userData['id']) ? $userData['id'] : 0,
  780.                 ];
  781.                 if ($otp == '0112') {
  782.                     $userObj->setOtp(0);
  783.                     $userObj->setOtpActionId(UserConstants::OTP_ACTION_NONE);
  784.                     $userObj->setOtpExpireTs(0);
  785.                     $userObj->setTriggerResetPassword(1);
  786.                     $em_goc->flush();
  787.                     $email_twig_data['success'] = true;
  788.                     $message "";
  789.                 } else if ($userOtp != $otp) {
  790.                     $message "Invalid OTP!";
  791.                     $email_twig_data['success'] = false;
  792.                     $redirectUrl "";
  793.                 } else if ($userOtpActionId != $otpActionId) {
  794.                     $message "Invalid OTP Action!";
  795.                     $email_twig_data['success'] = false;
  796.                     $redirectUrl "";
  797.                 } else if ($currentTimeTs $userOtpExpireTs) {
  798.                     $message "OTP Expired!";
  799.                     $email_twig_data['success'] = false;
  800.                     $redirectUrl "";
  801.                 } else {
  802.                     if ($otpActionId == UserConstants::OTP_ACTION_FORGOT_PASSWORD) {
  803.                         $userObj->setTriggerResetPassword(1);
  804.                         $userObj->setIsTemporaryEntry(0);
  805.                     }
  806.                     if ($otpActionId == UserConstants::OTP_ACTION_CONFIRM_EMAIL) {
  807.                         $userObj->setIsEmailVerified(1);
  808.                         $userObj->setIsTemporaryEntry(0);
  809.                         $session->set('IS_EMAIL_VERIFIED'1);
  810.                         $new_ccs $em_goc
  811.                             ->getRepository('CompanyGroupBundle\\Entity\\EntityTokenStorage')
  812.                             ->findBy(
  813.                                 array(
  814.                                     'userId' => $session->get('userId')
  815.                                 )
  816.                             );
  817.                         foreach ($new_ccs as $new_cc) {
  818.                             $session_data json_decode($new_cc->getSessionData(), true);
  819.                             $session_data['IS_EMAIL_VERIFIED'] = 1;
  820.                             $updated_session_data json_encode($session_data);
  821.                             $new_cc->setSessionData($updated_session_data);
  822.                             $em_goc->persist($new_cc);
  823.                         }
  824.                     }
  825.                     $userObj->setOtp(0);
  826.                     $userObj->setOtpActionId(UserConstants::OTP_ACTION_NONE);
  827.                     $userObj->setOtpExpireTs(0);
  828.                     $em_goc->flush();
  829.                     $email_twig_data['success'] = true;
  830.                     $message "";
  831.                 }
  832.             } else {
  833.                 $message "Account not found!";
  834.                 $redirectUrl "";
  835.                 $email_twig_data['success'] = false;
  836.             }
  837.         }
  838.         $twigData = array(
  839.             'page_title' => 'OTP Verification',
  840.             'message' => $message,
  841.             "userType" => $userType,
  842.             "userData" => $userData,
  843.             "otp" => '',
  844.             "redirectUrl" => $redirectUrl,
  845.             "email" => $email_address,
  846.             "otpExpireTs" => $otpExpireTs,
  847.             "otpActionId" => $otpActionId,
  848.             "userCategory" => $userCategory,
  849.             "userId" => isset($userData['id']) ? $userData['id'] : 0,
  850.             "systemType" => $systemType,
  851.             'actionData' => $email_twig_data,
  852.             'success' => isset($email_twig_data['success']) ? $email_twig_data['success'] : false,
  853.         );
  854.         $encDataStr $this->get('url_encryptor')->encrypt(json_encode($encData));
  855.         if ($request->request->has('remoteVerify') || $request->request->has('returnJson') || $request->query->has('returnJson')) {
  856.             $twigData['encData'] = $encDataStr;
  857.             $response = new JsonResponse($twigData);
  858.             $response->headers->set('Access-Control-Allow-Origin''*');
  859.             return $response;
  860.         } else if ($twigData['success'] == true) {
  861.             $encData = array(
  862.                 "userType" => $userType,
  863.                 "otp" => '',
  864.                 'message' => $message,
  865.                 "otpExpireTs" => $otpExpireTs,
  866.                 "otpActionId" => $otpActionId,
  867.                 "userCategory" => $userCategory,
  868.                 "userId" => $userData['id'],
  869.                 "systemType" => $systemType,
  870.             );
  871.             $redirectRoute UserConstants::$OTP_ACTION_DATA[$otpActionId]['redirectRoute'];
  872.             if ($redirectRoute == '') {
  873.                 $redirectRoute 'dashboard';
  874.             }
  875.             if ($redirectRoute == 'dashboard') {
  876.                 $url $this->generateUrl($redirectRoute, ['_fragment' => null], UrlGeneratorInterface::ABSOLUTE_URL);
  877.                 $redirectUrl $url '?data=' urlencode($encDataStr);
  878.             } else {
  879.                 $encDataStr $this->get('url_encryptor')->encrypt(json_encode($encData));
  880.                 $url $this->generateUrl(
  881.                     $redirectRoute
  882.                 );
  883.                 $redirectUrl $url "/" $encDataStr;
  884.             }
  885.             return $this->redirect($redirectUrl);
  886. //            $encDataStr = $this->get('url_encryptor')->encrypt(json_encode($encData));
  887. //            $url = $this->generateUrl(
  888. //                'central_landing'
  889. //            );
  890. //            $redirectUrl = $url . "/" . $encDataStr;
  891. //            return $this->redirect($redirectUrl);
  892.         } else {
  893.             return $this->render(
  894.                 $twig_file,
  895.                 $twigData
  896.             );
  897.         }
  898.     }
  899.     public function VerifyOtpWebAction(Request $request$encData '')
  900.     {
  901.         $em $this->getDoctrine()->getManager();
  902.         $em_goc $this->getDoctrine()->getManager('company_group');
  903.         $session $request->getSession();
  904.         $message "";
  905.         $retData = array();
  906.         $encData $request->query->get('encData'$encData);
  907.         $encryptedData = [];
  908.         if ($encData != '')
  909.             $encryptedData json_decode($this->get('url_encryptor')->decrypt($encData), true);
  910.         if ($encryptedData == null$encryptedData = [];
  911.         $systemType $this->container->hasParameter('system_type') ? $this->container->getParameter('system_type') : '_ERP_';
  912.         $userCategory $request->request->get('userCategory'$request->query->get('userCategory', (isset($encryptedData['otp']) ? $encryptedData['userCategory'] : '_BUDDYBEE_USER_')));
  913.         $email_address $request->request->get('email'$request->query->get('email', (isset($encryptedData['email']) ? $encryptedData['email'] : '')));
  914.         $otpExpireSecond $request->request->get('otpExpireSecond'$request->query->get('otpExpireSecond'180));
  915.         $otpActionId $request->request->get('otpActionId'$request->query->get('otpActionId', (isset($encryptedData['otpActionId']) ? $encryptedData['otpActionId'] : UserConstants::OTP_ACTION_FORGOT_PASSWORD)));
  916.         $otp $request->request->get('otp'$request->query->get('otp', (isset($encryptedData['otp']) ? $encryptedData['otp'] : '')));
  917.         $otpExpireTs = isset($encryptedData['otpExpireTs']) ? $encryptedData['otpExpireTs'] : 0;
  918.         $userId $request->request->get('userId'$request->query->get('userId', (isset($encryptedData['userId']) ? $encryptedData['userId'] : $session->get(UserConstants::USER_ID0))));
  919.         $userType UserConstants::USER_TYPE_APPLICANT;
  920.         $userEntity 'CompanyGroupBundle\\Entity\\EntityApplicantDetails';
  921.         $userEntityManager $em_goc;
  922.         $userEntityIdField 'applicantId';
  923.         $userEntityUserNameField 'username';
  924.         $userEntityEmailField1 'email';
  925.         $userEntityEmailField1Getter 'getEmail';
  926.         $userEntityEmailField1Setter 'setEmail';
  927.         $userEntityEmailField2 'oAuthEmail';
  928.         $userEntityEmailField2Getter 'geOAuthEmail';
  929.         $userEntityEmailField2Setter 'seOAuthEmail';
  930.         $twig_file '@HoneybeeWeb/pages/views/verify_otp_honeybee.html.twig';
  931.         $twigData = [];
  932.         $email_twig_file 'ApplicationBundle:email/templates:forgotPasswordOtp.html.twig';
  933.         $email_twig_data = array('success' => false);
  934.         $redirectUrl '';
  935.         $userObj null;
  936.         $userData = [];
  937.         if ($systemType == '_ERP_') {
  938.             if ($userCategory == '_APPLICANT_') {
  939.                 $userType UserConstants::USER_TYPE_APPLICANT;
  940.                 $twig_file '@HoneybeeWeb/pages/views/verify_otp_honeybee.html.twig';
  941.                 $twigData = [];
  942.                 $userEntity 'CompanyGroupBundle\\Entity\\EntityApplicantDetails';
  943.                 $userEntityManager $em_goc;
  944.                 $userEntityIdField 'applicantId';
  945.                 $userEntityUserNameField 'username';
  946.                 $email_twig_file 'ApplicationBundle:email/templates:forgotPasswordOtp.html.twig';
  947.                 //    $email_twig_file = 'ApplicationBundle:pages/email:find_account_buddybee.html.twig';
  948.             } else {
  949.                 $userType UserConstants::USER_TYPE_GENERAL;
  950.                 $twig_file '@HoneybeeWeb/pages/views/verify_otp_honeybee.html.twig';
  951.                 $twigData = [];
  952.                 $userEntity 'ApplicationBundle:SysUser';
  953.                 $userEntityManager $em;
  954.                 $userEntityIdField 'userId';
  955.                 $userEntityUserNameField 'userName';
  956.                 $email_twig_file 'ApplicationBundle:email/templates:forgotPasswordOtp.html.twig';
  957.                 //    $email_twig_file = 'ApplicationBundle:pages/email:find_account_buddybee.html.twig';
  958.             }
  959.         } else if ($systemType == '_BUDDYBEE_') {
  960.             $userType UserConstants::USER_TYPE_APPLICANT;
  961.             $twig_file '@HoneybeeWeb/pages/views/verify_otp_honeybee.html.twig';
  962.             $twigData = [];
  963.             $userEntity 'CompanyGroupBundle\\Entity\\EntityApplicantDetails';
  964.             $userEntityManager $em_goc;
  965.             $userEntityIdField 'applicantId';
  966.             $userEntityUserNameField 'username';
  967.             $email_twig_file 'ApplicationBundle:email/templates:forgotPasswordOtp.html.twig';
  968.             //            $email_twig_file = 'ApplicationBundle:pages/email:find_account_buddybee.html.twig';
  969.         } else if ($systemType == '_CENTRAL_') {
  970.             $userType UserConstants::USER_TYPE_APPLICANT;
  971.             $twig_file '@HoneybeeWeb/pages/views/verify_otp_honeybee.html.twig';
  972.             $twigData = [];
  973.             $userEntity 'CompanyGroupBundle\\Entity\\EntityApplicantDetails';
  974.             $userEntityManager $em_goc;
  975.             $userEntityIdField 'applicantId';
  976.             $userEntityUserNameField 'username';
  977.             $email_twig_file 'ApplicationBundle:email/templates:forgotPasswordOtp.html.twig';
  978.             //            $email_twig_file = 'ApplicationBundle:pages/email:find_account_buddybee.html.twig';
  979.         }
  980.         if ($request->isMethod('POST') || $otp != '') {
  981.             $userObj $userEntityManager->getRepository($userEntity)->findOneBy(
  982.                 array(
  983.                     $userEntityIdField => $userId
  984.                 )
  985.             );
  986.             if ($userObj) {
  987.             } else {
  988.                 $userObj $userEntityManager->getRepository($userEntity)->findOneBy(
  989.                     array(
  990.                         $userEntityEmailField1 => $email_address
  991.                     )
  992.                 );
  993.                 if ($userObj) {
  994.                 } else {
  995.                     $userObj $userEntityManager->getRepository($userEntity)->findOneBy(
  996.                         array(
  997.                             $userEntityEmailField2 => $email_address
  998.                         )
  999.                     );
  1000.                     if ($userObj) {
  1001.                     } else {
  1002.                         $userObj $em_goc->getRepository('CompanyGroupBundle\\Entity\\EntityApplicantDetails')->findOneBy(
  1003.                             array(
  1004.                                 $userEntityUserNameField => $email_address
  1005.                             )
  1006.                         );
  1007.                     }
  1008.                 }
  1009.             }
  1010.             if ($userObj) {
  1011.                 $userOtp $userObj->getOtp();
  1012.                 $userOtpActionId $userObj->getOtpActionId();
  1013.                 $userOtpExpireTs $userObj->getOtpExpireTs();
  1014.                 $currentTime = new \DateTime();
  1015.                 $currentTimeTs $currentTime->format('U');
  1016.                 $userData = array(
  1017.                     'id' => $userObj->getApplicantId(),
  1018.                     'email' => $email_address,
  1019.                     'appId' => 0,
  1020.                     'image' => $userObj->getImage(),
  1021.                     'firstName' => $userObj->getFirstname(),
  1022.                     'lastName' => $userObj->getLastname(),
  1023.                     //                        'appId'=>$userObj->getUserAppId(),
  1024.                 );
  1025.                 $email_twig_data = [
  1026.                     'page_title' => 'OTP',
  1027.                     'success' => false,
  1028.                     //                        'encryptedData' => $encryptedData,
  1029.                     'message' => $message,
  1030.                     'userType' => $userType,
  1031.                     //                        'errorField' => $errorField,
  1032.                     'otp' => '',
  1033.                     'otpExpireSecond' => $otpExpireSecond,
  1034.                     'otpActionId' => $otpActionId,
  1035.                     'otpExpireTs' => $userOtpExpireTs,
  1036.                     'systemType' => $systemType,
  1037.                     'userCategory' => $userCategory,
  1038.                     'userData' => $userData,
  1039.                     "email" => $email_address,
  1040.                     "userId" => isset($userData['id']) ? $userData['id'] : 0,
  1041.                 ];
  1042.                 if ($otp == '0112') {
  1043.                     $userObj->setOtp(0);
  1044.                     $userObj->setOtpActionId(UserConstants::OTP_ACTION_NONE);
  1045.                     $userObj->setOtpExpireTs(0);
  1046.                     $userObj->setTriggerResetPassword(1);
  1047.                     $em_goc->flush();
  1048.                     $email_twig_data['success'] = true;
  1049.                     $message "";
  1050.                 } else if ($userOtp != $otp) {
  1051.                     $message "Invalid OTP!";
  1052.                     $email_twig_data['success'] = false;
  1053.                     $redirectUrl "";
  1054.                 } else if ($userOtpActionId != $otpActionId) {
  1055.                     $message "Invalid OTP Action!";
  1056.                     $email_twig_data['success'] = false;
  1057.                     $redirectUrl "";
  1058.                 } else if ($currentTimeTs $userOtpExpireTs) {
  1059.                     $message "OTP Expired!";
  1060.                     $email_twig_data['success'] = false;
  1061.                     $redirectUrl "";
  1062.                 } else {
  1063.                     $userObj->setOtp(0);
  1064.                     $userObj->setOtpActionId(UserConstants::OTP_ACTION_NONE);
  1065.                     $userObj->setOtpExpireTs(0);
  1066.                     $userObj->setTriggerResetPassword(0);
  1067.                     $userObj->setIsEmailVerified(0);
  1068.                     $userObj->setIsTemporaryEntry(0);
  1069.                     $em_goc->flush();
  1070.                     $email_twig_data['success'] = true;
  1071.                     $message "";
  1072.                 }
  1073.             } else {
  1074.                 $message "Account not found!";
  1075.                 $redirectUrl "";
  1076.                 $email_twig_data['success'] = false;
  1077.             }
  1078.         }
  1079.         $twigData = array(
  1080.             'page_title' => 'OTP Verification',
  1081.             'message' => $message,
  1082.             "userType" => $userType,
  1083.             "userData" => $userData,
  1084.             "otp" => '',
  1085.             "redirectUrl" => $redirectUrl,
  1086.             "email" => $email_address,
  1087.             "otpExpireTs" => $otpExpireTs,
  1088.             "otpActionId" => $otpActionId,
  1089.             "userCategory" => $userCategory,
  1090.             "userId" => isset($userData['id']) ? $userData['id'] : 0,
  1091.             "systemType" => $systemType,
  1092.             'actionData' => $email_twig_data,
  1093.             'success' => isset($email_twig_data['success']) ? $email_twig_data['success'] : false,
  1094.         );
  1095.         if ($request->request->has('remoteVerify') || $request->request->has('returnJson') || $request->query->has('returnJson')) {
  1096.             $response = new JsonResponse($twigData);
  1097.             $response->headers->set('Access-Control-Allow-Origin''*');
  1098.             return $response;
  1099.         } else if ($twigData['success'] == true) {
  1100.             $encData = array(
  1101.                 "userType" => $userType,
  1102.                 "otp" => '',
  1103.                 'message' => $message,
  1104.                 "otpExpireTs" => $otpExpireTs,
  1105.                 "otpActionId" => $otpActionId,
  1106.                 "userCategory" => $userCategory,
  1107.                 "userId" => $userData['id'],
  1108.                 "systemType" => $systemType,
  1109.             );
  1110. //            $encDataStr = $this->get('url_encryptor')->encrypt(json_encode($encData));
  1111. //            $url = $this->generateUrl(
  1112. //                UserConstants::$OTP_ACTION_DATA[$otpActionId]['redirectRoute']
  1113. //            );
  1114. //            $redirectUrl = $url . "/" . $encDataStr;
  1115. //            return $this->redirect($redirectUrl);
  1116.             $encDataStr $this->get('url_encryptor')->encrypt(json_encode($encData));
  1117.             $url $this->generateUrl(
  1118.                 'central_landing'
  1119.             );
  1120.             $redirectUrl $url "/" $encDataStr;
  1121.             $this->addFlash('success''Email Verified!');
  1122.             return $this->redirect($redirectUrl);
  1123.         } else {
  1124.             return $this->render(
  1125.                 $twig_file,
  1126.                 $twigData
  1127.             );
  1128.         }
  1129.     }
  1130.     // reset new password **
  1131.     public function NewPasswordAction(Request $request$encData '')
  1132.     {
  1133.         //  $userCategory=$request->request->has('userCategory');
  1134.         $encryptedData = [];
  1135.         $errorField '';
  1136.         $message '';
  1137.         $userType '';
  1138.         $otpExpireSecond 180;
  1139.         $session $request->getSession();
  1140.         if ($encData == '')
  1141.             $encData $request->get('encData''');
  1142.         if ($encData != '')
  1143.             $encryptedData json_decode($this->get('url_encryptor')->decrypt($encData), true);
  1144.         //    $encryptedData = $this->get('url_encryptor')->decrypt($encData);
  1145.         $otp = isset($encryptedData['otp']) ? $encryptedData['otp'] : 0;
  1146.         $password = isset($encryptedData['password']) ? $encryptedData['password'] : 0;
  1147.         $otpActionId = isset($encryptedData['otpActionId']) ? $encryptedData['otpActionId'] : 0;
  1148.         $userId = isset($encryptedData['userId']) ? $encryptedData['userId'] : $session->get(UserConstants::USER_ID);
  1149.         $userCategory = isset($encryptedData['userCategory']) ? $encryptedData['userCategory'] : '_BUDDYBEE_USER_';
  1150.         //    $em = $this->getDoctrine()->getManager('company_group');
  1151.         $em_goc $this->getDoctrine()->getManager('company_group');
  1152.         $systemType $this->container->hasParameter('system_type') ? $this->container->getParameter('system_type') : '_ERP_';
  1153.         $twig_file 'ApplicationBundle:pages/login:find_account_buddybee.html.twig';
  1154.         $twigData = [];
  1155.         $email_twig_file 'ApplicationBundle:pages/email:find_account_buddybee.html.twig';
  1156.         $email_twig_data = [];
  1157.         if ($request->isMethod('POST')) {
  1158.             $otp $request->request->get('otp'$otp);
  1159.             $password $request->request->get('password'$password);
  1160.             $otpActionId $request->request->get('otpActionId'$otpActionId);
  1161.             $userId $request->request->get('userId'$userId);
  1162.             $userCategory $request->request->get('userCategory'$userCategory);
  1163.             $email_address $request->request->get('email');
  1164.             if ($systemType == '_ERP_') {
  1165.                 $gocId $session->get(UserConstants::USER_GOC_ID);
  1166.                 $appId $session->get(UserConstants::USER_APP_ID);
  1167.                 list($em$goc) = $this->getPublicDocumentEntityManager($appId);
  1168.                 if (!$em || !$goc) {
  1169.                     return $this->render('@Buddybee/pages/404NotFound.html.twig', array(
  1170.                         'page_title' => '404 Not Found',
  1171.                     ));
  1172.                 }
  1173.                 if (!$em || !$goc) {
  1174.                     return $this->render('@Buddybee/pages/404NotFound.html.twig', array(
  1175.                         'page_title' => '404 Not Found',
  1176.                     ));
  1177.                 }
  1178.                 if ($userCategory == '_APPLICANT_') {
  1179.                     $userType UserConstants::USER_TYPE_APPLICANT;
  1180.                     $userObj $em_goc->getRepository('CompanyGroupBundle\\Entity\\EntityApplicantDetails')->findOneBy(
  1181.                         array(
  1182.                             'applicantId' => $userId
  1183.                         )
  1184.                     );
  1185.                     if ($userObj) {
  1186.                         if ($userObj->getTriggerResetPassword() == 1) {
  1187.                             $encodedPassword $this->container->get('sha256salted_encoder')->encodePassword($password$userObj->getSalt());
  1188.                             $userObj->setPassword($encodedPassword);
  1189.                             $userObj->setTempPassword('');
  1190.                             $userObj->setTriggerResetPassword(0);
  1191.                             $em_goc->flush();
  1192.                             $email_twig_data['success'] = true;
  1193.                             $message "";
  1194.                             $userData = array(
  1195.                                 'id' => $userObj->getApplicantId(),
  1196.                                 'email' => $email_address,
  1197.                                 'appId' => 0,
  1198.                                 'image' => $userObj->getImage(),
  1199.                                 'firstName' => $userObj->getFirstname(),
  1200.                                 'lastName' => $userObj->getLastname(),
  1201.                                 //                        'appId'=>$userObj->getUserAppId(),
  1202.                             );
  1203.                         } else {
  1204.                             $message "Action not allowed!";
  1205.                             $email_twig_data['success'] = false;
  1206.                         }
  1207.                     } else {
  1208.                         $message "Account not found!";
  1209.                         $email_twig_data['success'] = false;
  1210.                     }
  1211.                 } else {
  1212.                     $userType $session->get(UserConstants::USER_TYPE);
  1213.                     $userObj $em->getRepository('ApplicationBundle\\Entity\\SysUser')->findOneBy(
  1214.                         array(
  1215.                             'userId' => $userId
  1216.                         )
  1217.                     );
  1218.                     if ($userObj) {
  1219.                         if ($userObj->getTriggerResetPassword() == 1) {
  1220.                             $encodedPassword $this->container->get('sha256salted_encoder')->encodePassword($password$userObj->getSalt());
  1221.                             $userObj->setPassword($encodedPassword);
  1222.                             $userObj->setTempPassword('');
  1223.                             $userObj->setTriggerResetPassword(0);
  1224.                             $em->flush();
  1225.                             $email_twig_data['success'] = true;
  1226.                             $message "";
  1227.                         } else {
  1228.                             $message "Action not allowed!";
  1229.                             $email_twig_data['success'] = false;
  1230.                         }
  1231.                     } else {
  1232.                         $message "Account not found!";
  1233.                         $email_twig_data['success'] = false;
  1234.                     }
  1235.                 }
  1236.                 if ($request->request->has('remoteVerify') || $request->request->has('returnJson') || $request->query->has('returnJson')) {
  1237.                     $response = new JsonResponse(array(
  1238.                             'templateData' => $twigData,
  1239.                             'message' => $message,
  1240.                             'actionData' => $email_twig_data,
  1241.                             'success' => isset($email_twig_data['success']) ? $email_twig_data['success'] : false,
  1242.                         )
  1243.                     );
  1244.                     $response->headers->set('Access-Control-Allow-Origin''*');
  1245.                     return $response;
  1246.                 } else if ($email_twig_data['success'] == true) {
  1247.                     //                    $twig_file = '@Authentication/pages/views/reset_password_success_buddybee.html.twig';
  1248.                     //                    $twigData = [
  1249.                     //                        'page_title' => 'Reset Successful',
  1250.                     //                        'encryptedData' => $encryptedData,
  1251.                     //                        'message' => $message,
  1252.                     //                        'userType' => $userType,
  1253.                     //                        'errorField' => $errorField,
  1254.                     //
  1255.                     //                    ];
  1256.                     //                    return $this->render(
  1257.                     //                        $twig_file,
  1258.                     //                        $twigData
  1259.                     //                    );
  1260.                     return $this->redirectToRoute('dashboard');
  1261.                 }
  1262.             } else if ($systemType == '_BUDDYBEE_') {
  1263.                 $userType UserConstants::USER_TYPE_APPLICANT;
  1264.                 $userObj $em_goc->getRepository('CompanyGroupBundle\\Entity\\EntityApplicantDetails')->findOneBy(
  1265.                     array(
  1266.                         'applicantId' => $userId
  1267.                     )
  1268.                 );
  1269.                 if ($userObj) {
  1270.                     if ($userObj->getTriggerResetPassword() == 1) {
  1271.                         $encodedPassword $this->container->get('sha256salted_encoder')->encodePassword($password$userObj->getSalt());
  1272.                         $userObj->setPassword($encodedPassword);
  1273.                         $userObj->setTempPassword('');
  1274.                         $userObj->setTriggerResetPassword(0);
  1275.                         $em_goc->flush();
  1276.                         $email_twig_data['success'] = true;
  1277.                         $message "";
  1278.                         $userData = array(
  1279.                             'id' => $userObj->getApplicantId(),
  1280.                             'email' => $email_address,
  1281.                             'appId' => 0,
  1282.                             'image' => $userObj->getImage(),
  1283.                             'firstName' => $userObj->getFirstname(),
  1284.                             'lastName' => $userObj->getLastname(),
  1285.                             //                        'appId'=>$userObj->getUserAppId(),
  1286.                         );
  1287.                     } else {
  1288.                         $message "Action not allowed!";
  1289.                         $email_twig_data['success'] = false;
  1290.                     }
  1291.                 } else {
  1292.                     $message "Account not found!";
  1293.                     $email_twig_data['success'] = false;
  1294.                 }
  1295.             } else if ($systemType == '_CENTRAL_') {
  1296.                 $userType UserConstants::USER_TYPE_APPLICANT;
  1297.                 $userObj $em_goc->getRepository('CompanyGroupBundle\\Entity\\EntityApplicantDetails')->findOneBy(
  1298.                     array(
  1299.                         'applicantId' => $userId
  1300.                     )
  1301.                 );
  1302.                 if ($userObj) {
  1303.                     if ($userObj->getTriggerResetPassword() == 1) {
  1304.                         $encodedPassword $this->container->get('sha256salted_encoder')->encodePassword($password$userObj->getSalt());
  1305.                         $userObj->setPassword($encodedPassword);
  1306.                         $userObj->setTempPassword('');
  1307.                         $userObj->setTriggerResetPassword(0);
  1308.                         $em_goc->flush();
  1309.                         $email_twig_data['success'] = true;
  1310.                         $message "";
  1311.                         $userData = array(
  1312.                             'id' => $userObj->getApplicantId(),
  1313.                             'email' => $email_address,
  1314.                             'appId' => 0,
  1315.                             'image' => $userObj->getImage(),
  1316.                             'firstName' => $userObj->getFirstname(),
  1317.                             'lastName' => $userObj->getLastname(),
  1318.                             //                        'appId'=>$userObj->getUserAppId(),
  1319.                         );
  1320.                     } else {
  1321.                         $message "Action not allowed!";
  1322.                         $email_twig_data['success'] = false;
  1323.                     }
  1324.                 } else {
  1325.                     $message "Account not found!";
  1326.                     $email_twig_data['success'] = false;
  1327.                 }
  1328.             }
  1329.             if ($request->request->has('remoteVerify') || $request->request->has('returnJson') || $request->query->has('returnJson')) {
  1330.                 $response = new JsonResponse(array(
  1331.                         'templateData' => $twigData,
  1332.                         'message' => $message,
  1333.                         'actionData' => $email_twig_data,
  1334.                         'success' => isset($email_twig_data['success']) ? $email_twig_data['success'] : false,
  1335.                     )
  1336.                 );
  1337.                 $response->headers->set('Access-Control-Allow-Origin''*');
  1338.                 return $response;
  1339.             } else if ($email_twig_data['success'] == true) {
  1340.                 if ($systemType == '_ERP_'$twig_file '@Authentication/pages/views/reset_password_success_central.html.twig';
  1341.                 else if ($systemType == '_BUDDYBEE_'$twig_file '@Authentication/pages/views/reset_password_success_buddybee.html.twig';
  1342.                 else if ($systemType == '_CENTRAL_'$twig_file '@Authentication/pages/views/reset_password_success_central.html.twig';
  1343.                 $twigData = [
  1344.                     'page_title' => 'Reset Successful',
  1345.                     'encryptedData' => $encryptedData,
  1346.                     'message' => $message,
  1347.                     'userType' => $userType,
  1348.                     'errorField' => $errorField,
  1349.                 ];
  1350.                 return $this->render(
  1351.                     $twig_file,
  1352.                     $twigData
  1353.                 );
  1354.             }
  1355.         }
  1356.         if ($systemType == '_ERP_') {
  1357.             if ($userCategory == '_APPLICANT_') {
  1358.                 $userType $session->get(UserConstants::USER_TYPE);
  1359.                 $twig_file 'ApplicationBundle:pages/login:find_account_buddybee.html.twig';
  1360.                 $twigData = [
  1361.                     'page_title' => 'Find Account',
  1362.                     'encryptedData' => $encryptedData,
  1363.                     'message' => $message,
  1364.                     'userType' => $userType,
  1365.                     'errorField' => $errorField,
  1366.                 ];
  1367.             } else {
  1368.                 $userType $session->get(UserConstants::USER_TYPE);
  1369.                 $twig_file 'ApplicationBundle:pages/login:reset_password_erp.html.twig';
  1370.                 $twigData = [
  1371.                     'page_title' => 'Reset Password',
  1372.                     'encryptedData' => $encryptedData,
  1373.                     'message' => $message,
  1374.                     'userType' => $userType,
  1375.                     'errorField' => $errorField,
  1376.                 ];
  1377.             }
  1378.         } else if ($systemType == '_BUDDYBEE_') {
  1379.             $userType UserConstants::USER_TYPE_APPLICANT;
  1380.             $twig_file '@Authentication/pages/views/reset_new_password_buddybee.html.twig';
  1381.             $twigData = [
  1382.                 'page_title' => 'Reset Password',
  1383.                 'encryptedData' => $encryptedData,
  1384.                 'message' => $message,
  1385.                 'userType' => $userType,
  1386.                 'errorField' => $errorField,
  1387.             ];
  1388.         } else if ($systemType == '_CENTRAL_') {
  1389.             $userType UserConstants::USER_TYPE_APPLICANT;
  1390.             $twig_file '@HoneybeeWeb/pages/views/reset_new_password_honeybee.html.twig';
  1391.             $twigData = [
  1392.                 'page_title' => 'Reset Password',
  1393.                 'encryptedData' => $encryptedData,
  1394.                 'message' => $message,
  1395.                 'userType' => $userType,
  1396.                 'errorField' => $errorField,
  1397.             ];
  1398.         }
  1399.         if ($request->request->has('remoteVerify') || $request->request->has('returnJson') || $request->query->has('returnJson')) {
  1400.             if ($userId != && $userId != null) {
  1401.                 $response = new JsonResponse(array(
  1402.                         'templateData' => $twigData,
  1403.                         'message' => $message,
  1404. //                        'encryptedData' => $encryptedData,
  1405.                         'actionData' => $email_twig_data,
  1406.                         'success' => isset($email_twig_data['success']) ? $email_twig_data['success'] : false,
  1407.                     )
  1408.                 );
  1409.             } else {
  1410.                 $response = new JsonResponse(array(
  1411.                         'templateData' => [],
  1412.                         'message' => 'Unauthorized',
  1413.                         'actionData' => [],
  1414. //                        'encryptedData' => $encryptedData,
  1415.                         'success' => false,
  1416.                     )
  1417.                 );
  1418.             }
  1419.             $response->headers->set('Access-Control-Allow-Origin''*');
  1420.             return $response;
  1421.         } else {
  1422.             if ($userId != && $userId != null) {
  1423.                 return $this->render(
  1424.                     $twig_file,
  1425.                     $twigData
  1426.                 );
  1427.             } else
  1428.                 return $this->render('@Buddybee/pages/404NotFound.html.twig', array(
  1429.                     'page_title' => '404 Not Found',
  1430.                 ));
  1431.         }
  1432.     }
  1433.     // hire
  1434. //    public function CentralHirePageAction()
  1435. //    {
  1436. //        $em_goc = $this->getDoctrine()->getManager('company_group');
  1437. //        $freelancersData = $em_goc->getRepository('CompanyGroupBundle\\Entity\\EntityApplicantDetails')
  1438. //            ->createQueryBuilder('m')
  1439. //             ->where("m.isConsultant =1")
  1440. //
  1441. //            ->getQuery()
  1442. //            ->getResult();
  1443. //
  1444. //        return $this->render('@HoneybeeWeb/pages/hire.html.twig', array(
  1445. //            'page_title' => 'Hire',
  1446. //            'freelancersData' => $freelancersData,
  1447. //
  1448. //        ));
  1449. //    }
  1450. //    public function CentralHirePageAction(Request $request)
  1451. //    {
  1452. //        $em_goc = $this->getDoctrine()->getManager('company_group');
  1453. //        $search = $request->query->get('q'); // get search text
  1454. //
  1455. //        $qb = $em_goc->getRepository('CompanyGroupBundle\\Entity\\EntityApplicantDetails')
  1456. //            ->createQueryBuilder('m')
  1457. //            ->where('m.isConsultant = 1');
  1458. //
  1459. //        if (!empty($search)) {
  1460. //            $qb->andWhere('m.firstname LIKE :search
  1461. //                       OR m.lastname LIKE :search ')
  1462. //                ->setParameter('search', '%' . $search . '%');
  1463. //        }
  1464. //
  1465. //        $freelancersData = $qb->getQuery()->getResult();
  1466. //
  1467. //        return $this->render('@HoneybeeWeb/pages/hire.html.twig', [
  1468. //            'page_title' => 'Hire',
  1469. //            'freelancersData' => $freelancersData,
  1470. //            'searchValue' => $search
  1471. //        ]);
  1472. //    }
  1473.     public function CentralHirePageAction(Request $request)
  1474.     {
  1475.         $em_goc $this->getDoctrine()->getManager('company_group');
  1476.         $search $request->query->get('q'); // search text
  1477.         $qb $em_goc->getRepository('CompanyGroupBundle\\Entity\\EntityApplicantDetails')
  1478.             ->createQueryBuilder('m')
  1479.             ->where('m.isConsultant = 1');
  1480.         if (!empty($search)) {
  1481.             $qb->andWhere('m.firstname LIKE :search OR m.lastname LIKE :search')
  1482.                 ->setParameter('search''%' $search '%');
  1483.         }
  1484.         $freelancersData $qb->getQuery()->getResult();
  1485.         // For AJAX requests, we return the same Twig, but we include the searchValue
  1486.         if ($request->isXmlHttpRequest()) {
  1487.             return $this->render('@HoneybeeWeb/pages/hire.html.twig', [
  1488.                 'page_title' => 'Hire',
  1489.                 'freelancersData' => $freelancersData,
  1490.                 'searchValue' => $search// so input retains value
  1491.                 'isAjax' => true// flag to indicate AJAX
  1492.             ]);
  1493.         }
  1494.         // Normal page load
  1495.         return $this->render('@HoneybeeWeb/pages/hire.html.twig', [
  1496.             'page_title' => 'Hire',
  1497.             'freelancersData' => $freelancersData,
  1498.             'searchValue' => $search,
  1499.             'isAjax' => false,
  1500.         ]);
  1501.     }
  1502.     // end of centralHire
  1503.     // pricing
  1504.     public function CentralPricingPageAction(Request $request)
  1505.     {
  1506.         $em_goc $this->getDoctrine()->getManager('company_group');
  1507.         $session $request->getSession();
  1508.         $userId $session->get(UserConstants::USER_ID);
  1509.         $companiesForUser = [];
  1510.         if ($userId) {
  1511.             $userDetails $em_goc->getRepository('CompanyGroupBundle\Entity\EntityApplicantDetails')->find($userId);
  1512.             if ($userDetails) {
  1513.                 $userTypeByAppIds json_decode($userDetails->getUserTypesByAppIds(), true);
  1514.                 if (is_array($userTypeByAppIds)) {
  1515.                     $adminAppIds = [];
  1516.                     foreach ($userTypeByAppIds as $appId => $types) {
  1517.                         if (in_array(1$types)) {
  1518.                             $adminAppIds[] = $appId;
  1519.                         }
  1520.                     }
  1521.                     if (!empty($adminAppIds)) {
  1522.                         $companiesForUser $em_goc->getRepository('CompanyGroupBundle\Entity\CompanyGroup')
  1523.                             ->createQueryBuilder('c')
  1524.                             ->where('c.appId IN (:appIds)')
  1525.                             ->setParameter('appIds'$adminAppIds)
  1526.                             ->getQuery()
  1527.                             ->getResult();
  1528.                     }
  1529.                 }
  1530.             }
  1531.         }
  1532.         $packageDetails GeneralConstant::$packageDetails;
  1533.         return $this->render('@HoneybeeWeb/pages/pricing.html.twig', [
  1534.             'page_title' => 'HoneyBee Pricing | Software Subscription + Project-Based Edge+ Deployment',
  1535.             'og_title' => 'HoneyBee Pricing | Software Subscription + Project-Based Edge+ Deployment',
  1536.             'og_description' => 'HoneyBee software subscription starts from €7.99/user/month. Edge+ hardware, IoT sensors, and local ML deployment are scoped and quoted per project.',
  1537.             'packageDetails' => $packageDetails,
  1538.             'companies' => $companiesForUser,
  1539.         ]);
  1540.     }
  1541.     // faq
  1542.     public function CentralFaqPageAction()
  1543.     {
  1544.         return $this->render('@HoneybeeWeb/pages/faq.html.twig', array(
  1545.             'page_title'     => 'FAQ | HoneyBee — EPC, Industrial & Platform Questions',
  1546.             'packageDetails' => GeneralConstant::$packageDetails,
  1547.         ));
  1548.     }
  1549.     // terms and condiitons
  1550.     public function CentralTermsAndConditionPageAction()
  1551.     {
  1552.         return $this->render('@HoneybeeWeb/pages/terms_and_conditions.html.twig', array(
  1553.             'page_title' => 'Terms and Conditions',
  1554.         ));
  1555.     }
  1556.     // Refund Policy
  1557.    public function CentralRefundPolicyPageAction()
  1558. {
  1559.     return $this->render('@HoneybeeWeb/pages/refund_policy.html.twig', array(
  1560.         'page_title' => 'Refund Policy',
  1561.     ));
  1562. }
  1563.     // Cancellation Policy
  1564.    public function CentralCancellationPolicyPageAction()
  1565. {
  1566.     return $this->render('@HoneybeeWeb/pages/cancellation_policy.html.twig', array(
  1567.            'page_title' => 'Cancellation Policy',
  1568.     ));
  1569. }
  1570.     // Help page
  1571.    public function CentralHelpPageAction()
  1572.    {
  1573.     return $this->render('@HoneybeeWeb/pages/help.html.twig', array(
  1574.         'page_title' => 'Help',
  1575.     ));
  1576.    }
  1577.  // Career page
  1578.    public function CentralCareerPageAction()
  1579. {
  1580.     return $this->render('@HoneybeeWeb/pages/career.html.twig', array(
  1581.         'page_title' => 'Career',
  1582.     ));
  1583. }
  1584.     public function CentralPrivacyPolicyAction()
  1585.     {
  1586.         return $this->render('@HoneybeeWeb/pages/privacy_policy.html.twig', array(
  1587.             'page_title' => 'Privacy Policy — HoneyBee',
  1588.         ));
  1589.     }
  1590.     public function CentralDpaPageAction()
  1591.     {
  1592.         return $this->render('@HoneybeeWeb/pages/dpa.html.twig', array(
  1593.             'page_title' => 'Data Processing Addendum (DPA) — HoneyBee',
  1594.         ));
  1595.     }
  1596.     public function CentralSolutionsPageAction()
  1597.     {
  1598.         return $this->render('@HoneybeeWeb/pages/solutions.html.twig', array(
  1599.             'page_title' => 'HoneyBee Solutions | EPC, Energy Asset, IPP/OPEX/PPA & Multi-Site Operations',
  1600.             'og_title' => 'HoneyBee Solutions | EPC, Energy Asset, IPP/OPEX/PPA & Multi-Site Operations',
  1601.             'og_description' => 'HoneyBee delivers purpose-built solutions for EPC contractors, energy asset managers, IPP/OPEX/PPA operators, and multi-site industrial businesses. HoneyBee is not an EPC contractor or project developer.',
  1602.         ));
  1603.     }
  1604.     public function CentralPartnersPageAction()
  1605.     {
  1606.         return $this->render('@HoneybeeWeb/pages/partners.html.twig', array(
  1607.             'page_title' => 'HoneyBee Partner Program | Implementation, Edge+, IoT & Infrastructure Partners',
  1608.             'og_title' => 'HoneyBee Partner Program | Implementation, Edge+, IoT & Infrastructure Partners',
  1609.             'og_description' => 'Join the HoneyBee partner ecosystem as an implementation partner, Edge+ local infrastructure partner, IoT hardware reseller, or software integration partner.',
  1610.         ));
  1611.     }
  1612.     public function CheckoutPageAction(Request $request$encData '')
  1613.     {
  1614.         $em $this->getDoctrine()->getManager('company_group');
  1615.         $em_goc $this->getDoctrine()->getManager('company_group');
  1616.         $sandBoxMode $this->container->hasParameter('sand_box_mode') ? $this->container->getParameter('sand_box_mode') : 0;
  1617.         $invoiceId $request->request->get('invoiceId'$request->query->get('invoiceId'0));
  1618.         if ($encData != "") {
  1619.             $encryptedData json_decode($this->get('url_encryptor')->decrypt($encData), true);
  1620.             if ($encryptedData == null$encryptedData = [];
  1621.             if (isset($encryptedData['invoiceId'])) $invoiceId $encryptedData['invoiceId'];
  1622.         }
  1623.         $session $request->getSession();
  1624.         $currencyForGateway 'eur';
  1625.         $gatewayInvoice null;
  1626.         if ($invoiceId != 0)
  1627.             $gatewayInvoice $em->getRepository(EntityInvoice::class)->find($invoiceId);
  1628.         $paymentGateway $request->request->get('paymentGateway''stripe'); //aamarpay,bkash
  1629.         $paymentType $request->request->get('paymentType''credit');
  1630.         $retailerId $request->request->get('retailerId'0);
  1631.         if ($request->query->has('currency'))
  1632.             $currencyForGateway $request->query->get('currency');
  1633.         else
  1634.             $currencyForGateway $request->request->get('currency''eur');
  1635. //        {
  1636. //            if ($request->query->has('meetingSessionId'))
  1637. //                $id = $request->query->get('meetingSessionId');
  1638. //        }
  1639.         $currentUserBalance 0;
  1640.         $currentUserCoinBalance 0;
  1641.         $gatewayAmount 0;
  1642.         $redeemedAmount 0;
  1643.         $redeemedSessionCount 0;
  1644.         $toConsumeSessionCount 0;
  1645.         $invoiceSessionCount 0;
  1646.         $payableAmount 0;
  1647.         $promoClaimedAmount 0;
  1648.         $promoCodeId 0;
  1649.         $promoClaimedSession 0;
  1650.         $bookingExpireTime null;
  1651.         $bookingExpireTs 0;
  1652.         $imageBySessionCount = [
  1653.             => "https://www.buddybee.eu/buddybee_assets/ADULT-BEE.png",
  1654.             100 => "https://www.buddybee.eu/buddybee_assets/ADULT-BEE.png",
  1655.             200 => "https://www.buddybee.eu/buddybee_assets/ADULT-BEE.png",
  1656.             300 => "https://www.buddybee.eu/buddybee_assets/ADULT-BEE.png",
  1657.             400 => "https://www.buddybee.eu/buddybee_assets/ADULT-BEE.png",
  1658.             500 => "https://www.buddybee.eu/buddybee_assets/ADULT-BEE.png",
  1659.             600 => "https://www.buddybee.eu/buddybee_assets/ADULT-BEE.png",
  1660.             700 => "https://www.buddybee.eu/buddybee_assets/ADULT-BEE.png",
  1661.             800 => "https://www.buddybee.eu/buddybee_assets/ADULT-BEE.png",
  1662.             900 => "https://www.buddybee.eu/buddybee_assets/ADULT-BEE.png",
  1663.             1000 => "https://www.buddybee.eu/buddybee_assets/ADULT-BEE.png",
  1664.             1100 => "https://www.buddybee.eu/buddybee_assets/ADULT-BEE.png",
  1665.             1200 => "https://www.buddybee.eu/buddybee_assets/ADULT-BEE.png",
  1666.             1300 => "https://www.buddybee.eu/buddybee_assets/ADULT-BEE.png",
  1667.             1400 => "https://www.buddybee.eu/buddybee_assets/ADULT-BEE.png",
  1668.             1500 => "https://www.buddybee.eu/buddybee_assets/ADULT-BEE.png",
  1669.             1600 => "https://www.buddybee.eu/buddybee_assets/ADULT-BEE.png",
  1670.             1700 => "https://www.buddybee.eu/buddybee_assets/ADULT-BEE.png",
  1671.             1800 => "https://www.buddybee.eu/buddybee_assets/ADULT-BEE.png",
  1672.             1900 => "https://www.buddybee.eu/buddybee_assets/ADULT-BEE.png",
  1673.             2000 => "https://www.buddybee.eu/buddybee_assets/ADULT-BEE.png",
  1674.             2100 => "https://www.buddybee.eu/buddybee_assets/ADULT-BEE.png",
  1675.             2200 => "https://www.buddybee.eu/buddybee_assets/ADULT-BEE.png",
  1676.             2300 => "https://www.buddybee.eu/buddybee_assets/ADULT-BEE.png",
  1677.             2400 => "https://www.buddybee.eu/buddybee_assets/ADULT-BEE.png",
  1678.             2500 => "https://www.buddybee.eu/buddybee_assets/ADULT-BEE.png",
  1679.             2600 => "https://www.buddybee.eu/buddybee_assets/ADULT-BEE.png",
  1680.             2700 => "https://www.buddybee.eu/buddybee_assets/ADULT-BEE.png",
  1681.             2800 => "https://www.buddybee.eu/buddybee_assets/ADULT-BEE.png",
  1682.             2900 => "https://www.buddybee.eu/buddybee_assets/ADULT-BEE.png",
  1683.             3000 => "https://www.buddybee.eu/buddybee_assets/ADULT-BEE.png",
  1684.             3100 => "https://www.buddybee.eu/buddybee_assets/ADULT-BEE.png",
  1685.             3200 => "https://www.buddybee.eu/buddybee_assets/ADULT-BEE.png",
  1686.             3300 => "https://www.buddybee.eu/buddybee_assets/ADULT-BEE.png",
  1687.             3400 => "https://www.buddybee.eu/buddybee_assets/ADULT-BEE.png",
  1688.             3500 => "https://www.buddybee.eu/buddybee_assets/ADULT-BEE.png",
  1689.             3600 => "https://www.buddybee.eu/buddybee_assets/ADULT-BEE.png",
  1690.             3700 => "https://www.buddybee.eu/buddybee_assets/ADULT-BEE.png",
  1691.         ];
  1692.         if (!$gatewayInvoice) {
  1693.             if ($request->isMethod('POST')) {
  1694.                 $totalAmount 0;
  1695.                 $totalSessionCount 0;
  1696.                 $consumedAmount 0;
  1697.                 $consumedSessionCount 0;
  1698.                 $bookedById 0;
  1699.                 $bookingRefererId 0;
  1700.                 if ($session->get(UserConstants::USER_ID)) {
  1701.                     $bookedById $session->get(UserConstants::USER_ID);
  1702.                     $bookingRefererId 0;
  1703. //                    $toConsumeSessionCount = 1 * $request->request->get('meetingSessionConsumeCount', 0);
  1704.                     $invoiceSessionCount * ($request->request->get('sessionCount'0) == '' $request->request->get('sessionCount'0));
  1705.                     //1st do the necessary
  1706.                     $extMeeting null;
  1707.                     $meetingSessionId 0;
  1708.                     if ($request->request->has('purchasePackage')) {
  1709.                         //1. check if any bee card if yes try to claim it , modify current balance then
  1710.                         $beeCodeSerial $request->request->get('beeCodeSerial''');
  1711.                         $promoCode $request->request->get('promoCode''');
  1712.                         $beeCodePin $request->request->get('beeCodePin''');
  1713.                         $userId $request->request->get('userId'$session->get(UserConstants::USER_ID));
  1714.                         $studentDetails null;
  1715.                         $studentDetails $em_goc->getRepository(EntityApplicantDetails::class)->find($userId);
  1716.                         if ($studentDetails) {
  1717.                             $currentUserBalance $studentDetails->getAccountBalance();
  1718.                         }
  1719.                         if ($beeCodeSerial != '' && $beeCodePin != '') {
  1720.                             $claimData MiscActions::ClaimBeeCode($em,
  1721.                                 [
  1722.                                     'claimFlag' => 1,
  1723.                                     'pin' => $beeCodePin,
  1724.                                     'serial' => $beeCodeSerial,
  1725.                                     'userId' => $userId,
  1726.                                 ]);
  1727.                             if ($userId == $session->get(UserConstants::USER_ID)) {
  1728.                                 MiscActions::RefreshBuddybeeBalanceOnSession($em$request->getSession());
  1729.                                 $claimData['newCoinBalance'] = $session->get('BUDDYBEE_COIN_BALANCE');
  1730.                                 $claimData['newBalance'] = $session->get('BUDDYBEE_BALANCE');
  1731.                             }
  1732.                             $redeemedAmount $claimData['data']['claimedAmount'];
  1733.                             $redeemedSessionCount $claimData['data']['claimedCoin'];
  1734.                         } else
  1735.                             if ($userId == $session->get(UserConstants::USER_ID)) {
  1736.                                 MiscActions::RefreshBuddybeeBalanceOnSession($em$request->getSession());
  1737.                             }
  1738.                         $payableAmount round($request->request->get('payableAmount'0), 0);
  1739.                         $totalAmountWoDiscount round($request->request->get('totalAmountWoDiscount'0), 0);
  1740.                         //now claim and process promocode
  1741.                         if ($promoCode != '') {
  1742.                             $claimData MiscActions::ClaimPromoCode($em,
  1743.                                 [
  1744.                                     'claimFlag' => 1,
  1745.                                     'promoCode' => $promoCode,
  1746.                                     'decryptedPromoCodeData' => json_decode($this->get('url_encryptor')->decrypt($promoCode), true),
  1747.                                     'orderValue' => $totalAmountWoDiscount,
  1748.                                     'currency' => $currencyForGateway,
  1749.                                     'orderCoin' => $invoiceSessionCount,
  1750.                                     'userId' => $userId,
  1751.                                 ]);
  1752.                             $promoClaimedAmount 0;
  1753. //                            $promoClaimedAmount = $claimData['data']['claimedAmount']*(BuddybeeConstant::$convMultFromTo['eur'][$currencyForGateway]);
  1754.                             $promoCodeId $claimData['promoCodeId'];
  1755.                             $promoClaimedSession $claimData['data']['claimedCoin'];
  1756.                         }
  1757.                         if ($userId == $session->get(UserConstants::USER_ID)) {
  1758.                             MiscActions::RefreshBuddybeeBalanceOnSession($em$request->getSession());
  1759.                             $currentUserBalance $session->get('BUDDYBEE_BALANCE');
  1760.                             $currentUserCoinBalance $session->get('BUDDYBEE_COIN_BALANCE');
  1761.                         } else {
  1762.                             if ($bookingRefererId == 0)
  1763.                                 $bookingRefererId $session->get(UserConstants::USER_ID);
  1764.                             $studentDetails $em_goc->getRepository(EntityApplicantDetails::class)->find($userId);
  1765.                             if ($studentDetails) {
  1766.                                 $currentUserBalance $studentDetails->getAccountBalance();
  1767.                                 $currentUserCoinBalance $studentDetails->getSessionCountBalance();
  1768.                                 if ($bookingRefererId != $userId && $bookingRefererId != 0) {
  1769.                                     $bookingReferer $em_goc->getRepository(EntityApplicantDetails::class)->find($bookingRefererId);
  1770.                                     if ($bookingReferer)
  1771.                                         if ($bookingReferer->getIsAdmin()) {
  1772.                                             $studentDetails->setAssignedSalesRepresentativeId($bookingRefererId);
  1773.                                             $em_goc->flush();
  1774.                                         }
  1775.                                 }
  1776.                             }
  1777.                         }
  1778.                         //2. check if any promo code  if yes add it to promo discount
  1779.                         //3. check if scheule is still temporarily booked if not return that you cannot book it
  1780.                         Buddybee::ExpireAnyMeetingSessionIfNeeded($em);
  1781.                         Buddybee::ExpireAnyEntityInvoiceIfNeeded($em);
  1782. //                        if ($request->request->get('autoAssignMeetingSession', 0) == 1
  1783. //                            && $request->request->get('consultancyScheduleId', 0) != 0
  1784. //                            && $request->request->get('consultancyScheduleId', 0) != ''
  1785. //                        )
  1786.                         {
  1787.                             //1st check if a meeting session exxists with same TS, student id , consultant id
  1788. //                            $scheduledStartTime = new \DateTime('@' . $request->request->get('consultancyScheduleId', ''));
  1789. //                            $extMeeting = $em->getRepository('CompanyGroupBundle\\Entity\\EntityMeetingSession')
  1790. //                                ->findOneBy(
  1791. //                                    array(
  1792. //                                        'scheduledTimeTs' => $scheduledStartTime->format('U'),
  1793. //                                        'consultantId' => $request->request->get('consultantId', 0),
  1794. //                                        'studentId' => $request->request->get('studentId', 0),
  1795. //                                        'durationAllowedMin' => $request->request->get('meetingSessionScheduledDuration', BuddybeeConstant::PER_SESSION_MINUTE),
  1796. //                                    )
  1797. //                                );
  1798. //                            if ($extMeeting) {
  1799. //                                $new = $extMeeting;
  1800. //                                $meetingSessionId = $new->getSessionId();
  1801. //                                $periodMarker = $scheduledStartTime->format('Ym');
  1802. //
  1803. //                            }
  1804. //                            else {
  1805. //
  1806. //
  1807. //                                $scheduleValidity = MiscActions::CheckIfScheduleCanBeConfirmed(
  1808. //                                    $em,
  1809. //                                    $request->request->get('consultantId', 0),
  1810. //                                    $request->request->get('studentId', 0),
  1811. //                                    $scheduledStartTime->format('U'),
  1812. //                                    $request->request->get('meetingSessionScheduledDuration', BuddybeeConstant::PER_SESSION_MINUTE),
  1813. //                                    1
  1814. //                                );
  1815. //
  1816. //                                if (!$scheduleValidity) {
  1817. //                                    $url = $this->generateUrl(
  1818. //                                        'consultant_profile'
  1819. //                                    );
  1820. //                                    $output = [
  1821. //
  1822. //                                        'proceedToCheckout' => 0,
  1823. //                                        'message' => 'Session Booking Expired or not Found!',
  1824. //                                        'errorFlag' => 1,
  1825. //                                        'redirectUrl' => $url . '/' . $request->request->get('consultantId', 0)
  1826. //                                    ];
  1827. //                                    return new JsonResponse($output);
  1828. //                                }
  1829. //                                $new = new EntityMeetingSession();
  1830. //
  1831. //                                $new->setTopicId($request->request->get('consultancyTopic', 0));
  1832. //                                $new->setConsultantId($request->request->get('consultantId', 0));
  1833. //                                $new->setStudentId($request->request->get('studentId', 0));
  1834. //                                $consultancyTopic = $em_goc->getRepository(EntityCreateTopic::class)->find($request->request->get('consultancyTopic', 0));
  1835. //                                $new->setMeetingType($consultancyTopic ? $consultancyTopic->getMeetingType() : 0);
  1836. //                                $new->setConsultantCanUpload($consultancyTopic ? $consultancyTopic->getConsultantCanUpload() : 0);
  1837. //
  1838. //
  1839. //                                $scheduledEndTime = new \DateTime($request->request->get('scheduledTime', ''));
  1840. //                                $scheduledEndTime = $scheduledEndTime->modify('+' . $request->request->get('meetingSessionScheduledDuration', 30) . ' minute');
  1841. //
  1842. //                                //$new->setScheduledTime($request->request->get('setScheduledTime'));
  1843. //                                $new->setScheduledTime($scheduledStartTime);
  1844. //                                $new->setDurationAllowedMin($request->request->get('meetingSessionScheduledDuration', 30));
  1845. //                                $new->setDurationLeftMin($request->request->get('meetingSessionScheduledDuration', 30));
  1846. //                                $new->setSessionExpireDate($scheduledEndTime);
  1847. //                                $new->setSessionExpireDateTs($scheduledEndTime->format('U'));
  1848. //                                $new->setEquivalentSessionCount($request->request->get('meetingSessionConsumeCount', 0));
  1849. //                                $new->setMeetingSpecificNote($request->request->get('meetingSpecificNote', ''));
  1850. //
  1851. //                                $new->setUsableSessionCount($request->request->get('meetingSessionConsumeCount', 0));
  1852. //                                $new->setRedeemSessionCount($request->request->get('meetingSessionConsumeCount', 0));
  1853. //                                $new->setMeetingActionFlag(0);// no action waiting for meeting
  1854. //                                $new->setScheduledTime($scheduledStartTime);
  1855. //                                $new->setScheduledTimeTs($scheduledStartTime->format('U'));
  1856. //                                $new->setPayableAmount($request->request->get('payableAmount', 0));
  1857. //                                $new->setDueAmount($request->request->get('dueAmount', 0));
  1858. //                                //$new->setScheduledTime(new \DateTime($request->get('setScheduledTime')));
  1859. //                                //$new->setPcakageDetails(json_encode(($request->request->get('packageData'))));
  1860. //                                $new->setPackageName(($request->request->get('packageName', '')));
  1861. //                                $new->setPcakageDetails(($request->request->get('packageData', '')));
  1862. //                                $new->setScheduleId(($request->request->get('consultancyScheduleId', 0)));
  1863. //                                $currentUnixTime = new \DateTime();
  1864. //                                $currentUnixTimeStamp = $currentUnixTime->format('U');
  1865. //                                $studentId = $request->request->get('studentId', 0);
  1866. //                                $consultantId = $request->request->get('consultantId', 0);
  1867. //                                $new->setMeetingRoomId(str_pad($consultantId, 4, STR_PAD_LEFT) . $currentUnixTimeStamp . str_pad($studentId, 4, STR_PAD_LEFT));
  1868. //                                $new->setSessionValue(($request->request->get('sessionValue', 0)));
  1869. ////                        $new->setIsPayment(0);
  1870. //                                $new->setConsultantIsPaidFull(0);
  1871. //
  1872. //                                if ($bookingExpireTs == 0) {
  1873. //
  1874. //                                    $bookingExpireTime = new \DateTime();
  1875. //                                    $currTime = new \DateTime();
  1876. //                                    $currTimeTs = $currTime->format('U');
  1877. //                                    $bookingExpireTs = (1 * $scheduledStartTime->format('U')) - (24 * 3600);
  1878. //                                    if ($bookingExpireTs < $currTimeTs) {
  1879. //                                        if ((1 * $scheduledStartTime->format('U')) - $currTimeTs > (12 * 3600))
  1880. //                                            $bookingExpireTs = (1 * $scheduledStartTime->format('U')) - (2 * 3600);
  1881. //                                        else
  1882. //                                            $bookingExpireTs = (1 * $scheduledStartTime->format('U'));
  1883. //                                    }
  1884. //
  1885. ////                                    $bookingExpireTs = $bookingExpireTime->format('U');
  1886. //                                }
  1887. //
  1888. //                                $new->setPaidSessionCount(0);
  1889. //                                $new->setBookedById($bookedById);
  1890. //                                $new->setBookingRefererId($bookingRefererId);
  1891. //                                $new->setDueSessionCount($request->request->get('meetingSessionConsumeCount', 0));
  1892. //                                $new->setExpireIfUnpaidTs($bookingExpireTs);
  1893. //                                $new->setBookingExpireTs($bookingExpireTs);
  1894. //                                $new->setConfirmationExpireTs($bookingExpireTs);
  1895. //                                $new->setIsPaidFull(0);
  1896. //                                $new->setIsExpired(0);
  1897. //
  1898. //
  1899. //                                $em_goc->persist($new);
  1900. //                                $em_goc->flush();
  1901. //                                $meetingSessionId = $new->getSessionId();
  1902. //                                $periodMarker = $scheduledStartTime->format('Ym');
  1903. //                                MiscActions::UpdateSchedulingRestrictions($em_goc, $consultantId, $periodMarker, (($request->request->get('meetingSessionScheduledDuration', 30)) / 60), -(($request->request->get('meetingSessionScheduledDuration', 30)) / 60));
  1904. //                            }
  1905.                         }
  1906.                         //4. if after all this stages passed then calcualte gateway payable
  1907.                         if ($request->request->get('isRecharge'0) == 1) {
  1908.                             if (($redeemedAmount $promoClaimedAmount) >= $payableAmount) {
  1909.                                 $payableAmount = ($redeemedAmount $promoClaimedAmount);
  1910.                                 $gatewayAmount 0;
  1911.                             } else
  1912.                                 $gatewayAmount $payableAmount - ($redeemedAmount $promoClaimedAmount);
  1913.                         } else {
  1914.                             if ($toConsumeSessionCount <= $currentUserCoinBalance && $invoiceSessionCount <= $toConsumeSessionCount) {
  1915.                                 $payableAmount 0;
  1916.                                 $gatewayAmount 0;
  1917.                             } else if (($redeemedAmount $promoClaimedAmount) >= $payableAmount) {
  1918.                                 $payableAmount = ($redeemedAmount $promoClaimedAmount);
  1919.                                 $gatewayAmount 0;
  1920.                             } else
  1921.                                 $gatewayAmount $payableAmount <= ($currentUserBalance + ($redeemedAmount $promoClaimedAmount)) ? : ($payableAmount $currentUserBalance - ($redeemedAmount $promoClaimedAmount));
  1922.                         }
  1923.                         $gatewayAmount round($gatewayAmount2);
  1924.                         $dueAmount round($request->request->get('dueAmount'$payableAmount), 0);
  1925.                         if ($request->request->has('gatewayProductData'))
  1926.                             $gatewayProductData $request->request->get('gatewayProductData');
  1927.                         $gatewayProductData = [[
  1928.                             'price_data' => [
  1929.                                 'currency' => $currencyForGateway,
  1930.                                 'unit_amount' => $gatewayAmount != ? ((100 $gatewayAmount) / ($invoiceSessionCount != $invoiceSessionCount 1)) : 200000,
  1931.                                 'product_data' => [
  1932. //                            'name' => $request->request->has('packageName') ? $request->request->get('packageName') : 'Advanced Consultancy Package',
  1933.                                     'name' => 'Bee Coins',
  1934.                                     'images' => [$imageBySessionCount[0]],
  1935.                                 ],
  1936.                             ],
  1937.                             'quantity' => $invoiceSessionCount != $invoiceSessionCount 1,
  1938.                         ]];
  1939.                         $new_invoice null;
  1940.                         if ($extMeeting) {
  1941.                             $new_invoice $em->getRepository('CompanyGroupBundle\\Entity\\EntityInvoice')
  1942.                                 ->findOneBy(
  1943.                                     array(
  1944.                                         'invoiceType' => $request->request->get('invoiceType'BuddybeeConstant::ENTITY_INVOICE_TYPE_PAYMENT_TO_HONEYBEE),
  1945.                                         'meetingId' => $extMeeting->getSessionId(),
  1946.                                     )
  1947.                                 );
  1948.                         }
  1949.                         if ($new_invoice) {
  1950.                         } else {
  1951.                             $new_invoice = new EntityInvoice();
  1952.                             $invoiceDate = new \DateTime();
  1953.                             $new_invoice->setInvoiceDate($invoiceDate);
  1954.                             $new_invoice->setInvoiceDateTs($invoiceDate->format('U'));
  1955.                             $new_invoice->setStudentId($userId);
  1956.                             $new_invoice->setBillerId($retailerId == $retailerId);
  1957.                             $new_invoice->setRetailerId($retailerId);
  1958.                             $new_invoice->setBillToId($userId);
  1959.                             $new_invoice->setAmountTransferGateWayHash($paymentGateway);
  1960.                             $new_invoice->setAmountCurrency($currencyForGateway);
  1961.                             $cardIds $request->request->get('cardIds', []);
  1962.                             $new_invoice->setMeetingId($meetingSessionId);
  1963.                             $new_invoice->setGatewayBillAmount($gatewayAmount);
  1964.                             $new_invoice->setRedeemedAmount($redeemedAmount);
  1965.                             $new_invoice->setPromoDiscountAmount($promoClaimedAmount);
  1966.                             $new_invoice->setPromoCodeId($promoCodeId);
  1967.                             $new_invoice->setRedeemedSessionCount($redeemedSessionCount);
  1968.                             $new_invoice->setPaidAmount($payableAmount $dueAmount);
  1969.                             $new_invoice->setProductDataForPaymentGateway(json_encode($gatewayProductData));
  1970.                             $new_invoice->setDueAmount($dueAmount);
  1971.                             $new_invoice->setInvoiceType($request->request->get('invoiceType'BuddybeeConstant::ENTITY_INVOICE_TYPE_PAYMENT_TO_HONEYBEE));
  1972.                             $new_invoice->setDocumentHash(MiscActions::GenerateRandomCrypto('BEI' microtime(true)));
  1973.                             $new_invoice->setCardIds(json_encode($cardIds));
  1974.                             $new_invoice->setAmountType($request->request->get('amountType'1));
  1975.                             $new_invoice->setAmount($payableAmount);
  1976.                             $new_invoice->setConsumeAmount($payableAmount);
  1977.                             $new_invoice->setSessionCount($invoiceSessionCount);
  1978.                             $new_invoice->setConsumeSessionCount($toConsumeSessionCount);
  1979.                             $new_invoice->setIsPaidfull(0);
  1980.                             $new_invoice->setIsProcessed(0);
  1981.                             $new_invoice->setApplicantId($userId);
  1982.                             $new_invoice->setBookedById($bookedById);
  1983.                             $new_invoice->setBookingRefererId($bookingRefererId);
  1984.                             $new_invoice->setIsRecharge($request->request->get('isRecharge'0));
  1985.                             $new_invoice->setAutoConfirmTaggedMeeting($request->request->get('autoConfirmTaggedMeeting'0));
  1986.                             $new_invoice->setAutoConfirmOtherMeeting($request->request->get('autoConfirmOtherMeeting'0));
  1987.                             $new_invoice->setAutoClaimPurchasedCards($request->request->get('autoClaimPurchasedCards'0));
  1988.                             $new_invoice->setIsPayment(0); //0 means receive
  1989.                             $new_invoice->setStatus(GeneralConstant::ACTIVE); //0 means receive
  1990.                             $new_invoice->setStage(BuddybeeConstant::ENTITY_INVOICE_STAGE_INITIATED); //0 means receive
  1991.                             if ($bookingExpireTs == 0) {
  1992.                                 $bookingExpireTime = new \DateTime();
  1993.                                 $bookingExpireTime->modify('+30 day');
  1994.                                 $bookingExpireTs $bookingExpireTime->format('U');
  1995.                             }
  1996.                             $new_invoice->setExpireIfUnpaidTs($bookingExpireTs);
  1997.                             $new_invoice->setBookingExpireTs($bookingExpireTs);
  1998.                             $new_invoice->setConfirmationExpireTs($bookingExpireTs);
  1999. //            $new_invoice->setStatus($request->request->get(0));
  2000.                             $em_goc->persist($new_invoice);
  2001.                             $em_goc->flush();
  2002.                         }
  2003.                         $invoiceId $new_invoice->getId();
  2004.                         $gatewayInvoice $new_invoice;
  2005.                         if ($request->request->get('isRecharge'0) == 1) {
  2006.                         } else {
  2007.                             if ($gatewayAmount <= 0) {
  2008.                                 $meetingId 0;
  2009.                                 if ($invoiceId != 0) {
  2010.                                     $retData Buddybee::ProcessEntityInvoice($em_goc$invoiceId, ['stage' => BuddybeeConstant::ENTITY_INVOICE_STAGE_COMPLETED], $this->container->getParameter('kernel.root_dir'), false,
  2011.                                         $this->container->getParameter('notification_enabled'),
  2012.                                         $this->container->getParameter('notification_server')
  2013.                                     );
  2014.                                     $meetingId $retData['meetingId'];
  2015.                                 }
  2016.                                 MiscActions::RefreshBuddybeeBalanceOnSession($em$request->getSession());
  2017.                                 if (GeneralConstant::EMAIL_ENABLED == 1) {
  2018.                                     $billerDetails = [];
  2019.                                     $billToDetails = [];
  2020.                                     $invoice $gatewayInvoice;
  2021.                                     if ($invoice) {
  2022.                                         $billerDetails $em->getRepository('CompanyGroupBundle\\Entity\\EntityApplicantDetails')
  2023.                                             ->findOneBy(
  2024.                                                 array(
  2025.                                                     'applicantId' => $invoice->getBillerId(),
  2026.                                                 )
  2027.                                             );
  2028.                                         $billToDetails $em->getRepository('CompanyGroupBundle\\Entity\\EntityApplicantDetails')
  2029.                                             ->findOneBy(
  2030.                                                 array(
  2031.                                                     'applicantId' => $invoice->getBillToId(),
  2032.                                                 )
  2033.                                             );
  2034.                                     }
  2035.                                     $bodyTemplate 'ApplicationBundle:email/templates:buddybeeInvoiceEmail.html.twig';
  2036.                                     $bodyData = array(
  2037.                                         'page_title' => 'Invoice',
  2038. //            'studentDetails' => $student,
  2039.                                         'billerDetails' => $billerDetails,
  2040.                                         'billToDetails' => $billToDetails,
  2041.                                         'invoice' => $invoice,
  2042.                                         'currencyList' => BuddybeeConstant::$currency_List,
  2043.                                         'currencyListByMarker' => BuddybeeConstant::$currency_List_by_marker,
  2044.                                     );
  2045.                                     $attachments = [];
  2046.                                     $forwardToMailAddress $billToDetails->getOAuthEmail();
  2047. //                    $upl_dir = $this->container->getParameter('kernel.root_dir') . '/../web/uploads/temp/' . 'ledger' . '.pdf'
  2048.                                     $new_mail $this->get('mail_module');
  2049.                                     $new_mail->sendMyMail(array(
  2050.                                         'senderHash' => '_CUSTOM_',
  2051.                                         //                        'senderHash'=>'_CUSTOM_',
  2052.                                         'forwardToMailAddress' => $forwardToMailAddress,
  2053.                                         'subject' => 'YourInvoice #' 'D' str_pad('BB'5'0'STR_PAD_LEFT) . str_pad('76'2'0'STR_PAD_LEFT) . str_pad($invoice->getId(), 8"0"STR_PAD_LEFT) . ' from BuddyBee ',
  2054. //                        'fileName' => 'Order#' . str_pad($id, 8, '0', STR_PAD_LEFT) . '.pdf',
  2055.                                         'attachments' => $attachments,
  2056.                                         'toAddress' => $forwardToMailAddress,
  2057.                                         'fromAddress' => 'no-reply@buddybee.eu',
  2058.                                         'userName' => 'no-reply@buddybee.eu',
  2059.                                         'password' => 'Honeybee@0112',
  2060.                                         'smtpServer' => 'smtp.hostinger.com',
  2061.                                         'smtpPort' => 465,
  2062. //                            'emailBody' => $bodyHtml,
  2063.                                         'mailTemplate' => $bodyTemplate,
  2064.                                         'templateData' => $bodyData,
  2065.                                         'embedCompanyImage' => 0,
  2066.                                         'companyId' => 0,
  2067.                                         'companyImagePath' => ''
  2068. //                        'embedCompanyImage' => 1,
  2069. //                        'companyId' => $companyId,
  2070. //                        'companyImagePath' => $company_data->getImage()
  2071.                                     ));
  2072.                                 }
  2073.                                 if ($meetingId != 0) {
  2074.                                     $url $this->generateUrl(
  2075.                                         'consultancy_session'
  2076.                                     );
  2077.                                     $output = [
  2078.                                         'invoiceId' => $gatewayInvoice->getId(),
  2079.                                         'meetingId' => $meetingId,
  2080.                                         'proceedToCheckout' => 0,
  2081.                                         'redirectUrl' => $url '/' $meetingId
  2082.                                     ];
  2083.                                 } else {
  2084.                                     $url $this->generateUrl(
  2085.                                         'buddybee_dashboard'
  2086.                                     );
  2087.                                     $output = [
  2088.                                         'invoiceId' => $gatewayInvoice->getId(),
  2089.                                         'meetingId' => 0,
  2090.                                         'proceedToCheckout' => 0,
  2091.                                         'redirectUrl' => $url
  2092.                                     ];
  2093.                                 }
  2094.                                 return new JsonResponse($output);
  2095. //                return $this->redirect($url);
  2096.                             } else {
  2097.                             }
  2098. //                $url = $this->generateUrl(
  2099. //                    'checkout_page'
  2100. //                );
  2101. //
  2102. //                return $this->redirect($url."?meetingSessionId=".$new->getSessionId().'&invoiceId='.$invoiceId);
  2103.                         }
  2104.                     }
  2105.                 } else {
  2106.                     $url $this->generateUrl(
  2107.                         'user_login'
  2108.                     );
  2109.                     $session->set('LAST_REQUEST_URI_BEFORE_LOGIN'$this->generateUrl(
  2110.                         'pricing_plan_page', [
  2111.                         'autoRedirected' => 1
  2112.                     ],
  2113.                         UrlGenerator::ABSOLUTE_URL
  2114.                     ));
  2115.                     $output = [
  2116.                         'proceedToCheckout' => 0,
  2117.                         'redirectUrl' => $url,
  2118.                         'clearLs' => 0
  2119.                     ];
  2120.                     return new JsonResponse($output);
  2121.                 }
  2122.                 //now proceed to checkout page if the user has lower balance or recharging
  2123.                 //$invoiceDetails = $em->getRepository('CompanyGroupBundle\\Entity\\EntityInvoice')->
  2124.             }
  2125.         }
  2126.         if ($gatewayInvoice) {
  2127.             $gatewayProductData json_decode($gatewayInvoice->getProductDataForPaymentGateway(), true);
  2128.             if ($gatewayProductData == null$gatewayProductData = [];
  2129.             if (empty($gatewayProductData))
  2130.                 $gatewayProductData = [
  2131.                     [
  2132.                         'price_data' => [
  2133.                             'currency' => 'eur',
  2134.                             'unit_amount' => $gatewayAmount != ? (100 $gatewayAmount) : 200000,
  2135.                             'product_data' => [
  2136. //                            'name' => $request->request->has('packageName') ? $request->request->get('packageName') : 'Advanced Consultancy Package',
  2137.                                 'name' => 'Bee Coins',
  2138.                                 'images' => [$imageBySessionCount[0]],
  2139.                             ],
  2140.                         ],
  2141.                         'quantity' => 1,
  2142.                     ]
  2143.                 ];
  2144.             $productDescStr '';
  2145.             $productDescArr = [];
  2146.             foreach ($gatewayProductData as $gpd) {
  2147.                 $productDescArr[] = $gpd['price_data']['product_data']['name'];
  2148.             }
  2149.             $productDescStr implode(','$productDescArr);
  2150.             $paymentGatewayFromInvoice $gatewayInvoice->getAmountTransferGateWayHash();
  2151. //            return new JsonResponse(
  2152. //                [
  2153. //                    'paymentGateway' => $paymentGatewayFromInvoice,
  2154. //                    'gateWayData' => $gatewayProductData[0]
  2155. //                ]
  2156. //            );
  2157.             if ($paymentGateway == null$paymentGatewayFromInvoice 'stripe';
  2158.             if ($paymentGatewayFromInvoice == 'stripe' || $paymentGatewayFromInvoice == 'aamarpay' || $paymentGatewayFromInvoice == 'bkash') {
  2159.                 if (GeneralConstant::EMAIL_ENABLED == 1) {
  2160.                     $billerDetails = [];
  2161.                     $billToDetails = [];
  2162.                     $invoice $gatewayInvoice;
  2163.                     if ($invoice) {
  2164.                         $billerDetails $em->getRepository('CompanyGroupBundle\\Entity\\EntityApplicantDetails')
  2165.                             ->findOneBy(
  2166.                                 array(
  2167.                                     'applicantId' => $invoice->getBillerId(),
  2168.                                 )
  2169.                             );
  2170.                         $billToDetails $em->getRepository('CompanyGroupBundle\\Entity\\EntityApplicantDetails')
  2171.                             ->findOneBy(
  2172.                                 array(
  2173.                                     'applicantId' => $invoice->getBillToId(),
  2174.                                 )
  2175.                             );
  2176.                     }
  2177.                     $bodyTemplate 'ApplicationBundle:email/templates:buddybeeInvoiceEmail.html.twig';
  2178.                     $bodyData = array(
  2179.                         'page_title' => 'Invoice',
  2180. //            'studentDetails' => $student,
  2181.                         'billerDetails' => $billerDetails,
  2182.                         'billToDetails' => $billToDetails,
  2183.                         'invoice' => $invoice,
  2184.                         'currencyList' => BuddybeeConstant::$currency_List,
  2185.                         'currencyListByMarker' => BuddybeeConstant::$currency_List_by_marker,
  2186.                     );
  2187.                     $attachments = [];
  2188.                     $forwardToMailAddress $billToDetails->getOAuthEmail();
  2189. //                    $upl_dir = $this->container->getParameter('kernel.root_dir') . '/../web/uploads/temp/' . 'ledger' . '.pdf'
  2190.                     $new_mail $this->get('mail_module');
  2191.                     $new_mail->sendMyMail(array(
  2192.                         'senderHash' => '_CUSTOM_',
  2193.                         //                        'senderHash'=>'_CUSTOM_',
  2194.                         'forwardToMailAddress' => $forwardToMailAddress,
  2195.                         'subject' => 'YourInvoice #' 'D' str_pad('BB'5'0'STR_PAD_LEFT) . str_pad('76'2'0'STR_PAD_LEFT) . str_pad($invoice->getId(), 8"0"STR_PAD_LEFT) . ' from BuddyBee ',
  2196. //                        'fileName' => 'Order#' . str_pad($id, 8, '0', STR_PAD_LEFT) . '.pdf',
  2197.                         'attachments' => $attachments,
  2198.                         'toAddress' => $forwardToMailAddress,
  2199.                         'fromAddress' => 'no-reply@buddybee.eu',
  2200.                         'userName' => 'no-reply@buddybee.eu',
  2201.                         'password' => 'Honeybee@0112',
  2202.                         'smtpServer' => 'smtp.hostinger.com',
  2203.                         'smtpPort' => 465,
  2204. //                            'emailBody' => $bodyHtml,
  2205.                         'mailTemplate' => $bodyTemplate,
  2206.                         'templateData' => $bodyData,
  2207.                         'embedCompanyImage' => 0,
  2208.                         'companyId' => 0,
  2209.                         'companyImagePath' => ''
  2210. //                        'embedCompanyImage' => 1,
  2211. //                        'companyId' => $companyId,
  2212. //                        'companyImagePath' => $company_data->getImage()
  2213.                     ));
  2214.                 }
  2215.             }
  2216.             if ($paymentGatewayFromInvoice == 'stripe') {
  2217.                 $stripe = new \Stripe\Stripe();
  2218.                 \Stripe\Stripe::setApiKey('sk_test_51IxYTAJXs21fVb0QMop2Nb0E7u9Da4LwGrym1nGHUHqaSNtT3p9HBgHd7YyDsTKHscgPPECPQniTy79Ab8Sgxfbm00JF2AndUz');
  2219.                 $stripe::setApiKey('sk_test_51IxYTAJXs21fVb0QMop2Nb0E7u9Da4LwGrym1nGHUHqaSNtT3p9HBgHd7YyDsTKHscgPPECPQniTy79Ab8Sgxfbm00JF2AndUz');
  2220.                 {
  2221.                     if ($request->query->has('meetingSessionId'))
  2222.                         $id $request->query->get('meetingSessionId');
  2223.                 }
  2224.                 $paymentIntent = [
  2225.                     "id" => "pi_1DoWjK2eZvKYlo2Csy9J3BHs",
  2226.                     "object" => "payment_intent",
  2227.                     "amount" => 3000,
  2228.                     "amount_capturable" => 0,
  2229.                     "amount_received" => 0,
  2230.                     "application" => null,
  2231.                     "application_fee_amount" => null,
  2232.                     "canceled_at" => null,
  2233.                     "cancellation_reason" => null,
  2234.                     "capture_method" => "automatic",
  2235.                     "charges" => [
  2236.                         "object" => "list",
  2237.                         "data" => [],
  2238.                         "has_more" => false,
  2239.                         "url" => "/v1/charges?payment_intent=pi_1DoWjK2eZvKYlo2Csy9J3BHs"
  2240.                     ],
  2241.                     "client_secret" => "pi_1DoWjK2eZvKYlo2Csy9J3BHs_secret_vmxAcWZxo2kt1XhpWtZtnjDtd",
  2242.                     "confirmation_method" => "automatic",
  2243.                     "created" => 1546523966,
  2244.                     "currency" => $currencyForGateway,
  2245.                     "customer" => null,
  2246.                     "description" => null,
  2247.                     "invoice" => null,
  2248.                     "last_payment_error" => null,
  2249.                     "livemode" => false,
  2250.                     "metadata" => [],
  2251.                     "next_action" => null,
  2252.                     "on_behalf_of" => null,
  2253.                     "payment_method" => null,
  2254.                     "payment_method_options" => [],
  2255.                     "payment_method_types" => [
  2256.                         "card"
  2257.                     ],
  2258.                     "receipt_email" => null,
  2259.                     "review" => null,
  2260.                     "setup_future_usage" => null,
  2261.                     "shipping" => null,
  2262.                     "statement_descriptor" => null,
  2263.                     "statement_descriptor_suffix" => null,
  2264.                     "status" => "requires_payment_method",
  2265.                     "transfer_data" => null,
  2266.                     "transfer_group" => null
  2267.                 ];
  2268.                 $checkout_session = \Stripe\Checkout\Session::create([
  2269.                     'payment_method_types' => ['card'],
  2270.                     'line_items' => $gatewayProductData,
  2271.                     'mode' => 'payment',
  2272.                     'success_url' => $this->generateUrl(
  2273.                         'payment_gateway_success',
  2274.                         ['encData' => $this->get('url_encryptor')->encrypt(json_encode(array(
  2275.                             'invoiceId' => $invoiceId'autoRedirect' => $request->request->get('autoRedirect'1)
  2276.                         ))), 'hbeeSessionToken' => $session->get('token'0)], UrlGenerator::ABSOLUTE_URL
  2277.                     ),
  2278.                     'cancel_url' => $this->generateUrl(
  2279.                         'payment_gateway_cancel', ['invoiceId' => $invoiceId'autoRedirect' => $request->request->get('autoRedirect'1), 'hbeeSessionToken' => $session->get('token'0)], UrlGenerator::ABSOLUTE_URL
  2280.                     ),
  2281.                 ]);
  2282.                 $output = [
  2283.                     'clientSecret' => $paymentIntent['client_secret'],
  2284.                     'id' => $checkout_session->id,
  2285.                     'paymentGateway' => $paymentGatewayFromInvoice,
  2286.                     'proceedToCheckout' => 1
  2287.                 ];
  2288.                 return new JsonResponse($output);
  2289.             }
  2290.             if ($paymentGatewayFromInvoice == 'aamarpay') {
  2291.                 $studentDetails $em_goc->getRepository(EntityApplicantDetails::class)->find($gatewayInvoice->getBillToId());
  2292.                 $url $sandBoxMode == 'https://sandbox.aamarpay.com/request.php' 'https://secure.aamarpay.com/request.php';
  2293.                 $fields = array(
  2294. //                    'store_id' => 'aamarpaytest', //store id will be aamarpay,  contact integration@aamarpay.com for test/live id
  2295.                     'store_id' => $sandBoxMode == 'aamarpaytest' 'buddybee'//store id will be aamarpay,  contact integration@aamarpay.com for test/live id
  2296.                     'amount' => $gatewayInvoice->getGateWayBillamount(), //transaction amount
  2297.                     'payment_type' => 'VISA'//no need to change
  2298.                     'currency' => strtoupper($currencyForGateway),  //currenct will be USD/BDT
  2299.                     'tran_id' => $gatewayInvoice->getDocumentHash(), //transaction id must be unique from your end
  2300.                     'cus_name' => $studentDetails->getFirstname() . ' ' $studentDetails->getLastName(),  //customer name
  2301.                     'cus_email' => $studentDetails->getEmail(), //customer email address
  2302.                     'cus_add1' => $studentDetails->getCurrAddr(),  //customer address
  2303.                     'cus_add2' => $studentDetails->getCurrAddrCity(), //customer address
  2304.                     'cus_city' => $studentDetails->getCurrAddrCity(),  //customer city
  2305.                     'cus_state' => $studentDetails->getCurrAddrState(),  //state
  2306.                     'cus_postcode' => $studentDetails->getCurrAddrZip(), //postcode or zipcode
  2307.                     'cus_country' => 'Bangladesh',  //country
  2308.                     'cus_phone' => ($studentDetails->getPhone() == null || $studentDetails->getPhone() == '') ? '+8801911706483' $studentDetails->getPhone(), //customer phone number
  2309.                     'cus_fax' => '',  //fax
  2310.                     'ship_name' => ''//ship name
  2311.                     'ship_add1' => '',  //ship address
  2312.                     'ship_add2' => '',
  2313.                     'ship_city' => '',
  2314.                     'ship_state' => '',
  2315.                     'ship_postcode' => '',
  2316.                     'ship_country' => 'Bangladesh',
  2317.                     'desc' => $productDescStr,
  2318.                     'success_url' => $this->generateUrl(
  2319.                         'payment_gateway_success',
  2320.                         ['encData' => $this->get('url_encryptor')->encrypt(json_encode(array(
  2321.                             'invoiceId' => $invoiceId'autoRedirect' => $request->request->get('autoRedirect'1)
  2322.                         ))), 'hbeeSessionToken' => $session->get('token'0)], UrlGenerator::ABSOLUTE_URL
  2323.                     ),
  2324.                     'fail_url' => $this->generateUrl(
  2325.                         'payment_gateway_cancel', ['invoiceId' => $invoiceId'autoRedirect' => $request->request->get('autoRedirect'1), 'hbeeSessionToken' => $session->get('token'0)], UrlGenerator::ABSOLUTE_URL
  2326.                     ),
  2327.                     'cancel_url' => $this->generateUrl(
  2328.                         'payment_gateway_cancel', ['invoiceId' => $invoiceId'autoRedirect' => $request->request->get('autoRedirect'1), 'hbeeSessionToken' => $session->get('token'0)], UrlGenerator::ABSOLUTE_URL
  2329.                     ),
  2330. //                    'opt_a' => 'Reshad',  //optional paramter
  2331. //                    'opt_b' => 'Akil',
  2332. //                    'opt_c' => 'Liza',
  2333. //                    'opt_d' => 'Sohel',
  2334. //                    'signature_key' => 'dbb74894e82415a2f7ff0ec3a97e4183',  //sandbox
  2335.                     'signature_key' => $sandBoxMode == 'dbb74894e82415a2f7ff0ec3a97e4183' 'b7304a40e21fe15af3be9a948307f524'  //live
  2336.                 ); //signature key will provided aamarpay, contact integration@aamarpay.com for test/live signature key
  2337.                 $fields_string http_build_query($fields);
  2338. //                $ch = curl_init();
  2339. //                curl_setopt($ch, CURLOPT_VERBOSE, true);
  2340. //                curl_setopt($ch, CURLOPT_URL, $url);
  2341. //
  2342. //                curl_setopt($ch, CURLOPT_POSTFIELDS, $fields_string);
  2343. //                curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
  2344. //                curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
  2345. //                $url_forward = str_replace('"', '', stripslashes(curl_exec($ch)));
  2346. //                curl_close($ch);
  2347. //                $this->redirect_to_merchant($url_forward);
  2348.                 $output = [
  2349. //
  2350. //                    'redirectUrl' => ($sandBoxMode == 1 ? 'https://sandbox.aamarpay.com/' : 'https://secure.aamarpay.com/') . $url_forward, //keeping it off temporarily
  2351. //                    'fields'=>$fields,
  2352. //                    'fields_string'=>$fields_string,
  2353. //                    'redirectUrl' => $this->generateUrl(
  2354. //                        'payment_gateway_success',
  2355. //                        ['encData' => $this->get('url_encryptor')->encrypt(json_encode(array(
  2356. //                            'invoiceId' => $invoiceId, 'autoRedirect' => $request->request->get('autoRedirect', 1)
  2357. //                        ))), 'hbeeSessionToken' => $request->request->get('token', 0)], UrlGenerator::ABSOLUTE_URL
  2358. //                    ),
  2359.                     'paymentGateway' => $paymentGatewayFromInvoice,
  2360.                     'proceedToCheckout' => 1,
  2361.                     'data' => $fields
  2362.                 ];
  2363.                 return new JsonResponse($output);
  2364.             } else if ($paymentGatewayFromInvoice == 'bkash') {
  2365.                 $studentDetails $em_goc->getRepository(EntityApplicantDetails::class)->find($gatewayInvoice->getBillToId());
  2366.                 $baseUrl = ($sandBoxMode == 1) ? 'https://tokenized.sandbox.bka.sh/v1.2.0-beta' 'https://tokenized.pay.bka.sh/v1.2.0-beta';
  2367.                 $username_value = ($sandBoxMode == 1) ? 'sandboxTokenizedUser02' '01891962953';
  2368.                 $password_value = ($sandBoxMode == 1) ? 'sandboxTokenizedUser02@12345' ',a&kPV4deq&';
  2369.                 $app_key_value = ($sandBoxMode == 1) ? '4f6o0cjiki2rfm34kfdadl1eqq' '2ueVHdwz5gH3nxx7xn8wotlztc';
  2370.                 $app_secret_value = ($sandBoxMode == 1) ? '2is7hdktrekvrbljjh44ll3d9l1dtjo4pasmjvs5vl5qr3fug4b' '49Ay3h3wWJMBFD7WF5CassyLrtA1jt6ONhspqjqFx5hTjhqh5dHU';
  2371.                 $request_data = array(
  2372.                     'app_key' => $app_key_value,
  2373.                     'app_secret' => $app_secret_value
  2374.                 );
  2375.                 $url curl_init($baseUrl '/tokenized/checkout/token/grant');
  2376.                 $request_data_json json_encode($request_data);
  2377.                 $header = array(
  2378.                     'Content-Type:application/json',
  2379.                     'username:' $username_value,
  2380.                     'password:' $password_value
  2381.                 );
  2382.                 curl_setopt($urlCURLOPT_HTTPHEADER$header);
  2383.                 curl_setopt($urlCURLOPT_CUSTOMREQUEST"POST");
  2384.                 curl_setopt($urlCURLOPT_RETURNTRANSFERtrue);
  2385.                 curl_setopt($urlCURLOPT_POSTFIELDS$request_data_json);
  2386.                 curl_setopt($urlCURLOPT_FOLLOWLOCATION1);
  2387.                 curl_setopt($urlCURLOPT_IPRESOLVECURL_IPRESOLVE_V4);
  2388.                 $tokenData json_decode(curl_exec($url), true);
  2389.                 curl_close($url);
  2390.                 $id_token $tokenData['id_token'];
  2391.                 $goToBkashPage 0;
  2392.                 if ($tokenData['statusCode'] == '0000') {
  2393.                     $auth $id_token;
  2394.                     $requestbody = array(
  2395.                         "mode" => "0011",
  2396. //                        "payerReference" => "01723888888",
  2397.                         "payerReference" => $invoiceDate->format('U'),
  2398.                         "callbackURL" => $this->generateUrl(
  2399.                             'bkash_callback', [], UrlGenerator::ABSOLUTE_URL
  2400.                         ),
  2401. //                    "merchantAssociationInfo" => "MI05MID54RF09123456One",
  2402.                         "amount" => number_format($gatewayInvoice->getGateWayBillamount(), 2'.'''),
  2403.                         "currency" => "BDT",
  2404.                         "intent" => "sale",
  2405.                         "merchantInvoiceNumber" => $invoiceId
  2406.                     );
  2407.                     $url curl_init($baseUrl '/tokenized/checkout/create');
  2408.                     $requestbodyJson json_encode($requestbody);
  2409.                     $header = array(
  2410.                         'Content-Type:application/json',
  2411.                         'Authorization:' $auth,
  2412.                         'X-APP-Key:' $app_key_value
  2413.                     );
  2414.                     curl_setopt($urlCURLOPT_HTTPHEADER$header);
  2415.                     curl_setopt($urlCURLOPT_CUSTOMREQUEST"POST");
  2416.                     curl_setopt($urlCURLOPT_RETURNTRANSFERtrue);
  2417.                     curl_setopt($urlCURLOPT_POSTFIELDS$requestbodyJson);
  2418.                     curl_setopt($urlCURLOPT_FOLLOWLOCATION1);
  2419.                     curl_setopt($urlCURLOPT_IPRESOLVECURL_IPRESOLVE_V4);
  2420.                     $resultdata curl_exec($url);
  2421. //                    curl_close($url);
  2422. //                    echo $resultdata;
  2423.                     $obj json_decode($resultdatatrue);
  2424.                     $goToBkashPage 1;
  2425.                     $justNow = new \DateTime();
  2426.                     $justNow->modify('+' $tokenData['expires_in'] . ' second');
  2427.                     $gatewayInvoice->setGatewayIdTokenExpireTs($justNow->format('U'));
  2428.                     $gatewayInvoice->setGatewayIdToken($tokenData['id_token']);
  2429.                     $gatewayInvoice->setGatewayPaymentId($obj['paymentID']);
  2430.                     $gatewayInvoice->setGatewayIdRefreshToken($tokenData['refresh_token']);
  2431.                     $em->flush();
  2432.                     $output = [
  2433. //                        'redirectUrl' => $obj['bkashURL'],
  2434.                         'paymentGateway' => $paymentGatewayFromInvoice,
  2435.                         'proceedToCheckout' => $goToBkashPage,
  2436.                         'tokenData' => $tokenData,
  2437.                         'obj' => $obj,
  2438.                         'id_token' => $tokenData['id_token'],
  2439.                         'data' => [
  2440.                             'amount' => $gatewayInvoice->getGateWayBillamount(), //transaction amount
  2441. //                            'payment_type' => 'VISA', //no need to change
  2442.                             'currency' => strtoupper($currencyForGateway),  //currenct will be USD/BDT
  2443.                             'tran_id' => $gatewayInvoice->getDocumentHash(), //transaction id must be unique from your end
  2444.                             'cus_name' => $studentDetails->getFirstname() . ' ' $studentDetails->getLastName(),  //customer name
  2445.                             'cus_email' => $studentDetails->getEmail(), //customer email address
  2446.                             'cus_add1' => $studentDetails->getCurrAddr(),  //customer address
  2447.                             'cus_add2' => $studentDetails->getCurrAddrCity(), //customer address
  2448.                             'cus_city' => $studentDetails->getCurrAddrCity(),  //customer city
  2449.                             'cus_state' => $studentDetails->getCurrAddrState(),  //state
  2450.                             'cus_postcode' => $studentDetails->getCurrAddrZip(), //postcode or zipcode
  2451.                             'cus_country' => 'Bangladesh',  //country
  2452.                             'cus_phone' => ($studentDetails->getPhone() == null || $studentDetails->getPhone() == '') ? '+8801911706483' $studentDetails->getPhone(), //customer phone number
  2453.                             'cus_fax' => '',  //fax
  2454.                             'ship_name' => ''//ship name
  2455.                             'ship_add1' => '',  //ship address
  2456.                             'ship_add2' => '',
  2457.                             'ship_city' => '',
  2458.                             'ship_state' => '',
  2459.                             'ship_postcode' => '',
  2460.                             'ship_country' => 'Bangladesh',
  2461.                             'desc' => $productDescStr,
  2462.                         ]
  2463.                     ];
  2464.                     return new JsonResponse($output);
  2465.                 }
  2466. //                $fields = array(
  2467. //
  2468. //                    "mode" => "0011",
  2469. //                    "payerReference" => "01723888888",
  2470. //                    "callbackURL" => $this->generateUrl(
  2471. //                        'payment_gateway_success',
  2472. //                        ['encData' => $this->get('url_encryptor')->encrypt(json_encode(array(
  2473. //                            'invoiceId' => $invoiceId, 'autoRedirect' => $request->request->get('autoRedirect', 1)
  2474. //                        ))), 'hbeeSessionToken' => $session->get('token', 0)], UrlGenerator::ABSOLUTE_URL
  2475. //                    ),
  2476. //                    "merchantAssociationInfo" => "MI05MID54RF09123456One",
  2477. //                    "amount" => 1*number_format($gatewayInvoice->getGateWayBillamount(),2,'.',''),,
  2478. //                    "currency" => "BDT",
  2479. //                    "intent" => "sale",
  2480. //                    "merchantInvoiceNumber" => 'BEI' . str_pad($gatewayInvoice->getBillerId(), 3, '0', STR_PAD_LEFT) . str_pad($gatewayInvoice->getBillToId(), 5, '0', STR_PAD_LEFT) . str_pad($gatewayInvoice->getId(), 4, '0', STR_PAD_LEFT)
  2481. //
  2482. //                );
  2483. //                $fields = array(
  2484. ////                    'store_id' => 'aamarpaytest', //store id will be aamarpay,  contact integration@aamarpay.com for test/live id
  2485. //                    'store_id' => $sandBoxMode == 1 ? 'aamarpaytest' : 'buddybee', //store id will be aamarpay,  contact integration@aamarpay.com for test/live id
  2486. //                    'amount' => 1*number_format($gatewayInvoice->getGateWayBillamount(),2,'.',''),, //transaction amount
  2487. //                    'payment_type' => 'VISA', //no need to change
  2488. //                    'currency' => strtoupper($currencyForGateway),  //currenct will be USD/BDT
  2489. //                    'tran_id' => 'BEI' . str_pad($gatewayInvoice->getBillerId(), 3, '0', STR_PAD_LEFT) . str_pad($gatewayInvoice->getBillToId(), 5, '0', STR_PAD_LEFT) . str_pad($gatewayInvoice->getId(), 4, '0', STR_PAD_LEFT), //transaction id must be unique from your end
  2490. //                    'cus_name' => $studentDetails->getFirstname() . ' ' . $studentDetails->getLastName(),  //customer name
  2491. //                    'cus_email' => $studentDetails->getEmail(), //customer email address
  2492. //                    'cus_add1' => $studentDetails->getCurrAddr(),  //customer address
  2493. //                    'cus_add2' => $studentDetails->getCurrAddrCity(), //customer address
  2494. //                    'cus_city' => $studentDetails->getCurrAddrCity(),  //customer city
  2495. //                    'cus_state' => $studentDetails->getCurrAddrState(),  //state
  2496. //                    'cus_postcode' => $studentDetails->getCurrAddrZip(), //postcode or zipcode
  2497. //                    'cus_country' => 'Bangladesh',  //country
  2498. //                    'cus_phone' => ($studentDetails->getPhone() == null || $studentDetails->getPhone() == '') ? ' + 8801911706483' : $studentDetails->getPhone(), //customer phone number
  2499. //                    'cus_fax' => '',  //fax
  2500. //                    'ship_name' => '', //ship name
  2501. //                    'ship_add1' => '',  //ship address
  2502. //                    'ship_add2' => '',
  2503. //                    'ship_city' => '',
  2504. //                    'ship_state' => '',
  2505. //                    'ship_postcode' => '',
  2506. //                    'ship_country' => 'Bangladesh',
  2507. //                    'desc' => $productDescStr,
  2508. //                    'success_url' => $this->generateUrl(
  2509. //                        'payment_gateway_success',
  2510. //                        ['encData' => $this->get('url_encryptor')->encrypt(json_encode(array(
  2511. //                            'invoiceId' => $invoiceId, 'autoRedirect' => $request->request->get('autoRedirect', 1)
  2512. //                        ))), 'hbeeSessionToken' => $session->get('token', 0)], UrlGenerator::ABSOLUTE_URL
  2513. //                    ),
  2514. //                    'fail_url' => $this->generateUrl(
  2515. //                        'payment_gateway_cancel', ['invoiceId' => $invoiceId, 'autoRedirect' => $request->request->get('autoRedirect', 1), 'hbeeSessionToken' => $session->get('token', 0)], UrlGenerator::ABSOLUTE_URL
  2516. //                    ),
  2517. //                    'cancel_url' => $this->generateUrl(
  2518. //                        'payment_gateway_cancel', ['invoiceId' => $invoiceId, 'autoRedirect' => $request->request->get('autoRedirect', 1), 'hbeeSessionToken' => $session->get('token', 0)], UrlGenerator::ABSOLUTE_URL
  2519. //                    ),
  2520. ////                    'opt_a' => 'Reshad',  //optional paramter
  2521. ////                    'opt_b' => 'Akil',
  2522. ////                    'opt_c' => 'Liza',
  2523. ////                    'opt_d' => 'Sohel',
  2524. ////                    'signature_key' => 'dbb74894e82415a2f7ff0ec3a97e4183',  //sandbox
  2525. //                    'signature_key' => $sandBoxMode == 1 ? 'dbb74894e82415a2f7ff0ec3a97e4183' : 'b7304a40e21fe15af3be9a948307f524'  //live
  2526. //
  2527. //                ); //signature key will provided aamarpay, contact integration@aamarpay.com for test/live signature key
  2528. //
  2529. //                $fields_string = http_build_query($fields);
  2530. //
  2531. //                $ch = curl_init();
  2532. //                curl_setopt($ch, CURLOPT_VERBOSE, true);
  2533. //                curl_setopt($ch, CURLOPT_URL, $url);
  2534. //
  2535. //                curl_setopt($ch, CURLOPT_POSTFIELDS, $fields_string);
  2536. //                curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
  2537. //                curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
  2538. //                $url_forward = str_replace('"', '', stripslashes(curl_exec($ch)));
  2539. //                curl_close($ch);
  2540. //                $this->redirect_to_merchant($url_forward);
  2541.             } else if ($paymentGatewayFromInvoice == 'onsite_pos' || $paymentGatewayFromInvoice == 'onsite_cash' || $paymentGatewayFromInvoice == 'onsite_bkash') {
  2542.                 $meetingId 0;
  2543.                 if ($gatewayInvoice->getId() != 0) {
  2544.                     if ($gatewayInvoice->getDueAmount() <= 0) {
  2545.                         $retData Buddybee::ProcessEntityInvoice($em_goc$gatewayInvoice->getId(), ['stage' => BuddybeeConstant::ENTITY_INVOICE_STAGE_COMPLETED], $this->container->getParameter('kernel.root_dir'), false,
  2546.                             $this->container->getParameter('notification_enabled'),
  2547.                             $this->container->getParameter('notification_server')
  2548.                         );
  2549.                         $meetingId $retData['meetingId'];
  2550.                     }
  2551.                     if (GeneralConstant::EMAIL_ENABLED == 1) {
  2552.                         $billerDetails = [];
  2553.                         $billToDetails = [];
  2554.                         $invoice $gatewayInvoice;
  2555.                         if ($invoice) {
  2556.                             $billerDetails $em->getRepository('CompanyGroupBundle\\Entity\\EntityApplicantDetails')
  2557.                                 ->findOneBy(
  2558.                                     array(
  2559.                                         'applicantId' => $invoice->getBillerId(),
  2560.                                     )
  2561.                                 );
  2562.                             $billToDetails $em->getRepository('CompanyGroupBundle\\Entity\\EntityApplicantDetails')
  2563.                                 ->findOneBy(
  2564.                                     array(
  2565.                                         'applicantId' => $invoice->getBillToId(),
  2566.                                     )
  2567.                                 );
  2568.                         }
  2569.                         $bodyTemplate 'ApplicationBundle:email/templates:buddybeeInvoiceEmail.html.twig';
  2570.                         $bodyData = array(
  2571.                             'page_title' => 'Invoice',
  2572. //            'studentDetails' => $student,
  2573.                             'billerDetails' => $billerDetails,
  2574.                             'billToDetails' => $billToDetails,
  2575.                             'invoice' => $invoice,
  2576.                             'currencyList' => BuddybeeConstant::$currency_List,
  2577.                             'currencyListByMarker' => BuddybeeConstant::$currency_List_by_marker,
  2578.                         );
  2579.                         $attachments = [];
  2580.                         $forwardToMailAddress $billToDetails->getOAuthEmail();
  2581. //                    $upl_dir = $this->container->getParameter('kernel.root_dir') . '/../web/uploads/temp/' . 'ledger' . '.pdf'
  2582.                         $new_mail $this->get('mail_module');
  2583.                         $new_mail->sendMyMail(array(
  2584.                             'senderHash' => '_CUSTOM_',
  2585.                             //                        'senderHash'=>'_CUSTOM_',
  2586.                             'forwardToMailAddress' => $forwardToMailAddress,
  2587.                             'subject' => 'YourInvoice #' 'D' str_pad('BB'5'0'STR_PAD_LEFT) . str_pad('76'2'0'STR_PAD_LEFT) . str_pad($invoice->getId(), 8"0"STR_PAD_LEFT) . ' from BuddyBee ',
  2588. //                        'fileName' => 'Order#' . str_pad($id, 8, '0', STR_PAD_LEFT) . '.pdf',
  2589.                             'attachments' => $attachments,
  2590.                             'toAddress' => $forwardToMailAddress,
  2591.                             'fromAddress' => 'no-reply@buddybee.eu',
  2592.                             'userName' => 'no-reply@buddybee.eu',
  2593.                             'password' => 'Honeybee@0112',
  2594.                             'smtpServer' => 'smtp.hostinger.com',
  2595.                             'smtpPort' => 465,
  2596. //                            'emailBody' => $bodyHtml,
  2597.                             'mailTemplate' => $bodyTemplate,
  2598.                             'templateData' => $bodyData,
  2599.                             'embedCompanyImage' => 0,
  2600.                             'companyId' => 0,
  2601.                             'companyImagePath' => ''
  2602. //                        'embedCompanyImage' => 1,
  2603. //                        'companyId' => $companyId,
  2604. //                        'companyImagePath' => $company_data->getImage()
  2605.                         ));
  2606.                     }
  2607.                 }
  2608.                 MiscActions::RefreshBuddybeeBalanceOnSession($em$request->getSession());
  2609.                 if ($meetingId != 0) {
  2610.                     $url $this->generateUrl(
  2611.                         'consultancy_session'
  2612.                     );
  2613.                     $output = [
  2614.                         'proceedToCheckout' => 0,
  2615.                         'invoiceId' => $gatewayInvoice->getId(),
  2616.                         'meetingId' => $meetingId,
  2617.                         'redirectUrl' => $url '/' $meetingId
  2618.                     ];
  2619.                 } else {
  2620.                     $url $this->generateUrl(
  2621.                         'buddybee_dashboard'
  2622.                     );
  2623.                     $output = [
  2624.                         'proceedToCheckout' => 0,
  2625.                         'invoiceId' => $gatewayInvoice->getId(),
  2626.                         'meetingId' => $meetingId,
  2627.                         'redirectUrl' => $url
  2628.                     ];
  2629.                 }
  2630.                 return new JsonResponse($output);
  2631.             }
  2632.         }
  2633.         $output = [
  2634.             'clientSecret' => 0,
  2635.             'id' => 0,
  2636.             'proceedToCheckout' => 0
  2637.         ];
  2638.         return new JsonResponse($output);
  2639. //        return $this->render('ApplicationBundle:pages/stripe:checkout.html.twig', array(
  2640. //            'page_title' => 'Checkout',
  2641. ////            'stripe' => $stripe,
  2642. //            'stripe' => null,
  2643. ////            'PaymentIntent' => $paymentIntent,
  2644. //
  2645. ////            'consultantDetail' => $consultantDetail,
  2646. ////            'consultantDetails'=> $consultantDetails,
  2647. ////
  2648. ////            'meetingSession' => $meetingSession,
  2649. ////            'packageDetails' => json_decode($meetingSession->getPcakageDetails(),true),
  2650. ////            'packageName' => json_decode($meetingSession->getPackageName(),true),
  2651. ////            'pay' => $payableAmount,
  2652. ////            'balance' => $currStudentBal
  2653. //        ));
  2654.     }
  2655.     public function PaymentGatewaySuccessAction(Request $request$encData '')
  2656.     {
  2657.         $em $this->getDoctrine()->getManager('company_group');
  2658.         $invoiceId 0;
  2659.         $autoRedirect 1;
  2660.         $redirectUrl '';
  2661.         $meetingId 0;
  2662.         $setupOnly 0;
  2663.         $appId 0;
  2664.         $ownerId 0;
  2665.         $systemType $this->container->hasParameter('system_type') ? $this->container->getParameter('system_type') : '_ERP_';
  2666.         if ($systemType == '_CENTRAL_') {
  2667.             if ($encData != '') {
  2668.                 $encryptedData json_decode($this->get('url_encryptor')->decrypt($encData), true);
  2669.                 if (isset($encryptedData['invoiceId']))
  2670.                     $invoiceId $encryptedData['invoiceId'];
  2671.                 if (isset($encryptedData['autoRedirect']))
  2672.                     $autoRedirect $encryptedData['autoRedirect'];
  2673.                 if (isset($encryptedData['setupOnly']))
  2674.                     $setupOnly = (int)$encryptedData['setupOnly'];
  2675.                 if (isset($encryptedData['appId']))
  2676.                     $appId = (int)$encryptedData['appId'];
  2677.                 if (isset($encryptedData['ownerId']))
  2678.                     $ownerId = (int)$encryptedData['ownerId'];
  2679.                 if (isset($encryptedData['redirectUrl']))
  2680.                     $redirectUrl $encryptedData['redirectUrl'];
  2681.             } else {
  2682.                 $invoiceId $request->query->get('invoiceId'0);
  2683.                 $meetingId 0;
  2684.                 $autoRedirect $request->query->get('autoRedirect'1);
  2685.                 $redirectUrl $request->query->get('redirectUrl''');
  2686.                 $setupOnly = (int)$request->query->get('setupOnly'0);
  2687.                 $appId = (int)$request->query->get('appId'0);
  2688.                 $ownerId = (int)$request->query->get('ownerId'0);
  2689.             }
  2690.             if ($setupOnly === 1) {
  2691.                 $sessionId $request->query->get('session_id');
  2692.                 if (!$sessionId) {
  2693.                     return $this->render('ApplicationBundle:pages/stripe:cancel.html.twig', array(
  2694.                         'page_title' => 'Failed',
  2695.                     ));
  2696.                 }
  2697.                 $stripeSession = \Stripe\Checkout\Session::retrieve($sessionId);
  2698.                 if (!$stripeSession || !$stripeSession->setup_intent) {
  2699.                     return $this->render('ApplicationBundle:pages/stripe:cancel.html.twig', array(
  2700.                         'page_title' => 'Failed',
  2701.                     ));
  2702.                 }
  2703.                 $setupIntent = \Stripe\SetupIntent::retrieve($stripeSession->setup_intent);
  2704.                 if ($setupIntent->status !== 'succeeded') {
  2705.                     return $this->render('ApplicationBundle:pages/stripe:cancel.html.twig', array(
  2706.                         'page_title' => 'Failed',
  2707.                     ));
  2708.                 }
  2709.                 $paymentMethodId $setupIntent->payment_method;
  2710.                 $customerId $setupIntent->customer;
  2711.                 if ($appId === && isset($stripeSession->metadata['app_id'])) {
  2712.                     $appId = (int)$stripeSession->metadata['app_id'];
  2713.                 }
  2714.                 if ($ownerId === && isset($stripeSession->metadata['owner_id'])) {
  2715.                     $ownerId = (int)$stripeSession->metadata['owner_id'];
  2716.                 }
  2717.                 if ($redirectUrl === '' && isset($stripeSession->metadata['redirect_url'])) {
  2718.                     $redirectUrl $stripeSession->metadata['redirect_url'];
  2719.                 }
  2720.                 $companyGroup null;
  2721.                 if ($appId !== 0) {
  2722.                     $companyGroup $em
  2723.                         ->getRepository("CompanyGroupBundle\\Entity\\CompanyGroup")
  2724.                         ->findOneBy([
  2725.                             'appId' => $appId
  2726.                         ]);
  2727.                 }
  2728.                 $existing $em->getRepository(PaymentMethod::class)
  2729.                     ->findOneBy([
  2730.                         'stripePaymentMethodId' => $paymentMethodId,
  2731.                         'appId' => $appId
  2732.                     ]);
  2733.                 if (!$existing) {
  2734.                     if ($companyGroup && !$companyGroup->getStripeCustomerId()) {
  2735.                         $companyGroup->setStripeCustomerId($customerId);
  2736.                     }
  2737.                     $paymentMethod = new PaymentMethod();
  2738.                     $paymentMethod->setAppId($appId);
  2739.                     $paymentMethod->setApplicantId($ownerId);
  2740.                     $paymentMethod->setStripeCustomerId($customerId);
  2741.                     $paymentMethod->setStripePaymentMethodId($paymentMethodId);
  2742.                     $paymentMethod->setIsDefault(1);
  2743.                     $em->persist($paymentMethod);
  2744.                     $em->flush();
  2745.                 }
  2746.                 if ($companyGroup) {
  2747.                     $em->flush();
  2748.                 }
  2749.                 $redirectUrl $redirectUrl !== '' $redirectUrl $this->generateUrl(
  2750.                     'central_landing'
  2751.                 );
  2752.                 return $this->render('ApplicationBundle:pages:stripe:success.html.twig', array(
  2753.                     'page_title' => 'Success',
  2754.                     'meetingId' => 0,
  2755.                     'autoRedirect' => 0,
  2756.                     'redirectUrl' => $redirectUrl,
  2757.                     'initiateCompany' => 1,
  2758.                     'appId' => $appId,
  2759.                     'ownerId' => $ownerId,
  2760.                     'setupOnly' => 1,
  2761.                 ));
  2762.             }
  2763.             if ($invoiceId != 0) {
  2764.                 $invoice $em
  2765.                     ->getRepository("CompanyGroupBundle\\Entity\\EntityInvoice")
  2766.                     ->findOneBy([
  2767.                         'id' => $invoiceId
  2768.                     ]);
  2769.                 if($invoice->getAmountTransferGateWayHash() == 'stripe') {
  2770.                     $stripeSession = \Stripe\Checkout\Session::retrieve($request->query->get('session_id'));
  2771.                     $paymentIntent = \Stripe\PaymentIntent::retrieve($stripeSession->payment_intent);
  2772.                     if ($paymentIntent->status !== 'succeeded') {
  2773.                         return $this->render('ApplicationBundle:pages/stripe:cancel.html.twig', array(
  2774.                             'page_title' => 'Failed',
  2775.                         ));
  2776.                     }
  2777.                     $paymentMethodId $paymentIntent->payment_method;
  2778.                     $customerId $paymentIntent->customer;
  2779.                     $companyGroup $this->get('app.quote_company_provisioning_service')
  2780.                         ->ensureCompanyForInvoice($invoice$request->getSession(), $customerId);
  2781.                     if (!isset($companyGroup) || !$companyGroup) {
  2782.                         $companyGroup $em
  2783.                             ->getRepository("CompanyGroupBundle\\Entity\\CompanyGroup")
  2784.                             ->findOneBy([
  2785.                                 'appId' => $invoice->getAppId()
  2786.                             ]);
  2787.                     }
  2788.                     $existing $em->getRepository(PaymentMethod::class)
  2789.                         ->findOneBy([
  2790.                             'stripePaymentMethodId' => $paymentMethodId
  2791.                         ]);
  2792.                     if (!$existing) {
  2793.                         if ($companyGroup) {
  2794.                             // save customer id (safety)
  2795.                             if (!$companyGroup->getStripeCustomerId()) {
  2796.                                 $companyGroup->setStripeCustomerId($customerId);
  2797.                             }
  2798.                             // save payment method
  2799.                             $paymentMethod = new PaymentMethod(); // your entity
  2800.                             $paymentMethod->setAppId($companyGroup->getAppId());;
  2801.                             $paymentMethod->setApplicantId($invoice->getApplicantId());
  2802.                             $paymentMethod->setStripeCustomerId($customerId);
  2803.                             $paymentMethod->setStripePaymentMethodId($paymentMethodId);
  2804.                             $paymentMethod->setIsDefault(1);
  2805.                             $em->persist($paymentMethod);
  2806.                             $em->flush();
  2807.                         }
  2808.                     }
  2809.                 }
  2810.                 $retData Buddybee::ProcessEntityInvoice($em$invoiceId, ['stage' => BuddybeeConstant::ENTITY_INVOICE_STAGE_COMPLETED],
  2811.                     $this->container->getParameter('kernel.root_dir'),
  2812.                     false,
  2813.                     $this->container->getParameter('notification_enabled'),
  2814.                     $this->container->getParameter('notification_server')
  2815.                 );
  2816.                 $this->get('app.subscription_state_sync_service')->syncFromLegacyInvoice($invoice);
  2817.                 if (($retData['initiateCompany'] ?? 0) == && ($retData['ownerId'] ?? 0) != 0) {
  2818.                     $this->get('app.post_payment_company_setup_service')
  2819.                         ->finalizeOwnerServerSync((int)$retData['ownerId']);
  2820.                 }
  2821.                 if ($retData['sendCards'] == 1) {
  2822.                     $cardList = array();
  2823.                     $cards $em->getRepository('CompanyGroupBundle\\Entity\\BeeCode')
  2824.                         ->findBy(
  2825.                             array(
  2826.                                 'id' => $retData['cardIds']
  2827.                             )
  2828.                         );
  2829.                     foreach ($cards as $card) {
  2830.                         $cardList[] = array(
  2831.                             'id' => $card->getId(),
  2832.                             'printed' => $card->getPrinted(),
  2833.                             'amount' => $card->getAmount(),
  2834.                             'coinCount' => $card->getCoinCount(),
  2835.                             'pin' => $card->getPin(),
  2836.                             'serial' => $card->getSerial(),
  2837.                         );
  2838.                     }
  2839.                     $receiverEmail $retData['receiverEmail'];
  2840.                     if (GeneralConstant::EMAIL_ENABLED == 1) {
  2841.                         $bodyHtml '';
  2842.                         $bodyTemplate 'ApplicationBundle:email/templates:beeCodeDigitalDelivery.html.twig';
  2843.                         $bodyData = array(
  2844.                             'cardList' => $cardList,
  2845. //                        'name' => $newApplicant->getFirstname() . ' ' . $newApplicant->getLastname(),
  2846. //                        'email' => $userName,
  2847. //                        'password' => $newApplicant->getPassword(),
  2848.                         );
  2849.                         $attachments = [];
  2850.                         $forwardToMailAddress $receiverEmail;
  2851. //                    $upl_dir = $this->container->getParameter('kernel.root_dir') . '/../web/uploads/temp/' . 'ledger' . '.pdf'
  2852.                         $new_mail $this->get('mail_module');
  2853.                         $new_mail->sendMyMail(array(
  2854.                             'senderHash' => '_CUSTOM_',
  2855.                             //                        'senderHash'=>'_CUSTOM_',
  2856.                             'forwardToMailAddress' => $forwardToMailAddress,
  2857.                             'subject' => 'Digital Bee Card Delivery',
  2858. //                        'fileName' => 'Order#' . str_pad($id, 8, '0', STR_PAD_LEFT) . '.pdf',
  2859.                             'attachments' => $attachments,
  2860.                             'toAddress' => $forwardToMailAddress,
  2861.                             'fromAddress' => 'delivery@buddybee.eu',
  2862.                             'userName' => 'delivery@buddybee.eu',
  2863.                             'password' => 'Honeybee@0112',
  2864.                             'smtpServer' => 'smtp.hostinger.com',
  2865.                             'smtpPort' => 465,
  2866. //                        'encryptionMethod' => 'tls',
  2867.                             'encryptionMethod' => 'ssl',
  2868. //                            'emailBody' => $bodyHtml,
  2869.                             'mailTemplate' => $bodyTemplate,
  2870.                             'templateData' => $bodyData,
  2871. //                        'embedCompanyImage' => 1,
  2872. //                        'companyId' => $companyId,
  2873. //                        'companyImagePath' => $company_data->getImage()
  2874.                         ));
  2875.                         foreach ($cards as $card) {
  2876.                             $card->setPrinted(1);
  2877.                         }
  2878.                         $em->flush();
  2879.                     }
  2880.                     return new JsonResponse(
  2881.                         array(
  2882.                             'success' => true
  2883.                         )
  2884.                     );
  2885.                 }
  2886.                 MiscActions::RefreshBuddybeeBalanceOnSession($em$request->getSession());
  2887.                 $meetingId $retData['meetingId'];
  2888.                 if (GeneralConstant::EMAIL_ENABLED == 1) {
  2889.                     $billerDetails = [];
  2890.                     $billToDetails = [];
  2891.                     $invoice $em->getRepository('CompanyGroupBundle\\Entity\\EntityInvoice')
  2892.                         ->findOneBy(
  2893.                             array(
  2894.                                 'Id' => $invoiceId,
  2895.                             )
  2896.                         );;
  2897.                     if ($invoice) {
  2898.                         $billerDetails $em->getRepository('CompanyGroupBundle\\Entity\\EntityApplicantDetails')
  2899.                             ->findOneBy(
  2900.                                 array(
  2901.                                     'applicantId' => $invoice->getBillerId(),
  2902.                                 )
  2903.                             );
  2904.                         $billToDetails $em->getRepository('CompanyGroupBundle\\Entity\\EntityApplicantDetails')
  2905.                             ->findOneBy(
  2906.                                 array(
  2907.                                     'applicantId' => $invoice->getBillToId(),
  2908.                                 )
  2909.                             );
  2910.                     }
  2911.                     $bodyTemplate 'ApplicationBundle:email/templates:buddybeeInvoiceEmail.html.twig';
  2912.                     $bodyData = array(
  2913.                         'page_title' => 'Invoice',
  2914. //            'studentDetails' => $student,
  2915.                         'billerDetails' => $billerDetails,
  2916.                         'billToDetails' => $billToDetails,
  2917.                         'invoice' => $invoice,
  2918.                         'currencyList' => BuddybeeConstant::$currency_List,
  2919.                         'currencyListByMarker' => BuddybeeConstant::$currency_List_by_marker,
  2920.                     );
  2921.                     $attachments = [];
  2922.                     $forwardToMailAddress $billToDetails->getOAuthEmail();
  2923. //                    $upl_dir = $this->container->getParameter('kernel.root_dir') . '/../web/uploads/temp/' . 'ledger' . '.pdf'
  2924.                     $new_mail $this->get('mail_module');
  2925.                     $new_mail->sendMyMail(array(
  2926.                         'senderHash' => '_CUSTOM_',
  2927.                         //                        'senderHash'=>'_CUSTOM_',
  2928.                         'forwardToMailAddress' => $forwardToMailAddress,
  2929.                         'subject' => 'YourInvoice #' 'D' str_pad('BB'5'0'STR_PAD_LEFT) . str_pad('76'2'0'STR_PAD_LEFT) . str_pad($invoice->getId(), 8"0"STR_PAD_LEFT) . ' from BuddyBee ',
  2930. //                        'fileName' => 'Order#' . str_pad($id, 8, '0', STR_PAD_LEFT) . '.pdf',
  2931.                         'attachments' => $attachments,
  2932.                         'toAddress' => $forwardToMailAddress,
  2933.                         'fromAddress' => 'no-reply@buddybee.eu',
  2934.                         'userName' => 'no-reply@buddybee.eu',
  2935.                         'password' => 'Honeybee@0112',
  2936.                         'smtpServer' => 'smtp.hostinger.com',
  2937.                         'smtpPort' => 465,
  2938. //                            'emailBody' => $bodyHtml,
  2939.                         'mailTemplate' => $bodyTemplate,
  2940.                         'templateData' => $bodyData,
  2941.                         'embedCompanyImage' => 0,
  2942.                         'companyId' => 0,
  2943.                         'companyImagePath' => ''
  2944. //                        'embedCompanyImage' => 1,
  2945. //                        'companyId' => $companyId,
  2946. //                        'companyImagePath' => $company_data->getImage()
  2947.                     ));
  2948.                 }
  2949. //
  2950.                 if ($meetingId != 0) {
  2951.                     $url $this->generateUrl(
  2952.                         'consultancy_session'
  2953.                     );
  2954. //                if($request->query->get('autoRedirect',1))
  2955. //                    return $this->redirect($url . '/' . $meetingId);
  2956.                     $redirectUrl $url '/' $meetingId;
  2957.                 } else {
  2958.                     $url $this->generateUrl(
  2959.                         'central_landing'
  2960.                     );
  2961. //                if($request->query->get('autoRedirect',1))
  2962. //                    return $this->redirect($url);
  2963.                     $redirectUrl $url;
  2964.                     $autoRedirect=0;
  2965.                 }
  2966.                 if (($retData['initiateCompany'] ?? 0) == && ($retData['appId'] ?? 0) != && ($retData['ownerId'] ?? 0) != 0) {
  2967.                     $companyGroup $em->getRepository("CompanyGroupBundle\\Entity\\CompanyGroup")
  2968.                         ->findOneBy([
  2969.                             'appId' => (int)$retData['appId']
  2970.                         ]);
  2971.                     if ($companyGroup) {
  2972.                         $postPaymentSetup $this->get('app.post_payment_company_setup_service');
  2973.                         $authenticationStr $this->get('url_encryptor')->encrypt(json_encode(
  2974.                             $postPaymentSetup->buildAuthenticationPayload((int)$retData['ownerId'], (int)$retData['appId'])
  2975.                         ));
  2976.                         $redirectUrl $postPaymentSetup->buildSwitchAppUrl(
  2977.                             (int)$retData['appId'],
  2978.                             (int)$retData['ownerId'],
  2979.                             (string)$companyGroup->getCompanyGroupServerAddress(),
  2980.                             $authenticationStr,
  2981.                             (string)$request->getSession()->get('csToken''')
  2982.                         );
  2983.                         $autoRedirect 1;
  2984.                     }
  2985.                 }
  2986.             }
  2987.             return $this->render('ApplicationBundle:pages/stripe:success.html.twig', array(
  2988.                 'page_title' => 'Success',
  2989.                 'meetingId' => $meetingId,
  2990.                 'autoRedirect' => $autoRedirect,
  2991.                 'redirectUrl' => $redirectUrl,
  2992.                 'initiateCompany' => $retData['initiateCompany']??0,
  2993.                 'appId' => $retData['appId']??0,
  2994.                 'ownerId' => $retData['ownerId']??0,
  2995.             ));
  2996.         }
  2997.         else if ($systemType == '_BUDDYBEE_') {
  2998.             if ($encData != '') {
  2999.                 $encryptedData json_decode($this->get('url_encryptor')->decrypt($encData), true);
  3000.                 if (isset($encryptedData['invoiceId']))
  3001.                     $invoiceId $encryptedData['invoiceId'];
  3002.                 if (isset($encryptedData['autoRedirect']))
  3003.                     $autoRedirect $encryptedData['autoRedirect'];
  3004.             } else {
  3005.                 $invoiceId $request->query->get('invoiceId'0);
  3006.                 $meetingId 0;
  3007.                 $autoRedirect $request->query->get('autoRedirect'1);
  3008.                 $redirectUrl '';
  3009.             }
  3010.             if ($invoiceId != 0) {
  3011.                 $retData Buddybee::ProcessEntityInvoice($em$invoiceId, ['stage' => BuddybeeConstant::ENTITY_INVOICE_STAGE_COMPLETED], false,
  3012.                     $this->container->getParameter('notification_enabled'),
  3013.                     $this->container->getParameter('notification_server')
  3014.                 );
  3015.                 if ($retData['sendCards'] == 1) {
  3016.                     $cardList = array();
  3017.                     $cards $em->getRepository('CompanyGroupBundle\\Entity\\BeeCode')
  3018.                         ->findBy(
  3019.                             array(
  3020.                                 'id' => $retData['cardIds']
  3021.                             )
  3022.                         );
  3023.                     foreach ($cards as $card) {
  3024.                         $cardList[] = array(
  3025.                             'id' => $card->getId(),
  3026.                             'printed' => $card->getPrinted(),
  3027.                             'amount' => $card->getAmount(),
  3028.                             'coinCount' => $card->getCoinCount(),
  3029.                             'pin' => $card->getPin(),
  3030.                             'serial' => $card->getSerial(),
  3031.                         );
  3032.                     }
  3033.                     $receiverEmail $retData['receiverEmail'];
  3034.                     if (GeneralConstant::EMAIL_ENABLED == 1) {
  3035.                         $bodyHtml '';
  3036.                         $bodyTemplate 'ApplicationBundle:email/templates:beeCodeDigitalDelivery.html.twig';
  3037.                         $bodyData = array(
  3038.                             'cardList' => $cardList,
  3039. //                        'name' => $newApplicant->getFirstname() . ' ' . $newApplicant->getLastname(),
  3040. //                        'email' => $userName,
  3041. //                        'password' => $newApplicant->getPassword(),
  3042.                         );
  3043.                         $attachments = [];
  3044.                         $forwardToMailAddress $receiverEmail;
  3045. //                    $upl_dir = $this->container->getParameter('kernel.root_dir') . '/../web/uploads/temp/' . 'ledger' . '.pdf'
  3046.                         $new_mail $this->get('mail_module');
  3047.                         $new_mail->sendMyMail(array(
  3048.                             'senderHash' => '_CUSTOM_',
  3049.                             //                        'senderHash'=>'_CUSTOM_',
  3050.                             'forwardToMailAddress' => $forwardToMailAddress,
  3051.                             'subject' => 'Digital Bee Card Delivery',
  3052. //                        'fileName' => 'Order#' . str_pad($id, 8, '0', STR_PAD_LEFT) . '.pdf',
  3053.                             'attachments' => $attachments,
  3054.                             'toAddress' => $forwardToMailAddress,
  3055.                             'fromAddress' => 'delivery@buddybee.eu',
  3056.                             'userName' => 'delivery@buddybee.eu',
  3057.                             'password' => 'Honeybee@0112',
  3058.                             'smtpServer' => 'smtp.hostinger.com',
  3059.                             'smtpPort' => 465,
  3060. //                        'encryptionMethod' => 'tls',
  3061.                             'encryptionMethod' => 'ssl',
  3062. //                            'emailBody' => $bodyHtml,
  3063.                             'mailTemplate' => $bodyTemplate,
  3064.                             'templateData' => $bodyData,
  3065. //                        'embedCompanyImage' => 1,
  3066. //                        'companyId' => $companyId,
  3067. //                        'companyImagePath' => $company_data->getImage()
  3068.                         ));
  3069.                         foreach ($cards as $card) {
  3070.                             $card->setPrinted(1);
  3071.                         }
  3072.                         $em->flush();
  3073.                     }
  3074.                     return new JsonResponse(
  3075.                         array(
  3076.                             'success' => true
  3077.                         )
  3078.                     );
  3079.                 }
  3080.                 MiscActions::RefreshBuddybeeBalanceOnSession($em$request->getSession());
  3081.                 $meetingId $retData['meetingId'];
  3082.                 if (GeneralConstant::EMAIL_ENABLED == 1) {
  3083.                     $billerDetails = [];
  3084.                     $billToDetails = [];
  3085.                     $invoice $em->getRepository('CompanyGroupBundle\\Entity\\EntityInvoice')
  3086.                         ->findOneBy(
  3087.                             array(
  3088.                                 'Id' => $invoiceId,
  3089.                             )
  3090.                         );;
  3091.                     if ($invoice) {
  3092.                         $billerDetails $em->getRepository('CompanyGroupBundle\\Entity\\EntityApplicantDetails')
  3093.                             ->findOneBy(
  3094.                                 array(
  3095.                                     'applicantId' => $invoice->getBillerId(),
  3096.                                 )
  3097.                             );
  3098.                         $billToDetails $em->getRepository('CompanyGroupBundle\\Entity\\EntityApplicantDetails')
  3099.                             ->findOneBy(
  3100.                                 array(
  3101.                                     'applicantId' => $invoice->getBillToId(),
  3102.                                 )
  3103.                             );
  3104.                     }
  3105.                     $bodyTemplate 'ApplicationBundle:email/templates:buddybeeInvoiceEmail.html.twig';
  3106.                     $bodyData = array(
  3107.                         'page_title' => 'Invoice',
  3108. //            'studentDetails' => $student,
  3109.                         'billerDetails' => $billerDetails,
  3110.                         'billToDetails' => $billToDetails,
  3111.                         'invoice' => $invoice,
  3112.                         'currencyList' => BuddybeeConstant::$currency_List,
  3113.                         'currencyListByMarker' => BuddybeeConstant::$currency_List_by_marker,
  3114.                     );
  3115.                     $attachments = [];
  3116.                     $forwardToMailAddress $billToDetails->getOAuthEmail();
  3117. //                    $upl_dir = $this->container->getParameter('kernel.root_dir') . '/../web/uploads/temp/' . 'ledger' . '.pdf'
  3118.                     $new_mail $this->get('mail_module');
  3119.                     $new_mail->sendMyMail(array(
  3120.                         'senderHash' => '_CUSTOM_',
  3121.                         //                        'senderHash'=>'_CUSTOM_',
  3122.                         'forwardToMailAddress' => $forwardToMailAddress,
  3123.                         'subject' => 'YourInvoice #' 'D' str_pad('BB'5'0'STR_PAD_LEFT) . str_pad('76'2'0'STR_PAD_LEFT) . str_pad($invoice->getId(), 8"0"STR_PAD_LEFT) . ' from BuddyBee ',
  3124. //                        'fileName' => 'Order#' . str_pad($id, 8, '0', STR_PAD_LEFT) . '.pdf',
  3125.                         'attachments' => $attachments,
  3126.                         'toAddress' => $forwardToMailAddress,
  3127.                         'fromAddress' => 'no-reply@buddybee.eu',
  3128.                         'userName' => 'no-reply@buddybee.eu',
  3129.                         'password' => 'Honeybee@0112',
  3130.                         'smtpServer' => 'smtp.hostinger.com',
  3131.                         'smtpPort' => 465,
  3132. //                            'emailBody' => $bodyHtml,
  3133.                         'mailTemplate' => $bodyTemplate,
  3134.                         'templateData' => $bodyData,
  3135.                         'embedCompanyImage' => 0,
  3136.                         'companyId' => 0,
  3137.                         'companyImagePath' => ''
  3138. //                        'embedCompanyImage' => 1,
  3139. //                        'companyId' => $companyId,
  3140. //                        'companyImagePath' => $company_data->getImage()
  3141.                     ));
  3142.                 }
  3143. //
  3144.                 if ($meetingId != 0) {
  3145.                     $url $this->generateUrl(
  3146.                         'consultancy_session'
  3147.                     );
  3148. //                if($request->query->get('autoRedirect',1))
  3149. //                    return $this->redirect($url . '/' . $meetingId);
  3150.                     $redirectUrl $url '/' $meetingId;
  3151.                 } else {
  3152.                     $url $this->generateUrl(
  3153.                         'buddybee_dashboard'
  3154.                     );
  3155. //                if($request->query->get('autoRedirect',1))
  3156. //                    return $this->redirect($url);
  3157.                     $redirectUrl $url;
  3158.                 }
  3159.             }
  3160.             return $this->render('ApplicationBundle:pages/stripe:success.html.twig', array(
  3161.                 'page_title' => 'Success',
  3162.                 'meetingId' => $meetingId,
  3163.                 'autoRedirect' => $autoRedirect,
  3164.                 'redirectUrl' => $redirectUrl,
  3165.             ));
  3166.         }
  3167.     }
  3168.     public function PaymentGatewayCancelAction(Request $request$msg 'The Payment was unsuccessful'$encData '')
  3169.     {
  3170.         $em $this->getDoctrine()->getManager('company_group');
  3171. //        $consultantDetail = $em->getRepository('CompanyGroupBundle\\Entity\\EntityApplicantDetails')->findOneBy(array());
  3172.         $session $request->getSession();
  3173.         if ($msg == '')
  3174.             $msg $request->query->get('msg'$request->request->get('msg''The Payment was unsuccessful'));
  3175.         return $this->render('ApplicationBundle:pages/stripe:cancel.html.twig', array(
  3176.             'page_title' => 'Success',
  3177.             'msg' => $msg,
  3178.         ));
  3179.     }
  3180.     public function BkashCallbackAction(Request $request$encData '')
  3181.     {
  3182.         $em $this->getDoctrine()->getManager('company_group');
  3183.         $invoiceId 0;
  3184.         $session $request->getSession();
  3185.         $sandBoxMode $this->container->hasParameter('sand_box_mode') ? $this->container->getParameter('sand_box_mode') : 0;
  3186.         $paymentId $request->query->get('paymentID'0);
  3187.         $status $request->query->get('status'0);
  3188.         if ($status == 'success') {
  3189.             $paymentID $paymentId;
  3190.             $gatewayInvoice $em->getRepository('CompanyGroupBundle\\Entity\\EntityInvoice')->findOneBy(
  3191.                 array(
  3192.                     'gatewayPaymentId' => $paymentId,
  3193.                     'isProcessed' => [02]
  3194.                 ));
  3195.             if ($gatewayInvoice) {
  3196.                 $invoiceId $gatewayInvoice->getId();
  3197.                 $justNow = new \DateTime();
  3198.                 $baseUrl = ($sandBoxMode == 1) ? 'https://tokenized.sandbox.bka.sh/v1.2.0-beta' 'https://tokenized.pay.bka.sh/v1.2.0-beta';
  3199.                 $username_value = ($sandBoxMode == 1) ? 'sandboxTokenizedUser02' '01891962953';
  3200.                 $password_value = ($sandBoxMode == 1) ? 'sandboxTokenizedUser02@12345' ',a&kPV4deq&';
  3201.                 $app_key_value = ($sandBoxMode == 1) ? '4f6o0cjiki2rfm34kfdadl1eqq' '2ueVHdwz5gH3nxx7xn8wotlztc';
  3202.                 $app_secret_value = ($sandBoxMode == 1) ? '2is7hdktrekvrbljjh44ll3d9l1dtjo4pasmjvs5vl5qr3fug4b' '49Ay3h3wWJMBFD7WF5CassyLrtA1jt6ONhspqjqFx5hTjhqh5dHU';
  3203.                 $justNowTs $justNow->format('U');
  3204.                 if ($gatewayInvoice->getGatewayIdTokenExpireTs() <= $justNowTs) {
  3205.                     $refresh_token $gatewayInvoice->getGatewayIdRefreshToken();
  3206.                     $request_data = array(
  3207.                         'app_key' => $app_key_value,
  3208.                         'app_secret' => $app_secret_value,
  3209.                         'refresh_token' => $refresh_token
  3210.                     );
  3211.                     $url curl_init($baseUrl '/tokenized/checkout/token/refresh');
  3212.                     $request_data_json json_encode($request_data);
  3213.                     $header = array(
  3214.                         'Content-Type:application/json',
  3215.                         'username:' $username_value,
  3216.                         'password:' $password_value
  3217.                     );
  3218.                     curl_setopt($urlCURLOPT_HTTPHEADER$header);
  3219.                     curl_setopt($urlCURLOPT_CUSTOMREQUEST"POST");
  3220.                     curl_setopt($urlCURLOPT_RETURNTRANSFERtrue);
  3221.                     curl_setopt($urlCURLOPT_POSTFIELDS$request_data_json);
  3222.                     curl_setopt($urlCURLOPT_FOLLOWLOCATION1);
  3223.                     curl_setopt($urlCURLOPT_IPRESOLVECURL_IPRESOLVE_V4);
  3224.                     $tokenData json_decode(curl_exec($url), true);
  3225.                     curl_close($url);
  3226.                     $justNow = new \DateTime();
  3227.                     $justNow->modify('+' $tokenData['expires_in'] . ' second');
  3228.                     $gatewayInvoice->setGatewayIdTokenExpireTs($justNow->format('U'));
  3229.                     $gatewayInvoice->setGatewayIdToken($tokenData['id_token']);
  3230.                     $gatewayInvoice->setGatewayIdRefreshToken($tokenData['refresh_token']);
  3231.                     $em->flush();
  3232.                 }
  3233.                 $auth $gatewayInvoice->getGatewayIdToken();;
  3234.                 $post_token = array(
  3235.                     'paymentID' => $paymentID
  3236.                 );
  3237. //                $url = curl_init();
  3238.                 $url curl_init($baseUrl '/tokenized/checkout/execute');
  3239.                 $posttoken json_encode($post_token);
  3240.                 $header = array(
  3241.                     'Content-Type:application/json',
  3242.                     'Authorization:' $auth,
  3243.                     'X-APP-Key:' $app_key_value
  3244.                 );
  3245. //                curl_setopt_array($url, array(
  3246. //                    CURLOPT_HTTPHEADER => $header,
  3247. //                    CURLOPT_RETURNTRANSFER => 1,
  3248. //                    CURLOPT_URL => $baseUrl . '/tokenized/checkout/execute',
  3249. //
  3250. //                    CURLOPT_FOLLOWLOCATION => 1,
  3251. //                    CURLOPT_POST => 1,
  3252. //                    CURLOPT_IPRESOLVE => CURL_IPRESOLVE_V4,
  3253. //                    CURLOPT_POSTFIELDS => http_build_query($post_token)
  3254. //                ));
  3255.                 curl_setopt($urlCURLOPT_HTTPHEADER$header);
  3256.                 curl_setopt($urlCURLOPT_CUSTOMREQUEST"POST");
  3257.                 curl_setopt($urlCURLOPT_RETURNTRANSFERtrue);
  3258.                 curl_setopt($urlCURLOPT_POSTFIELDS$posttoken);
  3259.                 curl_setopt($urlCURLOPT_FOLLOWLOCATION1);
  3260.                 curl_setopt($urlCURLOPT_IPRESOLVECURL_IPRESOLVE_V4);
  3261.                 $resultdata curl_exec($url);
  3262.                 curl_close($url);
  3263.                 $obj json_decode($resultdatatrue);
  3264. //                return new JsonResponse(array(
  3265. //                    'obj' => $obj,
  3266. //                    'url' => $baseUrl . '/tokenized/checkout/execute',
  3267. //                    'header' => $header,
  3268. //                    'paymentID' => $paymentID,
  3269. //                    'posttoken' => $posttoken,
  3270. //                ));
  3271. //                                return new JsonResponse($obj);
  3272.                 if (isset($obj['statusCode'])) {
  3273.                     if ($obj['statusCode'] == '0000') {
  3274.                         $gatewayInvoice->setGatewayTransId($obj['trxID']);
  3275.                         $em->flush();
  3276.                         return $this->redirectToRoute("payment_gateway_success", ['encData' => $this->get('url_encryptor')->encrypt(json_encode(array(
  3277.                             'invoiceId' => $invoiceId'autoRedirect' => 1
  3278.                         ))),
  3279.                             'hbeeSessionToken' => $session->get('token'0)]);
  3280.                     } else {
  3281.                         return $this->redirectToRoute("payment_gateway_cancel", [
  3282.                             'msg' => isset($obj['statusMessage']) ? $obj['statusMessage'] : (isset($obj['errorMessage']) ? $obj['errorMessage'] : 'Payment Failed')
  3283.                         ]);
  3284.                     }
  3285.                 }
  3286.             } else {
  3287.                 return $this->redirectToRoute("payment_gateway_cancel", [
  3288.                     'msg' => isset($obj['statusMessage']) ? $obj['statusMessage'] : (isset($obj['errorMessage']) ? $obj['errorMessage'] : 'Payment Failed')
  3289.                 ]);
  3290.             }
  3291.         } else {
  3292.             return $this->redirectToRoute("payment_gateway_cancel", [
  3293.                 'msg' => isset($obj['statusMessage']) ? $obj['statusMessage'] : (isset($obj['errorMessage']) ? $obj['errorMessage'] : 'The Payment was unsuccessful')
  3294.             ]);
  3295.         }
  3296.     }
  3297.     public function MakePaymentOfEntityInvoiceAction(Request $request$encData '')
  3298.     {
  3299.         $em $this->getDoctrine()->getManager('company_group');
  3300.         $em_goc $em;
  3301.         $invoiceId 0;
  3302.         $autoRedirect 1;
  3303.         $redirectUrl '';
  3304.         $meetingId 0;
  3305.         $triggerMiddlePage 0;
  3306.         $session $request->getSession();
  3307.         $sandBoxMode $this->container->hasParameter('sand_box_mode') ? $this->container->getParameter('sand_box_mode') : 0;
  3308.         $refundSuccess 0;
  3309.         $errorMsg '';
  3310.         $errorCode '';
  3311.         if ($encData != '') {
  3312.             $invoiceId $encData;
  3313.             $encryptedData json_decode($this->get('url_encryptor')->decrypt($encData), true);
  3314.             if (isset($encryptedData['invoiceId']))
  3315.                 $invoiceId $encryptedData['invoiceId'];
  3316.             if (isset($encryptedData['triggerMiddlePage']))
  3317.                 $triggerMiddlePage $encryptedData['triggerMiddlePage'];
  3318.             if (isset($encryptedData['autoRedirect']))
  3319.                 $autoRedirect $encryptedData['autoRedirect'];
  3320.         } else {
  3321.             $invoiceId $request->request->get('invoiceId'$request->query->get('invoiceId'0));
  3322.             $triggerMiddlePage $request->request->get('triggerMiddlePage'$request->query->get('triggerMiddlePage'0));
  3323.             $meetingId 0;
  3324.             $autoRedirect $request->query->get('autoRedirect'1);
  3325.             $redirectUrl '';
  3326.         }
  3327.         $meetingId $request->request->get('meetingId'$request->query->get('meetingId'0));
  3328.         $actionDone 0;
  3329.         if ($meetingId != 0) {
  3330.             $dt Buddybee::ConfirmAnyMeetingSessionIfPossible($em0$meetingIdfalse,
  3331.                 $this->container->getParameter('notification_enabled'),
  3332.                 $this->container->getParameter('notification_server'));
  3333.             if ($invoiceId == && $dt['success'] == true) {
  3334.                 $actionDone 1;
  3335.                 return new JsonResponse(array(
  3336.                     'clientSecret' => 0,
  3337.                     'actionDone' => $actionDone,
  3338.                     'id' => 0,
  3339.                     'proceedToCheckout' => 0
  3340.                 ));
  3341.             }
  3342.         }
  3343. //        $invoiceId = $request->request->get('meetingId', $request->query->get('meetingId', 0));
  3344.         $output = [
  3345.             'clientSecret' => 0,
  3346.             'id' => 0,
  3347.             'proceedToCheckout' => 0
  3348.         ];
  3349.         if ($invoiceId != 0) {
  3350.             $gatewayInvoice $em->getRepository('CompanyGroupBundle\\Entity\\EntityInvoice')->findOneBy(
  3351.                 array(
  3352.                     'Id' => $invoiceId,
  3353.                     'isProcessed' => [0]
  3354.                 ));
  3355.         } else {
  3356.             $gatewayInvoice $em->getRepository('CompanyGroupBundle\\Entity\\EntityInvoice')->findOneBy(
  3357.                 array(
  3358.                     'meetingId' => $meetingId,
  3359.                     'isProcessed' => [0]
  3360.                 ));
  3361.         }
  3362.         if ($gatewayInvoice)
  3363.             $invoiceId $gatewayInvoice->getId();
  3364.         $invoiceSessionCount 0;
  3365.         $payableAmount 0;
  3366.         $imageBySessionCount = [
  3367.             => "https://www.buddybee.eu/buddybee_assets/ADULT-BEE.png",
  3368.             100 => "https://www.buddybee.eu/buddybee_assets/ADULT-BEE.png",
  3369.             200 => "https://www.buddybee.eu/buddybee_assets/ADULT-BEE.png",
  3370.             300 => "https://www.buddybee.eu/buddybee_assets/ADULT-BEE.png",
  3371.             400 => "https://www.buddybee.eu/buddybee_assets/ADULT-BEE.png",
  3372.             500 => "https://www.buddybee.eu/buddybee_assets/ADULT-BEE.png",
  3373.             600 => "https://www.buddybee.eu/buddybee_assets/ADULT-BEE.png",
  3374.             700 => "https://www.buddybee.eu/buddybee_assets/ADULT-BEE.png",
  3375.             800 => "https://www.buddybee.eu/buddybee_assets/ADULT-BEE.png",
  3376.             900 => "https://www.buddybee.eu/buddybee_assets/ADULT-BEE.png",
  3377.             1000 => "https://www.buddybee.eu/buddybee_assets/ADULT-BEE.png",
  3378.             1100 => "https://www.buddybee.eu/buddybee_assets/ADULT-BEE.png",
  3379.             1200 => "https://www.buddybee.eu/buddybee_assets/ADULT-BEE.png",
  3380.             1300 => "https://www.buddybee.eu/buddybee_assets/ADULT-BEE.png",
  3381.             1400 => "https://www.buddybee.eu/buddybee_assets/ADULT-BEE.png",
  3382.             1500 => "https://www.buddybee.eu/buddybee_assets/ADULT-BEE.png",
  3383.             1600 => "https://www.buddybee.eu/buddybee_assets/ADULT-BEE.png",
  3384.             1700 => "https://www.buddybee.eu/buddybee_assets/ADULT-BEE.png",
  3385.             1800 => "https://www.buddybee.eu/buddybee_assets/ADULT-BEE.png",
  3386.             1900 => "https://www.buddybee.eu/buddybee_assets/ADULT-BEE.png",
  3387.             2000 => "https://www.buddybee.eu/buddybee_assets/ADULT-BEE.png",
  3388.             2100 => "https://www.buddybee.eu/buddybee_assets/ADULT-BEE.png",
  3389.             2200 => "https://www.buddybee.eu/buddybee_assets/ADULT-BEE.png",
  3390.             2300 => "https://www.buddybee.eu/buddybee_assets/ADULT-BEE.png",
  3391.             2400 => "https://www.buddybee.eu/buddybee_assets/ADULT-BEE.png",
  3392.             2500 => "https://www.buddybee.eu/buddybee_assets/ADULT-BEE.png",
  3393.             2600 => "https://www.buddybee.eu/buddybee_assets/ADULT-BEE.png",
  3394.             2700 => "https://www.buddybee.eu/buddybee_assets/ADULT-BEE.png",
  3395.             2800 => "https://www.buddybee.eu/buddybee_assets/ADULT-BEE.png",
  3396.             2900 => "https://www.buddybee.eu/buddybee_assets/ADULT-BEE.png",
  3397.             3000 => "https://www.buddybee.eu/buddybee_assets/ADULT-BEE.png",
  3398.             3100 => "https://www.buddybee.eu/buddybee_assets/ADULT-BEE.png",
  3399.             3200 => "https://www.buddybee.eu/buddybee_assets/ADULT-BEE.png",
  3400.             3300 => "https://www.buddybee.eu/buddybee_assets/ADULT-BEE.png",
  3401.             3400 => "https://www.buddybee.eu/buddybee_assets/ADULT-BEE.png",
  3402.             3500 => "https://www.buddybee.eu/buddybee_assets/ADULT-BEE.png",
  3403.             3600 => "https://www.buddybee.eu/buddybee_assets/ADULT-BEE.png",
  3404.             3700 => "https://www.buddybee.eu/buddybee_assets/ADULT-BEE.png",
  3405.         ];
  3406.         if ($gatewayInvoice) {
  3407.             $gatewayProductData json_decode($gatewayInvoice->getProductDataForPaymentGateway(), true);
  3408.             if ($gatewayProductData == null$gatewayProductData = [];
  3409.             $gatewayAmount number_format($gatewayInvoice->getGateWayBillamount(), 2'.''');
  3410.             $invoiceSessionCount $gatewayInvoice->getSessionCount();
  3411.             $currencyForGateway $gatewayInvoice->getAmountCurrency();
  3412.             $gatewayAmount round($gatewayAmount2);
  3413.             if (empty($gatewayProductData))
  3414.                 $gatewayProductData = [
  3415.                     [
  3416.                         'price_data' => [
  3417.                             'currency' => 'eur',
  3418.                             'unit_amount' => $gatewayAmount != ? (100 $gatewayAmount) : 200000,
  3419.                             'product_data' => [
  3420. //                            'name' => $request->request->has('packageName') ? $request->request->get('packageName') : 'Advanced Consultancy Package',
  3421.                                 'name' => 'Bee Coins',
  3422. //                                'images' => [$imageBySessionCount[$invoiceSessionCount]],
  3423.                                 'images' => [$imageBySessionCount[0]],
  3424.                             ],
  3425.                         ],
  3426.                         'quantity' => 1,
  3427.                     ]
  3428.                 ];
  3429.             $productDescStr '';
  3430.             $productDescArr = [];
  3431.             foreach ($gatewayProductData as $gpd) {
  3432.                 $productDescArr[] = $gpd['price_data']['product_data']['name'];
  3433.             }
  3434.             $productDescStr implode(','$productDescArr);
  3435.             $paymentGatewayFromInvoice $gatewayInvoice->getAmountTransferGateWayHash();
  3436.             if ($paymentGatewayFromInvoice == 'stripe') {
  3437.                 $stripe = new \Stripe\Stripe();
  3438.                 \Stripe\Stripe::setApiKey('sk_test_51IxYTAJXs21fVb0QMop2Nb0E7u9Da4LwGrym1nGHUHqaSNtT3p9HBgHd7YyDsTKHscgPPECPQniTy79Ab8Sgxfbm00JF2AndUz');
  3439.                 $stripe::setApiKey('sk_test_51IxYTAJXs21fVb0QMop2Nb0E7u9Da4LwGrym1nGHUHqaSNtT3p9HBgHd7YyDsTKHscgPPECPQniTy79Ab8Sgxfbm00JF2AndUz');
  3440.                 {
  3441.                     if ($request->query->has('meetingSessionId'))
  3442.                         $id $request->query->get('meetingSessionId');
  3443.                 }
  3444.                 $paymentIntent = [
  3445.                     "id" => "pi_1DoWjK2eZvKYlo2Csy9J3BHs",
  3446.                     "object" => "payment_intent",
  3447.                     "amount" => 3000,
  3448.                     "amount_capturable" => 0,
  3449.                     "amount_received" => 0,
  3450.                     "application" => null,
  3451.                     "application_fee_amount" => null,
  3452.                     "canceled_at" => null,
  3453.                     "cancellation_reason" => null,
  3454.                     "capture_method" => "automatic",
  3455.                     "charges" => [
  3456.                         "object" => "list",
  3457.                         "data" => [],
  3458.                         "has_more" => false,
  3459.                         "url" => "/v1/charges?payment_intent=pi_1DoWjK2eZvKYlo2Csy9J3BHs"
  3460.                     ],
  3461.                     "client_secret" => "pi_1DoWjK2eZvKYlo2Csy9J3BHs_secret_vmxAcWZxo2kt1XhpWtZtnjDtd",
  3462.                     "confirmation_method" => "automatic",
  3463.                     "created" => 1546523966,
  3464.                     "currency" => $currencyForGateway,
  3465.                     "customer" => null,
  3466.                     "description" => null,
  3467.                     "invoice" => null,
  3468.                     "last_payment_error" => null,
  3469.                     "livemode" => false,
  3470.                     "metadata" => [],
  3471.                     "next_action" => null,
  3472.                     "on_behalf_of" => null,
  3473.                     "payment_method" => null,
  3474.                     "payment_method_options" => [],
  3475.                     "payment_method_types" => [
  3476.                         "card"
  3477.                     ],
  3478.                     "receipt_email" => null,
  3479.                     "review" => null,
  3480.                     "setup_future_usage" => null,
  3481.                     "shipping" => null,
  3482.                     "statement_descriptor" => null,
  3483.                     "statement_descriptor_suffix" => null,
  3484.                     "status" => "requires_payment_method",
  3485.                     "transfer_data" => null,
  3486.                     "transfer_group" => null
  3487.                 ];
  3488.                 $checkout_session = \Stripe\Checkout\Session::create([
  3489.                     'payment_method_types' => ['card'],
  3490.                     'line_items' => $gatewayProductData,
  3491.                     'mode' => 'payment',
  3492.                     'success_url' => $this->generateUrl(
  3493.                         'payment_gateway_success',
  3494.                         ['encData' => $this->get('url_encryptor')->encrypt(json_encode(array(
  3495.                             'invoiceId' => $invoiceId'autoRedirect' => $request->request->get('autoRedirect'1)
  3496.                         ))), 'hbeeSessionToken' => $session->get('token'0)], UrlGenerator::ABSOLUTE_URL
  3497.                     ),
  3498.                     'cancel_url' => $this->generateUrl(
  3499.                         'payment_gateway_cancel', ['invoiceId' => $invoiceId'autoRedirect' => $request->request->get('autoRedirect'1), 'hbeeSessionToken' => $session->get('token'0)], UrlGenerator::ABSOLUTE_URL
  3500.                     ),
  3501.                 ]);
  3502.                 $output = [
  3503.                     'clientSecret' => $paymentIntent['client_secret'],
  3504.                     'id' => $checkout_session->id,
  3505.                     'paymentGateway' => $paymentGatewayFromInvoice,
  3506.                     'proceedToCheckout' => 1
  3507.                 ];
  3508. //                return new JsonResponse($output);
  3509.             }
  3510.             if ($paymentGatewayFromInvoice == 'aamarpay') {
  3511.                 $studentDetails $em_goc->getRepository(EntityApplicantDetails::class)->find($gatewayInvoice->getBillToId());
  3512.                 $url $sandBoxMode == 'https://sandbox.aamarpay.com/request.php' 'https://secure.aamarpay.com/request.php';
  3513.                 $fields = array(
  3514. //                    'store_id' => 'aamarpaytest', //store id will be aamarpay,  contact integration@aamarpay.com for test/live id
  3515.                     'store_id' => $sandBoxMode == 'aamarpaytest' 'buddybee'//store id will be aamarpay,  contact integration@aamarpay.com for test/live id
  3516.                     'amount' => number_format($gatewayInvoice->getGateWayBillamount(), 2'.'''), //transaction amount
  3517.                     'payment_type' => 'VISA'//no need to change
  3518.                     'currency' => strtoupper($currencyForGateway),  //currenct will be USD/BDT
  3519.                     'tran_id' => 'BEI' str_pad($gatewayInvoice->getBillerId(), 3'0'STR_PAD_LEFT) . str_pad($gatewayInvoice->getBillToId(), 5'0'STR_PAD_LEFT) . str_pad($gatewayInvoice->getId(), 4'0'STR_PAD_LEFT), //transaction id must be unique from your end
  3520.                     'cus_name' => $studentDetails->getFirstname() . ' ' $studentDetails->getLastName(),  //customer name
  3521.                     'cus_email' => $studentDetails->getEmail(), //customer email address
  3522.                     'cus_add1' => $studentDetails->getCurrAddr(),  //customer address
  3523.                     'cus_add2' => $studentDetails->getCurrAddrCity(), //customer address
  3524.                     'cus_city' => $studentDetails->getCurrAddrCity(),  //customer city
  3525.                     'cus_state' => $studentDetails->getCurrAddrState(),  //state
  3526.                     'cus_postcode' => $studentDetails->getCurrAddrZip(), //postcode or zipcode
  3527.                     'cus_country' => 'Bangladesh',  //country
  3528.                     'cus_phone' => ($studentDetails->getPhone() == null || $studentDetails->getPhone() == '') ? '+8801911706483' $studentDetails->getPhone(), //customer phone number
  3529.                     'cus_fax' => '',  //fax
  3530.                     'ship_name' => ''//ship name
  3531.                     'ship_add1' => '',  //ship address
  3532.                     'ship_add2' => '',
  3533.                     'ship_city' => '',
  3534.                     'ship_state' => '',
  3535.                     'ship_postcode' => '',
  3536.                     'ship_country' => 'Bangladesh',
  3537.                     'desc' => $productDescStr,
  3538.                     'success_url' => $this->generateUrl(
  3539.                         'payment_gateway_success',
  3540.                         ['encData' => $this->get('url_encryptor')->encrypt(json_encode(array(
  3541.                             'invoiceId' => $invoiceId'autoRedirect' => $request->request->get('autoRedirect'1)
  3542.                         ))), 'hbeeSessionToken' => $session->get('token'0)], UrlGenerator::ABSOLUTE_URL
  3543.                     ),
  3544.                     'fail_url' => $this->generateUrl(
  3545.                         'payment_gateway_cancel', ['invoiceId' => $invoiceId'autoRedirect' => $request->request->get('autoRedirect'1), 'hbeeSessionToken' => $session->get('token'0)], UrlGenerator::ABSOLUTE_URL
  3546.                     ),
  3547.                     'cancel_url' => $this->generateUrl(
  3548.                         'payment_gateway_cancel', ['invoiceId' => $invoiceId'autoRedirect' => $request->request->get('autoRedirect'1), 'hbeeSessionToken' => $session->get('token'0)], UrlGenerator::ABSOLUTE_URL
  3549.                     ),
  3550. //                    'opt_a' => 'Reshad',  //optional paramter
  3551. //                    'opt_b' => 'Akil',
  3552. //                    'opt_c' => 'Liza',
  3553. //                    'opt_d' => 'Sohel',
  3554. //                    'signature_key' => 'dbb74894e82415a2f7ff0ec3a97e4183',  //sandbox
  3555.                     'signature_key' => $sandBoxMode == 'dbb74894e82415a2f7ff0ec3a97e4183' 'b7304a40e21fe15af3be9a948307f524'  //live
  3556.                 ); //signature key will provided aamarpay, contact integration@aamarpay.com for test/live signature key
  3557.                 $fields_string http_build_query($fields);
  3558.                 $ch curl_init();
  3559.                 curl_setopt($chCURLOPT_VERBOSEtrue);
  3560.                 curl_setopt($chCURLOPT_URL$url);
  3561.                 curl_setopt($chCURLOPT_POSTFIELDS$fields_string);
  3562.                 curl_setopt($chCURLOPT_RETURNTRANSFERtrue);
  3563.                 curl_setopt($chCURLOPT_SSL_VERIFYPEERfalse);
  3564.                 $url_forward str_replace('"'''stripslashes(curl_exec($ch)));
  3565.                 curl_close($ch);
  3566. //                $this->redirect_to_merchant($url_forward);
  3567.                 $output = [
  3568. //                    'redirectUrl' => 'https://sandbox.aamarpay.com/'.$url_forward, //keeping it off temporarily
  3569.                     'redirectUrl' => ($sandBoxMode == 'https://sandbox.aamarpay.com/' 'https://secure.aamarpay.com/') . $url_forward//keeping it off temporarily
  3570. //                    'fields'=>$fields,
  3571. //                    'fields_string'=>$fields_string,
  3572. //                    'redirectUrl' => $this->generateUrl(
  3573. //                        'payment_gateway_success',
  3574. //                        ['encData' => $this->get('url_encryptor')->encrypt(json_encode(array(
  3575. //                            'invoiceId' => $invoiceId, 'autoRedirect' => $request->request->get('autoRedirect', 1)
  3576. //                        ))), 'hbeeSessionToken' => $request->request->get('token', 0)], UrlGenerator::ABSOLUTE_URL
  3577. //                    ),
  3578.                     'paymentGateway' => $paymentGatewayFromInvoice,
  3579.                     'proceedToCheckout' => 1
  3580.                 ];
  3581. //                return new JsonResponse($output);
  3582.             } else if ($paymentGatewayFromInvoice == 'bkash') {
  3583.                 $studentDetails $em_goc->getRepository(EntityApplicantDetails::class)->find($gatewayInvoice->getBillToId());
  3584.                 $baseUrl = ($sandBoxMode == 1) ? 'https://tokenized.sandbox.bka.sh/v1.2.0-beta' 'https://tokenized.pay.bka.sh/v1.2.0-beta';
  3585.                 $username_value = ($sandBoxMode == 1) ? 'sandboxTokenizedUser02' '01891962953';
  3586.                 $password_value = ($sandBoxMode == 1) ? 'sandboxTokenizedUser02@12345' ',a&kPV4deq&';
  3587.                 $app_key_value = ($sandBoxMode == 1) ? '4f6o0cjiki2rfm34kfdadl1eqq' '2ueVHdwz5gH3nxx7xn8wotlztc';
  3588.                 $app_secret_value = ($sandBoxMode == 1) ? '2is7hdktrekvrbljjh44ll3d9l1dtjo4pasmjvs5vl5qr3fug4b' '49Ay3h3wWJMBFD7WF5CassyLrtA1jt6ONhspqjqFx5hTjhqh5dHU';
  3589.                 $request_data = array(
  3590.                     'app_key' => $app_key_value,
  3591.                     'app_secret' => $app_secret_value
  3592.                 );
  3593.                 $url curl_init($baseUrl '/tokenized/checkout/token/grant');
  3594.                 $request_data_json json_encode($request_data);
  3595.                 $header = array(
  3596.                     'Content-Type:application/json',
  3597.                     'username:' $username_value,
  3598.                     'password:' $password_value
  3599.                 );
  3600.                 curl_setopt($urlCURLOPT_HTTPHEADER$header);
  3601.                 curl_setopt($urlCURLOPT_CUSTOMREQUEST"POST");
  3602.                 curl_setopt($urlCURLOPT_RETURNTRANSFERtrue);
  3603.                 curl_setopt($urlCURLOPT_POSTFIELDS$request_data_json);
  3604.                 curl_setopt($urlCURLOPT_FOLLOWLOCATION1);
  3605.                 curl_setopt($urlCURLOPT_IPRESOLVECURL_IPRESOLVE_V4);
  3606.                 $tokenData json_decode(curl_exec($url), true);
  3607.                 curl_close($url);
  3608.                 $id_token $tokenData['id_token'];
  3609.                 $goToBkashPage 0;
  3610.                 if ($tokenData['statusCode'] == '0000') {
  3611.                     $auth $id_token;
  3612.                     $requestbody = array(
  3613.                         "mode" => "0011",
  3614. //                        "payerReference" => "",
  3615.                         "payerReference" => $gatewayInvoice->getInvoiceDateTs(),
  3616.                         "callbackURL" => $this->generateUrl(
  3617.                             'bkash_callback', [], UrlGenerator::ABSOLUTE_URL
  3618.                         ),
  3619. //                    "merchantAssociationInfo" => "MI05MID54RF09123456One",
  3620.                         "amount" => number_format($gatewayInvoice->getGateWayBillamount(), 2'.'''),
  3621.                         "currency" => "BDT",
  3622.                         "intent" => "sale",
  3623.                         "merchantInvoiceNumber" => $invoiceId
  3624.                     );
  3625.                     $url curl_init($baseUrl '/tokenized/checkout/create');
  3626.                     $requestbodyJson json_encode($requestbody);
  3627.                     $header = array(
  3628.                         'Content-Type:application/json',
  3629.                         'Authorization:' $auth,
  3630.                         'X-APP-Key:' $app_key_value
  3631.                     );
  3632.                     curl_setopt($urlCURLOPT_HTTPHEADER$header);
  3633.                     curl_setopt($urlCURLOPT_CUSTOMREQUEST"POST");
  3634.                     curl_setopt($urlCURLOPT_RETURNTRANSFERtrue);
  3635.                     curl_setopt($urlCURLOPT_POSTFIELDS$requestbodyJson);
  3636.                     curl_setopt($urlCURLOPT_FOLLOWLOCATION1);
  3637.                     curl_setopt($urlCURLOPT_IPRESOLVECURL_IPRESOLVE_V4);
  3638.                     $resultdata curl_exec($url);
  3639.                     curl_close($url);
  3640. //                    return new JsonResponse($resultdata);
  3641.                     $obj json_decode($resultdatatrue);
  3642.                     $goToBkashPage 1;
  3643.                     $justNow = new \DateTime();
  3644.                     $justNow->modify('+' $tokenData['expires_in'] . ' second');
  3645.                     $gatewayInvoice->setGatewayIdTokenExpireTs($justNow->format('U'));
  3646.                     $gatewayInvoice->setGatewayIdToken($tokenData['id_token']);
  3647.                     $gatewayInvoice->setGatewayPaymentId($obj['paymentID']);
  3648.                     $gatewayInvoice->setGatewayIdRefreshToken($tokenData['refresh_token']);
  3649.                     $em->flush();
  3650.                     $output = [
  3651.                         'redirectUrl' => $obj['bkashURL'],
  3652.                         'paymentGateway' => $paymentGatewayFromInvoice,
  3653.                         'proceedToCheckout' => $goToBkashPage,
  3654.                         'tokenData' => $tokenData,
  3655.                         'obj' => $obj,
  3656.                         'id_token' => $tokenData['id_token'],
  3657.                     ];
  3658.                 }
  3659. //                $fields = array(
  3660. //
  3661. //                    "mode" => "0011",
  3662. //                    "payerReference" => "01723888888",
  3663. //                    "callbackURL" => $this->generateUrl(
  3664. //                        'payment_gateway_success',
  3665. //                        ['encData' => $this->get('url_encryptor')->encrypt(json_encode(array(
  3666. //                            'invoiceId' => $invoiceId, 'autoRedirect' => $request->request->get('autoRedirect', 1)
  3667. //                        ))), 'hbeeSessionToken' => $session->get('token', 0)], UrlGenerator::ABSOLUTE_URL
  3668. //                    ),
  3669. //                    "merchantAssociationInfo" => "MI05MID54RF09123456One",
  3670. //                    "amount" => $gatewayInvoice->getGateWayBillamount(),
  3671. //                    "currency" => "BDT",
  3672. //                    "intent" => "sale",
  3673. //                    "merchantInvoiceNumber" => 'BEI' . str_pad($gatewayInvoice->getBillerId(), 3, '0', STR_PAD_LEFT) . str_pad($gatewayInvoice->getBillToId(), 5, '0', STR_PAD_LEFT) . str_pad($gatewayInvoice->getId(), 4, '0', STR_PAD_LEFT)
  3674. //
  3675. //                );
  3676. //                $fields = array(
  3677. ////                    'store_id' => 'aamarpaytest', //store id will be aamarpay,  contact integration@aamarpay.com for test/live id
  3678. //                    'store_id' => $sandBoxMode == 1 ? 'aamarpaytest' : 'buddybee', //store id will be aamarpay,  contact integration@aamarpay.com for test/live id
  3679. //                    'amount' => $gatewayInvoice->getGateWayBillamount(), //transaction amount
  3680. //                    'payment_type' => 'VISA', //no need to change
  3681. //                    'currency' => strtoupper($currencyForGateway),  //currenct will be USD/BDT
  3682. //                    'tran_id' => 'BEI' . str_pad($gatewayInvoice->getBillerId(), 3, '0', STR_PAD_LEFT) . str_pad($gatewayInvoice->getBillToId(), 5, '0', STR_PAD_LEFT) . str_pad($gatewayInvoice->getId(), 4, '0', STR_PAD_LEFT), //transaction id must be unique from your end
  3683. //                    'cus_name' => $studentDetails->getFirstname() . ' ' . $studentDetails->getLastName(),  //customer name
  3684. //                    'cus_email' => $studentDetails->getEmail(), //customer email address
  3685. //                    'cus_add1' => $studentDetails->getCurrAddr(),  //customer address
  3686. //                    'cus_add2' => $studentDetails->getCurrAddrCity(), //customer address
  3687. //                    'cus_city' => $studentDetails->getCurrAddrCity(),  //customer city
  3688. //                    'cus_state' => $studentDetails->getCurrAddrState(),  //state
  3689. //                    'cus_postcode' => $studentDetails->getCurrAddrZip(), //postcode or zipcode
  3690. //                    'cus_country' => 'Bangladesh',  //country
  3691. //                    'cus_phone' => ($studentDetails->getPhone() == null || $studentDetails->getPhone() == '') ? ' + 8801911706483' : $studentDetails->getPhone(), //customer phone number
  3692. //                    'cus_fax' => '',  //fax
  3693. //                    'ship_name' => '', //ship name
  3694. //                    'ship_add1' => '',  //ship address
  3695. //                    'ship_add2' => '',
  3696. //                    'ship_city' => '',
  3697. //                    'ship_state' => '',
  3698. //                    'ship_postcode' => '',
  3699. //                    'ship_country' => 'Bangladesh',
  3700. //                    'desc' => $productDescStr,
  3701. //                    'success_url' => $this->generateUrl(
  3702. //                        'payment_gateway_success',
  3703. //                        ['encData' => $this->get('url_encryptor')->encrypt(json_encode(array(
  3704. //                            'invoiceId' => $invoiceId, 'autoRedirect' => $request->request->get('autoRedirect', 1)
  3705. //                        ))), 'hbeeSessionToken' => $session->get('token', 0)], UrlGenerator::ABSOLUTE_URL
  3706. //                    ),
  3707. //                    'fail_url' => $this->generateUrl(
  3708. //                        'payment_gateway_cancel', ['invoiceId' => $invoiceId, 'autoRedirect' => $request->request->get('autoRedirect', 1), 'hbeeSessionToken' => $session->get('token', 0)], UrlGenerator::ABSOLUTE_URL
  3709. //                    ),
  3710. //                    'cancel_url' => $this->generateUrl(
  3711. //                        'payment_gateway_cancel', ['invoiceId' => $invoiceId, 'autoRedirect' => $request->request->get('autoRedirect', 1), 'hbeeSessionToken' => $session->get('token', 0)], UrlGenerator::ABSOLUTE_URL
  3712. //                    ),
  3713. ////                    'opt_a' => 'Reshad',  //optional paramter
  3714. ////                    'opt_b' => 'Akil',
  3715. ////                    'opt_c' => 'Liza',
  3716. ////                    'opt_d' => 'Sohel',
  3717. ////                    'signature_key' => 'dbb74894e82415a2f7ff0ec3a97e4183',  //sandbox
  3718. //                    'signature_key' => $sandBoxMode == 1 ? 'dbb74894e82415a2f7ff0ec3a97e4183' : 'b7304a40e21fe15af3be9a948307f524'  //live
  3719. //
  3720. //                ); //signature key will provided aamarpay, contact integration@aamarpay.com for test/live signature key
  3721. //
  3722. //                $fields_string = http_build_query($fields);
  3723. //
  3724. //                $ch = curl_init();
  3725. //                curl_setopt($ch, CURLOPT_VERBOSE, true);
  3726. //                curl_setopt($ch, CURLOPT_URL, $url);
  3727. //
  3728. //                curl_setopt($ch, CURLOPT_POSTFIELDS, $fields_string);
  3729. //                curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
  3730. //                curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
  3731. //                $url_forward = str_replace('"', '', stripslashes(curl_exec($ch)));
  3732. //                curl_close($ch);
  3733. //                $this->redirect_to_merchant($url_forward);
  3734.             }
  3735.         }
  3736.         if ($triggerMiddlePage == 1) return $this->render('@Buddybee/pages/makePaymentOfEntityInvoiceLandingPage.html.twig', array(
  3737.             'page_title' => 'Invoice Payment',
  3738.             'data' => $output,
  3739.         ));
  3740.         else
  3741.             return new JsonResponse($output);
  3742.     }
  3743.     public function RefundEntityInvoiceAction(Request $request$encData '')
  3744.     {
  3745.         $em $this->getDoctrine()->getManager('company_group');
  3746.         $invoiceId 0;
  3747.         $currIsProcessedFlagValue '_UNSET_';
  3748.         $session $request->getSession();
  3749.         $sandBoxMode $this->container->hasParameter('sand_box_mode') ? $this->container->getParameter('sand_box_mode') : 0;
  3750.         $paymentId $request->query->get('paymentID'0);
  3751.         $status $request->query->get('status'0);
  3752.         $refundSuccess 0;
  3753.         $errorMsg '';
  3754.         $errorCode '';
  3755.         if ($encData != '') {
  3756.             $invoiceId $encData;
  3757.             $encryptedData json_decode($this->get('url_encryptor')->decrypt($encData), true);
  3758.             if (isset($encryptedData['invoiceId']))
  3759.                 $invoiceId $encryptedData['invoiceId'];
  3760.             if (isset($encryptedData['autoRedirect']))
  3761.                 $autoRedirect $encryptedData['autoRedirect'];
  3762.         } else {
  3763.             $invoiceId $request->request->get('invoiceId'$request->query->get('invoiceId'0));
  3764.             $meetingId 0;
  3765.             $autoRedirect $request->query->get('autoRedirect'1);
  3766.             $redirectUrl '';
  3767.         }
  3768.         $gatewayInvoice $em->getRepository('CompanyGroupBundle\\Entity\\EntityInvoice')->findOneBy(
  3769.             array(
  3770.                 'Id' => $invoiceId,
  3771.                 'isProcessed' => [1]
  3772.             ));
  3773.         if ($gatewayInvoice) {
  3774.             $gatewayInvoice->setIsProcessed(3); //pending settlement
  3775.             $currIsProcessedFlagValue $gatewayInvoice->getIsProcessed();
  3776.             $em->flush();
  3777.             if ($gatewayInvoice->getAmountTransferGateWayHash() == 'bkash') {
  3778.                 $invoiceId $gatewayInvoice->getId();
  3779.                 $paymentID $gatewayInvoice->getGatewayPaymentId();
  3780.                 $trxID $gatewayInvoice->getGatewayTransId();
  3781.                 $justNow = new \DateTime();
  3782.                 $baseUrl = ($sandBoxMode == 1) ? 'https://tokenized.sandbox.bka.sh/v1.2.0-beta' 'https://tokenized.pay.bka.sh/v1.2.0-beta';
  3783.                 $username_value = ($sandBoxMode == 1) ? 'sandboxTokenizedUser02' '01891962953';
  3784.                 $password_value = ($sandBoxMode == 1) ? 'sandboxTokenizedUser02@12345' ',a&kPV4deq&';
  3785.                 $app_key_value = ($sandBoxMode == 1) ? '4f6o0cjiki2rfm34kfdadl1eqq' '2ueVHdwz5gH3nxx7xn8wotlztc';
  3786.                 $app_secret_value = ($sandBoxMode == 1) ? '2is7hdktrekvrbljjh44ll3d9l1dtjo4pasmjvs5vl5qr3fug4b' '49Ay3h3wWJMBFD7WF5CassyLrtA1jt6ONhspqjqFx5hTjhqh5dHU';
  3787.                 $justNowTs $justNow->format('U');
  3788.                 if ($gatewayInvoice->getGatewayIdTokenExpireTs() <= $justNowTs) {
  3789.                     $refresh_token $gatewayInvoice->getGatewayIdRefreshToken();
  3790.                     $request_data = array(
  3791.                         'app_key' => $app_key_value,
  3792.                         'app_secret' => $app_secret_value,
  3793.                         'refresh_token' => $refresh_token
  3794.                     );
  3795.                     $url curl_init($baseUrl '/tokenized/checkout/token/refresh');
  3796.                     $request_data_json json_encode($request_data);
  3797.                     $header = array(
  3798.                         'Content-Type:application/json',
  3799.                         'username:' $username_value,
  3800.                         'password:' $password_value
  3801.                     );
  3802.                     curl_setopt($urlCURLOPT_HTTPHEADER$header);
  3803.                     curl_setopt($urlCURLOPT_CUSTOMREQUEST"POST");
  3804.                     curl_setopt($urlCURLOPT_RETURNTRANSFERtrue);
  3805.                     curl_setopt($urlCURLOPT_POSTFIELDS$request_data_json);
  3806.                     curl_setopt($urlCURLOPT_FOLLOWLOCATION1);
  3807.                     curl_setopt($urlCURLOPT_IPRESOLVECURL_IPRESOLVE_V4);
  3808.                     $tokenData json_decode(curl_exec($url), true);
  3809.                     curl_close($url);
  3810.                     $justNow = new \DateTime();
  3811.                     $justNow->modify('+' $tokenData['expires_in'] . ' second');
  3812.                     $gatewayInvoice->setGatewayIdTokenExpireTs($justNow->format('U'));
  3813.                     $gatewayInvoice->setGatewayIdToken($tokenData['id_token']);
  3814.                     $gatewayInvoice->setGatewayIdRefreshToken($tokenData['refresh_token']);
  3815.                     $em->flush();
  3816.                 }
  3817.                 $auth $gatewayInvoice->getGatewayIdToken();;
  3818.                 $post_token = array(
  3819.                     'paymentID' => $paymentID,
  3820.                     'trxID' => $trxID,
  3821.                     'reason' => 'Full Refund Policy',
  3822.                     'sku' => 'RSTR',
  3823.                     'amount' => number_format($gatewayInvoice->getGateWayBillamount(), 2'.'''),
  3824.                 );
  3825.                 $url curl_init($baseUrl '/tokenized/checkout/payment/refund');
  3826.                 $posttoken json_encode($post_token);
  3827.                 $header = array(
  3828.                     'Content-Type:application/json',
  3829.                     'Authorization:' $auth,
  3830.                     'X-APP-Key:' $app_key_value
  3831.                 );
  3832.                 curl_setopt($urlCURLOPT_HTTPHEADER$header);
  3833.                 curl_setopt($urlCURLOPT_CUSTOMREQUEST"POST");
  3834.                 curl_setopt($urlCURLOPT_RETURNTRANSFERtrue);
  3835.                 curl_setopt($urlCURLOPT_POSTFIELDS$posttoken);
  3836.                 curl_setopt($urlCURLOPT_FOLLOWLOCATION1);
  3837.                 curl_setopt($urlCURLOPT_IPRESOLVECURL_IPRESOLVE_V4);
  3838.                 $resultdata curl_exec($url);
  3839.                 curl_close($url);
  3840.                 $obj json_decode($resultdatatrue);
  3841. //                return new JsonResponse($obj);
  3842.                 if (isset($obj['completedTime']))
  3843.                     $refundSuccess 1;
  3844.                 else if (isset($obj['errorCode'])) {
  3845.                     $refundSuccess 0;
  3846.                     $errorCode $obj['errorCode'];
  3847.                     $errorMsg $obj['errorMessage'];
  3848.                 }
  3849. //                    $gatewayInvoice->setGatewayTransId($obj['trxID']);
  3850.                 $em->flush();
  3851.             }
  3852.             if ($refundSuccess == 1) {
  3853.                 Buddybee::RefundEntityInvoice($em$invoiceId);
  3854.                 $currIsProcessedFlagValue 4;
  3855.             }
  3856.         } else {
  3857.         }
  3858.         MiscActions::RefreshBuddybeeBalanceOnSession($em$request->getSession());
  3859.         return new JsonResponse(
  3860.             array(
  3861.                 'success' => $refundSuccess,
  3862.                 'errorCode' => $errorCode,
  3863.                 'isProcessed' => $currIsProcessedFlagValue,
  3864.                 'errorMsg' => $errorMsg,
  3865.             )
  3866.         );
  3867.     }
  3868.     public function ViewEntityInvoiceAction(Request $request$encData '')
  3869.     {
  3870.         $em $this->getDoctrine()->getManager('company_group');
  3871.         $invoiceId 0;
  3872.         $autoRedirect 1;
  3873.         $redirectUrl '';
  3874.         $meetingId 0;
  3875.         $invoice null;
  3876.         if ($encData != '') {
  3877.             $encryptedData json_decode($this->get('url_encryptor')->decrypt($encData), true);
  3878.             $invoiceId $encData;
  3879.             if (isset($encryptedData['invoiceId']))
  3880.                 $invoiceId $encryptedData['invoiceId'];
  3881.             if (isset($encryptedData['autoRedirect']))
  3882.                 $autoRedirect $encryptedData['autoRedirect'];
  3883.         } else {
  3884.             $invoiceId $request->query->get('invoiceId'0);
  3885.             $meetingId 0;
  3886.             $autoRedirect $request->query->get('autoRedirect'1);
  3887.             $redirectUrl '';
  3888.         }
  3889. //    $invoiceList = [];
  3890.         $billerDetails = [];
  3891.         $billToDetails = [];
  3892.         if ($invoiceId != 0) {
  3893.             $invoice $em->getRepository('CompanyGroupBundle\\Entity\\EntityInvoice')
  3894.                 ->findOneBy(
  3895.                     array(
  3896.                         'Id' => $invoiceId,
  3897.                     )
  3898.                 );
  3899.             if ($invoice) {
  3900.                 $billerDetails $em->getRepository('CompanyGroupBundle\\Entity\\EntityApplicantDetails')
  3901.                     ->findOneBy(
  3902.                         array(
  3903.                             'applicantId' => $invoice->getBillerId(),
  3904.                         )
  3905.                     );
  3906.                 $billToDetails $em->getRepository('CompanyGroupBundle\\Entity\\EntityApplicantDetails')
  3907.                     ->findOneBy(
  3908.                         array(
  3909.                             'applicantId' => $invoice->getBillToId(),
  3910.                         )
  3911.                     );
  3912.             }
  3913.             if ($request->query->get('sendMail'0) == && GeneralConstant::EMAIL_ENABLED == 1) {
  3914.                 $billerDetails = [];
  3915.                 $billToDetails = [];
  3916.                 if ($invoice) {
  3917.                     $billerDetails $em->getRepository('CompanyGroupBundle\\Entity\\EntityApplicantDetails')
  3918.                         ->findOneBy(
  3919.                             array(
  3920.                                 'applicantId' => $invoice->getBillerId(),
  3921.                             )
  3922.                         );
  3923.                     $billToDetails $em->getRepository('CompanyGroupBundle\\Entity\\EntityApplicantDetails')
  3924.                         ->findOneBy(
  3925.                             array(
  3926.                                 'applicantId' => $invoice->getBillToId(),
  3927.                             )
  3928.                         );
  3929.                     $bodyTemplate 'ApplicationBundle:email/templates:buddybeeInvoiceEmail.html.twig';
  3930.                     $bodyData = array(
  3931.                         'page_title' => 'Invoice',
  3932. //            'studentDetails' => $student,
  3933.                         'billerDetails' => $billerDetails,
  3934.                         'billToDetails' => $billToDetails,
  3935.                         'invoice' => $invoice,
  3936.                         'currencyList' => BuddybeeConstant::$currency_List,
  3937.                         'currencyListByMarker' => BuddybeeConstant::$currency_List_by_marker,
  3938.                     );
  3939.                     $attachments = [];
  3940.                     $forwardToMailAddress $billToDetails->getOAuthEmail();
  3941. //                    $upl_dir = $this->container->getParameter('kernel.root_dir') . '/../web/uploads/temp/' . 'ledger' . '.pdf'
  3942.                     $new_mail $this->get('mail_module');
  3943.                     $new_mail->sendMyMail(array(
  3944.                         'senderHash' => '_CUSTOM_',
  3945.                         //                        'senderHash'=>'_CUSTOM_',
  3946.                         'forwardToMailAddress' => $forwardToMailAddress,
  3947.                         'subject' => 'YourInvoice #' 'D' str_pad('BB'5'0'STR_PAD_LEFT) . str_pad('76'2'0'STR_PAD_LEFT) . str_pad($invoice->getId(), 8"0"STR_PAD_LEFT) . ' from BuddyBee ',
  3948. //                        'fileName' => 'Order#' . str_pad($id, 8, '0', STR_PAD_LEFT) . '.pdf',
  3949.                         'attachments' => $attachments,
  3950.                         'toAddress' => $forwardToMailAddress,
  3951.                         'fromAddress' => 'no-reply@buddybee.eu',
  3952.                         'userName' => 'no-reply@buddybee.eu',
  3953.                         'password' => 'Honeybee@0112',
  3954.                         'smtpServer' => 'smtp.hostinger.com',
  3955.                         'smtpPort' => 465,
  3956. //                            'emailBody' => $bodyHtml,
  3957.                         'mailTemplate' => $bodyTemplate,
  3958.                         'templateData' => $bodyData,
  3959.                         'embedCompanyImage' => 0,
  3960.                         'companyId' => 0,
  3961.                         'companyImagePath' => ''
  3962. //                        'embedCompanyImage' => 1,
  3963. //                        'companyId' => $companyId,
  3964. //                        'companyImagePath' => $company_data->getImage()
  3965.                     ));
  3966.                 }
  3967.             }
  3968. //            if ($invoice) {
  3969. //
  3970. //            } else {
  3971. //                return $this->render('@Buddybee/pages/404NotFound.html.twig', array(
  3972. //                    'page_title' => '404 Not Found',
  3973. //
  3974. //                ));
  3975. //            }
  3976.             return $this->render('@HoneybeeWeb/pages/views/honeybee_ecosystem_invoice.html.twig', array(
  3977.                 'page_title' => 'Invoice',
  3978. //            'studentDetails' => $student,
  3979.                 'billerDetails' => $billerDetails,
  3980.                 'billToDetails' => $billToDetails,
  3981.                 'invoice' => $invoice,
  3982.                 'currencyList' => BuddybeeConstant::$currency_List,
  3983.                 'currencyListByMarker' => BuddybeeConstant::$currency_List_by_marker,
  3984.             ));
  3985.         }
  3986.     }
  3987.     public function SignatureCheckFromCentralAction(Request $request)
  3988.     {
  3989.         $systemType $this->container->hasParameter('system_type') ? $this->container->getParameter('system_type') : '_ERP_';
  3990.         if ($systemType !== '_CENTRAL_') {
  3991.             return new JsonResponse(['success' => false'message' => 'Only allowed on CENTRAL server.'], 403);
  3992.         }
  3993.         $em $this->getDoctrine()->getManager('company_group');
  3994.         $em->getConnection()->connect();
  3995.         $data json_decode($request->getContent(), true);
  3996.         if (
  3997.             !$data ||
  3998.             !isset($data['userId']) ||
  3999.             !isset($data['companyId']) ||
  4000.             !isset($data['signatureData']) ||
  4001.             !isset($data['approvalHash']) ||
  4002.             !isset($data['applicantId'])
  4003.         ) {
  4004.             return new JsonResponse(['success' => false'message' => 'Missing parameters.'], 400);
  4005.         }
  4006.         $userId $data['userId'];
  4007.         $companyId $data['companyId'];
  4008.         $signatureData $data['signatureData'];
  4009.         $approvalHash $data['approvalHash'];
  4010.         $applicantId $data['applicantId'];
  4011.         try {
  4012.             $centralUser $em
  4013.                 ->getRepository("CompanyGroupBundle\\Entity\\EntityApplicantDetails")
  4014.                 ->findOneBy(['applicantId' => $applicantId]);
  4015.             if (!$centralUser) {
  4016.                 return new JsonResponse(['success' => false'message' => 'Central user not found.'], 404);
  4017.             }
  4018.             $userAppIds json_decode($centralUser->getUserAppIds(), true);
  4019.             if (!is_array($userAppIds)) $userAppIds = [];
  4020.             $companies $em->getRepository('CompanyGroupBundle\\Entity\\CompanyGroup')->findBy([
  4021.                 'appId' => $userAppIds
  4022.             ]);
  4023.             if (count($companies) < 1) {
  4024.                 return new JsonResponse(['success' => false'message' => 'No companies found for userAppIds.'], 404);
  4025.             }
  4026.             $repo $em->getRepository('CompanyGroupBundle\\Entity\\EntitySignature');
  4027.             $record $repo->findOneBy(['userId' => $userId]);
  4028.             if (!$record) {
  4029.                 $record = new \CompanyGroupBundle\Entity\EntitySignature();
  4030.                 $record->setUserId($applicantId);
  4031.                 $record->setCreatedAt(new \DateTime());
  4032.             }
  4033.             $record->setCompanyId($companyId);
  4034.             $record->setApplicantId($applicantId);
  4035.             $record->setData($signatureData);
  4036.             $record->setSigExists(0);
  4037.             $record->setLastDecryptedSigId(0);
  4038.             $record->setUpdatedAt(new \DateTime());
  4039.             $em->persist($record);
  4040.             $em->flush();
  4041.             $dataByServerId = [];
  4042.             $gocDataListByAppId = [];
  4043.             foreach ($companies as $entry) {
  4044.                 $gocDataListByAppId[$entry->getAppId()] = [
  4045.                     'dbName' => $entry->getDbName(),
  4046.                     'dbUser' => $entry->getDbUser(),
  4047.                     'dbPass' => $entry->getDbPass(),
  4048.                     'dbHost' => $entry->getDbHost(),
  4049.                     'serverAddress' => $entry->getCompanyGroupServerAddress(),
  4050.                     'port' => $entry->getCompanyGroupServerPort() ?: 80,
  4051.                     'appId' => $entry->getAppId(),
  4052.                     'serverId' => $entry->getCompanyGroupServerId(),
  4053.                 ];
  4054.                 if (!isset($dataByServerId[$entry->getCompanyGroupServerId()]))
  4055.                     $dataByServerId[$entry->getCompanyGroupServerId()] = array(
  4056.                         'serverId' => $entry->getCompanyGroupServerId(),
  4057.                         'serverAddress' => $entry->getCompanyGroupServerAddress(),
  4058.                         'port' => $entry->getCompanyGroupServerPort() ?: 80,
  4059.                         'payload' => array(
  4060.                             'globalId' => $applicantId,
  4061.                             'companyId' => $userAppIds,
  4062.                             'signatureData' => $signatureData,
  4063. //                                      'approvalHash' => $approvalHash
  4064.                         )
  4065.                     );
  4066.             }
  4067.             $urls = [];
  4068.             foreach ($dataByServerId as $entry) {
  4069.                 $serverAddress $entry['serverAddress'];
  4070.                 if (!$serverAddress) continue;
  4071. //                     $connector = $this->container->get('application_connector');
  4072. //                     $connector->resetConnection(
  4073. //                         'default',
  4074. //                         $entry['dbName'],
  4075. //                         $entry['dbUser'],
  4076. //                         $entry['dbPass'],
  4077. //                         $entry['dbHost'],
  4078. //                         $reset = true
  4079. //                     );
  4080.                 $syncUrl $serverAddress '/ReceiveSignatureFromCentral';
  4081.                 $payload $entry['payload'];
  4082.                 $curl curl_init();
  4083.                 curl_setopt_array($curl, [
  4084.                     CURLOPT_RETURNTRANSFER => true,
  4085.                     CURLOPT_POST => true,
  4086.                     CURLOPT_URL => $syncUrl,
  4087. //                         CURLOPT_PORT => $entry['port'],
  4088.                     CURLOPT_CONNECTTIMEOUT => 10,
  4089.                     CURLOPT_SSL_VERIFYPEER => false,
  4090.                     CURLOPT_SSL_VERIFYHOST => false,
  4091.                     CURLOPT_HTTPHEADER => [
  4092.                         'Accept: application/json',
  4093.                         'Content-Type: application/json'
  4094.                     ],
  4095.                     CURLOPT_POSTFIELDS => json_encode($payload)
  4096.                 ]);
  4097.                 $response curl_exec($curl);
  4098.                 $err curl_error($curl);
  4099.                 $httpCode curl_getinfo($curlCURLINFO_HTTP_CODE);
  4100.                 curl_close($curl);
  4101. //                     if ($err) {
  4102. //                         error_log("ERP Sync Error [AppID $appId]: $err");
  4103. //                          $urls[]=$err;
  4104. //                     } else {
  4105. //                         error_log("ERP Sync Response [AppID $appId] (HTTP $httpCode): $response");
  4106. //                         $res = json_decode($response, true);
  4107. //                         if (!isset($res['success']) || !$res['success']) {
  4108. //                             error_log("❗ ERP Sync error for AppID $appId: " . ($res['message'] ?? 'Unknown'));
  4109. //                         }
  4110. //
  4111. //                      $urls[]=$response;
  4112. //                     }
  4113.             }
  4114.             return new JsonResponse(['success' => true'message' => 'Signature synced successfully.']);
  4115.         } catch (\Exception $e) {
  4116.             return new JsonResponse(['success' => false'message' => 'DB error: ' $e->getMessage()], 500);
  4117.         }
  4118.     }
  4119.  //datev cntroller
  4120.     public function connectDatev(Request $request)
  4121.     {
  4122.         $clientId "51b09bdcf577c5b998cddce7fe7d5c92";
  4123.         $redirectUri "https://ourhoneybee.eu/datev/callback";
  4124.         $state bin2hex(random_bytes(10));
  4125.         $scope "openid profile email accounting:documents accounting:dxso-jobs accounting:clients:read datev:accounting:extf-files-import datev:accounting:clients";
  4126.         $codeVerifier bin2hex(random_bytes(32));
  4127.         $codeChallenge rtrim(strtr(base64_encode(hash('sha256'$codeVerifiertrue)), '+/''-_'), '=');
  4128.         $session $request->getSession();
  4129.         $applicantId $session->get(UserConstants::APPLICANT_ID);
  4130.         $em_goc $this->getDoctrine()->getManager('company_group');
  4131.         $token $em_goc->getRepository('CompanyGroupBundle\\Entity\\EntityDatevToken')
  4132.             ->findOneBy(['userId' => $applicantId]);
  4133.         if (!$token) {
  4134.             $token = new EntityDatevToken();
  4135.             $token->setUserId($applicantId);
  4136.         }
  4137.         $token->setState($state);
  4138.         $token->setCodeChallenge($codeChallenge);
  4139.         $token->setCodeVerifier($codeVerifier);
  4140.         $em_goc->persist($token);
  4141.         $em_goc->flush();
  4142.         $url "https://login.datev.de/openidsandbox/authorize?"
  4143.             ."response_type=code"
  4144.             ."&client_id=".$clientId
  4145.             ."&state=".$state
  4146.             ."&scope=".urlencode($scope)
  4147.             ."&redirect_uri=".urlencode($redirectUri)
  4148.             ."&code_challenge=".$codeChallenge
  4149.             ."&code_challenge_method=S256"
  4150.             ."&prompt=login";
  4151.         return $this->redirect($url);
  4152.     }
  4153.     public function datevCallback(Request $request)
  4154.     {
  4155.         $code  $request->get('code');
  4156.         $state $request->get('state');
  4157.         if (!$code || !$state) {
  4158.             return new Response("Invalid callback request");
  4159.         }
  4160.         $em_goc $this->getDoctrine()->getManager('company_group');
  4161.         $tokenEntity $em_goc->getRepository('CompanyGroupBundle\\Entity\\EntityDatevToken')
  4162.             ->findOneBy(['state' => $state]);
  4163.         if (!$tokenEntity) {
  4164.             return new Response("Invalid or expired state");
  4165.         }
  4166.         $codeVerifier $tokenEntity->getCodeVerifier();
  4167.         if (!$codeVerifier) {
  4168.             return new Response("Code verifier missing");
  4169.         }
  4170.         $clientId "51b09bdcf577c5b998cddce7fe7d5c92";
  4171.         $clientSecret "9b1c4e72a966e9f231584393ff1d3469";
  4172.         // from parameters
  4173. //        $clientId= $this->getContainer()->getParameter('datev_client_id');
  4174. //        $clientSecret= $this->getContainer()->getParameter('datev_client_secret');
  4175.         $authString base64_encode($clientId ":" $clientSecret);
  4176.         $redirectUri "https://ourhoneybee.eu/datev/callback";
  4177.         $postFields http_build_query([
  4178.             "grant_type"    => "authorization_code",
  4179.             "code"          => $code,
  4180.             "redirect_uri"  => $redirectUri,
  4181.             "client_id"     => $clientId,
  4182.             "code_verifier" => $codeVerifier
  4183.         ]);
  4184.         $ch curl_init();
  4185.         curl_setopt_array($ch, [
  4186.             CURLOPT_URL            => "https://sandbox-api.datev.de/token",
  4187.             CURLOPT_POST           => true,
  4188.             CURLOPT_RETURNTRANSFER => true,
  4189.             CURLOPT_POSTFIELDS     => $postFields,
  4190.             CURLOPT_HTTPHEADER     => [
  4191.                 "Content-Type: application/x-www-form-urlencoded",
  4192.                 "Authorization: Basic " $authString
  4193.             ]
  4194.         ]);
  4195.         $response curl_exec($ch);
  4196.         if (curl_errno($ch)) {
  4197.             return new Response("cURL Error: " curl_error($ch), 500);
  4198.         }
  4199.         curl_close($ch);
  4200.         $data json_decode($responsetrue);
  4201.         if (!$data) {
  4202.             return new Response("Invalid token response"500);
  4203.         }
  4204.         if (isset($data['access_token'])) {
  4205.             $tokenEntity->setAccessToken($data['access_token']);
  4206.             $session $request->getSession();  //remove it later
  4207.             $session->set('DATEV_ACCESS_TOKEN'$data['access_token']);
  4208.             if (isset($data['refresh_token'])) {
  4209.                 $tokenEntity->setRefreshToken($data['refresh_token']);
  4210.             }
  4211.             if (isset($data['expires_in'])) {
  4212.                 $tokenEntity->setExpiresAt(time() + $data['expires_in']);
  4213.             }
  4214. //            $tokenEntity->setState(null);
  4215.             $tokenEntity->setCode($code);
  4216.             $em_goc->flush();
  4217.             return $this->redirect("/datev/home");
  4218.         }
  4219.         return new Response(
  4220.             "Token exchange failed: " json_encode($data),
  4221.             400
  4222.         );
  4223.     }
  4224.     public function refreshToken(Request $request)
  4225.     {
  4226.         $em_goc $this->getDoctrine()->getManager('company_group');
  4227.         $session $request->getSession();
  4228.         $applicantId $session->get(UserConstants::APPLICANT_ID);
  4229.         $token $em_goc->getRepository('CompanyGroupBundle\\Entity\\EntityDatevToken')
  4230.             ->findOneBy(['userId' => $applicantId]);
  4231.         if (!$token) {
  4232.             return new JsonResponse([
  4233.                 'status' => false,
  4234.                 'message' => 'User token not found'
  4235.             ]);
  4236.         }
  4237.         if (!$token->getRefreshToken()) {
  4238.             return new JsonResponse([
  4239.                 'status' => false,
  4240.                 'message' => 'No refresh token available'
  4241.             ]);
  4242.         }
  4243.         $clientId "51b09bdcf577c5b998cddce7fe7d5c92";
  4244.         $clientSecret "9b1c4e72a966e9f231584393ff1d3469";
  4245.         $authString base64_encode($clientId ":" $clientSecret);
  4246.         $postFields http_build_query([
  4247.             "grant_type" => "refresh_token",
  4248.             "refresh_token" => $token->getRefreshToken(),
  4249.         ]);
  4250.         $ch curl_init();
  4251.         curl_setopt_array($ch, [
  4252.             CURLOPT_URL => "https://sandbox-api.datev.de/token",
  4253.             CURLOPT_POST => true,
  4254.             CURLOPT_RETURNTRANSFER => true,
  4255.             CURLOPT_POSTFIELDS => $postFields,
  4256.             CURLOPT_HTTPHEADER => [
  4257.                 "Content-Type: application/x-www-form-urlencoded",
  4258.                 "Authorization: Basic " $authString
  4259.             ]
  4260.         ]);
  4261.         $response curl_exec($ch);
  4262.         if (curl_errno($ch)) {
  4263.             return new JsonResponse([
  4264.                 'status' => false,
  4265.                 'message' => curl_error($ch)
  4266.             ]);
  4267.         }
  4268.         curl_close($ch);
  4269.         $data json_decode($responsetrue);
  4270.         if (!isset($data['access_token'])) {
  4271.             return new JsonResponse([
  4272.                 'status' => false,
  4273.                 'message' => 'Refresh failed',
  4274.                 'error' => $data
  4275.             ]);
  4276.         }
  4277.         $token->setAccessToken($data['access_token']);
  4278.         if (isset($data['refresh_token'])) {
  4279.             $token->setRefreshToken($data['refresh_token']);
  4280.         }
  4281.         $token->setExpiresAt(time() + $data['expires_in']);
  4282.         $em_goc->flush();
  4283.         return new JsonResponse([
  4284.             'status' => true,
  4285.             'message' => 'Token refreshed successfully'
  4286.         ]);
  4287.     }
  4288.     public function registerDevice(Request $request)
  4289.     {
  4290.         $em_goc $this->getDoctrine()->getManager('company_group');
  4291.         $data json_decode($request->getContent(), true);
  4292.         if (!$data) {
  4293.             $data $request->request->all();
  4294.         }
  4295.         $deviceSerial $data['device_id'] ?? null;
  4296.         if (!$deviceSerial) {
  4297.             return new JsonResponse([
  4298.                 'success' => false,
  4299.                 'message' => 'Device serial is required',
  4300.                 'data' => null
  4301.             ], 400);
  4302.         }
  4303.         $device =  $em_goc->getRepository('CompanyGroupBundle\\Entity\\Device')
  4304.             ->findOneBy(['deviceSerial' => $deviceSerial]);
  4305.         if (!$device) {
  4306.             $device = new Device();
  4307.             $device->setDeviceSerial($deviceSerial);
  4308.             $message 'Device registered successfully';
  4309.         } else {
  4310.             $message 'Device updated successfully';
  4311.         }
  4312.         if (isset($data['deviceName'])) {
  4313.             $device->setDeviceName($data['deviceName']);
  4314.         }
  4315.         if (isset($data['appId'])) {
  4316.             $device->setAppId($data['appId']);
  4317.         }
  4318.         if (isset($data['deviceType'])) {
  4319.             $device->setDeviceType($data['deviceType']);
  4320.         }
  4321.         if (isset($data['deviceMarker'])) {
  4322.             $device->setDeviceMarker($data['deviceMarker']);
  4323.         }
  4324.         if (isset($data['timezoneStr'])) {
  4325.             $device->setTimezoneStr($data['timezoneStr']);
  4326.         }
  4327.         if (isset($data['hostname'])) {
  4328.             $device->setHostName($data['hostname']);
  4329.         }
  4330.         $em_goc->persist($device);
  4331.         $em_goc->flush();
  4332.         return new JsonResponse([
  4333.             'success' => true,
  4334.             'message' => $message,
  4335.             'data' => [
  4336.                 'id' => $device->getId(),
  4337.                 'deviceSerial' => $device->getDeviceSerial(),
  4338.                 'deviceName' => $device->getDeviceName(),
  4339.                 'deviceType' => $device->getDeviceType(),
  4340.                 'hostName' => $device->getHostName(),
  4341.             ]
  4342.         ]);
  4343.     }
  4344. }