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

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