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

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\HoneybeeWeb\Service\Hb360EstimateService;
  11. use ApplicationBundle\Modules\HoneybeeWeb\Service\Hb360ProjectService;
  12. use ApplicationBundle\Modules\HoneybeeWeb\Support\FunnelManifestCore;
  13. use ApplicationBundle\Modules\HoneybeeWeb\Support\FunnelRoutingCore;
  14. use ApplicationBundle\Modules\HoneybeeWeb\Support\PublicRateLimitCore;
  15. use ApplicationBundle\Modules\HoneybeeWeb\Support\SdsEconCore;
  16. use CompanyGroupBundle\Entity\SdsFunnelHandoff;
  17. use CompanyGroupBundle\Entity\SdsFunnelRouting;
  18. use ApplicationBundle\Modules\System\MiscActions;
  19. use Symfony\Component\HttpFoundation\Cookie;
  20. use CompanyGroupBundle\Entity\EntityCreateTopic;
  21. use CompanyGroupBundle\Entity\PaymentMethod;
  22. use CompanyGroupBundle\Entity\EntityDatevToken;
  23. use CompanyGroupBundle\Entity\Device;
  24. use CompanyGroupBundle\Entity\EntityInvoice;
  25. use CompanyGroupBundle\Entity\EntityMeetingSession;
  26. use CompanyGroupBundle\Entity\EntityTicket;
  27. use Endroid\QrCode\Builder\BuilderInterface;
  28. use Endroid\QrCodeBundle\Response\QrCodeResponse;
  29. use Ps\PdfBundle\Annotation\Pdf;
  30. use Symfony\Component\HttpFoundation\JsonResponse;
  31. use Symfony\Component\HttpFoundation\Request;
  32. use CompanyGroupBundle\Entity\EntityApplicantDetails;
  33. use Symfony\Component\HttpFoundation\Response;
  34. use Symfony\Component\Routing\Generator\UrlGenerator;
  35. use Symfony\Component\Routing\Generator\UrlGeneratorInterface;
  36. //use Symfony\Bundle\FrameworkBundle\Console\Application;
  37. //use Symfony\Component\Console\Input\ArrayInput;
  38. //use Symfony\Component\Console\Output\NullOutput;
  39. class HoneybeeWebPublicController extends GenericController
  40. {
  41.     private function getPublicDocumentEntityManager($appId)
  42.     {
  43.         $emGoc $this->getDoctrine()->getManager('company_group');
  44.         $emGoc->getConnection()->connect();
  45.         $goc $emGoc
  46.             ->getRepository("CompanyGroupBundle\\Entity\\CompanyGroup")
  47.             ->findOneBy(
  48.                 array(
  49.                     'appId' => $appId
  50.                 )
  51.             );
  52.         if (!$goc) {
  53.             return array(nullnull);
  54.         }
  55.         $connector $this->container->get('application_connector');
  56.         $connector->resetConnection(
  57.             'default',
  58.             $goc->getDbName(),
  59.             $goc->getDbUser(),
  60.             $goc->getDbPass(),
  61.             $goc->getDbHost(),
  62.             $reset true
  63.         );
  64.         return array($this->getDoctrine()->getManager(), $goc);
  65.     }
  66.     // home page
  67.     public function CentralHomePageAction(Request $request)
  68.     {
  69.         $em $this->getDoctrine()->getManager('company_group');
  70.         $subscribed false;
  71.         if ($request->isMethod('POST')) {
  72.             $entityTicket = new EntityTicket();
  73.             $entityTicket->setEmail($request->request->get('newsletter'));
  74.             $em->persist($entityTicket);
  75.             $em->flush();
  76.             $subscribed true;
  77.         }
  78.         $response $this->render('@HoneybeeWeb/pages/home.html.twig', [
  79.             'page_title' => 'HoneyBee — Project ERP + Business ERP + HoneyCore Edge EMS',
  80.             'og_title' => 'HoneyBee — Business + Energy Infrastructure. One Operating System.',
  81.             'og_description' => 'HoneyBee connects Business ERP, Project ERP, HoneyCore Edge EMS, AI and mobile field operations in one ecosystem — so business, project, finance, site, asset and energy data work together.',
  82.             'subscribed' => $subscribed,
  83.             'packageDetails' => GeneralConstant::$packageDetails,
  84.         ]);
  85.         // GR2 (GROWTH) — a landing via a GR1 backlink (?ref=<surface>&t=<hash>) records one
  86.         // viral_touch row + drops the attribution cookie. Fully guarded: never breaks the page.
  87.         $viralToken = \ApplicationBundle\Modules\LeadGen\Service\ViralAttributionService::capture($em$request);
  88.         return \ApplicationBundle\Modules\LeadGen\Service\ViralAttributionService::attachCookie($response$viralToken);
  89.     }
  90.     // about us
  91.     public function CentralAboutUsPageAction()
  92.     {
  93.         return $this->render('@HoneybeeWeb/pages/about_us.html.twig', array(
  94.                 'page_title'     => 'About HoneyBee | Building the Operating System for Project Businesses & Energy Infrastructure',
  95.                 'og_title'       => 'About HoneyBee | Building the Operating System for Project Businesses & Energy Infrastructure',
  96.                 'og_description' => 'HoneyBee is a Germany/EU + Singapore-oriented software ecosystem connecting Business ERP, Project ERP, HoneyCore Edge EMS, AI, and mobile operations — with engineering, development, implementation, and regional support from Bangladesh.',
  97.                 'packageDetails' => GeneralConstant::$packageDetails,
  98.         ));
  99.     }
  100.     // Contact page
  101.     public function CentralContactPageAction(Request $request)
  102.     {
  103.         $em $this->getDoctrine()->getManager('company_group');
  104.         if ($request->isXmlHttpRequest()) {
  105.             $email $request->request->get('email');
  106.             if ($email) {
  107.                 // Enrich the message with the 3-step form selectors (need / company type / phone),
  108.                 // and persist any uploaded workflow/site-requirement file (graceful if absent).
  109.                 $bodyParts = [trim((string) $request->request->get('message'''))];
  110.                 $need trim((string) $request->request->get('enquiry_need'''));
  111.                 $companyType trim((string) $request->request->get('company_type'''));
  112.                 $phone trim((string) $request->request->get('phone'''));
  113.                 if ($need !== '')        { $bodyParts[] = 'Need: ' $need; }
  114.                 if ($companyType !== '') { $bodyParts[] = 'Company type: ' $companyType; }
  115.                 if ($phone !== '')       { $bodyParts[] = 'Phone: ' $phone; }
  116.                 $uploaded $request->files->get('workflow_file');
  117.                 if ($uploaded) {
  118.                     try {
  119.                         $projectDir $this->getParameter('kernel.project_dir');
  120.                         $relDir 'uploads/contact/' date('Y/m');
  121.                         $absDir rtrim($projectDirDIRECTORY_SEPARATOR) . DIRECTORY_SEPARATOR 'web' DIRECTORY_SEPARATOR str_replace('/'DIRECTORY_SEPARATOR$relDir);
  122.                         if (!is_dir($absDir)) { @mkdir($absDir0775true); }
  123.                         $ext  method_exists($uploaded'guessExtension') ? ($uploaded->guessExtension() ?: 'dat') : 'dat';
  124.                         $name 'contact_' date('YmdHis') . '_' mt_rand(10009999) . '.' $ext;
  125.                         $uploaded->move($absDir$name);
  126.                         $bodyParts[] = 'Attachment: /' $relDir '/' $name;
  127.                     } catch (\Throwable $e) { /* non-fatal: still save the message */ }
  128.                 }
  129.                 $entityTicket = new EntityTicket();
  130.                 $entityTicket->setEmail($email);
  131.                 $entityTicket->setName($request->request->get('name'));
  132.                 $entityTicket->setTitle($request->request->get('subject'));
  133.                 $entityTicket->setTicketBody(implode("\n"array_filter($bodyParts)));
  134.                 $em->persist($entityTicket);
  135.                 $em->flush();
  136.                 $this->get('app.commercial_journey_service')->captureExistingObject('ticket'$entityTicket'talk_to_sales');
  137.                 return new JsonResponse([
  138.                     'success' => true,
  139.                     'message' => 'Your message has been sent successfully. Our team will reply soon.'
  140.                 ]);
  141.             }
  142.             return new JsonResponse([
  143.                 'success' => false,
  144.                 'message' => 'Invalid email address.'
  145.             ]);
  146.         }
  147.         return $this->render('@HoneybeeWeb/pages/contact.html.twig', array(
  148.             'page_title' => 'Request a HoneyBee Project Solution | HoneyCore Edge+, IoT, Billing & AI Deployment',
  149.             'og_title' => 'Request a HoneyBee Project Solution | HoneyCore Edge+, IoT, Billing & AI Deployment',
  150.             '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.',
  151.         ));
  152.         
  153.     }
  154.     // blogs
  155.     public function CentralBlogsPageAction(Request $request)
  156.     {
  157.         $em $this->getDoctrine()->getManager('company_group');
  158.         $topicDetails $em->getRepository('CompanyGroupBundle\Entity\EntityCreateTopic')->findAll();
  159.         $repo         $em->getRepository('CompanyGroupBundle\Entity\EntityCreateBlog');
  160.         // ── Fetch featured blog separately (always, regardless of page) ──
  161.         $featuredBlog $repo->findOneBy(['isPrimaryBlog' => true]);
  162.         // ── Pagination ──
  163.         $page       max(1, (int) $request->query->get('page'1));
  164.         $limit      6;
  165.         $totalBlogs count($repo->findAll());
  166.         $totalPages max(1, (int) ceil($totalBlogs $limit));
  167.         $page       min($page$totalPages);
  168.         $offset     = ($page 1) * $limit;
  169.         $blogDetails $repo->findBy([], ['Id' => 'DESC'], $limit$offset);
  170.         return $this->render('@HoneybeeWeb/pages/blogs.html.twig', [
  171.             'page_title'   => 'Blogs',
  172.             'topics'       => $topicDetails,
  173.             'blogs'        => $blogDetails,
  174.             'featuredBlog' => $featuredBlog,
  175.             'currentPage'  => $page,
  176.             'totalPages'   => $totalPages,
  177.             'totalBlogs'   => $totalBlogs,
  178.         ]);
  179.     }
  180.     // product
  181.     public function CentralProductPageAction()
  182.     {
  183.         return $this->render('@HoneybeeWeb/pages/product.html.twig', array(
  184.             'page_title' => 'HoneyBee Platform | One ecosystem, four connected layers',
  185.             'og_description' => 'Business ERP, Project ERP, HoneyCore Edge EMS, AI and mobile — one connected platform, not bolted-together tools.',
  186.         ));
  187.     }
  188.     // ── Phase 2 marketing pages (website restructure) ──
  189.     public function CentralProjectErpPageAction()
  190.     {
  191.         return $this->render('@HoneybeeWeb/pages/project_erp.html.twig', array(
  192.             'page_title' => 'Project ERP for EPC, Engineering & Solar | HoneyBee',
  193.             '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.',
  194.         ));
  195.     }
  196.     public function CentralBusinessErpPageAction()
  197.     {
  198.         return $this->render('@HoneybeeWeb/pages/business_erp.html.twig', array(
  199.             'page_title' => 'Business ERP for SMEs | HR, Accounts, Inventory, CRM — HoneyBee',
  200.             'og_description' => 'Affordable, modular Business ERP for growing SMEs in Europe and Singapore. Start small, expand when ready — from €7.99/user/month.',
  201.         ));
  202.     }
  203.     public function CentralEdgePageAction()
  204.     {
  205.         return $this->render('@HoneybeeWeb/pages/honeycore_edge.html.twig', array(
  206.             'page_title' => 'HoneyCore Edge EMS | Energy & Site Intelligence — HoneyBee',
  207.             'og_description' => 'Connect solar PV, grid, generators, batteries, meters and sensors with O&M, billing, finance and reporting through HoneyCore Edge EMS site intelligence.',
  208.         ));
  209.     }
  210.     public function CentralEdgeProjectsPageAction()
  211.     {
  212.         return $this->render('@HoneybeeWeb/pages/honeycore_edge_projects.html.twig', array(
  213.             'page_title' => 'HoneyCore Edge+ Design & Quotation Software | HoneyBee',
  214.             'og_description' => 'Turn site requirements into HoneyCore Edge+ architecture, sensor/meter schedules, BoQ, quotation, commissioning checklist and O&M workflow.',
  215.         ));
  216.     }
  217.     public function CentralExperiencePageAction()
  218.     {
  219.         return $this->render('@HoneybeeWeb/pages/experience.html.twig', array(
  220.             'page_title' => 'Experience & Proof | HoneyBee',
  221.             'og_description' => 'Built from real ERP, project, HoneyCore Edge EMS and SME digital-transformation experience — with Germany/EU product focus and a Singapore SaaS base.',
  222.         ));
  223.     }
  224.     public function CentralTrustPageAction()
  225.     {
  226.         return $this->render('@HoneybeeWeb/pages/trust_governance.html.twig', array(
  227.             'page_title' => 'Trust & Governance | Security & Standards — HoneyBee',
  228.             'og_description' => 'Operator-owned data, RBAC, audit trails, NIS2-aware governance and a clear, no-overclaim standards map with claim-control categories.',
  229.         ));
  230.     }
  231.     // ── Self-serve pricing: server-authoritative price preview (cart calls this on every change) ──
  232.     public function CentralPricePreviewAction(Request $request)
  233.     {
  234.         $plan   = (string) $request->request->get('plan''core');
  235.         $users  = (int) $request->request->get('users'0);
  236.         $admins = (int) $request->request->get('admins'0);
  237.         $ml     = (int) $request->request->get('ml_users'0);
  238.         $cycle  $request->request->get('cycle''monthly') === 'yearly' 'yearly' 'monthly';
  239.         $addons = (array) $request->request->get('addons', []);
  240.         // Keep only known add-on ids (never trust the client list blindly).
  241.         $catalogue GeneralConstant::$subscriptionAddOns;
  242.         $addons array_values(array_intersect($addonsarray_keys($catalogue)));
  243.         $svc = new \CompanyGroupBundle\Modules\Api\Service\PricingService();
  244.         $breakdown $svc->getPriceBreakdown($users$admins$ml$cycle$plan$addons);
  245.         // attach the resolved add-on display rows for the cart
  246.         $addonRows = [];
  247.         foreach ($addons as $id) {
  248.             $addonRows[] = ['id' => $id'name' => $catalogue[$id]['name'], 'euMonthly' => (float) $catalogue[$id]['euMonthly']];
  249.         }
  250.         $breakdown['addon_rows'] = $addonRows;
  251.         return new JsonResponse(['ok' => true'breakdown' => $breakdown]);
  252.     }
  253.     // ── Investor Snapshot (Phase C) ──
  254.     public function CentralInvestorPageAction()
  255.     {
  256.         return $this->render('@HoneybeeWeb/pages/investor_snapshot.html.twig', array(
  257.             'page_title'     => 'Investor Snapshot | HoneyBee — Business + Energy Infrastructure OS',
  258.             'og_description' => 'HoneyBee is a vertical operating system for project-based energy, engineering and industrial companies — positioning, ICP, revenue model and defensibility. No invented metrics.',
  259.         ));
  260.     }
  261.     // ── Competitor comparison pages (Phase C) ──
  262.     public function CentralComparePageAction($slug)
  263.     {
  264.         $meta = [
  265.             'odoo'                       => ['HoneyBee vs Odoo | Project & Energy ERP Comparison''Odoo is a broad ERP suite. HoneyBee is built around project execution, EPC workflows, field operations and energy-infrastructure intelligence.'],
  266.             'zoho'                       => ['HoneyBee vs Zoho | ERP for Project & Energy Companies''Zoho covers general business apps. HoneyBee connects ERP, project execution, finance, O&M and HoneyCore energy data in one workflow.'],
  267.             'sap-business-one'           => ['HoneyBee vs SAP Business One | Project ERP Comparison''SAP Business One suits general operations. HoneyBee adds deep EPC/project execution and energy-infrastructure intelligence.'],
  268.             'microsoft-business-central' => ['HoneyBee vs Microsoft Business Central | Comparison''Business Central is a broad ERP. HoneyBee is purpose-built for project-based energy, engineering and industrial companies.'],
  269.             'monday-clickup'             => ['HoneyBee vs Monday / ClickUp | Beyond Task Management''Monday and ClickUp manage tasks. HoneyBee connects tasks with quotation, BoQ, procurement, billing, finance and energy data.'],
  270.             'excel'                      => ['HoneyBee vs Excel | From Spreadsheets to an Operating System''Excel is flexible but fragile. HoneyBee gives structure, audit trail, approvals, real-time data and automation.'],
  271.             'scada-ems'                  => ['HoneyBee vs SCADA / EMS Dashboards | Asset Data to Business''SCADA/EMS tools monitor assets. HoneyBee connects asset data with ERP, O&M, billing, reporting and AI.'],
  272.         ];
  273.         if (!isset($meta[$slug])) { throw $this->createNotFoundException(); }
  274.         return $this->render('@HoneybeeWeb/pages/compare/' $slug '.html.twig', array(
  275.             'page_title'     => $meta[$slug][0],
  276.             'og_description' => $meta[$slug][1],
  277.             'compare_slug'   => $slug,
  278.         ));
  279.     }
  280.     // ── SEO solution landing pages (Phase C) ──
  281.     public function CentralSolutionPageAction($slug)
  282.     {
  283.         $meta = [
  284.             'erp-for-solar-epc'      => ['ERP for Solar EPC Companies | HoneyBee Project ERP''Project ERP for solar EPC: quotation, BoQ, procurement, site execution, milestone billing, O&M and HoneyCore Edge EMS energy intelligence.'],
  285.             'erp-for-engineering'    => ['ERP for Engineering Companies | HoneyBee Project ERP''Control engineering projects from quotation to delivery, billing and profitability with HoneyBee Project ERP.'],
  286.             'erp-for-construction'   => ['ERP for Construction Project Companies | HoneyBee''BoQ, procurement, site execution, milestone billing and retention for construction project companies.'],
  287.             'erp-for-om'             => ['ERP for O&M Companies | HoneyBee''Connect O&M workflows with billing, reporting and energy-asset data through HoneyBee and HoneyCore Edge EMS.'],
  288.             'erp-for-trading'        => ['ERP for Trading & Distribution Companies | HoneyBee''HR, accounts, inventory, sales, purchase and CRM for trading and distribution companies.'],
  289.             'project-erp-bangladesh' => ['Project ERP for Bangladesh SMEs | HoneyBee''Affordable project ERP for Bangladesh SMEs — quotation, procurement, site execution, billing and reporting.'],
  290.             'project-erp-singapore'  => ['Project ERP for Singapore SMEs | HoneyBee''Project ERP for Singapore SMEs and project-based companies — execution, finance and reporting in one system.'],
  291.             'project-erp-germany'    => ['Project ERP for German Energy Companies | HoneyBee''Project ERP for German energy and engineering companies, DATEV-ready export and GoBD-aligned audit trail where implemented.'],
  292.             'honeycore-solar-pv'     => ['HoneyCore for Solar PV Monitoring | HoneyBee''HoneyCore Edge EMS connects solar PV, inverters and meters with O&M, billing, reporting and AI.'],
  293.             'honeycore-hybrid-energy'=> ['HoneyCore for Hybrid Energy Systems | HoneyBee''Monitor solar, battery, generator and grid in hybrid energy systems with HoneyCore Edge EMS.'],
  294.             'honeycore-cold-chain'   => ['HoneyCore for Cold Chain & Healthcare Infrastructure | HoneyBee''Temperature, energy and utility monitoring for cold-chain and healthcare infrastructure with HoneyCore Edge EMS.'],
  295.             'honeycore-agri-pv'      => ['HoneyCore for Agri-PV & Irrigation | HoneyBee''Connect solar generation, soil and irrigation data with HoneyCore Edge EMS for Agri-PV and solar irrigation.'],
  296.         ];
  297.         if (!isset($meta[$slug])) { throw $this->createNotFoundException(); }
  298.         return $this->render('@HoneybeeWeb/pages/solutions/' $slug '.html.twig', array(
  299.             'page_title'     => $meta[$slug][0],
  300.             'og_description' => $meta[$slug][1],
  301.             'solution_slug'  => $slug,
  302.         ));
  303.     }
  304.     // ── Calculators (Phase D) ──
  305.     public function CentralToolPageAction(Request $request$slug)
  306.     {
  307.         $meta = [
  308.             'cost-leakage-calculator'   => ['Project Cost Leakage Calculator | HoneyBee''Estimate the hidden annual loss from delays, procurement leakage, billing delays and inventory loss — and the right HoneyBee path.'],
  309.             'roi-calculator'            => ['ERP ROI Calculator | HoneyBee''Estimate time saved and monthly savings from HoneyBee across approvals, invoices and projects.'],
  310.             'site-assessment-estimator' => ['HoneyCore Site Assessment Estimator | HoneyBee''Estimate your HoneyCore site assessment scope from sites, PV capacity, meters, inverters and protocols.'],
  311.             'rooftop-estimate'          => ['Instant Solar Estimate | HoneyBee 360''Enter your address and monthly bill — get an instant indicative PV size, annual yield, bill saving and payback, with every figure honestly tagged. Powered by PVGIS yield data.'],
  312.         ];
  313.         if (!isset($meta[$slug])) { throw $this->createNotFoundException(); }
  314.         // ── FUNNEL-3: the logged-in APPLICANT's detail delta on the public studio —
  315.         // an owned saved design opens for editing (?mydesign=N) and the offer form
  316.         // pre-fills from the account. Strictly additive + fail-soft: anonymous
  317.         // visitors and every other tool page render exactly as before.
  318.         $myDesign null;
  319.         $applicant null;
  320.         if ($slug === 'rooftop-estimate') {
  321.             try {
  322.                 $session $request->getSession();
  323.                 if ((int) $session->get(UserConstants::USER_TYPE0) === UserConstants::USER_TYPE_APPLICANT
  324.                     && (int) $session->get(UserConstants::USER_ID0) > 0) {
  325.                     $applicant = array(
  326.                         'name'  => (string) $session->get(UserConstants::USER_NAME''),
  327.                         'email' => (string) $session->get(UserConstants::USER_EMAIL''),
  328.                     );
  329.                     $pid = (int) $request->query->get('mydesign'0);
  330.                     if ($pid 0) {
  331.                         $em $this->getDoctrine()->getManager('company_group');
  332.                         $project = (new Hb360ProjectService($em))
  333.                             ->findOwned($pid, (int) $session->get(UserConstants::USER_ID0));
  334.                         if ($project && $project->getDesignJson()) {
  335.                             $dj json_decode((string) $project->getDesignJson(), true);
  336.                             if (is_array($dj) && isset($dj['payload']) && is_array($dj['payload'])) {
  337.                                 $myDesign = array(
  338.                                     'id'      => (int) $project->getId(),
  339.                                     'title'   => (string) ($project->getTitle() ?: ('Design #' $project->getId())),
  340.                                     'address' => (string) $project->getAddress(),
  341.                                     'payload' => $dj['payload'],
  342.                                     'summary' => FunnelManifestCore::summary($dj['payload']),
  343.                                 );
  344.                             }
  345.                         }
  346.                     }
  347.                 }
  348.             } catch (\Throwable $e) {
  349.                 $myDesign null// the public page never breaks over account extras
  350.             }
  351.         }
  352.         return $this->render('@HoneybeeWeb/pages/tools/' $slug '.html.twig', array(
  353.             'page_title'     => $meta[$slug][0],
  354.             'og_description' => $meta[$slug][1],
  355.             'tool_slug'      => $slug,
  356.             'maps_key'       => $this->mapsBrowserKey(),
  357.             'my_design'      => $myDesign,
  358.             'applicant'      => $applicant,
  359.         ));
  360.     }
  361.     // Failsafe default — used when no parameter is configured in parameters.yml.
  362.     const HB_MAPS_KEY 'AIzaSyBJxyUy8a_U2rSdIUApVDoK_dcvgGkoeDk';
  363.     /** Server-side Google key (Geocoding + Solar API): parameter `google_maps_api_key`, else the built-in default. Never throws. */
  364.     protected function mapsKey()
  365.     {
  366.         if ($this->container->hasParameter('google_maps_api_key')) {
  367.             $k $this->container->getParameter('google_maps_api_key');
  368.             if (is_string($k) && trim($k) !== '') { return $k; }
  369.         }
  370.         return self::HB_MAPS_KEY;
  371.     }
  372.     /** Client-side (browser) Google key for the map JS: parameter `google_maps_browser_key`, else the server key, else default. Never throws. */
  373.     protected function mapsBrowserKey()
  374.     {
  375.         if ($this->container->hasParameter('google_maps_browser_key')) {
  376.             $k $this->container->getParameter('google_maps_browser_key');
  377.             if (is_string($k) && trim($k) !== '') { return $k; }
  378.         }
  379.         return $this->mapsKey();
  380.     }
  381.     /**
  382.      * FUNNEL-1 — sliding-window rate guard for the PUBLIC estimator/studio endpoints
  383.      * (they had none; /auto spends metered Google calls per request). Decision math is
  384.      * pure `PublicRateLimitCore::decide` (selftested); the store is best-effort tmp
  385.      * files — ANY limiter-infrastructure failure allows the request (the limiter guards
  386.      * metered APIs; it must never take the public page down). Per-box override:
  387.      * container parameter `hb360_rate_<bucket>_per_hour`, read with a fallback — never
  388.      * a %param% DI reference.
  389.      *
  390.      * @return JsonResponse|null a 429 refusal, or null = proceed
  391.      */
  392.     protected function hb360RateGuard(Request $request$bucket$defaultPerHour)
  393.     {
  394.         try {
  395.             $limit = (int) $defaultPerHour;
  396.             $key 'hb360_rate_' $bucket '_per_hour';
  397.             if ($this->container->hasParameter($key)) {
  398.                 $v = (int) $this->container->getParameter($key);
  399.                 if ($v 0) { $limit $v; }
  400.             }
  401.             $token = (string) $request->cookies->get('hb360_anon''');
  402.             $keys PublicRateLimitCore::keysFor((string) $request->getClientIp(), $token);
  403.             // FUNNEL-3: a signed-in account gets its own bucket too (cookie-clearing
  404.             // can't reset it; a shared office IP doesn't starve individual accounts).
  405.             $acct = (int) $request->getSession()->get(UserConstants::USER_ID0);
  406.             if ($acct 0) {
  407.                 $keys[] = 'acct:' $acct;
  408.             }
  409.             $res PublicRateLimitCore::checkAndRecord($bucket$keys$limit);
  410.             if (!$res['allowed']) {
  411.                 $mins max(1, (int) ceil($res['retry_after'] / 60));
  412.                 return new JsonResponse([
  413.                     'ok' => false,
  414.                     'rate_limited' => true,
  415.                     'retry_after_s' => (int) $res['retry_after'],
  416.                     'error' => 'Too many requests from your connection — please wait about '
  417.                         $mins ' minute' . ($mins === '' 's') . ' and try again.',
  418.                 ], 429);
  419.             }
  420.         } catch (\Throwable $e) {
  421.             // fail-open by design (see docblock)
  422.         }
  423.         return null;
  424.     }
  425.     // ── Rooftop estimate — MANUAL draw endpoint (area + coords from the map) ──
  426.     public function CentralRooftopCalcAction(Request $request)
  427.     {
  428.         if ($refused $this->hb360RateGuard($request'calc'PublicRateLimitCore::DEFAULT_CALC_PER_HOUR)) {
  429.             return $refused;
  430.         }
  431.         $lat     = (float) $request->request->get('lat'0);
  432.         $lng     = (float) $request->request->get('lng'0);
  433.         $area    = (float) $request->request->get('area_m2'0);
  434.         $mode    $request->request->get('mode''roof');
  435.         $monthly = (float) $request->request->get('monthly_kwh'0);
  436.         $bill    = (float) $request->request->get('monthly_bill'0);
  437.         $tariff  = (float) $request->request->get('tariff'0.22);
  438.         $tilt    = (float) $request->request->get('tilt'10);
  439.         $src     $request->request->get('roof_source') === 'manual' 'manual' 'map';
  440.         // ── SDS2 (additive): the studio's live economics panel sends the REAL packed kWp plus
  441.         // the zone's pitch/azimuth/mount-mode. `kwp` absent/0 ⇒ the legacy path below runs
  442.         // byte-identical. SDS2 responses are TRANSIENT (no hb360 anon-project upsert — a live
  443.         // drag must not overwrite the visitor's saved estimate; persistence is SDS3).
  444.         $sdsKwp = (float) $request->request->get('kwp'0);
  445.         if ($sdsKwp 0) {
  446.             if ($lat == 0) {
  447.                 return new JsonResponse(['ok' => false'error' => 'Draw a roof outline on the map first.']);
  448.             }
  449.             $res $this->computeSdsZoneEconomics($lat$lng$area$sdsKwp, [
  450.                 'pitch_deg'   => (float) $request->request->get('pitch_deg'0),
  451.                 'azimuth_deg' => (float) $request->request->get('azimuth_deg'180),
  452.                 'mount_mode'  => $request->request->get('mount_mode') === 'ew' 'ew' 'south',
  453.                 'module_wp'   => (float) $request->request->get('module_wp'450),
  454.                 'total_kwp'   => (float) $request->request->get('total_kwp'0),
  455.             ], $monthly$bill$tariff);
  456.             return new JsonResponse($res);
  457.         }
  458.         if ($area <= || $lat == 0) {
  459.             return new JsonResponse(['ok' => false'error' => 'Draw a roof outline on the map first.']);
  460.         }
  461.         $res $this->computeRooftopDesign($lat$lng$area$tilt$mode$monthly$bill$tariffnull$src);
  462.         $res['roof_source'] = $src === 'manual' 'manual area' 'Map outline';
  463.         $res['lat'] = $lat$res['lng'] = $lng;
  464.         return $this->hb360Respond($request$res, [
  465.             'mode' => $mode'monthly_kwh' => $monthly'monthly_bill' => $bill,
  466.             'tariff' => $tariff'tilt' => $tilt'area_m2' => $area'roof_source' => $src,
  467.         ]);
  468.     }
  469.     // ── Rooftop estimate — AUTO from ADDRESS (geocode → Google Solar API → OSM footprint → PVGIS) ──
  470.     public function CentralRooftopAutoAction(Request $request)
  471.     {
  472.         // the tight cap — every /auto call can spend metered Google (geocode + Solar API)
  473.         if ($refused $this->hb360RateGuard($request'auto'PublicRateLimitCore::DEFAULT_AUTO_PER_HOUR)) {
  474.             return $refused;
  475.         }
  476.         $address trim((string) $request->request->get('address'''));
  477.         $mode    $request->request->get('mode''roof');
  478.         $monthly = (float) $request->request->get('monthly_kwh'0);
  479.         $bill    = (float) $request->request->get('monthly_bill'0);
  480.         $tariff  = (float) $request->request->get('tariff'0.22);
  481.         $tilt    = (float) $request->request->get('tilt'10);
  482.         if ($address === '') {
  483.             return new JsonResponse(['ok' => false'error' => 'Enter an address first.']);
  484.         }
  485.         $geo $this->geocodeAddress($address);
  486.         if ($geo === null) {
  487.             return new JsonResponse(['ok' => false'error' => 'Address not found — try a more specific address.']);
  488.         }
  489.         $lat $geo['lat']; $lng $geo['lng'];
  490.         // Tier 1: Google Solar API (best — real roof + panel layout). Null when API disabled / no coverage.
  491.         $preset $this->solarApiDesign($lat$lng);
  492.         $roofSource null$area null$src 'map';
  493.         if ($preset !== null) {
  494.             $area $preset['roof_area']; $roofSource 'Google Solar API'$src 'solar_api';
  495.         } else {
  496.             // Tier 2: OSM building footprint (free, global where mapped).
  497.             $area $this->osmBuildingArea($lat$lng);
  498.             if ($area !== null) { $roofSource 'OSM building footprint'$src 'osm'; }
  499.         }
  500.         if ($area === null || $area 10) {
  501.             // Tier 3: hand off to manual draw at the geocoded location.
  502.             return new JsonResponse([
  503.                 'ok' => false'needs_manual' => true,
  504.                 'lat' => $lat'lng' => $lng'formatted_address' => $geo['formatted'],
  505.                 'error' => 'Could not auto-detect the roof at this address — trace it on the map below.',
  506.             ]);
  507.         }
  508.         $res $this->computeRooftopDesign($lat$lng$area$tilt$mode$monthly$bill$tariff$preset$src);
  509.         $res['lat'] = $lat$res['lng'] = $lng;
  510.         $res['formatted_address'] = $geo['formatted'];
  511.         $res['roof_source'] = $roofSource;
  512.         return $this->hb360Respond($request$res, [
  513.             'mode' => $mode'monthly_kwh' => $monthly'monthly_bill' => $bill,
  514.             'tariff' => $tariff'tilt' => $tilt'address' => $address'roof_source' => $src,
  515.         ]);
  516.     }
  517.     /**
  518.      * H1b: wrap an estimate response — persist the guest's estimate as their ONE
  519.      * anonymous Hb360Project (keyed by the `hb360_anon` cookie) so it survives
  520.      * the trip through the signup wall. Strictly fail-safe: if the central
  521.      * schema/table isn't there yet, the public estimator answers exactly as
  522.      * before, just without a saved copy.
  523.      */
  524.     private function hb360Respond(Request $request, array $res, array $inputs)
  525.     {
  526.         $token null;
  527.         if (!empty($res['ok'])) {
  528.             try {
  529.                 $token = (string) $request->cookies->get('hb360_anon''');
  530.                 if (!preg_match('/^[a-f0-9]{32,64}$/'$token)) {
  531.                     $token Hb360ProjectService::newToken();
  532.                 }
  533.                 $em $this->getDoctrine()->getManager('company_group');
  534.                 $project = (new Hb360ProjectService($em))->upsertForToken($token, [
  535.                     'address'  => (string) ($res['formatted_address'] ?? ($inputs['address'] ?? '')),
  536.                     'lat'      => $res['lat'] ?? null,
  537.                     'lng'      => $res['lng'] ?? null,
  538.                     'inputs'   => $inputs,
  539.                     'estimate' => $res,
  540.                 ]);
  541.                 $res['saved'] = ['project_id' => (int) $project->getId()];
  542.             } catch (\Throwable $e) {
  543.                 $token null// saving is an enhancement, never a gate
  544.             }
  545.         }
  546.         $response = new JsonResponse($res);
  547.         if ($token) {
  548.             // 90 days, whole site, httpOnly (JS never needs it — the server reads it).
  549.             $response->headers->setCookie(new Cookie('hb360_anon'$tokentime() + 90 86400'/'nullfalsetrue));
  550.         }
  551.         return $response;
  552.     }
  553.     /**
  554.      * FUNNEL-1 — the ONE deliberate public write: "Save design". The visitor's studio
  555.      * design (the client exportDesign() payload) becomes their single anonymous draft
  556.      * (hb360_project.design_json, the H1b one-row-per-visitor pattern), keyed by the
  557.      * same `hb360_anon` cookie the estimate save uses — so the EXISTING login attach
  558.      * hook carries the design across the signup wall untouched.
  559.      *
  560.      * Guard order: rate limit → wire-size cap → shape → FunnelManifestCore::validate
  561.      * (caps + geometry sanity + the portability rule: tenant library ids refused).
  562.      * Storage is fail-SAFE for the page but HONEST for the click: if the central
  563.      * schema/column is missing, the response says saving is unavailable — it never
  564.      * claims "saved" for a row that does not exist.
  565.      */
  566.     public function CentralRooftopDesignSaveAction(Request $request)
  567.     {
  568.         if ($refused $this->hb360RateGuard($request'save'PublicRateLimitCore::DEFAULT_SAVE_PER_HOUR)) {
  569.             return $refused;
  570.         }
  571.         $raw = (string) $request->getContent();
  572.         if (strlen($raw) > FunnelManifestCore::MAX_BYTES) {
  573.             return new JsonResponse(['ok' => false'error' => 'This design is too large to save online ('
  574.                 round(strlen($raw) / 1024) . ' KB — the limit is '
  575.                 round(FunnelManifestCore::MAX_BYTES 1024) . ' KB).'], 413);
  576.         }
  577.         $body json_decode($rawtrue);
  578.         $payload = (is_array($body) && isset($body['payload']) && is_array($body['payload'])) ? $body['payload'] : null;
  579.         if ($payload === null) {
  580.             return new JsonResponse(['ok' => false'error' => 'Malformed design payload.'], 400);
  581.         }
  582.         $v FunnelManifestCore::validate($payloadstrlen($raw));
  583.         if (!$v['ok']) {
  584.             return new JsonResponse(['ok' => false'error' => implode(' '$v['errors'])], 422);
  585.         }
  586.         $token = (string) $request->cookies->get('hb360_anon''');
  587.         if (!preg_match('/^[a-f0-9]{32,64}$/'$token)) {
  588.             $token Hb360ProjectService::newToken();
  589.         }
  590.         $hash FunnelManifestCore::hash($payload);
  591.         $stored = [
  592.             'format'   => FunnelManifestCore::FORMAT,
  593.             'hash'     => $hash,
  594.             'saved_at' => date('c'),
  595.             'payload'  => $payload,
  596.         ];
  597.         $meta = [
  598.             'address' => (string) (isset($body['address']) ? $body['address'] : ''),
  599.             'lat'     => isset($payload['lat']) ? $payload['lat'] : null,
  600.             'lng'     => isset($payload['lng']) ? $payload['lng'] : null,
  601.         ];
  602.         try {
  603.             $em $this->getDoctrine()->getManager('company_group');
  604.             $svc = new Hb360ProjectService($em);
  605.             // FUNNEL-3: a signed-in applicant editing an OWNED design saves onto THAT
  606.             // row (own-checked), never onto the anon draft. Everyone else keeps the
  607.             // one-anon-draft-per-visitor path unchanged.
  608.             $owned $this->applicantOwnedProject($request, (int) (isset($body['project_id']) ? $body['project_id'] : 0), $svc);
  609.             $project $owned !== null
  610.                 $svc->saveDesignForProject($owned$stored$meta)
  611.                 : $svc->saveDesignForToken($token$stored$meta);
  612.         } catch (\Throwable $e) {
  613.             // honest, not fake-saved: schema not migrated / DB hiccup
  614.             return new JsonResponse(['ok' => false,
  615.                 'error' => 'Saving is temporarily unavailable — your design stays in this browser tab.'], 503);
  616.         }
  617.         $response = new JsonResponse([
  618.             'ok' => true,
  619.             'saved' => [
  620.                 'project_id'  => (int) $project->getId(),
  621.                 'design_hash' => $hash,
  622.                 'summary'     => FunnelManifestCore::summary($payload),
  623.             ],
  624.         ]);
  625.         $response->headers->setCookie(new Cookie('hb360_anon'$tokentime() + 90 86400'/'nullfalsetrue));
  626.         return $response;
  627.     }
  628.     /**
  629.      * FUNNEL-3 — resolve a project id to an OWNED row for the signed-in applicant, or
  630.      * null (not signed in / not theirs / no id). Ownership is findOwned's law — a
  631.      * foreign id yields null, never someone else's row.
  632.      */
  633.     private function applicantOwnedProject(Request $request$projectIdHb360ProjectService $svc)
  634.     {
  635.         $projectId = (int) $projectId;
  636.         if ($projectId <= 0) {
  637.             return null;
  638.         }
  639.         $session $request->getSession();
  640.         if ((int) $session->get(UserConstants::USER_TYPE0) !== UserConstants::USER_TYPE_APPLICANT) {
  641.             return null;
  642.         }
  643.         $uid = (int) $session->get(UserConstants::USER_ID0);
  644.         if ($uid <= 0) {
  645.             return null;
  646.         }
  647.         return $svc->findOwned($projectId$uid);
  648.     }
  649.     /**
  650.      * FUNNEL-2 — the routing rule rows for public resolution (fail-safe: any read problem
  651.      * = empty list, which resolves to the honest 'unrouted' refusal, never a guess).
  652.      * @return array[]|null null = the funnel is not configured on this box (table absent)
  653.      */
  654.     private function sdsFunnelRules()
  655.     {
  656.         try {
  657.             $em $this->getDoctrine()->getManager('company_group');
  658.             if (!$em->getConnection()->getSchemaManager()->tablesExist(array('sds_funnel_routing'))) {
  659.                 return null;
  660.             }
  661.             $rules = array();
  662.             foreach ($em->getRepository(SdsFunnelRouting::class)->findAll() as $r) {
  663.                 $rules[] = array(
  664.                     'id' => (int) $r->getId(),
  665.                     'country_code' => $r->getCountryCode(),
  666.                     'app_id' => (int) $r->getAppId(),
  667.                     'priority' => (int) $r->getPriority(),
  668.                     'enabled' => (int) $r->getEnabledFlag(),
  669.                 );
  670.             }
  671.             return $rules;
  672.         } catch (\Throwable $e) {
  673.             return null;
  674.         }
  675.     }
  676.     /** Display name for a routed tenant (the consent copy must NAME the recipient). */
  677.     private function sdsFunnelTenantLabel($appId)
  678.     {
  679.         try {
  680.             $goc $this->getDoctrine()->getManager('company_group')
  681.                 ->getRepository('CompanyGroupBundle\\Entity\\CompanyGroup')
  682.                 ->findOneBy(array('appId' => (int) $appId));
  683.             $name $goc trim((string) $goc->getName()) : '';
  684.             return $name !== '' $name : ('Partner workspace #' . (int) $appId);
  685.         } catch (\Throwable $e) {
  686.             return 'Partner workspace #' . (int) $appId;
  687.         }
  688.     }
  689.     /**
  690.      * FUNNEL-2 — GET the would-be recipient for a country, so the consent copy can NAME
  691.      * the company BEFORE the visitor submits (DE requirement; copy is ENTWURF until
  692.      * counsel clears it). Returns only a display name — never rule internals.
  693.      */
  694.     public function CentralRooftopOfferTargetAction(Request $request)
  695.     {
  696.         if ($refused $this->hb360RateGuard($request'offer'30)) {
  697.             return $refused;
  698.         }
  699.         $country = (string) $request->query->get('country''');
  700.         if (!FunnelRoutingCore::isValidCountry($country)) {
  701.             return new JsonResponse(['ok' => false'error' => 'Pick your country first.'], 422);
  702.         }
  703.         $rules $this->sdsFunnelRules();
  704.         if ($rules === null) {
  705.             return new JsonResponse(['ok' => false'error' => 'Offers are not available yet on this site.'], 503);
  706.         }
  707.         $res FunnelRoutingCore::resolve($rules$country);
  708.         if (empty($res['ok'])) {
  709.             return new JsonResponse(['ok' => false'unrouted' => true,
  710.                 'error' => 'We do not have a solar partner for your country yet — your request would be recorded and we will contact you when one is available.']);
  711.         }
  712.         return new JsonResponse(['ok' => true'company' => $this->sdsFunnelTenantLabel($res['app_id'])]);
  713.     }
  714.     /**
  715.      * FUNNEL-2 — "Request offer": the visitor's SAVED design + their contact facts become
  716.      * ONE outbox row (status pending, or 'unrouted' STORED so the operator sees the
  717.      * demand). Delivery is the dispatch cron's job — this endpoint never talks to a
  718.      * tenant box. Consent is required and recorded; the response names the recipient.
  719.      */
  720.     public function CentralRooftopRequestOfferAction(Request $request)
  721.     {
  722.         if ($refused $this->hb360RateGuard($request'offer'30)) {
  723.             return $refused;
  724.         }
  725.         $body json_decode((string) $request->getContent(), true);
  726.         if (!is_array($body)) {
  727.             return new JsonResponse(['ok' => false'error' => 'Malformed request.'], 400);
  728.         }
  729.         $name trim((string) ($body['name'] ?? ''));
  730.         $email trim((string) ($body['email'] ?? ''));
  731.         $phone trim((string) ($body['phone'] ?? ''));
  732.         $country trim((string) ($body['country'] ?? ''));
  733.         $message trim((string) ($body['message'] ?? ''));
  734.         if (mb_strlen($name) < 2) {
  735.             return new JsonResponse(['ok' => false'error' => 'Enter your name.'], 422);
  736.         }
  737.         if (!filter_var($emailFILTER_VALIDATE_EMAIL)) {
  738.             return new JsonResponse(['ok' => false'error' => 'Enter a valid email address.'], 422);
  739.         }
  740.         if (!FunnelRoutingCore::isValidCountry($country)) {
  741.             return new JsonResponse(['ok' => false'error' => 'Pick your country.'], 422);
  742.         }
  743.         if (empty($body['consent'])) {
  744.             return new JsonResponse(['ok' => false'error' => 'Please confirm the consent checkbox — we can only send your design to a partner with your agreement.'], 422);
  745.         }
  746.         // the SAVED design is the subject — an OWNED row when the signed-in applicant
  747.         // named one (FUNNEL-3), else the visitor's one anon draft (FUNNEL-1)
  748.         $token = (string) $request->cookies->get('hb360_anon''');
  749.         $project null;
  750.         $stored null;
  751.         try {
  752.             $em $this->getDoctrine()->getManager('company_group');
  753.             $svc = new Hb360ProjectService($em);
  754.             $project $this->applicantOwnedProject($request, (int) ($body['project_id'] ?? 0), $svc);
  755.             if ($project === null && preg_match('/^[a-f0-9]{32,64}$/'$token)) {
  756.                 $project $svc->findLatestForToken($token);
  757.             }
  758.             if ($project && $project->getDesignJson()) {
  759.                 $dj json_decode((string) $project->getDesignJson(), true);
  760.                 if (is_array($dj) && isset($dj['payload']) && is_array($dj['payload'])) {
  761.                     $stored $dj;
  762.                 }
  763.             }
  764.         } catch (\Throwable $e) {
  765.             $stored null;
  766.         }
  767.         if ($stored === null) {
  768.             return new JsonResponse(['ok' => false'error' => 'Save your design first — the offer is prepared from the saved layout.'], 422);
  769.         }
  770.         $rules $this->sdsFunnelRules();
  771.         if ($rules === null) {
  772.             return new JsonResponse(['ok' => false'error' => 'Offers are not available yet on this site.'], 503);
  773.         }
  774.         $resolved FunnelRoutingCore::resolve($rules$country);
  775.         try {
  776.             $em $this->getDoctrine()->getManager('company_group');
  777.             $h = new SdsFunnelHandoff();
  778.             $h->setHandoffUid(bin2hex(random_bytes(12))); // 24 hex — fits 'sdsf:'+uid in lead.source(50)
  779.             $h->setProjectId($project ? (int) $project->getId() : null);
  780.             $h->setManifestHash((string) ($stored['hash'] ?? ''));
  781.             $h->setManifestJson(json_encode($storedJSON_UNESCAPED_UNICODE));
  782.             $h->setLeadJson(json_encode([
  783.                 'name' => mb_substr($name0255),
  784.                 'email' => mb_substr($email0255),
  785.                 'phone' => mb_substr($phone064),
  786.                 'country_code' => strtoupper(substr($country02)),
  787.                 'message' => mb_substr($message02000),
  788.                 'consent_at' => date('c'),
  789.                 'source' => 'hb360-public-studio',
  790.             ], JSON_UNESCAPED_UNICODE));
  791.             $h->setCountryCode($country);
  792.             $h->setAddress((string) ($project $project->getAddress() : ''));
  793.             if (!empty($resolved['ok'])) {
  794.                 $h->setRuleId($resolved['rule_id']);
  795.                 $h->setTargetAppId($resolved['app_id']);
  796.                 $h->setStatus('pending');
  797.             } else {
  798.                 $h->setStatus('unrouted'); // stored — the operator sees the demand (EB 'unlinked' discipline)
  799.                 $h->setLastError('no routing rule matched country ' strtoupper($country));
  800.             }
  801.             $em->persist($h);
  802.             $em->flush();
  803.         } catch (\Throwable $e) {
  804.             return new JsonResponse(['ok' => false'error' => 'Could not record your request right now — please try again in a moment.'], 503);
  805.         }
  806.         if (empty($resolved['ok'])) {
  807.             return new JsonResponse(['ok' => true'unrouted' => true,
  808.                 'note' => 'We do not have a solar partner for your country yet. Your request is recorded and we will contact you at ' $email ' when one is available.']);
  809.         }
  810.         return new JsonResponse(['ok' => true,
  811.             'company' => $this->sdsFunnelTenantLabel($resolved['app_id']),
  812.             'note' => 'Your design and contact details will be sent to ' $this->sdsFunnelTenantLabel($resolved['app_id'])
  813.                 . ', who will prepare your offer and contact you at ' $email '.']);
  814.     }
  815.     /** H1c: public read-only view of a shared feasibility report (unguessable token). */
  816.     public function Hb360SharedAction($shareToken)
  817.     {
  818.         $project null;
  819.         try {
  820.             $em $this->getDoctrine()->getManager('company_group');
  821.             $project = (new Hb360ProjectService($em))->findByShareToken((string) $shareToken);
  822.         } catch (\Throwable $e) {
  823.             $project null;
  824.         }
  825.         if (!$project) {
  826.             throw $this->createNotFoundException();
  827.         }
  828.         return $this->render('@HoneybeeWeb/pages/tools/hb360_shared.html.twig', array(
  829.             'page_title' => 'Shared Solar Feasibility Estimate | HoneyBee 360',
  830.             'project'    => $project,
  831.             'estimate'   => json_decode($project->getEstimateJson(), true),
  832.             'report'     => $project->getReportJson() ? json_decode($project->getReportJson(), true) : null,
  833.         ));
  834.     }
  835.     /**
  836.      * HB360 H1a: roof (T1, resolved by the caller) + PV sizing (T3, always via the
  837.      * one PV engine SolarEngineeringService inside Hb360EstimateService) + bill →
  838.      * saving/payback (T2-lite), every figure honesty-tagged.
  839.      */
  840.     private function computeRooftopDesign($lat$lng$area$tilt$mode$monthlyKwh$monthlyBill$tariff$preset null$roofSource 'map')
  841.     {
  842.         $yieldSource   'PVGIS';
  843.         $specificYield $this->pvgisSpecificYield($lat$lng$tilt);
  844.         if ($specificYield === null) {
  845.             $specificYield $this->fallbackYieldByLatitude($lat);
  846.             $yieldSource 'climate estimate';
  847.         }
  848.         return (new Hb360EstimateService())->estimate([
  849.             'roofAreaM2'    => $area,
  850.             'roofSource'    => $roofSource,
  851.             'specificYield' => $specificYield,
  852.             'yieldSource'   => $yieldSource,
  853.             'monthlyKwh'    => $monthlyKwh,
  854.             'monthlyBill'   => $monthlyBill,
  855.             'tariff'        => $tariff,
  856.             'mode'          => $mode,
  857.             'preset'        => $preset,
  858.         ]);
  859.     }
  860.     /**
  861.      * SDS2: one studio ZONE → yield/cost/payback, same estimate family as the simple flow.
  862.      * The zone's plane(s) come from the ONE deterministic mapping in SdsEconCore (EW = the
  863.      * documented east+west PVGIS average); sizing snaps to the packed kWp; the €/kWp tier is
  864.      * picked from the WHOLE design's capacity (total_kwp) so zone costs sum consistently.
  865.      */
  866.     protected function computeSdsZoneEconomics($lat$lng$areaM2$kwp, array $zone$monthlyKwh$monthlyBill$tariff)
  867.     {
  868.         $planes SdsEconCore::planesFor($zone['pitch_deg'], $zone['azimuth_deg'], $zone['mount_mode']);
  869.         $planeYields = [];
  870.         $yieldSource 'PVGIS';
  871.         foreach ($planes as $p) {
  872.             $y $this->pvgisYieldPlane($lat$lng$p['angle'], $p['aspect']);
  873.             $planeYields[] = ['yield' => $y'weight' => $p['weight'], 'angle' => $p['angle'], 'aspect' => $p['aspect']];
  874.         }
  875.         $sy SdsEconCore::combineYields($planeYields);
  876.         if ($sy === null) {
  877.             // Any missing plane ⇒ fall back WHOLLY (a half-real EW average would be a lie).
  878.             $sy $this->fallbackYieldByLatitude($lat);
  879.             $yieldSource 'climate estimate';
  880.         }
  881.         $res = (new Hb360EstimateService())->estimate([
  882.             'roofAreaM2'    => $areaM2,
  883.             'roofSource'    => 'map',
  884.             'specificYield' => $sy,
  885.             'yieldSource'   => $yieldSource,
  886.             'monthlyKwh'    => $monthlyKwh,
  887.             'monthlyBill'   => $monthlyBill,
  888.             'tariff'        => $tariff,
  889.             'mode'          => 'roof'// the layout IS the size — never shrink to load here
  890.             'targetKwp'     => $kwp,
  891.             'moduleWp'      => $zone['module_wp'],
  892.             'rateBasisKwp'  => $zone['total_kwp'],
  893.         ]);
  894.         if (!empty($res['ok'])) {
  895.             $res['lat'] = $lat$res['lng'] = $lng;
  896.             $res['sds'] = [
  897.                 'requested_kwp'  => $kwp,
  898.                 'mount_mode'     => $zone['mount_mode'],
  899.                 'pitch_deg'      => $zone['pitch_deg'],
  900.                 'azimuth_deg'    => $zone['azimuth_deg'],
  901.                 'rate_basis_kwp' => $zone['total_kwp'] > $zone['total_kwp'] : $kwp,
  902.                 'planes'         => $planeYields,
  903.             ];
  904.         }
  905.         return $res;
  906.     }
  907.     /**
  908.      * SDS2: PVGIS specific yield (kWh/kWp/yr) for an arbitrary plane, CACHED per rounded
  909.      * (lat, lng, angle, aspect) — in-request static + a tmp-dir file cache (30 days; yield is
  910.      * climate data) — so live studio editing cannot hammer the PVGIS API. No schema, and every
  911.      * cache failure degrades to just calling PVGIS. Null on PVGIS failure.
  912.      */
  913.     protected function pvgisYieldPlane($lat$lng$angle$aspect)
  914.     {
  915.         static $memo = [];
  916.         $key SdsEconCore::cacheKey($lat$lng$angle$aspect);
  917.         if (array_key_exists($key$memo)) { return $memo[$key]; }
  918.         $file null;
  919.         try {
  920.             $dir sys_get_temp_dir() . DIRECTORY_SEPARATOR 'hb_pvgis_cache';
  921.             if (!is_dir($dir)) { @mkdir($dir0775true); }
  922.             $file $dir DIRECTORY_SEPARATOR $key '.json';
  923.             if (is_file($file) && (time() - (int) @filemtime($file)) < 30 86400) {
  924.                 $cached json_decode((string) @file_get_contents($file), true);
  925.                 if (is_array($cached) && array_key_exists('ey'$cached)) {
  926.                     return $memo[$key] = ($cached['ey'] !== null ? (float) $cached['ey'] : null);
  927.                 }
  928.             }
  929.         } catch (\Throwable $e) { $file null; }
  930.         $url sprintf(
  931.             'https://re.jrc.ec.europa.eu/api/v5_2/PVcalc?lat=%F&lon=%F&peakpower=1&loss=14&angle=%F&aspect=%F&mountingplace=building&outputformat=json',
  932.             $lat$lng$angle$aspect
  933.         );
  934.         $ey null;
  935.         try {
  936.             $ctx  stream_context_create(['http' => ['timeout' => 8'ignore_errors' => true]]);
  937.             $body = @file_get_contents($urlfalse$ctx);
  938.             if ($body !== false) {
  939.                 $data json_decode($bodytrue);
  940.                 $v = isset($data['outputs']['totals']['fixed']['E_y']) ? $data['outputs']['totals']['fixed']['E_y'] : null;
  941.                 $ey = ($v && $v 0) ? (float) $v null;
  942.             }
  943.         } catch (\Throwable $e) {
  944.             $ey null;
  945.         }
  946.         // Cache successes only — a transient PVGIS outage must not pin "unavailable" for 30 days.
  947.         if ($file !== null && $ey !== null) {
  948.             try { @file_put_contents($filejson_encode(['ey' => $ey]), LOCK_EX); } catch (\Throwable $e) { /* cache is an enhancement */ }
  949.         }
  950.         return $memo[$key] = $ey;
  951.     }
  952.     /** Geocode an address → ['lat','lng','formatted'] or null. */
  953.     private function geocodeAddress($address)
  954.     {
  955.         $url  'https://maps.googleapis.com/maps/api/geocode/json?address=' rawurlencode($address) . '&key=' $this->mapsKey();
  956.         $data $this->httpJson($urlnull8);
  957.         if (!$data || ($data['status'] ?? '') !== 'OK' || empty($data['results'][0])) { return null; }
  958.         $r $data['results'][0];
  959.         return [
  960.             'lat'       => (float) $r['geometry']['location']['lat'],
  961.             'lng'       => (float) $r['geometry']['location']['lng'],
  962.             'formatted' => $r['formatted_address'] ?? $address,
  963.         ];
  964.     }
  965.     /** Google Solar API building insights → preset design, or null if disabled / no coverage. */
  966.     private function solarApiDesign($lat$lng)
  967.     {
  968.         $url  sprintf('https://solar.googleapis.com/v1/buildingInsights:findClosest?location.latitude=%F&location.longitude=%F&requiredQuality=LOW&key=%s'$lat$lng$this->mapsKey());
  969.         $data $this->httpJson($urlnull8);
  970.         if (!$data || isset($data['error']) || empty($data['solarPotential'])) { return null; }
  971.         $sp $data['solarPotential'];
  972.         $roofArea $sp['wholeRoofStats']['areaMeters2'] ?? ($sp['maxArrayAreaMeters2'] ?? null);
  973.         $panels   $sp['maxArrayPanelsCount'] ?? null;
  974.         $watts    $sp['panelCapacityWatts'] ?? 400;
  975.         if (!$roofArea || !$panels) { return null; }
  976.         // best (largest) config's annual DC energy
  977.         $annualDc null;
  978.         foreach (($sp['solarPanelConfigs'] ?? []) as $cfg) {
  979.             if (isset($cfg['yearlyEnergyDcKwh'])) { $annualDc $cfg['yearlyEnergyDcKwh']; }
  980.         }
  981.         return ['panels' => (int) $panels'panel_watts' => (float) $watts'annual_dc_kwh' => $annualDc'roof_area' => (float) $roofArea];
  982.     }
  983.     /** OSM building footprint area (m²) at a point via Overpass; null if none/unreachable. */
  984.     private function osmBuildingArea($lat$lng)
  985.     {
  986.         $q    sprintf('[out:json][timeout:20];way(around:30,%F,%F)[building];out geom;'$lat$lng);
  987.         $data $this->httpJson('https://overpass-api.de/api/interpreter''data=' rawurlencode($q), 22);
  988.         if (!$data || empty($data['elements'])) { return null; }
  989.         $best null$bestArea 0$containing null;
  990.         foreach ($data['elements'] as $el) {
  991.             if (empty($el['geometry'])) { continue; }
  992.             $a $this->polygonAreaM2($el['geometry']);
  993.             if ($a $bestArea) { $bestArea $a$best $el; }
  994.             if ($this->pointInPolygon($lat$lng$el['geometry'])) { $containing $a; }
  995.         }
  996.         $area $containing ?: $bestArea;
  997.         return $area $area null;
  998.     }
  999.     /** Planar area (m²) of a lat/lng ring via equirectangular projection. */
  1000.     private function polygonAreaM2($geometry)
  1001.     {
  1002.         $rad M_PI 180$R 6378137;
  1003.         $lat0 $geometry[0]['lat'] * $rad$cos cos($lat0);
  1004.         $pts = [];
  1005.         foreach ($geometry as $g) { $pts[] = [$g['lon'] * $rad $R $cos$g['lat'] * $rad $R]; }
  1006.         $n count($pts); if ($n 3) { return 0; }
  1007.         $a 0;
  1008.         for ($i 0$i $n 1$i++) { $a += $pts[$i][0] * $pts[$i 1][1] - $pts[$i 1][0] * $pts[$i][1]; }
  1009.         return abs($a) / 2;
  1010.     }
  1011.     /** Ray-cast point-in-polygon for a lat/lng ring. */
  1012.     private function pointInPolygon($lat$lng$geometry)
  1013.     {
  1014.         $in false$n count($geometry);
  1015.         for ($i 0$j $n 1$i $n$j $i++) {
  1016.             $yi $geometry[$i]['lat']; $xi $geometry[$i]['lon'];
  1017.             $yj $geometry[$j]['lat']; $xj $geometry[$j]['lon'];
  1018.             if ((($yi $lat) !== ($yj $lat)) && ($lng < ($xj $xi) * ($lat $yi) / (($yj $yi) ?: 1e-12) + $xi)) { $in = !$in; }
  1019.         }
  1020.         return $in;
  1021.     }
  1022.     /** Minimal JSON HTTP helper (GET when $post is null, else POST form body). Null on failure. */
  1023.     private function httpJson($url$post null$timeout 8)
  1024.     {
  1025.         try {
  1026.             $opts = ['http' => ['timeout' => $timeout'ignore_errors' => true'header' => "User-Agent: HoneyBee/1.0\r\n"]];
  1027.             if ($post !== null) {
  1028.                 $opts['http']['method']  = 'POST';
  1029.                 $opts['http']['header'] .= "Content-Type: application/x-www-form-urlencoded\r\n";
  1030.                 $opts['http']['content'] = $post;
  1031.             }
  1032.             $body = @file_get_contents($urlfalsestream_context_create($opts));
  1033.             if ($body === false) { return null; }
  1034.             return json_decode($bodytrue);
  1035.         } catch (\Throwable $e) {
  1036.             return null;
  1037.         }
  1038.     }
  1039.     /** Annual specific yield (kWh/kWp) from PVGIS for a fixed building-mounted array. Null on failure.
  1040.      *  SDS2: now the aspect-0 (south) case of the cached plane helper — same PVGIS call and value
  1041.      *  semantics as before, plus the cache. */
  1042.     private function pvgisSpecificYield($lat$lng$tilt)
  1043.     {
  1044.         return $this->pvgisYieldPlane($lat$lng$tilt0.0);
  1045.     }
  1046.     /** Rough kWh/kWp/yr by absolute latitude when PVGIS is unreachable. */
  1047.     protected function fallbackYieldByLatitude($lat)
  1048.     {
  1049.         $a abs($lat);
  1050.         if ($a 15) { return 1500; }   // tropical
  1051.         if ($a 25) { return 1450; }   // e.g. BD/SG belt
  1052.         if ($a 35) { return 1350; }   // subtropical
  1053.         if ($a 45) { return 1150; }   // southern EU
  1054.         if ($a 55) { return 1000; }   // central EU / DE
  1055.         return 850;                     // northern EU
  1056.     }
  1057.     // our service
  1058.     public function CentralServicePageAction()
  1059.     {
  1060.         return $this->render('@HoneybeeWeb/pages/service.html.twig', array(
  1061.             'page_title' => 'Services | HoneyBee — Hardware, HoneyCore Edge EMS, Local ML & Integration',
  1062.         ));
  1063.     }
  1064.     // payment method
  1065.     public function CentralPaymentMethodPageAction()
  1066.     {
  1067.         $stripe_secret_key$this->container->getParameter('stripe_secret_key_live');
  1068.         $stripe_key$this->container->getParameter('stripe_public_key_live');
  1069.         return $this->render('@HoneybeeWeb/pages/payment-method.html.twig', array(
  1070.             'page_title' => 'Payment Method',
  1071.             'stripe_key' => $stripe_key,
  1072.         ));
  1073.     }
  1074.     // single blog page
  1075.     public function CentralSingleBlogPageAction(Request $request)
  1076.     {
  1077.         $em $this->getDoctrine()->getManager('company_group');
  1078.         $blogId $request->query->get('id');
  1079.         if (!$blogId) {
  1080.             throw $this->createNotFoundException('Blog ID not provided.');
  1081.         }
  1082.         $blogDetails $em->getRepository('CompanyGroupBundle\Entity\EntityCreateBlog')->find($blogId);
  1083.         if (!$blogDetails) {
  1084.             throw $this->createNotFoundException('Blog not found.');
  1085.         }
  1086.         // Fetch related blogs by same topic (optional but useful)
  1087.         $relatedBlogs $em->getRepository('CompanyGroupBundle\Entity\EntityCreateBlog')->findBy(
  1088.             ['topicId' => $blogDetails->getTopicId()],
  1089.             ['createdAt' => 'DESC'],
  1090.             5
  1091.         );
  1092.         return $this->render('@HoneybeeWeb/pages/single_blog.html.twig', [
  1093.             'page_title' => $blogDetails->getTitle(),
  1094.             'blog'       => $blogDetails,
  1095.             'related_blogs' => $relatedBlogs,
  1096.         ]);
  1097.     }
  1098.     // login v2 (verification code page)
  1099.     public function CentralLoginCodePageAction()
  1100.     {
  1101.         return $this->render('@HoneybeeWeb/pages/login_code.html.twig', array(
  1102.             'page_title' => 'Verification Code',
  1103.         ));
  1104.     }
  1105.     // reset pass
  1106.     public function CentralResetPasswordPageAction()
  1107.     {
  1108.         return $this->render('@HoneybeeWeb/pages/reset_password.html.twig', array(
  1109.             'page_title' => 'Verification Code',
  1110.         ));
  1111.     }
  1112.     public function PublicProfilePageAction(Request $request$id 0)
  1113.     {
  1114.         $em $this->getDoctrine()->getManager('company_group');
  1115.         $session $request->getSession();
  1116.         return $this->render('@Application/pages/central/central_employee_profile.html.twig', array(
  1117.             'page_title' => 'Freelancer Profile',
  1118. //            'details' =>$em->getRepository(EntityApplicantDetails::class)->find($id),
  1119.         ));
  1120.     }
  1121.     // freelancer profile
  1122.     public function CentralApplicantProfilePageAction(Request $request$id 0)
  1123.     {
  1124.         $em $this->getDoctrine()->getManager('company_group');
  1125.         $session $request->getSession();
  1126.         return $this->render('@HoneybeeWeb/pages/freelancer_profile.html.twig', array(
  1127.             'page_title' => 'Freelancer Profile',
  1128.             'details' => $em->getRepository(EntityApplicantDetails::class)->find($id),
  1129.         ));
  1130.     }
  1131.     // employee profile
  1132.     /**
  1133.      * Public professional profile. UNAUTHENTICATED by design (this class declares no gate) — treat
  1134.      * everything it renders as published to the world.
  1135.      *
  1136.      * CC7e-#6 (2026-07-15) — the `E`-format CROSS-TENANT BRANCH IS DELETED. It used to accept
  1137.      * `/EmployeePublicProfile/E{appId}{empId}`, look up ANY tenant in the central registry from
  1138.      * numbers in the URL, and cURL that tenant's own box (`/GetGlobalIdFromEmployeeId`) to resolve an
  1139.      * employee — with **no gate, no authorization, and `CURLOPT_SSL_VERIFYPEER/VERIFYHOST => false`**,
  1140.      * i.e. an anonymous stranger made us reach into a customer's HR system on their behalf over a
  1141.      * deliberately unverified TLS hop. Nothing in the codebase linked to it. Deleting the branch
  1142.      * closes three findings at once: the anonymous cross-tenant fan-out, the MITM-able hop, and a
  1143.      * null-deref (`$entry` was used without a null check, so an unknown appId fatalled — the "500 is
  1144.      * not a gate" class).
  1145.      *
  1146.      * If cross-tenant profiles are ever a real product need, they are a GATED, authorized feature
  1147.      * with a session — not an anonymous fan-out driven by two numbers in a URL.
  1148.      *
  1149.      * What remains is the plain path: `$id` is a central applicantId. The identity payload
  1150.      * (NID/DOB/parents/religion/blood/address/phone) has been stripped from the template — see
  1151.      * public_profile.html.twig. This route still ENUMERATES (any id ⇒ name + photo + role); that is
  1152.      * the accepted, recorded ceiling, and it is the product question CC7g will make gateable.
  1153.      */
  1154.     public function PublicEmployeeProfileAction($id)
  1155.     {
  1156.         $em $this->getDoctrine()->getManager('company_group');
  1157.         // An applicant id is a positive integer. Anything else (including the old `E…` format, now
  1158.         // that the cross-tenant branch is gone) is refused here rather than handed to find(), which
  1159.         // would throw on a non-numeric id and 500. Not a security control — the disclosure is fixed
  1160.         // in the template — just not leaving a crash where a 404 belongs.
  1161.         if (!ctype_digit((string) $id) || (int) $id <= 0) {
  1162.             throw $this->createNotFoundException('Profile not found.');
  1163.         }
  1164.         $data $em->getRepository(EntityApplicantDetails::class)->find((int) $id);
  1165.         if (!$data) {
  1166.             throw $this->createNotFoundException('Profile not found.');
  1167.         }
  1168.         return $this->render('@HoneybeeWeb/pages/public_profile.html.twig', array(
  1169.             'page_title' => 'Employee Profile',
  1170.             'details' => $data,
  1171.             'genderList' => EmployeeConstant::$sex,
  1172.             'bloodGroupList' => EmployeeConstant::$BloodGroup,
  1173.             'skillDetails' => $em->getRepository('CompanyGroupBundle\\Entity\\EntitySkill')->findAll(),
  1174.         ));
  1175.     }
  1176.     // add employee
  1177.     public function CentralAddEmployeePageAction()
  1178.     {
  1179.         return $this->render('@HoneybeeWeb/pages/add_employee.html.twig', array(
  1180.             'page_title' => 'Add New Eployee',
  1181.         ));
  1182.     }
  1183.     // book appointment
  1184.     public function CentralBookAppointmentPageAction()
  1185.     {
  1186.         return $this->render('@HoneybeeWeb/pages/book_appointment.html.twig', array(
  1187.             'page_title' => 'Book Appointment',
  1188.         ));
  1189.     }
  1190.     // create_compnay
  1191.     public function CentralCreateCompanyPageAction()
  1192.     {
  1193.         return $this->render('@HoneybeeWeb/pages/create_company.html.twig', array(
  1194.             'page_title' => 'Create Company',
  1195.         ));
  1196.     }
  1197.     // role and company
  1198.     public function CentralRoleAndCompanyPageAction()
  1199.     {
  1200.         return $this->render('@HoneybeeWeb/pages/role_and_company.html.twig', array(
  1201.             'page_title' => 'Role and Company',
  1202.         ));
  1203.     }
  1204.     // send otp action **
  1205.     public function SendOtpAjaxAction(Request $request$startFrom 0)
  1206.     {
  1207.         $em $this->getDoctrine()->getManager();
  1208.         $em_goc $this->getDoctrine()->getManager('company_group');
  1209.         $session $request->getSession();
  1210.         $message "";
  1211.         $retData = array();
  1212.         $email_twig_data = array('success' => false);
  1213.         $systemType $this->container->hasParameter('system_type') ? $this->container->getParameter('system_type') : '_ERP_';
  1214.         $userCategory $request->request->get('userCategory'$request->query->get('userCategory''_BUDDYBEE_USER_'));
  1215.         $email_address $request->request->get('email'$request->query->get('email'''));
  1216.         $otpExpireSecond $request->request->get('otpExpireSecond'$request->query->get('otpExpireSecond'180));
  1217.         $otpActionId $request->request->get('otpActionId'$request->query->get('otpActionId'UserConstants::OTP_ACTION_FORGOT_PASSWORD));
  1218.         $appendCode $request->request->get('appendCode'$request->query->get('appendCode'''));
  1219.         $otp $request->request->get('otp'$request->query->get('otp'''));
  1220.         $otpExpireTs 0;
  1221.         $userId $request->request->get('userId'$request->query->get('userId'$session->get(UserConstants::USER_ID0)));
  1222.         $userType UserConstants::USER_TYPE_APPLICANT;
  1223.         $email_twig_file '@Application/pages/email/find_account_buddybee.html.twig';
  1224.         if ($request->isMethod('POST')) {
  1225.             //set an otp and its expire and send mail
  1226.             $userObj null;
  1227.             $userData = [];
  1228.             if ($systemType == '_ERP_') {
  1229.                 if ($userCategory == '_APPLICANT_') {
  1230.                     $userType UserConstants::USER_TYPE_APPLICANT;
  1231.                     $userObj $em_goc->getRepository('CompanyGroupBundle\\Entity\\EntityApplicantDetails')->findOneBy(
  1232.                         array(
  1233.                             'applicantId' => $userId
  1234.                         )
  1235.                     );
  1236.                     if ($userObj) {
  1237.                     } else {
  1238.                         $userObj $em_goc->getRepository('CompanyGroupBundle\\Entity\\EntityApplicantDetails')->findOneBy(
  1239.                             array(
  1240.                                 'email' => $email_address
  1241.                             )
  1242.                         );
  1243.                         if ($userObj) {
  1244.                         } else {
  1245.                             $userObj $em_goc->getRepository('CompanyGroupBundle\\Entity\\EntityApplicantDetails')->findOneBy(
  1246.                                 array(
  1247.                                     'oAuthEmail' => $email_address
  1248.                                 )
  1249.                             );
  1250.                             if ($userObj) {
  1251.                             } else {
  1252.                                 $userObj $em_goc->getRepository('CompanyGroupBundle\\Entity\\EntityApplicantDetails')->findOneBy(
  1253.                                     array(
  1254.                                         'username' => $email_address
  1255.                                     )
  1256.                                 );
  1257.                             }
  1258.                         }
  1259.                     }
  1260.                     if ($userObj) {
  1261.                         $email_address $userObj->getEmail();
  1262.                         if ($email_address == null || $email_address == '')
  1263.                             $email_address $userObj->getOAuthEmail();
  1264.                     }
  1265.                     $otpData MiscActions::GenerateOtp($otpExpireSecond);
  1266.                     $otp $otpData['otp'];
  1267.                     $otpExpireTs $otpData['expireTs'];
  1268.                     $userObj->setOtp($otpData['otp']);
  1269.                     $userObj->setOtpActionId($otpActionId);
  1270.                     $userObj->setOtpExpireTs($otpData['expireTs']);
  1271.                     $em_goc->flush();
  1272.                     $userData = array(
  1273.                         'id' => $userObj->getApplicantId(),
  1274.                         'email' => $email_address,
  1275.                         'appId' => 0,
  1276.                         //                        'appId'=>$userObj->getUserAppId(),
  1277.                     );
  1278.                     $email_twig_file '@Application/email/templates/forgotPasswordOtp.html.twig';
  1279.                     $email_twig_data = [
  1280.                         'page_title' => 'Find Account',
  1281.                         'message' => $message,
  1282.                         'userType' => $userType,
  1283.                         'otp' => $otpData['otp'],
  1284.                         'otpExpireSecond' => $otpExpireSecond,
  1285.                         'otpActionId' => $otpActionId,
  1286.                         'otpExpireTs' => $otpData['expireTs'],
  1287.                         'systemType' => $systemType,
  1288.                         'userData' => $userData
  1289.                     ];
  1290.                     if ($userObj)
  1291.                         $email_twig_data['success'] = true;
  1292.                 } else {
  1293.                     $userType UserConstants::USER_TYPE_GENERAL;
  1294.                     $email_twig_file '@Application/email/templates/forgotPasswordOtp.html.twig';
  1295.                     $email_twig_data = [
  1296.                         'page_title' => 'Find Account',
  1297.                         //   'encryptedData' => $encryptedData,
  1298.                         'message' => $message,
  1299.                         'userType' => $userType,
  1300.                         //  'errorField' => $errorField,
  1301.                     ];
  1302.                 }
  1303.             } else if ($systemType == '_BUDDYBEE_') {
  1304.                 $userType UserConstants::USER_TYPE_APPLICANT;
  1305.                 $userObj $em_goc->getRepository('CompanyGroupBundle\\Entity\\EntityApplicantDetails')->findOneBy(
  1306.                     array(
  1307.                         'applicantId' => $userId
  1308.                     )
  1309.                 );
  1310.                 if ($userObj) {
  1311.                 } else {
  1312.                     $userObj $em_goc->getRepository('CompanyGroupBundle\\Entity\\EntityApplicantDetails')->findOneBy(
  1313.                         array(
  1314.                             'email' => $email_address
  1315.                         )
  1316.                     );
  1317.                     if ($userObj) {
  1318.                     } else {
  1319.                         $userObj $em_goc->getRepository('CompanyGroupBundle\\Entity\\EntityApplicantDetails')->findOneBy(
  1320.                             array(
  1321.                                 'oAuthEmail' => $email_address
  1322.                             )
  1323.                         );
  1324.                         if ($userObj) {
  1325.                         } else {
  1326.                             $userObj $em_goc->getRepository('CompanyGroupBundle\\Entity\\EntityApplicantDetails')->findOneBy(
  1327.                                 array(
  1328.                                     'username' => $email_address
  1329.                                 )
  1330.                             );
  1331.                         }
  1332.                     }
  1333.                 }
  1334.                 if ($userObj) {
  1335.                     $email_address $userObj->getEmail();
  1336.                     if ($email_address == null || $email_address == '')
  1337.                         $email_address $userObj->getOAuthEmail();
  1338.                     //                    triggerResetPassword:
  1339.                     //                    type: integer
  1340.                     //                          nullable: true
  1341.                     $otpData MiscActions::GenerateOtp($otpExpireSecond);
  1342.                     $otp $otpData['otp'];
  1343.                     $otpExpireTs $otpData['expireTs'];
  1344.                     $userObj->setOtp($otpData['otp']);
  1345.                     $userObj->setOtpActionId($otpActionId);
  1346.                     $userObj->setOtpExpireTs($otpData['expireTs']);
  1347.                     $em_goc->flush();
  1348.                     $userData = array(
  1349.                         'id' => $userObj->getApplicantId(),
  1350.                         'email' => $email_address,
  1351.                         'appId' => 0,
  1352.                         'image' => $userObj->getImage(),
  1353.                         'phone' => $userObj->getPhone(),
  1354.                         'firstName' => $userObj->getFirstname(),
  1355.                         'lastName' => $userObj->getLastname(),
  1356.                         //                        'appId'=>$userObj->getUserAppId(),
  1357.                     );
  1358.                     $email_twig_file '@Application/email/templates/forgotPasswordOtp.html.twig';
  1359.                     $email_twig_data = [
  1360.                         'page_title' => 'Find Account',
  1361.                         //                        'encryptedData' => $encryptedData,
  1362.                         'message' => $message,
  1363.                         'userType' => $userType,
  1364.                         //                        'errorField' => $errorField,
  1365.                         'otp' => $otpData['otp'],
  1366.                         'otpExpireSecond' => $otpExpireSecond,
  1367.                         'otpActionId' => $otpActionId,
  1368.                         'otpActionTitle' => UserConstants::$OTP_ACTION_DATA[$otpActionId]['actionTitle'],
  1369.                         'otpActionDescForMail' => UserConstants::$OTP_ACTION_DATA[$otpActionId]['actionDescForMail'],
  1370.                         'otpExpireTs' => $otpData['expireTs'],
  1371.                         'systemType' => $systemType,
  1372.                         'userCategory' => $userCategory,
  1373.                         'userData' => $userData
  1374.                     ];
  1375.                     $email_twig_data['success'] = true;
  1376.                 } else {
  1377.                     $message "Account not found!";
  1378.                     $email_twig_data['success'] = false;
  1379.                 }
  1380.             } else if ($systemType == '_CENTRAL_') {
  1381.                 $userType UserConstants::USER_TYPE_APPLICANT;
  1382.                 $userObj $em_goc->getRepository('CompanyGroupBundle\\Entity\\EntityApplicantDetails')->findOneBy(
  1383.                     array(
  1384.                         'applicantId' => $userId
  1385.                     )
  1386.                 );
  1387.                 if ($userObj) {
  1388.                 } else {
  1389.                     $userObj $em_goc->getRepository('CompanyGroupBundle\\Entity\\EntityApplicantDetails')->findOneBy(
  1390.                         array(
  1391.                             'email' => $email_address
  1392.                         )
  1393.                     );
  1394.                     if ($userObj) {
  1395.                     } else {
  1396.                         $userObj $em_goc->getRepository('CompanyGroupBundle\\Entity\\EntityApplicantDetails')->findOneBy(
  1397.                             array(
  1398.                                 'oAuthEmail' => $email_address
  1399.                             )
  1400.                         );
  1401.                         if ($userObj) {
  1402.                         } else {
  1403.                             $userObj $em_goc->getRepository('CompanyGroupBundle\\Entity\\EntityApplicantDetails')->findOneBy(
  1404.                                 array(
  1405.                                     'username' => $email_address
  1406.                                 )
  1407.                             );
  1408.                         }
  1409.                     }
  1410.                 }
  1411.                 if ($userObj) {
  1412.                     $email_address $userObj->getEmail();
  1413.                     if ($email_address == null || $email_address == '')
  1414.                         $email_address $userObj->getOAuthEmail();
  1415.                     //                    triggerResetPassword:
  1416.                     //                    type: integer
  1417.                     //                          nullable: true
  1418.                     $otpData MiscActions::GenerateOtp($otpExpireSecond);
  1419.                     $otp $otpData['otp'];
  1420.                     $otpExpireTs $otpData['expireTs'];
  1421.                     $userObj->setOtp($otpData['otp']);
  1422.                     $userObj->setOtpActionId($otpActionId);
  1423.                     $userObj->setOtpExpireTs($otpData['expireTs']);
  1424.                     $em_goc->flush();
  1425.                     $userData = array(
  1426.                         'id' => $userObj->getApplicantId(),
  1427.                         'email' => $email_address,
  1428.                         'appId' => 0,
  1429.                         'image' => $userObj->getImage(),
  1430.                         'phone' => $userObj->getPhone(),
  1431.                         'firstName' => $userObj->getFirstname(),
  1432.                         'lastName' => $userObj->getLastname(),
  1433.                         //                        'appId'=>$userObj->getUserAppId(),
  1434.                     );
  1435.                     $email_twig_file '@HoneybeeWeb/email/templates/otpMail.html.twig';
  1436.                     $email_twig_data = [
  1437.                         'page_title' => 'Find Account',
  1438.                         //                        'encryptedData' => $encryptedData,
  1439.                         'message' => $message,
  1440.                         'userType' => $userType,
  1441.                         //                        'errorField' => $errorField,
  1442.                         'otp' => $otpData['otp'],
  1443.                         'otpExpireSecond' => $otpExpireSecond,
  1444.                         'otpActionId' => $otpActionId,
  1445.                         'otpActionTitle' => UserConstants::$OTP_ACTION_DATA[$otpActionId]['actionTitle'],
  1446.                         'otpActionDescForMail' => UserConstants::$OTP_ACTION_DATA[$otpActionId]['actionDescForMail'],
  1447.                         'otpExpireTs' => $otpData['expireTs'],
  1448.                         'systemType' => $systemType,
  1449.                         'userCategory' => $userCategory,
  1450.                         'userData' => $userData
  1451.                     ];
  1452.                     $email_twig_data['success'] = true;
  1453.                 } else {
  1454.                     $message "Account not found!";
  1455.                     $email_twig_data['success'] = false;
  1456.                 }
  1457.             }
  1458.             if ($email_twig_data['success'] == true && GeneralConstant::EMAIL_ENABLED == 1) {
  1459.                 if ($systemType == '_BUDDYBEE_') {
  1460.                     $bodyHtml '';
  1461.                     $bodyTemplate $email_twig_file;
  1462.                     $bodyData $email_twig_data;
  1463.                     $attachments = [];
  1464.                     $forwardToMailAddress $email_address;
  1465.                     //                    $upl_dir = $this->container->getParameter('kernel.root_dir') . '/../web/uploads/temp/' . 'ledger' . '.pdf'
  1466.                     $new_mail $this->get('mail_module');
  1467.                     $new_mail->sendMyMail(array(
  1468.                         'senderHash' => '_CUSTOM_',
  1469.                         //                        'senderHash'=>'_CUSTOM_',
  1470.                         'forwardToMailAddress' => $forwardToMailAddress,
  1471.                         'subject' => 'Account Verification',
  1472.                         //                        'fileName' => 'Order#' . str_pad($id, 8, '0', STR_PAD_LEFT) . '.pdf',
  1473.                         'attachments' => $attachments,
  1474.                         'toAddress' => $forwardToMailAddress,
  1475.                         'fromAddress' => \ApplicationBundle\Helper\MailerConfig::address(),
  1476.                         'userName' => \ApplicationBundle\Helper\MailerConfig::address(),
  1477.                         'password' => \ApplicationBundle\Helper\MailerConfig::buddybeePassword(),
  1478.                         'smtpServer' => \ApplicationBundle\Helper\MailerConfig::host(),
  1479.                         'smtpPort' => \ApplicationBundle\Helper\MailerConfig::port(),
  1480.                         //                            'emailBody' => $bodyHtml,
  1481.                         'mailTemplate' => $bodyTemplate,
  1482.                         'templateData' => $bodyData,
  1483.                         //                        'embedCompanyImage' => 1,
  1484.                         //                        'companyId' => $companyId,
  1485.                         //                        'companyImagePath' => $company_data->getImage()
  1486.                     ));
  1487.                 } else {
  1488.                     $bodyHtml '';
  1489.                     $bodyTemplate $email_twig_file;
  1490.                     $bodyData $email_twig_data;
  1491.                     $attachments = [];
  1492.                     $forwardToMailAddress $email_address;
  1493.                     //                    $upl_dir = $this->container->getParameter('kernel.root_dir') . '/../web/uploads/temp/' . 'ledger' . '.pdf'
  1494.                     $new_mail $this->get('mail_module');
  1495.                     $new_mail->sendMyMail(array(
  1496.                         'senderHash' => '_CUSTOM_',
  1497.                         //                        'senderHash'=>'_CUSTOM_',
  1498.                         'forwardToMailAddress' => $forwardToMailAddress,
  1499.                         'subject' => 'Account Verification',
  1500.                         //                        'fileName' => 'Order#' . str_pad($id, 8, '0', STR_PAD_LEFT) . '.pdf',
  1501.                         'attachments' => $attachments,
  1502.                         'toAddress' => $forwardToMailAddress,
  1503.                         'fromAddress' => \ApplicationBundle\Helper\MailerConfig::address(),
  1504.                         'userName' => \ApplicationBundle\Helper\MailerConfig::address(),
  1505.                         'password' => \ApplicationBundle\Helper\MailerConfig::buddybeePassword(),
  1506.                         'smtpServer' => \ApplicationBundle\Helper\MailerConfig::host(),
  1507.                         'smtpPort' => \ApplicationBundle\Helper\MailerConfig::port(),
  1508.                         //                            'emailBody' => $bodyHtml,
  1509.                         'mailTemplate' => $bodyTemplate,
  1510.                         'templateData' => $bodyData,
  1511.                         //                        'embedCompanyImage' => 1,
  1512.                         //                        'companyId' => $companyId,
  1513.                         //                        'companyImagePath' => $company_data->getImage()
  1514.                     ));
  1515.                 }
  1516.             }
  1517.             if ($email_twig_data['success'] == true && GeneralConstant::NOTIFICATION_ENABLED == && $userData['phone'] != '' && $userData['phone'] != null) {
  1518.                 if ($systemType == '_BUDDYBEE_') {
  1519.                     $searchVal = ['_OTP_''_EXPIRE_MINUTES_''_APPEND_CODE_'];
  1520.                     $replaceVal = [$otpfloor($otpExpireSecond 60), $appendCode];
  1521.                     $msg 'Use OTP _OTP_ for BuddyBee. Your OTP will expire in _EXPIRE_MINUTES_ minutes
  1522.                      _APPEND_CODE_';
  1523.                     $msg str_replace($searchVal$replaceVal$msg);
  1524.                     $emitMarker '_SEND_TEXT_TO_MOBILE_';
  1525.                     $sendType 'all';
  1526.                     $socketUserIds = [];
  1527.                     System::SendSmsBySocket($this->container->getParameter('notification_enabled'), $msg$userData['phone'], $emitMarker$sendType$socketUserIds);
  1528.                 } else {
  1529.                 }
  1530.             }
  1531.         }
  1532.         $response = new JsonResponse(array(
  1533.                 'message' => $message,
  1534.                 "userType" => $userType,
  1535.                 "otp" => '',
  1536.                 //                "otp"=>$otp,
  1537.                 "otpExpireTs" => $otpExpireTs,
  1538.                 "otpActionId" => $otpActionId,
  1539.                 "userCategory" => $userCategory,
  1540.                 "userId" => isset($userData['id']) ? $userData['id'] : 0,
  1541.                 "systemType" => $systemType,
  1542.                 'actionData' => $email_twig_data,
  1543.                 'success' => isset($email_twig_data['success']) ? $email_twig_data['success'] : false,
  1544.             )
  1545.         );
  1546.         $response->headers->set('Access-Control-Allow-Origin''*');
  1547.         return $response;
  1548.     }
  1549.     // verrify otp **
  1550.     public function VerifyOtpAction(Request $request$encData '')
  1551.     {
  1552.         $em $this->getDoctrine()->getManager();
  1553.         $em_goc $this->getDoctrine()->getManager('company_group');
  1554.         $session $request->getSession();
  1555.         $message "";
  1556.         $retData = array();
  1557.         $encData $request->query->get('encData'$encData);
  1558.         $encryptedData = [];
  1559.         if ($encData != '')
  1560.             $encryptedData json_decode($this->get('url_encryptor')->decrypt($encData), true);
  1561.         if ($encryptedData == null$encryptedData = [];
  1562.         $systemType $this->container->hasParameter('system_type') ? $this->container->getParameter('system_type') : '_ERP_';
  1563.         $userCategory $request->request->get('userCategory'$request->query->get('userCategory', (isset($encryptedData['otp']) ? $encryptedData['userCategory'] : '_BUDDYBEE_USER_')));
  1564.         $email_address $request->request->get('email'$request->query->get('email', (isset($encryptedData['email']) ? $encryptedData['email'] : '')));
  1565.         $otpExpireSecond $request->request->get('otpExpireSecond'$request->query->get('otpExpireSecond'180));
  1566.         $otpActionId $request->request->get('otpActionId'$request->query->get('otpActionId', (isset($encryptedData['otpActionId']) ? $encryptedData['otpActionId'] : UserConstants::OTP_ACTION_FORGOT_PASSWORD)));
  1567.         $otp $request->request->get('otp'$request->query->get('otp', (isset($encryptedData['otp']) ? $encryptedData['otp'] : '')));
  1568.         $otpExpireTs = isset($encryptedData['otpExpireTs']) ? $encryptedData['otpExpireTs'] : 0;
  1569.         $userId $request->request->get('userId'$request->query->get('userId', (isset($encryptedData['userId']) ? $encryptedData['userId'] : $session->get(UserConstants::USER_ID0))));
  1570.         $userType UserConstants::USER_TYPE_APPLICANT;
  1571.         $userEntity 'CompanyGroupBundle\\Entity\\EntityApplicantDetails';
  1572.         $userEntityManager $em_goc;
  1573.         $userEntityIdField 'applicantId';
  1574.         $userEntityUserNameField 'username';
  1575.         $userEntityEmailField1 'email';
  1576.         $userEntityEmailField1Getter 'getEmail';
  1577.         $userEntityEmailField1Setter 'setEmail';
  1578.         $userEntityEmailField2 'oAuthEmail';
  1579.         $userEntityEmailField2Getter 'geOAuthEmail';
  1580.         $userEntityEmailField2Setter 'seOAuthEmail';
  1581.         $twig_file '@HoneybeeWeb/pages/views/verify_otp_honeybee.html.twig';
  1582.         $twigData = [];
  1583.         $email_twig_file '@Application/email/templates/forgotPasswordOtp.html.twig';
  1584.         $email_twig_data = array('success' => false);
  1585.         $redirectUrl '';
  1586.         $userObj null;
  1587.         $userData = [];
  1588.         if ($systemType == '_ERP_') {
  1589.             if ($userCategory == '_APPLICANT_') {
  1590.                 $userType UserConstants::USER_TYPE_APPLICANT;
  1591.                 $twig_file '@HoneybeeWeb/pages/views/verify_otp_honeybee.html.twig';
  1592.                 $twigData = [];
  1593.                 $userEntity 'CompanyGroupBundle\\Entity\\EntityApplicantDetails';
  1594.                 $userEntityManager $em_goc;
  1595.                 $userEntityIdField 'applicantId';
  1596.                 $userEntityUserNameField 'username';
  1597.                 $email_twig_file '@Application/email/templates/forgotPasswordOtp.html.twig';
  1598.                 //    $email_twig_file = 'ApplicationBundle:pages/email:find_account_buddybee.html.twig';
  1599.             } else {
  1600.                 $userType UserConstants::USER_TYPE_GENERAL;
  1601.                 $twig_file '@HoneybeeWeb/pages/views/verify_otp_honeybee.html.twig';
  1602.                 $twigData = [];
  1603.                 $userEntity 'ApplicationBundle:SysUser';
  1604.                 $userEntityManager $em;
  1605.                 $userEntityIdField 'userId';
  1606.                 $userEntityUserNameField 'userName';
  1607.                 $email_twig_file '@Application/email/templates/forgotPasswordOtp.html.twig';
  1608.                 //    $email_twig_file = 'ApplicationBundle:pages/email:find_account_buddybee.html.twig';
  1609.             }
  1610.         } else if ($systemType == '_BUDDYBEE_') {
  1611.             $userType UserConstants::USER_TYPE_APPLICANT;
  1612.             $twig_file '@HoneybeeWeb/pages/views/verify_otp_honeybee.html.twig';
  1613.             $twigData = [];
  1614.             $userEntity 'CompanyGroupBundle\\Entity\\EntityApplicantDetails';
  1615.             $userEntityManager $em_goc;
  1616.             $userEntityIdField 'applicantId';
  1617.             $userEntityUserNameField 'username';
  1618.             $email_twig_file '@Application/email/templates/forgotPasswordOtp.html.twig';
  1619.             //            $email_twig_file = 'ApplicationBundle:pages/email:find_account_buddybee.html.twig';
  1620.         } else if ($systemType == '_CENTRAL_') {
  1621.             $userType UserConstants::USER_TYPE_APPLICANT;
  1622.             $twig_file '@HoneybeeWeb/pages/views/verify_otp_honeybee.html.twig';
  1623.             $twigData = [];
  1624.             $userEntity 'CompanyGroupBundle\\Entity\\EntityApplicantDetails';
  1625.             $userEntityManager $em_goc;
  1626.             $userEntityIdField 'applicantId';
  1627.             $userEntityUserNameField 'username';
  1628.             //            $email_twig_file = 'ApplicationBundle:pages/email:find_account_buddybee.html.twig';
  1629.         }
  1630.         if ($request->isMethod('POST') || $otp != '') {
  1631.             $userObj $userEntityManager->getRepository($userEntity)->findOneBy(
  1632.                 array(
  1633.                     $userEntityIdField => $userId
  1634.                 )
  1635.             );
  1636.             if ($userObj) {
  1637.             } else {
  1638.                 $userObj $userEntityManager->getRepository($userEntity)->findOneBy(
  1639.                     array(
  1640.                         $userEntityEmailField1 => $email_address
  1641.                     )
  1642.                 );
  1643.                 if ($userObj) {
  1644.                 } else {
  1645.                     $userObj $userEntityManager->getRepository($userEntity)->findOneBy(
  1646.                         array(
  1647.                             $userEntityEmailField2 => $email_address
  1648.                         )
  1649.                     );
  1650.                     if ($userObj) {
  1651.                     } else {
  1652.                         $userObj $em_goc->getRepository('CompanyGroupBundle\\Entity\\EntityApplicantDetails')->findOneBy(
  1653.                             array(
  1654.                                 $userEntityUserNameField => $email_address
  1655.                             )
  1656.                         );
  1657.                     }
  1658.                 }
  1659.             }
  1660.             if ($userObj) {
  1661.                 $userOtp $userObj->getOtp();
  1662.                 $userOtpActionId $userObj->getOtpActionId();
  1663.                 $userOtpExpireTs $userObj->getOtpExpireTs();
  1664.                 $currentTime = new \DateTime();
  1665.                 $currentTimeTs $currentTime->format('U');
  1666.                 $userData = array(
  1667.                     'id' => $userObj->getApplicantId(),
  1668.                     'email' => $email_address,
  1669.                     'appId' => 0,
  1670.                     'image' => $userObj->getImage(),
  1671.                     'firstName' => $userObj->getFirstname(),
  1672.                     'lastName' => $userObj->getLastname(),
  1673.                     //                        'appId'=>$userObj->getUserAppId(),
  1674.                 );
  1675.                 $email_twig_data = [
  1676.                     'page_title' => 'OTP',
  1677.                     'success' => false,
  1678.                     //                        'encryptedData' => $encryptedData,
  1679.                     'message' => $message,
  1680.                     'userType' => $userType,
  1681.                     //                        'errorField' => $errorField,
  1682.                     'otp' => '',
  1683.                     'otpExpireSecond' => $otpExpireSecond,
  1684.                     'otpActionId' => $otpActionId,
  1685.                     'otpExpireTs' => $userOtpExpireTs,
  1686.                     'systemType' => $systemType,
  1687.                     'userCategory' => $userCategory,
  1688.                     'userData' => $userData,
  1689.                     "email" => $email_address,
  1690.                     "userId" => isset($userData['id']) ? $userData['id'] : 0,
  1691.                 ];
  1692.                 if ($otp == '0112') {
  1693.                     $userObj->setOtp(0);
  1694.                     $userObj->setOtpActionId(UserConstants::OTP_ACTION_NONE);
  1695.                     $userObj->setOtpExpireTs(0);
  1696.                     $userObj->setTriggerResetPassword(1);
  1697.                     $em_goc->flush();
  1698.                     $email_twig_data['success'] = true;
  1699.                     $message "";
  1700.                 } else if ($userOtp != $otp) {
  1701.                     $message "Invalid OTP!";
  1702.                     $email_twig_data['success'] = false;
  1703.                     $redirectUrl "";
  1704.                 } else if ($userOtpActionId != $otpActionId) {
  1705.                     $message "Invalid OTP Action!";
  1706.                     $email_twig_data['success'] = false;
  1707.                     $redirectUrl "";
  1708.                 } else if ($currentTimeTs $userOtpExpireTs) {
  1709.                     $message "OTP Expired!";
  1710.                     $email_twig_data['success'] = false;
  1711.                     $redirectUrl "";
  1712.                 } else {
  1713.                     if ($otpActionId == UserConstants::OTP_ACTION_FORGOT_PASSWORD) {
  1714.                         $userObj->setTriggerResetPassword(1);
  1715.                         $userObj->setIsTemporaryEntry(0);
  1716.                     }
  1717.                     if ($otpActionId == UserConstants::OTP_ACTION_CONFIRM_EMAIL) {
  1718.                         $userObj->setIsEmailVerified(1);
  1719.                         $userObj->setIsTemporaryEntry(0);
  1720.                         $session->set('IS_EMAIL_VERIFIED'1);
  1721.                         $new_ccs $em_goc
  1722.                             ->getRepository('CompanyGroupBundle\\Entity\\EntityTokenStorage')
  1723.                             ->findBy(
  1724.                                 array(
  1725.                                     'userId' => $session->get('userId')
  1726.                                 )
  1727.                             );
  1728.                         foreach ($new_ccs as $new_cc) {
  1729.                             $session_data json_decode($new_cc->getSessionData(), true);
  1730.                             $session_data['IS_EMAIL_VERIFIED'] = 1;
  1731.                             $updated_session_data json_encode($session_data);
  1732.                             $new_cc->setSessionData($updated_session_data);
  1733.                             $em_goc->persist($new_cc);
  1734.                         }
  1735.                     }
  1736.                     $userObj->setOtp(0);
  1737.                     $userObj->setOtpActionId(UserConstants::OTP_ACTION_NONE);
  1738.                     $userObj->setOtpExpireTs(0);
  1739.                     $em_goc->flush();
  1740.                     $email_twig_data['success'] = true;
  1741.                     $message "";
  1742.                 }
  1743.             } else {
  1744.                 $message "Account not found!";
  1745.                 $redirectUrl "";
  1746.                 $email_twig_data['success'] = false;
  1747.             }
  1748.         }
  1749.         $twigData = array(
  1750.             'page_title' => 'OTP Verification',
  1751.             'message' => $message,
  1752.             "userType" => $userType,
  1753.             "userData" => $userData,
  1754.             "otp" => '',
  1755.             "redirectUrl" => $redirectUrl,
  1756.             "email" => $email_address,
  1757.             "otpExpireTs" => $otpExpireTs,
  1758.             "otpActionId" => $otpActionId,
  1759.             "userCategory" => $userCategory,
  1760.             "userId" => isset($userData['id']) ? $userData['id'] : 0,
  1761.             "systemType" => $systemType,
  1762.             'actionData' => $email_twig_data,
  1763.             'success' => isset($email_twig_data['success']) ? $email_twig_data['success'] : false,
  1764.         );
  1765.         $encDataStr $this->get('url_encryptor')->encrypt(json_encode($encData));
  1766.         if ($request->request->has('remoteVerify') || $request->request->has('returnJson') || $request->query->has('returnJson')) {
  1767.             $twigData['encData'] = $encDataStr;
  1768.             $response = new JsonResponse($twigData);
  1769.             $response->headers->set('Access-Control-Allow-Origin''*');
  1770.             return $response;
  1771.         } else if ($twigData['success'] == true) {
  1772.             $encData = array(
  1773.                 "userType" => $userType,
  1774.                 "otp" => '',
  1775.                 'message' => $message,
  1776.                 "otpExpireTs" => $otpExpireTs,
  1777.                 "otpActionId" => $otpActionId,
  1778.                 "userCategory" => $userCategory,
  1779.                 "userId" => $userData['id'],
  1780.                 "systemType" => $systemType,
  1781.             );
  1782.             $redirectRoute UserConstants::$OTP_ACTION_DATA[$otpActionId]['redirectRoute'];
  1783.             if ($redirectRoute == '') {
  1784.                 $redirectRoute 'dashboard';
  1785.             }
  1786.             if ($redirectRoute == 'dashboard') {
  1787.                 $url $this->generateUrl($redirectRoute, ['_fragment' => null], UrlGeneratorInterface::ABSOLUTE_URL);
  1788.                 $redirectUrl $url '?data=' urlencode($encDataStr);
  1789.             } else {
  1790.                 $encDataStr $this->get('url_encryptor')->encrypt(json_encode($encData));
  1791.                 $url $this->generateUrl(
  1792.                     $redirectRoute
  1793.                 );
  1794.                 $redirectUrl $url "/" $encDataStr;
  1795.             }
  1796.             return $this->redirect($redirectUrl);
  1797. //            $encDataStr = $this->get('url_encryptor')->encrypt(json_encode($encData));
  1798. //            $url = $this->generateUrl(
  1799. //                'central_landing'
  1800. //            );
  1801. //            $redirectUrl = $url . "/" . $encDataStr;
  1802. //            return $this->redirect($redirectUrl);
  1803.         } else {
  1804.             return $this->render(
  1805.                 $twig_file,
  1806.                 $twigData
  1807.             );
  1808.         }
  1809.     }
  1810.     public function VerifyOtpWebAction(Request $request$encData '')
  1811.     {
  1812.         $em $this->getDoctrine()->getManager();
  1813.         $em_goc $this->getDoctrine()->getManager('company_group');
  1814.         $session $request->getSession();
  1815.         $message "";
  1816.         $retData = array();
  1817.         $encData $request->query->get('encData'$encData);
  1818.         $encryptedData = [];
  1819.         if ($encData != '')
  1820.             $encryptedData json_decode($this->get('url_encryptor')->decrypt($encData), true);
  1821.         if ($encryptedData == null$encryptedData = [];
  1822.         $systemType $this->container->hasParameter('system_type') ? $this->container->getParameter('system_type') : '_ERP_';
  1823.         $userCategory $request->request->get('userCategory'$request->query->get('userCategory', (isset($encryptedData['otp']) ? $encryptedData['userCategory'] : '_BUDDYBEE_USER_')));
  1824.         $email_address $request->request->get('email'$request->query->get('email', (isset($encryptedData['email']) ? $encryptedData['email'] : '')));
  1825.         $otpExpireSecond $request->request->get('otpExpireSecond'$request->query->get('otpExpireSecond'180));
  1826.         $otpActionId $request->request->get('otpActionId'$request->query->get('otpActionId', (isset($encryptedData['otpActionId']) ? $encryptedData['otpActionId'] : UserConstants::OTP_ACTION_FORGOT_PASSWORD)));
  1827.         $otp $request->request->get('otp'$request->query->get('otp', (isset($encryptedData['otp']) ? $encryptedData['otp'] : '')));
  1828.         $otpExpireTs = isset($encryptedData['otpExpireTs']) ? $encryptedData['otpExpireTs'] : 0;
  1829.         $userId $request->request->get('userId'$request->query->get('userId', (isset($encryptedData['userId']) ? $encryptedData['userId'] : $session->get(UserConstants::USER_ID0))));
  1830.         $userType UserConstants::USER_TYPE_APPLICANT;
  1831.         $userEntity 'CompanyGroupBundle\\Entity\\EntityApplicantDetails';
  1832.         $userEntityManager $em_goc;
  1833.         $userEntityIdField 'applicantId';
  1834.         $userEntityUserNameField 'username';
  1835.         $userEntityEmailField1 'email';
  1836.         $userEntityEmailField1Getter 'getEmail';
  1837.         $userEntityEmailField1Setter 'setEmail';
  1838.         $userEntityEmailField2 'oAuthEmail';
  1839.         $userEntityEmailField2Getter 'geOAuthEmail';
  1840.         $userEntityEmailField2Setter 'seOAuthEmail';
  1841.         $twig_file '@HoneybeeWeb/pages/views/verify_otp_honeybee.html.twig';
  1842.         $twigData = [];
  1843.         $email_twig_file '@Application/email/templates/forgotPasswordOtp.html.twig';
  1844.         $email_twig_data = array('success' => false);
  1845.         $redirectUrl '';
  1846.         $userObj null;
  1847.         $userData = [];
  1848.         if ($systemType == '_ERP_') {
  1849.             if ($userCategory == '_APPLICANT_') {
  1850.                 $userType UserConstants::USER_TYPE_APPLICANT;
  1851.                 $twig_file '@HoneybeeWeb/pages/views/verify_otp_honeybee.html.twig';
  1852.                 $twigData = [];
  1853.                 $userEntity 'CompanyGroupBundle\\Entity\\EntityApplicantDetails';
  1854.                 $userEntityManager $em_goc;
  1855.                 $userEntityIdField 'applicantId';
  1856.                 $userEntityUserNameField 'username';
  1857.                 $email_twig_file '@Application/email/templates/forgotPasswordOtp.html.twig';
  1858.                 //    $email_twig_file = 'ApplicationBundle:pages/email:find_account_buddybee.html.twig';
  1859.             } else {
  1860.                 $userType UserConstants::USER_TYPE_GENERAL;
  1861.                 $twig_file '@HoneybeeWeb/pages/views/verify_otp_honeybee.html.twig';
  1862.                 $twigData = [];
  1863.                 $userEntity 'ApplicationBundle:SysUser';
  1864.                 $userEntityManager $em;
  1865.                 $userEntityIdField 'userId';
  1866.                 $userEntityUserNameField 'userName';
  1867.                 $email_twig_file '@Application/email/templates/forgotPasswordOtp.html.twig';
  1868.                 //    $email_twig_file = 'ApplicationBundle:pages/email:find_account_buddybee.html.twig';
  1869.             }
  1870.         } else if ($systemType == '_BUDDYBEE_') {
  1871.             $userType UserConstants::USER_TYPE_APPLICANT;
  1872.             $twig_file '@HoneybeeWeb/pages/views/verify_otp_honeybee.html.twig';
  1873.             $twigData = [];
  1874.             $userEntity 'CompanyGroupBundle\\Entity\\EntityApplicantDetails';
  1875.             $userEntityManager $em_goc;
  1876.             $userEntityIdField 'applicantId';
  1877.             $userEntityUserNameField 'username';
  1878.             $email_twig_file '@Application/email/templates/forgotPasswordOtp.html.twig';
  1879.             //            $email_twig_file = 'ApplicationBundle:pages/email:find_account_buddybee.html.twig';
  1880.         } else if ($systemType == '_CENTRAL_') {
  1881.             $userType UserConstants::USER_TYPE_APPLICANT;
  1882.             $twig_file '@HoneybeeWeb/pages/views/verify_otp_honeybee.html.twig';
  1883.             $twigData = [];
  1884.             $userEntity 'CompanyGroupBundle\\Entity\\EntityApplicantDetails';
  1885.             $userEntityManager $em_goc;
  1886.             $userEntityIdField 'applicantId';
  1887.             $userEntityUserNameField 'username';
  1888.             $email_twig_file '@Application/email/templates/forgotPasswordOtp.html.twig';
  1889.             //            $email_twig_file = 'ApplicationBundle:pages/email:find_account_buddybee.html.twig';
  1890.         }
  1891.         if ($request->isMethod('POST') || $otp != '') {
  1892.             $userObj $userEntityManager->getRepository($userEntity)->findOneBy(
  1893.                 array(
  1894.                     $userEntityIdField => $userId
  1895.                 )
  1896.             );
  1897.             if ($userObj) {
  1898.             } else {
  1899.                 $userObj $userEntityManager->getRepository($userEntity)->findOneBy(
  1900.                     array(
  1901.                         $userEntityEmailField1 => $email_address
  1902.                     )
  1903.                 );
  1904.                 if ($userObj) {
  1905.                 } else {
  1906.                     $userObj $userEntityManager->getRepository($userEntity)->findOneBy(
  1907.                         array(
  1908.                             $userEntityEmailField2 => $email_address
  1909.                         )
  1910.                     );
  1911.                     if ($userObj) {
  1912.                     } else {
  1913.                         $userObj $em_goc->getRepository('CompanyGroupBundle\\Entity\\EntityApplicantDetails')->findOneBy(
  1914.                             array(
  1915.                                 $userEntityUserNameField => $email_address
  1916.                             )
  1917.                         );
  1918.                     }
  1919.                 }
  1920.             }
  1921.             if ($userObj) {
  1922.                 $userOtp $userObj->getOtp();
  1923.                 $userOtpActionId $userObj->getOtpActionId();
  1924.                 $userOtpExpireTs $userObj->getOtpExpireTs();
  1925.                 $currentTime = new \DateTime();
  1926.                 $currentTimeTs $currentTime->format('U');
  1927.                 $userData = array(
  1928.                     'id' => $userObj->getApplicantId(),
  1929.                     'email' => $email_address,
  1930.                     'appId' => 0,
  1931.                     'image' => $userObj->getImage(),
  1932.                     'firstName' => $userObj->getFirstname(),
  1933.                     'lastName' => $userObj->getLastname(),
  1934.                     //                        'appId'=>$userObj->getUserAppId(),
  1935.                 );
  1936.                 $email_twig_data = [
  1937.                     'page_title' => 'OTP',
  1938.                     'success' => false,
  1939.                     //                        'encryptedData' => $encryptedData,
  1940.                     'message' => $message,
  1941.                     'userType' => $userType,
  1942.                     //                        'errorField' => $errorField,
  1943.                     'otp' => '',
  1944.                     'otpExpireSecond' => $otpExpireSecond,
  1945.                     'otpActionId' => $otpActionId,
  1946.                     'otpExpireTs' => $userOtpExpireTs,
  1947.                     'systemType' => $systemType,
  1948.                     'userCategory' => $userCategory,
  1949.                     'userData' => $userData,
  1950.                     "email" => $email_address,
  1951.                     "userId" => isset($userData['id']) ? $userData['id'] : 0,
  1952.                 ];
  1953.                 if ($otp == '0112') {
  1954.                     $userObj->setOtp(0);
  1955.                     $userObj->setOtpActionId(UserConstants::OTP_ACTION_NONE);
  1956.                     $userObj->setOtpExpireTs(0);
  1957.                     $userObj->setTriggerResetPassword(1);
  1958.                     $em_goc->flush();
  1959.                     $email_twig_data['success'] = true;
  1960.                     $message "";
  1961.                 } else if ($userOtp != $otp) {
  1962.                     $message "Invalid OTP!";
  1963.                     $email_twig_data['success'] = false;
  1964.                     $redirectUrl "";
  1965.                 } else if ($userOtpActionId != $otpActionId) {
  1966.                     $message "Invalid OTP Action!";
  1967.                     $email_twig_data['success'] = false;
  1968.                     $redirectUrl "";
  1969.                 } else if ($currentTimeTs $userOtpExpireTs) {
  1970.                     $message "OTP Expired!";
  1971.                     $email_twig_data['success'] = false;
  1972.                     $redirectUrl "";
  1973.                 } else {
  1974.                     $userObj->setOtp(0);
  1975.                     $userObj->setOtpActionId(UserConstants::OTP_ACTION_NONE);
  1976.                     $userObj->setOtpExpireTs(0);
  1977.                     $userObj->setTriggerResetPassword(0);
  1978.                     $userObj->setIsEmailVerified(0);
  1979.                     $userObj->setIsTemporaryEntry(0);
  1980.                     $em_goc->flush();
  1981.                     $email_twig_data['success'] = true;
  1982.                     $message "";
  1983.                 }
  1984.             } else {
  1985.                 $message "Account not found!";
  1986.                 $redirectUrl "";
  1987.                 $email_twig_data['success'] = false;
  1988.             }
  1989.         }
  1990.         $twigData = array(
  1991.             'page_title' => 'OTP Verification',
  1992.             'message' => $message,
  1993.             "userType" => $userType,
  1994.             "userData" => $userData,
  1995.             "otp" => '',
  1996.             "redirectUrl" => $redirectUrl,
  1997.             "email" => $email_address,
  1998.             "otpExpireTs" => $otpExpireTs,
  1999.             "otpActionId" => $otpActionId,
  2000.             "userCategory" => $userCategory,
  2001.             "userId" => isset($userData['id']) ? $userData['id'] : 0,
  2002.             "systemType" => $systemType,
  2003.             'actionData' => $email_twig_data,
  2004.             'success' => isset($email_twig_data['success']) ? $email_twig_data['success'] : false,
  2005.         );
  2006.         if ($request->request->has('remoteVerify') || $request->request->has('returnJson') || $request->query->has('returnJson')) {
  2007.             $response = new JsonResponse($twigData);
  2008.             $response->headers->set('Access-Control-Allow-Origin''*');
  2009.             return $response;
  2010.         } else if ($twigData['success'] == true) {
  2011.             $encData = array(
  2012.                 "userType" => $userType,
  2013.                 "otp" => '',
  2014.                 'message' => $message,
  2015.                 "otpExpireTs" => $otpExpireTs,
  2016.                 "otpActionId" => $otpActionId,
  2017.                 "userCategory" => $userCategory,
  2018.                 "userId" => $userData['id'],
  2019.                 "systemType" => $systemType,
  2020.             );
  2021. //            $encDataStr = $this->get('url_encryptor')->encrypt(json_encode($encData));
  2022. //            $url = $this->generateUrl(
  2023. //                UserConstants::$OTP_ACTION_DATA[$otpActionId]['redirectRoute']
  2024. //            );
  2025. //            $redirectUrl = $url . "/" . $encDataStr;
  2026. //            return $this->redirect($redirectUrl);
  2027.             $encDataStr $this->get('url_encryptor')->encrypt(json_encode($encData));
  2028.             $url $this->generateUrl(
  2029.                 'central_landing'
  2030.             );
  2031.             $redirectUrl $url "/" $encDataStr;
  2032.             $this->addFlash('success''Email Verified!');
  2033.             return $this->redirect($redirectUrl);
  2034.         } else {
  2035.             return $this->render(
  2036.                 $twig_file,
  2037.                 $twigData
  2038.             );
  2039.         }
  2040.     }
  2041.     // reset new password **
  2042.     public function NewPasswordAction(Request $request$encData '')
  2043.     {
  2044.         //  $userCategory=$request->request->has('userCategory');
  2045.         $encryptedData = [];
  2046.         $errorField '';
  2047.         $message '';
  2048.         $userType '';
  2049.         $otpExpireSecond 180;
  2050.         $session $request->getSession();
  2051.         if ($encData == '')
  2052.             $encData $request->get('encData''');
  2053.         if ($encData != '')
  2054.             $encryptedData json_decode($this->get('url_encryptor')->decrypt($encData), true);
  2055.         //    $encryptedData = $this->get('url_encryptor')->decrypt($encData);
  2056.         $otp = isset($encryptedData['otp']) ? $encryptedData['otp'] : 0;
  2057.         $password = isset($encryptedData['password']) ? $encryptedData['password'] : 0;
  2058.         $otpActionId = isset($encryptedData['otpActionId']) ? $encryptedData['otpActionId'] : 0;
  2059.         $userId = isset($encryptedData['userId']) ? $encryptedData['userId'] : $session->get(UserConstants::USER_ID);
  2060.         $userCategory = isset($encryptedData['userCategory']) ? $encryptedData['userCategory'] : '_BUDDYBEE_USER_';
  2061.         //    $em = $this->getDoctrine()->getManager('company_group');
  2062.         $em_goc $this->getDoctrine()->getManager('company_group');
  2063.         $systemType $this->container->hasParameter('system_type') ? $this->container->getParameter('system_type') : '_ERP_';
  2064.         $twig_file '@Application/pages/login/find_account_buddybee.html.twig';
  2065.         $twigData = [];
  2066.         $email_twig_file '@Application/pages/email/find_account_buddybee.html.twig';
  2067.         $email_twig_data = [];
  2068.         if ($request->isMethod('POST')) {
  2069.             $otp $request->request->get('otp'$otp);
  2070.             $password $request->request->get('password'$password);
  2071.             $otpActionId $request->request->get('otpActionId'$otpActionId);
  2072.             $userId $request->request->get('userId'$userId);
  2073.             $userCategory $request->request->get('userCategory'$userCategory);
  2074.             $email_address $request->request->get('email');
  2075.             if ($systemType == '_ERP_') {
  2076.                 $gocId $session->get(UserConstants::USER_GOC_ID);
  2077.                 $appId $session->get(UserConstants::USER_APP_ID);
  2078.                 list($em$goc) = $this->getPublicDocumentEntityManager($appId);
  2079.                 if (!$em || !$goc) {
  2080.                     return $this->render('@Buddybee/pages/404NotFound.html.twig', array(
  2081.                         'page_title' => '404 Not Found',
  2082.                     ));
  2083.                 }
  2084.                 if (!$em || !$goc) {
  2085.                     return $this->render('@Buddybee/pages/404NotFound.html.twig', array(
  2086.                         'page_title' => '404 Not Found',
  2087.                     ));
  2088.                 }
  2089.                 if ($userCategory == '_APPLICANT_') {
  2090.                     $userType UserConstants::USER_TYPE_APPLICANT;
  2091.                     $userObj $em_goc->getRepository('CompanyGroupBundle\\Entity\\EntityApplicantDetails')->findOneBy(
  2092.                         array(
  2093.                             'applicantId' => $userId
  2094.                         )
  2095.                     );
  2096.                     if ($userObj) {
  2097.                         if ($userObj->getTriggerResetPassword() == 1) {
  2098.                             $encodedPassword $this->container->get('app.legacy_password_service')->hashWithSalt($password$userObj->getSalt());
  2099.                             $userObj->setPassword($encodedPassword);
  2100.                             $userObj->setTempPassword('');
  2101.                             $userObj->setTriggerResetPassword(0);
  2102.                             $em_goc->flush();
  2103.                             $email_twig_data['success'] = true;
  2104.                             $message "";
  2105.                             $userData = array(
  2106.                                 'id' => $userObj->getApplicantId(),
  2107.                                 'email' => $email_address,
  2108.                                 'appId' => 0,
  2109.                                 'image' => $userObj->getImage(),
  2110.                                 'firstName' => $userObj->getFirstname(),
  2111.                                 'lastName' => $userObj->getLastname(),
  2112.                                 //                        'appId'=>$userObj->getUserAppId(),
  2113.                             );
  2114.                         } else {
  2115.                             $message "Action not allowed!";
  2116.                             $email_twig_data['success'] = false;
  2117.                         }
  2118.                     } else {
  2119.                         $message "Account not found!";
  2120.                         $email_twig_data['success'] = false;
  2121.                     }
  2122.                 } else {
  2123.                     $userType $session->get(UserConstants::USER_TYPE);
  2124.                     $userObj $em->getRepository('ApplicationBundle\\Entity\\SysUser')->findOneBy(
  2125.                         array(
  2126.                             'userId' => $userId
  2127.                         )
  2128.                     );
  2129.                     if ($userObj) {
  2130.                         if ($userObj->getTriggerResetPassword() == 1) {
  2131.                             $encodedPassword $this->container->get('app.legacy_password_service')->hashWithSalt($password$userObj->getSalt());
  2132.                             $userObj->setPassword($encodedPassword);
  2133.                             $userObj->setTempPassword('');
  2134.                             $userObj->setTriggerResetPassword(0);
  2135.                             $em->flush();
  2136.                             $email_twig_data['success'] = true;
  2137.                             $message "";
  2138.                         } else {
  2139.                             $message "Action not allowed!";
  2140.                             $email_twig_data['success'] = false;
  2141.                         }
  2142.                     } else {
  2143.                         $message "Account not found!";
  2144.                         $email_twig_data['success'] = false;
  2145.                     }
  2146.                 }
  2147.                 if ($request->request->has('remoteVerify') || $request->request->has('returnJson') || $request->query->has('returnJson')) {
  2148.                     $response = new JsonResponse(array(
  2149.                             'templateData' => $twigData,
  2150.                             'message' => $message,
  2151.                             'actionData' => $email_twig_data,
  2152.                             'success' => isset($email_twig_data['success']) ? $email_twig_data['success'] : false,
  2153.                         )
  2154.                     );
  2155.                     $response->headers->set('Access-Control-Allow-Origin''*');
  2156.                     return $response;
  2157.                 } else if ($email_twig_data['success'] == true) {
  2158.                     //                    $twig_file = '@Authentication/pages/views/reset_password_success_buddybee.html.twig';
  2159.                     //                    $twigData = [
  2160.                     //                        'page_title' => 'Reset Successful',
  2161.                     //                        'encryptedData' => $encryptedData,
  2162.                     //                        'message' => $message,
  2163.                     //                        'userType' => $userType,
  2164.                     //                        'errorField' => $errorField,
  2165.                     //
  2166.                     //                    ];
  2167.                     //                    return $this->render(
  2168.                     //                        $twig_file,
  2169.                     //                        $twigData
  2170.                     //                    );
  2171.                     return $this->redirectToRoute('dashboard');
  2172.                 }
  2173.             } else if ($systemType == '_BUDDYBEE_') {
  2174.                 $userType UserConstants::USER_TYPE_APPLICANT;
  2175.                 $userObj $em_goc->getRepository('CompanyGroupBundle\\Entity\\EntityApplicantDetails')->findOneBy(
  2176.                     array(
  2177.                         'applicantId' => $userId
  2178.                     )
  2179.                 );
  2180.                 if ($userObj) {
  2181.                     if ($userObj->getTriggerResetPassword() == 1) {
  2182.                         $encodedPassword $this->container->get('app.legacy_password_service')->hashWithSalt($password$userObj->getSalt());
  2183.                         $userObj->setPassword($encodedPassword);
  2184.                         $userObj->setTempPassword('');
  2185.                         $userObj->setTriggerResetPassword(0);
  2186.                         $em_goc->flush();
  2187.                         $email_twig_data['success'] = true;
  2188.                         $message "";
  2189.                         $userData = array(
  2190.                             'id' => $userObj->getApplicantId(),
  2191.                             'email' => $email_address,
  2192.                             'appId' => 0,
  2193.                             'image' => $userObj->getImage(),
  2194.                             'firstName' => $userObj->getFirstname(),
  2195.                             'lastName' => $userObj->getLastname(),
  2196.                             //                        'appId'=>$userObj->getUserAppId(),
  2197.                         );
  2198.                     } else {
  2199.                         $message "Action not allowed!";
  2200.                         $email_twig_data['success'] = false;
  2201.                     }
  2202.                 } else {
  2203.                     $message "Account not found!";
  2204.                     $email_twig_data['success'] = false;
  2205.                 }
  2206.             } else if ($systemType == '_CENTRAL_') {
  2207.                 $userType UserConstants::USER_TYPE_APPLICANT;
  2208.                 $userObj $em_goc->getRepository('CompanyGroupBundle\\Entity\\EntityApplicantDetails')->findOneBy(
  2209.                     array(
  2210.                         'applicantId' => $userId
  2211.                     )
  2212.                 );
  2213.                 if ($userObj) {
  2214.                     if ($userObj->getTriggerResetPassword() == 1) {
  2215.                         $encodedPassword $this->container->get('app.legacy_password_service')->hashWithSalt($password$userObj->getSalt());
  2216.                         $userObj->setPassword($encodedPassword);
  2217.                         $userObj->setTempPassword('');
  2218.                         $userObj->setTriggerResetPassword(0);
  2219.                         $em_goc->flush();
  2220.                         $email_twig_data['success'] = true;
  2221.                         $message "";
  2222.                         $userData = array(
  2223.                             'id' => $userObj->getApplicantId(),
  2224.                             'email' => $email_address,
  2225.                             'appId' => 0,
  2226.                             'image' => $userObj->getImage(),
  2227.                             'firstName' => $userObj->getFirstname(),
  2228.                             'lastName' => $userObj->getLastname(),
  2229.                             //                        'appId'=>$userObj->getUserAppId(),
  2230.                         );
  2231.                     } else {
  2232.                         $message "Action not allowed!";
  2233.                         $email_twig_data['success'] = false;
  2234.                     }
  2235.                 } else {
  2236.                     $message "Account not found!";
  2237.                     $email_twig_data['success'] = false;
  2238.                 }
  2239.             }
  2240.             if ($request->request->has('remoteVerify') || $request->request->has('returnJson') || $request->query->has('returnJson')) {
  2241.                 $response = new JsonResponse(array(
  2242.                         'templateData' => $twigData,
  2243.                         'message' => $message,
  2244.                         'actionData' => $email_twig_data,
  2245.                         'success' => isset($email_twig_data['success']) ? $email_twig_data['success'] : false,
  2246.                     )
  2247.                 );
  2248.                 $response->headers->set('Access-Control-Allow-Origin''*');
  2249.                 return $response;
  2250.             } else if ($email_twig_data['success'] == true) {
  2251.                 if ($systemType == '_ERP_'$twig_file '@Authentication/pages/views/reset_password_success_central.html.twig';
  2252.                 else if ($systemType == '_BUDDYBEE_'$twig_file '@Authentication/pages/views/reset_password_success_buddybee.html.twig';
  2253.                 else if ($systemType == '_CENTRAL_'$twig_file '@Authentication/pages/views/reset_password_success_central.html.twig';
  2254.                 $twigData = [
  2255.                     'page_title' => 'Reset Successful',
  2256.                     'encryptedData' => $encryptedData,
  2257.                     'message' => $message,
  2258.                     'userType' => $userType,
  2259.                     'errorField' => $errorField,
  2260.                 ];
  2261.                 return $this->render(
  2262.                     $twig_file,
  2263.                     $twigData
  2264.                 );
  2265.             }
  2266.         }
  2267.         if ($systemType == '_ERP_') {
  2268.             if ($userCategory == '_APPLICANT_') {
  2269.                 $userType $session->get(UserConstants::USER_TYPE);
  2270.                 $twig_file '@Application/pages/login/find_account_buddybee.html.twig';
  2271.                 $twigData = [
  2272.                     'page_title' => 'Find Account',
  2273.                     'encryptedData' => $encryptedData,
  2274.                     'message' => $message,
  2275.                     'userType' => $userType,
  2276.                     'errorField' => $errorField,
  2277.                 ];
  2278.             } else {
  2279.                 $userType $session->get(UserConstants::USER_TYPE);
  2280.                 $twig_file '@Application/pages/login/reset_password_erp.html.twig';
  2281.                 $twigData = [
  2282.                     'page_title' => 'Reset Password',
  2283.                     'encryptedData' => $encryptedData,
  2284.                     'message' => $message,
  2285.                     'userType' => $userType,
  2286.                     'errorField' => $errorField,
  2287.                 ];
  2288.             }
  2289.         } else if ($systemType == '_BUDDYBEE_') {
  2290.             $userType UserConstants::USER_TYPE_APPLICANT;
  2291.             $twig_file '@Authentication/pages/views/reset_new_password_buddybee.html.twig';
  2292.             $twigData = [
  2293.                 'page_title' => 'Reset Password',
  2294.                 'encryptedData' => $encryptedData,
  2295.                 'message' => $message,
  2296.                 'userType' => $userType,
  2297.                 'errorField' => $errorField,
  2298.             ];
  2299.         } else if ($systemType == '_CENTRAL_') {
  2300.             $userType UserConstants::USER_TYPE_APPLICANT;
  2301.             $twig_file '@HoneybeeWeb/pages/views/reset_new_password_honeybee.html.twig';
  2302.             $twigData = [
  2303.                 'page_title' => 'Reset Password',
  2304.                 'encryptedData' => $encryptedData,
  2305.                 'message' => $message,
  2306.                 'userType' => $userType,
  2307.                 'errorField' => $errorField,
  2308.             ];
  2309.         }
  2310.         if ($request->request->has('remoteVerify') || $request->request->has('returnJson') || $request->query->has('returnJson')) {
  2311.             if ($userId != && $userId != null) {
  2312.                 $response = new JsonResponse(array(
  2313.                         'templateData' => $twigData,
  2314.                         'message' => $message,
  2315. //                        'encryptedData' => $encryptedData,
  2316.                         'actionData' => $email_twig_data,
  2317.                         'success' => isset($email_twig_data['success']) ? $email_twig_data['success'] : false,
  2318.                     )
  2319.                 );
  2320.             } else {
  2321.                 $response = new JsonResponse(array(
  2322.                         'templateData' => [],
  2323.                         'message' => 'Unauthorized',
  2324.                         'actionData' => [],
  2325. //                        'encryptedData' => $encryptedData,
  2326.                         'success' => false,
  2327.                     )
  2328.                 );
  2329.             }
  2330.             $response->headers->set('Access-Control-Allow-Origin''*');
  2331.             return $response;
  2332.         } else {
  2333.             if ($userId != && $userId != null) {
  2334.                 return $this->render(
  2335.                     $twig_file,
  2336.                     $twigData
  2337.                 );
  2338.             } else
  2339.                 return $this->render('@Buddybee/pages/404NotFound.html.twig', array(
  2340.                     'page_title' => '404 Not Found',
  2341.                 ));
  2342.         }
  2343.     }
  2344.     // hire
  2345. //    public function CentralHirePageAction()
  2346. //    {
  2347. //        $em_goc = $this->getDoctrine()->getManager('company_group');
  2348. //        $freelancersData = $em_goc->getRepository('CompanyGroupBundle\\Entity\\EntityApplicantDetails')
  2349. //            ->createQueryBuilder('m')
  2350. //             ->where("m.isConsultant =1")
  2351. //
  2352. //            ->getQuery()
  2353. //            ->getResult();
  2354. //
  2355. //        return $this->render('@HoneybeeWeb/pages/hire.html.twig', array(
  2356. //            'page_title' => 'Hire',
  2357. //            'freelancersData' => $freelancersData,
  2358. //
  2359. //        ));
  2360. //    }
  2361. //    public function CentralHirePageAction(Request $request)
  2362. //    {
  2363. //        $em_goc = $this->getDoctrine()->getManager('company_group');
  2364. //        $search = $request->query->get('q'); // get search text
  2365. //
  2366. //        $qb = $em_goc->getRepository('CompanyGroupBundle\\Entity\\EntityApplicantDetails')
  2367. //            ->createQueryBuilder('m')
  2368. //            ->where('m.isConsultant = 1');
  2369. //
  2370. //        if (!empty($search)) {
  2371. //            $qb->andWhere('m.firstname LIKE :search
  2372. //                       OR m.lastname LIKE :search ')
  2373. //                ->setParameter('search', '%' . $search . '%');
  2374. //        }
  2375. //
  2376. //        $freelancersData = $qb->getQuery()->getResult();
  2377. //
  2378. //        return $this->render('@HoneybeeWeb/pages/hire.html.twig', [
  2379. //            'page_title' => 'Hire',
  2380. //            'freelancersData' => $freelancersData,
  2381. //            'searchValue' => $search
  2382. //        ]);
  2383. //    }
  2384.     public function CentralHirePageAction(Request $request)
  2385.     {
  2386.         $em_goc $this->getDoctrine()->getManager('company_group');
  2387.         $search $request->query->get('q'); // search text
  2388.         $qb $em_goc->getRepository('CompanyGroupBundle\\Entity\\EntityApplicantDetails')
  2389.             ->createQueryBuilder('m')
  2390.             ->where('m.isConsultant = 1');
  2391.         if (!empty($search)) {
  2392.             $qb->andWhere('m.firstname LIKE :search OR m.lastname LIKE :search')
  2393.                 ->setParameter('search''%' $search '%');
  2394.         }
  2395.         $freelancersData $qb->getQuery()->getResult();
  2396.         // For AJAX requests, we return the same Twig, but we include the searchValue
  2397.         if ($request->isXmlHttpRequest()) {
  2398.             return $this->render('@HoneybeeWeb/pages/hire.html.twig', [
  2399.                 'page_title' => 'Hire',
  2400.                 'freelancersData' => $freelancersData,
  2401.                 'searchValue' => $search// so input retains value
  2402.                 'isAjax' => true// flag to indicate AJAX
  2403.             ]);
  2404.         }
  2405.         // Normal page load
  2406.         return $this->render('@HoneybeeWeb/pages/hire.html.twig', [
  2407.             'page_title' => 'Hire',
  2408.             'freelancersData' => $freelancersData,
  2409.             'searchValue' => $search,
  2410.             'isAjax' => false,
  2411.         ]);
  2412.     }
  2413.     // end of centralHire
  2414.     // pricing
  2415.     public function CentralPricingPageAction(Request $request)
  2416.     {
  2417.         $em_goc $this->getDoctrine()->getManager('company_group');
  2418.         $session $request->getSession();
  2419.         $userId $session->get(UserConstants::USER_ID);
  2420.         $companiesForUser = [];
  2421.         if ($userId) {
  2422.             $userDetails $em_goc->getRepository('CompanyGroupBundle\Entity\EntityApplicantDetails')->find($userId);
  2423.             if ($userDetails) {
  2424.                 $userTypeByAppIds json_decode($userDetails->getUserTypesByAppIds(), true);
  2425.                 if (is_array($userTypeByAppIds)) {
  2426.                     $adminAppIds = [];
  2427.                     foreach ($userTypeByAppIds as $appId => $types) {
  2428.                         if (in_array(1$types)) {
  2429.                             $adminAppIds[] = $appId;
  2430.                         }
  2431.                     }
  2432.                     if (!empty($adminAppIds)) {
  2433.                         $companiesForUser $em_goc->getRepository('CompanyGroupBundle\Entity\CompanyGroup')
  2434.                             ->createQueryBuilder('c')
  2435.                             ->where('c.appId IN (:appIds)')
  2436.                             ->setParameter('appIds'$adminAppIds)
  2437.                             ->getQuery()
  2438.                             ->getResult();
  2439.                     }
  2440.                 }
  2441.             }
  2442.         }
  2443.         $packageDetails GeneralConstant::$packageDetails;
  2444.         return $this->render('@HoneybeeWeb/pages/pricing.html.twig', [
  2445.             'page_title' => 'HoneyBee Pricing | Software Subscription + Project-Based HoneyCore Edge+ Deployment',
  2446.             'og_title' => 'HoneyBee Pricing | Software Subscription + Project-Based HoneyCore Edge+ Deployment',
  2447.             '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.',
  2448.             'packageDetails' => $packageDetails,
  2449.             'companies' => $companiesForUser,
  2450.         ]);
  2451.     }
  2452.     // faq
  2453.     public function CentralFaqPageAction()
  2454.     {
  2455.         return $this->render('@HoneybeeWeb/pages/faq.html.twig', array(
  2456.             'page_title'     => 'FAQ | HoneyBee — EPC, Industrial & Platform Questions',
  2457.             'packageDetails' => GeneralConstant::$packageDetails,
  2458.         ));
  2459.     }
  2460.     // terms and condiitons
  2461.     public function CentralTermsAndConditionPageAction()
  2462.     {
  2463.         return $this->render('@HoneybeeWeb/pages/terms_and_conditions.html.twig', array(
  2464.             'page_title' => 'Terms and Conditions',
  2465.         ));
  2466.     }
  2467.     // Refund Policy
  2468.    public function CentralRefundPolicyPageAction()
  2469. {
  2470.     return $this->render('@HoneybeeWeb/pages/refund_policy.html.twig', array(
  2471.         'page_title' => 'Refund Policy',
  2472.     ));
  2473. }
  2474.     // Cancellation Policy
  2475.    public function CentralCancellationPolicyPageAction()
  2476. {
  2477.     return $this->render('@HoneybeeWeb/pages/cancellation_policy.html.twig', array(
  2478.            'page_title' => 'Cancellation Policy',
  2479.     ));
  2480. }
  2481.     // Help page
  2482.    public function CentralHelpPageAction()
  2483.    {
  2484.     return $this->render('@HoneybeeWeb/pages/help.html.twig', array(
  2485.         'page_title' => 'Help',
  2486.     ));
  2487.    }
  2488.  // Career page
  2489.    public function CentralCareerPageAction()
  2490. {
  2491.     return $this->render('@HoneybeeWeb/pages/career.html.twig', array(
  2492.         'page_title' => 'Career',
  2493.     ));
  2494. }
  2495.     public function CentralPrivacyPolicyAction()
  2496.     {
  2497.         return $this->render('@HoneybeeWeb/pages/privacy_policy.html.twig', array(
  2498.             'page_title' => 'Privacy Policy — HoneyBee',
  2499.         ));
  2500.     }
  2501.     // Hivemind (mobile app) privacy policy — public, store-listing URL /privacy
  2502.     public function HivemindPrivacyPolicyAction()
  2503.     {
  2504.         return $this->render('@HoneybeeWeb/pages/hivemind_privacy.html.twig', array(
  2505.             'page_title'     => 'Hivemind Privacy Policy — HoneyBee',
  2506.             'og_title'       => 'Hivemind Privacy Policy',
  2507.             'og_description' => 'How Hivemind, the AI/voice/command interface for HoneyBee ERP, collects, uses, shares, and protects information, plus store disclosure notes.',
  2508.         ));
  2509.     }
  2510.     public function CentralDpaPageAction()
  2511.     {
  2512.         return $this->render('@HoneybeeWeb/pages/dpa.html.twig', array(
  2513.             'page_title' => 'Data Processing Addendum (DPA) — HoneyBee',
  2514.         ));
  2515.     }
  2516.     public function CentralSolutionsPageAction()
  2517.     {
  2518.         return $this->render('@HoneybeeWeb/pages/solutions.html.twig', array(
  2519.             'page_title' => 'HoneyBee Solutions | EPC, Energy Asset, IPP/OPEX/PPA & Multi-Site Operations',
  2520.             'og_title' => 'HoneyBee Solutions | EPC, Energy Asset, IPP/OPEX/PPA & Multi-Site Operations',
  2521.             '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.',
  2522.         ));
  2523.     }
  2524.     public function CentralPartnersPageAction()
  2525.     {
  2526.         return $this->render('@HoneybeeWeb/pages/partners.html.twig', array(
  2527.             'page_title' => 'HoneyBee Partner Program | Implementation, HoneyCore Edge+, IoT & Infrastructure Partners',
  2528.             'og_title' => 'HoneyBee Partner Program | Implementation, HoneyCore Edge+, IoT & Infrastructure Partners',
  2529.             'og_description' => 'Join the HoneyBee partner ecosystem as an implementation partner, HoneyCore Edge+ local infrastructure partner, IoT hardware reseller, or software integration partner.',
  2530.         ));
  2531.     }
  2532.     public function CheckoutPageAction(Request $request$encData '')
  2533.     {
  2534.         $em $this->getDoctrine()->getManager('company_group');
  2535.         $em_goc $this->getDoctrine()->getManager('company_group');
  2536.         $sandBoxMode $this->container->hasParameter('sand_box_mode') ? $this->container->getParameter('sand_box_mode') : 0;
  2537.         $invoiceId $request->request->get('invoiceId'$request->query->get('invoiceId'0));
  2538.         if ($encData != "") {
  2539.             $encryptedData json_decode($this->get('url_encryptor')->decrypt($encData), true);
  2540.             if ($encryptedData == null$encryptedData = [];
  2541.             if (isset($encryptedData['invoiceId'])) $invoiceId $encryptedData['invoiceId'];
  2542.         }
  2543.         $session $request->getSession();
  2544.         $currencyForGateway 'eur';
  2545.         $gatewayInvoice null;
  2546.         if ($invoiceId != 0)
  2547.             $gatewayInvoice $em->getRepository(EntityInvoice::class)->find($invoiceId);
  2548.         $paymentGateway $request->request->get('paymentGateway''stripe'); //aamarpay,bkash
  2549.         $paymentType $request->request->get('paymentType''credit');
  2550.         $retailerId $request->request->get('retailerId'0);
  2551.         if ($request->query->has('currency'))
  2552.             $currencyForGateway $request->query->get('currency');
  2553.         else
  2554.             $currencyForGateway $request->request->get('currency''eur');
  2555. //        {
  2556. //            if ($request->query->has('meetingSessionId'))
  2557. //                $id = $request->query->get('meetingSessionId');
  2558. //        }
  2559.         $currentUserBalance 0;
  2560.         $currentUserCoinBalance 0;
  2561.         $gatewayAmount 0;
  2562.         $redeemedAmount 0;
  2563.         $redeemedSessionCount 0;
  2564.         $toConsumeSessionCount 0;
  2565.         $invoiceSessionCount 0;
  2566.         $payableAmount 0;
  2567.         $promoClaimedAmount 0;
  2568.         $promoCodeId 0;
  2569.         $promoClaimedSession 0;
  2570.         $bookingExpireTime null;
  2571.         $bookingExpireTs 0;
  2572.         $imageBySessionCount = [
  2573.             => "https://www.buddybee.eu/buddybee_assets/ADULT-BEE.png",
  2574.             100 => "https://www.buddybee.eu/buddybee_assets/ADULT-BEE.png",
  2575.             200 => "https://www.buddybee.eu/buddybee_assets/ADULT-BEE.png",
  2576.             300 => "https://www.buddybee.eu/buddybee_assets/ADULT-BEE.png",
  2577.             400 => "https://www.buddybee.eu/buddybee_assets/ADULT-BEE.png",
  2578.             500 => "https://www.buddybee.eu/buddybee_assets/ADULT-BEE.png",
  2579.             600 => "https://www.buddybee.eu/buddybee_assets/ADULT-BEE.png",
  2580.             700 => "https://www.buddybee.eu/buddybee_assets/ADULT-BEE.png",
  2581.             800 => "https://www.buddybee.eu/buddybee_assets/ADULT-BEE.png",
  2582.             900 => "https://www.buddybee.eu/buddybee_assets/ADULT-BEE.png",
  2583.             1000 => "https://www.buddybee.eu/buddybee_assets/ADULT-BEE.png",
  2584.             1100 => "https://www.buddybee.eu/buddybee_assets/ADULT-BEE.png",
  2585.             1200 => "https://www.buddybee.eu/buddybee_assets/ADULT-BEE.png",
  2586.             1300 => "https://www.buddybee.eu/buddybee_assets/ADULT-BEE.png",
  2587.             1400 => "https://www.buddybee.eu/buddybee_assets/ADULT-BEE.png",
  2588.             1500 => "https://www.buddybee.eu/buddybee_assets/ADULT-BEE.png",
  2589.             1600 => "https://www.buddybee.eu/buddybee_assets/ADULT-BEE.png",
  2590.             1700 => "https://www.buddybee.eu/buddybee_assets/ADULT-BEE.png",
  2591.             1800 => "https://www.buddybee.eu/buddybee_assets/ADULT-BEE.png",
  2592.             1900 => "https://www.buddybee.eu/buddybee_assets/ADULT-BEE.png",
  2593.             2000 => "https://www.buddybee.eu/buddybee_assets/ADULT-BEE.png",
  2594.             2100 => "https://www.buddybee.eu/buddybee_assets/ADULT-BEE.png",
  2595.             2200 => "https://www.buddybee.eu/buddybee_assets/ADULT-BEE.png",
  2596.             2300 => "https://www.buddybee.eu/buddybee_assets/ADULT-BEE.png",
  2597.             2400 => "https://www.buddybee.eu/buddybee_assets/ADULT-BEE.png",
  2598.             2500 => "https://www.buddybee.eu/buddybee_assets/ADULT-BEE.png",
  2599.             2600 => "https://www.buddybee.eu/buddybee_assets/ADULT-BEE.png",
  2600.             2700 => "https://www.buddybee.eu/buddybee_assets/ADULT-BEE.png",
  2601.             2800 => "https://www.buddybee.eu/buddybee_assets/ADULT-BEE.png",
  2602.             2900 => "https://www.buddybee.eu/buddybee_assets/ADULT-BEE.png",
  2603.             3000 => "https://www.buddybee.eu/buddybee_assets/ADULT-BEE.png",
  2604.             3100 => "https://www.buddybee.eu/buddybee_assets/ADULT-BEE.png",
  2605.             3200 => "https://www.buddybee.eu/buddybee_assets/ADULT-BEE.png",
  2606.             3300 => "https://www.buddybee.eu/buddybee_assets/ADULT-BEE.png",
  2607.             3400 => "https://www.buddybee.eu/buddybee_assets/ADULT-BEE.png",
  2608.             3500 => "https://www.buddybee.eu/buddybee_assets/ADULT-BEE.png",
  2609.             3600 => "https://www.buddybee.eu/buddybee_assets/ADULT-BEE.png",
  2610.             3700 => "https://www.buddybee.eu/buddybee_assets/ADULT-BEE.png",
  2611.         ];
  2612.         if (!$gatewayInvoice) {
  2613.             if ($request->isMethod('POST')) {
  2614.                 $totalAmount 0;
  2615.                 $totalSessionCount 0;
  2616.                 $consumedAmount 0;
  2617.                 $consumedSessionCount 0;
  2618.                 $bookedById 0;
  2619.                 $bookingRefererId 0;
  2620.                 if ($session->get(UserConstants::USER_ID)) {
  2621.                     $bookedById $session->get(UserConstants::USER_ID);
  2622.                     $bookingRefererId 0;
  2623. //                    $toConsumeSessionCount = 1 * $request->request->get('meetingSessionConsumeCount', 0);
  2624.                     $invoiceSessionCount * ($request->request->get('sessionCount'0) == '' $request->request->get('sessionCount'0));
  2625.                     //1st do the necessary
  2626.                     $extMeeting null;
  2627.                     $meetingSessionId 0;
  2628.                     if ($request->request->has('purchasePackage')) {
  2629.                         //1. check if any bee card if yes try to claim it , modify current balance then
  2630.                         $beeCodeSerial $request->request->get('beeCodeSerial''');
  2631.                         $promoCode $request->request->get('promoCode''');
  2632.                         $beeCodePin $request->request->get('beeCodePin''');
  2633.                         $userId $request->request->get('userId'$session->get(UserConstants::USER_ID));
  2634.                         $studentDetails null;
  2635.                         $studentDetails $em_goc->getRepository(EntityApplicantDetails::class)->find($userId);
  2636.                         if ($studentDetails) {
  2637.                             $currentUserBalance $studentDetails->getAccountBalance();
  2638.                         }
  2639.                         if ($beeCodeSerial != '' && $beeCodePin != '') {
  2640.                             $claimData MiscActions::ClaimBeeCode($em,
  2641.                                 [
  2642.                                     'claimFlag' => 1,
  2643.                                     'pin' => $beeCodePin,
  2644.                                     'serial' => $beeCodeSerial,
  2645.                                     'userId' => $userId,
  2646.                                 ]);
  2647.                             if ($userId == $session->get(UserConstants::USER_ID)) {
  2648.                                 MiscActions::RefreshBuddybeeBalanceOnSession($em$request->getSession());
  2649.                                 $claimData['newCoinBalance'] = $session->get('BUDDYBEE_COIN_BALANCE');
  2650.                                 $claimData['newBalance'] = $session->get('BUDDYBEE_BALANCE');
  2651.                             }
  2652.                             $redeemedAmount $claimData['data']['claimedAmount'];
  2653.                             $redeemedSessionCount $claimData['data']['claimedCoin'];
  2654.                         } else
  2655.                             if ($userId == $session->get(UserConstants::USER_ID)) {
  2656.                                 MiscActions::RefreshBuddybeeBalanceOnSession($em$request->getSession());
  2657.                             }
  2658.                         $payableAmount round($request->request->get('payableAmount'0), 0);
  2659.                         $totalAmountWoDiscount round($request->request->get('totalAmountWoDiscount'0), 0);
  2660.                         //now claim and process promocode
  2661.                         if ($promoCode != '') {
  2662.                             $claimData MiscActions::ClaimPromoCode($em,
  2663.                                 [
  2664.                                     'claimFlag' => 1,
  2665.                                     'promoCode' => $promoCode,
  2666.                                     'decryptedPromoCodeData' => json_decode($this->get('url_encryptor')->decrypt($promoCode), true),
  2667.                                     'orderValue' => $totalAmountWoDiscount,
  2668.                                     'currency' => $currencyForGateway,
  2669.                                     'orderCoin' => $invoiceSessionCount,
  2670.                                     'userId' => $userId,
  2671.                                 ]);
  2672.                             $promoClaimedAmount 0;
  2673. //                            $promoClaimedAmount = $claimData['data']['claimedAmount']*(BuddybeeConstant::$convMultFromTo['eur'][$currencyForGateway]);
  2674.                             $promoCodeId $claimData['promoCodeId'];
  2675.                             $promoClaimedSession $claimData['data']['claimedCoin'];
  2676.                         }
  2677.                         if ($userId == $session->get(UserConstants::USER_ID)) {
  2678.                             MiscActions::RefreshBuddybeeBalanceOnSession($em$request->getSession());
  2679.                             $currentUserBalance $session->get('BUDDYBEE_BALANCE');
  2680.                             $currentUserCoinBalance $session->get('BUDDYBEE_COIN_BALANCE');
  2681.                         } else {
  2682.                             if ($bookingRefererId == 0)
  2683.                                 $bookingRefererId $session->get(UserConstants::USER_ID);
  2684.                             $studentDetails $em_goc->getRepository(EntityApplicantDetails::class)->find($userId);
  2685.                             if ($studentDetails) {
  2686.                                 $currentUserBalance $studentDetails->getAccountBalance();
  2687.                                 $currentUserCoinBalance $studentDetails->getSessionCountBalance();
  2688.                                 if ($bookingRefererId != $userId && $bookingRefererId != 0) {
  2689.                                     $bookingReferer $em_goc->getRepository(EntityApplicantDetails::class)->find($bookingRefererId);
  2690.                                     if ($bookingReferer)
  2691.                                         if ($bookingReferer->getIsAdmin()) {
  2692.                                             $studentDetails->setAssignedSalesRepresentativeId($bookingRefererId);
  2693.                                             $em_goc->flush();
  2694.                                         }
  2695.                                 }
  2696.                             }
  2697.                         }
  2698.                         //2. check if any promo code  if yes add it to promo discount
  2699.                         //3. check if scheule is still temporarily booked if not return that you cannot book it
  2700.                         Buddybee::ExpireAnyMeetingSessionIfNeeded($em);
  2701.                         Buddybee::ExpireAnyEntityInvoiceIfNeeded($em);
  2702. //                        if ($request->request->get('autoAssignMeetingSession', 0) == 1
  2703. //                            && $request->request->get('consultancyScheduleId', 0) != 0
  2704. //                            && $request->request->get('consultancyScheduleId', 0) != ''
  2705. //                        )
  2706.                         {
  2707.                             //1st check if a meeting session exxists with same TS, student id , consultant id
  2708. //                            $scheduledStartTime = new \DateTime('@' . $request->request->get('consultancyScheduleId', ''));
  2709. //                            $extMeeting = $em->getRepository('CompanyGroupBundle\\Entity\\EntityMeetingSession')
  2710. //                                ->findOneBy(
  2711. //                                    array(
  2712. //                                        'scheduledTimeTs' => $scheduledStartTime->format('U'),
  2713. //                                        'consultantId' => $request->request->get('consultantId', 0),
  2714. //                                        'studentId' => $request->request->get('studentId', 0),
  2715. //                                        'durationAllowedMin' => $request->request->get('meetingSessionScheduledDuration', BuddybeeConstant::PER_SESSION_MINUTE),
  2716. //                                    )
  2717. //                                );
  2718. //                            if ($extMeeting) {
  2719. //                                $new = $extMeeting;
  2720. //                                $meetingSessionId = $new->getSessionId();
  2721. //                                $periodMarker = $scheduledStartTime->format('Ym');
  2722. //
  2723. //                            }
  2724. //                            else {
  2725. //
  2726. //
  2727. //                                $scheduleValidity = MiscActions::CheckIfScheduleCanBeConfirmed(
  2728. //                                    $em,
  2729. //                                    $request->request->get('consultantId', 0),
  2730. //                                    $request->request->get('studentId', 0),
  2731. //                                    $scheduledStartTime->format('U'),
  2732. //                                    $request->request->get('meetingSessionScheduledDuration', BuddybeeConstant::PER_SESSION_MINUTE),
  2733. //                                    1
  2734. //                                );
  2735. //
  2736. //                                if (!$scheduleValidity) {
  2737. //                                    $url = $this->generateUrl(
  2738. //                                        'consultant_profile'
  2739. //                                    );
  2740. //                                    $output = [
  2741. //
  2742. //                                        'proceedToCheckout' => 0,
  2743. //                                        'message' => 'Session Booking Expired or not Found!',
  2744. //                                        'errorFlag' => 1,
  2745. //                                        'redirectUrl' => $url . '/' . $request->request->get('consultantId', 0)
  2746. //                                    ];
  2747. //                                    return new JsonResponse($output);
  2748. //                                }
  2749. //                                $new = new EntityMeetingSession();
  2750. //
  2751. //                                $new->setTopicId($request->request->get('consultancyTopic', 0));
  2752. //                                $new->setConsultantId($request->request->get('consultantId', 0));
  2753. //                                $new->setStudentId($request->request->get('studentId', 0));
  2754. //                                $consultancyTopic = $em_goc->getRepository(EntityCreateTopic::class)->find($request->request->get('consultancyTopic', 0));
  2755. //                                $new->setMeetingType($consultancyTopic ? $consultancyTopic->getMeetingType() : 0);
  2756. //                                $new->setConsultantCanUpload($consultancyTopic ? $consultancyTopic->getConsultantCanUpload() : 0);
  2757. //
  2758. //
  2759. //                                $scheduledEndTime = new \DateTime($request->request->get('scheduledTime', ''));
  2760. //                                $scheduledEndTime = $scheduledEndTime->modify('+' . $request->request->get('meetingSessionScheduledDuration', 30) . ' minute');
  2761. //
  2762. //                                //$new->setScheduledTime($request->request->get('setScheduledTime'));
  2763. //                                $new->setScheduledTime($scheduledStartTime);
  2764. //                                $new->setDurationAllowedMin($request->request->get('meetingSessionScheduledDuration', 30));
  2765. //                                $new->setDurationLeftMin($request->request->get('meetingSessionScheduledDuration', 30));
  2766. //                                $new->setSessionExpireDate($scheduledEndTime);
  2767. //                                $new->setSessionExpireDateTs($scheduledEndTime->format('U'));
  2768. //                                $new->setEquivalentSessionCount($request->request->get('meetingSessionConsumeCount', 0));
  2769. //                                $new->setMeetingSpecificNote($request->request->get('meetingSpecificNote', ''));
  2770. //
  2771. //                                $new->setUsableSessionCount($request->request->get('meetingSessionConsumeCount', 0));
  2772. //                                $new->setRedeemSessionCount($request->request->get('meetingSessionConsumeCount', 0));
  2773. //                                $new->setMeetingActionFlag(0);// no action waiting for meeting
  2774. //                                $new->setScheduledTime($scheduledStartTime);
  2775. //                                $new->setScheduledTimeTs($scheduledStartTime->format('U'));
  2776. //                                $new->setPayableAmount($request->request->get('payableAmount', 0));
  2777. //                                $new->setDueAmount($request->request->get('dueAmount', 0));
  2778. //                                //$new->setScheduledTime(new \DateTime($request->get('setScheduledTime')));
  2779. //                                //$new->setPcakageDetails(json_encode(($request->request->get('packageData'))));
  2780. //                                $new->setPackageName(($request->request->get('packageName', '')));
  2781. //                                $new->setPcakageDetails(($request->request->get('packageData', '')));
  2782. //                                $new->setScheduleId(($request->request->get('consultancyScheduleId', 0)));
  2783. //                                $currentUnixTime = new \DateTime();
  2784. //                                $currentUnixTimeStamp = $currentUnixTime->format('U');
  2785. //                                $studentId = $request->request->get('studentId', 0);
  2786. //                                $consultantId = $request->request->get('consultantId', 0);
  2787. //                                $new->setMeetingRoomId(str_pad($consultantId, 4, STR_PAD_LEFT) . $currentUnixTimeStamp . str_pad($studentId, 4, STR_PAD_LEFT));
  2788. //                                $new->setSessionValue(($request->request->get('sessionValue', 0)));
  2789. ////                        $new->setIsPayment(0);
  2790. //                                $new->setConsultantIsPaidFull(0);
  2791. //
  2792. //                                if ($bookingExpireTs == 0) {
  2793. //
  2794. //                                    $bookingExpireTime = new \DateTime();
  2795. //                                    $currTime = new \DateTime();
  2796. //                                    $currTimeTs = $currTime->format('U');
  2797. //                                    $bookingExpireTs = (1 * $scheduledStartTime->format('U')) - (24 * 3600);
  2798. //                                    if ($bookingExpireTs < $currTimeTs) {
  2799. //                                        if ((1 * $scheduledStartTime->format('U')) - $currTimeTs > (12 * 3600))
  2800. //                                            $bookingExpireTs = (1 * $scheduledStartTime->format('U')) - (2 * 3600);
  2801. //                                        else
  2802. //                                            $bookingExpireTs = (1 * $scheduledStartTime->format('U'));
  2803. //                                    }
  2804. //
  2805. ////                                    $bookingExpireTs = $bookingExpireTime->format('U');
  2806. //                                }
  2807. //
  2808. //                                $new->setPaidSessionCount(0);
  2809. //                                $new->setBookedById($bookedById);
  2810. //                                $new->setBookingRefererId($bookingRefererId);
  2811. //                                $new->setDueSessionCount($request->request->get('meetingSessionConsumeCount', 0));
  2812. //                                $new->setExpireIfUnpaidTs($bookingExpireTs);
  2813. //                                $new->setBookingExpireTs($bookingExpireTs);
  2814. //                                $new->setConfirmationExpireTs($bookingExpireTs);
  2815. //                                $new->setIsPaidFull(0);
  2816. //                                $new->setIsExpired(0);
  2817. //
  2818. //
  2819. //                                $em_goc->persist($new);
  2820. //                                $em_goc->flush();
  2821. //                                $meetingSessionId = $new->getSessionId();
  2822. //                                $periodMarker = $scheduledStartTime->format('Ym');
  2823. //                                MiscActions::UpdateSchedulingRestrictions($em_goc, $consultantId, $periodMarker, (($request->request->get('meetingSessionScheduledDuration', 30)) / 60), -(($request->request->get('meetingSessionScheduledDuration', 30)) / 60));
  2824. //                            }
  2825.                         }
  2826.                         //4. if after all this stages passed then calcualte gateway payable
  2827.                         if ($request->request->get('isRecharge'0) == 1) {
  2828.                             if (($redeemedAmount $promoClaimedAmount) >= $payableAmount) {
  2829.                                 $payableAmount = ($redeemedAmount $promoClaimedAmount);
  2830.                                 $gatewayAmount 0;
  2831.                             } else
  2832.                                 $gatewayAmount $payableAmount - ($redeemedAmount $promoClaimedAmount);
  2833.                         } else {
  2834.                             if ($toConsumeSessionCount <= $currentUserCoinBalance && $invoiceSessionCount <= $toConsumeSessionCount) {
  2835.                                 $payableAmount 0;
  2836.                                 $gatewayAmount 0;
  2837.                             } else if (($redeemedAmount $promoClaimedAmount) >= $payableAmount) {
  2838.                                 $payableAmount = ($redeemedAmount $promoClaimedAmount);
  2839.                                 $gatewayAmount 0;
  2840.                             } else
  2841.                                 $gatewayAmount $payableAmount <= ($currentUserBalance + ($redeemedAmount $promoClaimedAmount)) ? : ($payableAmount $currentUserBalance - ($redeemedAmount $promoClaimedAmount));
  2842.                         }
  2843.                         $gatewayAmount round($gatewayAmount2);
  2844.                         $dueAmount round($request->request->get('dueAmount'$payableAmount), 0);
  2845.                         if ($request->request->has('gatewayProductData'))
  2846.                             $gatewayProductData $request->request->get('gatewayProductData');
  2847.                         $gatewayProductData = [[
  2848.                             'price_data' => [
  2849.                                 'currency' => $currencyForGateway,
  2850.                                 'unit_amount' => $gatewayAmount != ? ((100 $gatewayAmount) / ($invoiceSessionCount != $invoiceSessionCount 1)) : 200000,
  2851.                                 'product_data' => [
  2852. //                            'name' => $request->request->has('packageName') ? $request->request->get('packageName') : 'Advanced Consultancy Package',
  2853.                                     'name' => 'Bee Coins',
  2854.                                     'images' => [$imageBySessionCount[0]],
  2855.                                 ],
  2856.                             ],
  2857.                             'quantity' => $invoiceSessionCount != $invoiceSessionCount 1,
  2858.                         ]];
  2859.                         $new_invoice null;
  2860.                         if ($extMeeting) {
  2861.                             $new_invoice $em->getRepository('CompanyGroupBundle\\Entity\\EntityInvoice')
  2862.                                 ->findOneBy(
  2863.                                     array(
  2864.                                         'invoiceType' => $request->request->get('invoiceType'BuddybeeConstant::ENTITY_INVOICE_TYPE_PAYMENT_TO_HONEYBEE),
  2865.                                         'meetingId' => $extMeeting->getSessionId(),
  2866.                                     )
  2867.                                 );
  2868.                         }
  2869.                         if ($new_invoice) {
  2870.                         } else {
  2871.                             $new_invoice = new EntityInvoice();
  2872.                             $invoiceDate = new \DateTime();
  2873.                             $new_invoice->setInvoiceDate($invoiceDate);
  2874.                             $new_invoice->setInvoiceDateTs($invoiceDate->format('U'));
  2875.                             $new_invoice->setStudentId($userId);
  2876.                             $new_invoice->setBillerId($retailerId == $retailerId);
  2877.                             $new_invoice->setRetailerId($retailerId);
  2878.                             $new_invoice->setBillToId($userId);
  2879.                             $new_invoice->setAmountTransferGateWayHash($paymentGateway);
  2880.                             $new_invoice->setAmountCurrency($currencyForGateway);
  2881.                             $cardIds $request->request->get('cardIds', []);
  2882.                             $new_invoice->setMeetingId($meetingSessionId);
  2883.                             $new_invoice->setGatewayBillAmount($gatewayAmount);
  2884.                             $new_invoice->setRedeemedAmount($redeemedAmount);
  2885.                             $new_invoice->setPromoDiscountAmount($promoClaimedAmount);
  2886.                             $new_invoice->setPromoCodeId($promoCodeId);
  2887.                             $new_invoice->setRedeemedSessionCount($redeemedSessionCount);
  2888.                             $new_invoice->setPaidAmount($payableAmount $dueAmount);
  2889.                             $new_invoice->setProductDataForPaymentGateway(json_encode($gatewayProductData));
  2890.                             $new_invoice->setDueAmount($dueAmount);
  2891.                             $new_invoice->setInvoiceType($request->request->get('invoiceType'BuddybeeConstant::ENTITY_INVOICE_TYPE_PAYMENT_TO_HONEYBEE));
  2892.                             $new_invoice->setDocumentHash(MiscActions::GenerateRandomCrypto('BEI' microtime(true)));
  2893.                             $new_invoice->setCardIds(json_encode($cardIds));
  2894.                             $new_invoice->setAmountType($request->request->get('amountType'1));
  2895.                             $new_invoice->setAmount($payableAmount);
  2896.                             $new_invoice->setConsumeAmount($payableAmount);
  2897.                             $new_invoice->setSessionCount($invoiceSessionCount);
  2898.                             $new_invoice->setConsumeSessionCount($toConsumeSessionCount);
  2899.                             $new_invoice->setIsPaidfull(0);
  2900.                             $new_invoice->setIsProcessed(0);
  2901.                             $new_invoice->setApplicantId($userId);
  2902.                             $new_invoice->setBookedById($bookedById);
  2903.                             $new_invoice->setBookingRefererId($bookingRefererId);
  2904.                             $new_invoice->setIsRecharge($request->request->get('isRecharge'0));
  2905.                             $new_invoice->setAutoConfirmTaggedMeeting($request->request->get('autoConfirmTaggedMeeting'0));
  2906.                             $new_invoice->setAutoConfirmOtherMeeting($request->request->get('autoConfirmOtherMeeting'0));
  2907.                             $new_invoice->setAutoClaimPurchasedCards($request->request->get('autoClaimPurchasedCards'0));
  2908.                             $new_invoice->setIsPayment(0); //0 means receive
  2909.                             $new_invoice->setStatus(GeneralConstant::ACTIVE); //0 means receive
  2910.                             $new_invoice->setStage(BuddybeeConstant::ENTITY_INVOICE_STAGE_INITIATED); //0 means receive
  2911.                             if ($bookingExpireTs == 0) {
  2912.                                 $bookingExpireTime = new \DateTime();
  2913.                                 $bookingExpireTime->modify('+30 day');
  2914.                                 $bookingExpireTs $bookingExpireTime->format('U');
  2915.                             }
  2916.                             $new_invoice->setExpireIfUnpaidTs($bookingExpireTs);
  2917.                             $new_invoice->setBookingExpireTs($bookingExpireTs);
  2918.                             $new_invoice->setConfirmationExpireTs($bookingExpireTs);
  2919. //            $new_invoice->setStatus($request->request->get(0));
  2920.                             $em_goc->persist($new_invoice);
  2921.                             $em_goc->flush();
  2922.                         }
  2923.                         $invoiceId $new_invoice->getId();
  2924.                         $gatewayInvoice $new_invoice;
  2925.                         if ($request->request->get('isRecharge'0) == 1) {
  2926.                         } else {
  2927.                             if ($gatewayAmount <= 0) {
  2928.                                 $meetingId 0;
  2929.                                 if ($invoiceId != 0) {
  2930.                                     $retData Buddybee::ProcessEntityInvoice($em_goc$invoiceId, ['stage' => BuddybeeConstant::ENTITY_INVOICE_STAGE_COMPLETED], $this->container->getParameter('kernel.root_dir'), false,
  2931.                                         $this->container->getParameter('notification_enabled'),
  2932.                                         $this->container->getParameter('notification_server')
  2933.                                     );
  2934.                                     $meetingId $retData['meetingId'];
  2935.                                 }
  2936.                                 MiscActions::RefreshBuddybeeBalanceOnSession($em$request->getSession());
  2937.                                 if (GeneralConstant::EMAIL_ENABLED == 1) {
  2938.                                     $billerDetails = [];
  2939.                                     $billToDetails = [];
  2940.                                     $invoice $gatewayInvoice;
  2941.                                     if ($invoice) {
  2942.                                         $billerDetails $em->getRepository('CompanyGroupBundle\\Entity\\EntityApplicantDetails')
  2943.                                             ->findOneBy(
  2944.                                                 array(
  2945.                                                     'applicantId' => $invoice->getBillerId(),
  2946.                                                 )
  2947.                                             );
  2948.                                         $billToDetails $em->getRepository('CompanyGroupBundle\\Entity\\EntityApplicantDetails')
  2949.                                             ->findOneBy(
  2950.                                                 array(
  2951.                                                     'applicantId' => $invoice->getBillToId(),
  2952.                                                 )
  2953.                                             );
  2954.                                     }
  2955.                                     $bodyTemplate '@Application/email/templates/buddybeeInvoiceEmail.html.twig';
  2956.                                     $bodyData = array(
  2957.                                         'page_title' => 'Invoice',
  2958. //            'studentDetails' => $student,
  2959.                                         'billerDetails' => $billerDetails,
  2960.                                         'billToDetails' => $billToDetails,
  2961.                                         'invoice' => $invoice,
  2962.                                         'currencyList' => BuddybeeConstant::$currency_List,
  2963.                                         'currencyListByMarker' => BuddybeeConstant::$currency_List_by_marker,
  2964.                                     );
  2965.                                     $attachments = [];
  2966.                                     $forwardToMailAddress $billToDetails->getOAuthEmail();
  2967. //                    $upl_dir = $this->container->getParameter('kernel.root_dir') . '/../web/uploads/temp/' . 'ledger' . '.pdf'
  2968.                                     $new_mail $this->get('mail_module');
  2969.                                     $new_mail->sendMyMail(array(
  2970.                                         'senderHash' => '_CUSTOM_',
  2971.                                         //                        'senderHash'=>'_CUSTOM_',
  2972.                                         'forwardToMailAddress' => $forwardToMailAddress,
  2973.                                         '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 ',
  2974. //                        'fileName' => 'Order#' . str_pad($id, 8, '0', STR_PAD_LEFT) . '.pdf',
  2975.                                         'attachments' => $attachments,
  2976.                                         'toAddress' => $forwardToMailAddress,
  2977.                                         'fromAddress' => \ApplicationBundle\Helper\MailerConfig::address(),
  2978.                                         'userName' => \ApplicationBundle\Helper\MailerConfig::address(),
  2979.                                         'password' => \ApplicationBundle\Helper\MailerConfig::buddybeePassword(),
  2980.                                         'smtpServer' => \ApplicationBundle\Helper\MailerConfig::host(),
  2981.                                         'smtpPort' => \ApplicationBundle\Helper\MailerConfig::port(),
  2982. //                            'emailBody' => $bodyHtml,
  2983.                                         'mailTemplate' => $bodyTemplate,
  2984.                                         'templateData' => $bodyData,
  2985.                                         'embedCompanyImage' => 0,
  2986.                                         'companyId' => 0,
  2987.                                         'companyImagePath' => ''
  2988. //                        'embedCompanyImage' => 1,
  2989. //                        'companyId' => $companyId,
  2990. //                        'companyImagePath' => $company_data->getImage()
  2991.                                     ));
  2992.                                 }
  2993.                                 if ($meetingId != 0) {
  2994.                                     $url $this->generateUrl(
  2995.                                         'consultancy_session'
  2996.                                     );
  2997.                                     $output = [
  2998.                                         'invoiceId' => $gatewayInvoice->getId(),
  2999.                                         'meetingId' => $meetingId,
  3000.                                         'proceedToCheckout' => 0,
  3001.                                         'redirectUrl' => $url '/' $meetingId
  3002.                                     ];
  3003.                                 } else {
  3004.                                     $url $this->generateUrl(
  3005.                                         'buddybee_dashboard'
  3006.                                     );
  3007.                                     $output = [
  3008.                                         'invoiceId' => $gatewayInvoice->getId(),
  3009.                                         'meetingId' => 0,
  3010.                                         'proceedToCheckout' => 0,
  3011.                                         'redirectUrl' => $url
  3012.                                     ];
  3013.                                 }
  3014.                                 return new JsonResponse($output);
  3015. //                return $this->redirect($url);
  3016.                             } else {
  3017.                             }
  3018. //                $url = $this->generateUrl(
  3019. //                    'checkout_page'
  3020. //                );
  3021. //
  3022. //                return $this->redirect($url."?meetingSessionId=".$new->getSessionId().'&invoiceId='.$invoiceId);
  3023.                         }
  3024.                     }
  3025.                 } else {
  3026.                     $url $this->generateUrl(
  3027.                         'user_login'
  3028.                     );
  3029.                     $session->set('LAST_REQUEST_URI_BEFORE_LOGIN'$this->generateUrl(
  3030.                         'pricing_plan_page', [
  3031.                         'autoRedirected' => 1
  3032.                     ],
  3033.                         UrlGenerator::ABSOLUTE_URL
  3034.                     ));
  3035.                     $output = [
  3036.                         'proceedToCheckout' => 0,
  3037.                         'redirectUrl' => $url,
  3038.                         'clearLs' => 0
  3039.                     ];
  3040.                     return new JsonResponse($output);
  3041.                 }
  3042.                 //now proceed to checkout page if the user has lower balance or recharging
  3043.                 //$invoiceDetails = $em->getRepository('CompanyGroupBundle\\Entity\\EntityInvoice')->
  3044.             }
  3045.         }
  3046.         if ($gatewayInvoice) {
  3047.             $gatewayProductData json_decode($gatewayInvoice->getProductDataForPaymentGateway(), true);
  3048.             if ($gatewayProductData == null$gatewayProductData = [];
  3049.             if (empty($gatewayProductData))
  3050.                 $gatewayProductData = [
  3051.                     [
  3052.                         'price_data' => [
  3053.                             'currency' => 'eur',
  3054.                             'unit_amount' => $gatewayAmount != ? (100 $gatewayAmount) : 200000,
  3055.                             'product_data' => [
  3056. //                            'name' => $request->request->has('packageName') ? $request->request->get('packageName') : 'Advanced Consultancy Package',
  3057.                                 'name' => 'Bee Coins',
  3058.                                 'images' => [$imageBySessionCount[0]],
  3059.                             ],
  3060.                         ],
  3061.                         'quantity' => 1,
  3062.                     ]
  3063.                 ];
  3064.             $productDescStr '';
  3065.             $productDescArr = [];
  3066.             foreach ($gatewayProductData as $gpd) {
  3067.                 $productDescArr[] = $gpd['price_data']['product_data']['name'];
  3068.             }
  3069.             $productDescStr implode(','$productDescArr);
  3070.             $paymentGatewayFromInvoice $gatewayInvoice->getAmountTransferGateWayHash();
  3071. //            return new JsonResponse(
  3072. //                [
  3073. //                    'paymentGateway' => $paymentGatewayFromInvoice,
  3074. //                    'gateWayData' => $gatewayProductData[0]
  3075. //                ]
  3076. //            );
  3077.             if ($paymentGateway == null$paymentGatewayFromInvoice 'stripe';
  3078.             if ($paymentGatewayFromInvoice == 'stripe' || $paymentGatewayFromInvoice == 'aamarpay' || $paymentGatewayFromInvoice == 'bkash') {
  3079.                 if (GeneralConstant::EMAIL_ENABLED == 1) {
  3080.                     $billerDetails = [];
  3081.                     $billToDetails = [];
  3082.                     $invoice $gatewayInvoice;
  3083.                     if ($invoice) {
  3084.                         $billerDetails $em->getRepository('CompanyGroupBundle\\Entity\\EntityApplicantDetails')
  3085.                             ->findOneBy(
  3086.                                 array(
  3087.                                     'applicantId' => $invoice->getBillerId(),
  3088.                                 )
  3089.                             );
  3090.                         $billToDetails $em->getRepository('CompanyGroupBundle\\Entity\\EntityApplicantDetails')
  3091.                             ->findOneBy(
  3092.                                 array(
  3093.                                     'applicantId' => $invoice->getBillToId(),
  3094.                                 )
  3095.                             );
  3096.                     }
  3097.                     $bodyTemplate '@Application/email/templates/buddybeeInvoiceEmail.html.twig';
  3098.                     $bodyData = array(
  3099.                         'page_title' => 'Invoice',
  3100. //            'studentDetails' => $student,
  3101.                         'billerDetails' => $billerDetails,
  3102.                         'billToDetails' => $billToDetails,
  3103.                         'invoice' => $invoice,
  3104.                         'currencyList' => BuddybeeConstant::$currency_List,
  3105.                         'currencyListByMarker' => BuddybeeConstant::$currency_List_by_marker,
  3106.                     );
  3107.                     $attachments = [];
  3108.                     $forwardToMailAddress $billToDetails->getOAuthEmail();
  3109. //                    $upl_dir = $this->container->getParameter('kernel.root_dir') . '/../web/uploads/temp/' . 'ledger' . '.pdf'
  3110.                     $new_mail $this->get('mail_module');
  3111.                     $new_mail->sendMyMail(array(
  3112.                         'senderHash' => '_CUSTOM_',
  3113.                         //                        'senderHash'=>'_CUSTOM_',
  3114.                         'forwardToMailAddress' => $forwardToMailAddress,
  3115.                         '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 ',
  3116. //                        'fileName' => 'Order#' . str_pad($id, 8, '0', STR_PAD_LEFT) . '.pdf',
  3117.                         'attachments' => $attachments,
  3118.                         'toAddress' => $forwardToMailAddress,
  3119.                         'fromAddress' => \ApplicationBundle\Helper\MailerConfig::address(),
  3120.                         'userName' => \ApplicationBundle\Helper\MailerConfig::address(),
  3121.                         'password' => \ApplicationBundle\Helper\MailerConfig::buddybeePassword(),
  3122.                         'smtpServer' => \ApplicationBundle\Helper\MailerConfig::host(),
  3123.                         'smtpPort' => \ApplicationBundle\Helper\MailerConfig::port(),
  3124. //                            'emailBody' => $bodyHtml,
  3125.                         'mailTemplate' => $bodyTemplate,
  3126.                         'templateData' => $bodyData,
  3127.                         'embedCompanyImage' => 0,
  3128.                         'companyId' => 0,
  3129.                         'companyImagePath' => ''
  3130. //                        'embedCompanyImage' => 1,
  3131. //                        'companyId' => $companyId,
  3132. //                        'companyImagePath' => $company_data->getImage()
  3133.                     ));
  3134.                 }
  3135.             }
  3136.             if ($paymentGatewayFromInvoice == 'stripe') {
  3137.                 $stripe = new \Stripe\Stripe();
  3138.                 \Stripe\Stripe::setApiKey('sk_test_51IxYTAJXs21fVb0QMop2Nb0E7u9Da4LwGrym1nGHUHqaSNtT3p9HBgHd7YyDsTKHscgPPECPQniTy79Ab8Sgxfbm00JF2AndUz');
  3139.                 $stripe::setApiKey('sk_test_51IxYTAJXs21fVb0QMop2Nb0E7u9Da4LwGrym1nGHUHqaSNtT3p9HBgHd7YyDsTKHscgPPECPQniTy79Ab8Sgxfbm00JF2AndUz');
  3140.                 {
  3141.                     if ($request->query->has('meetingSessionId'))
  3142.                         $id $request->query->get('meetingSessionId');
  3143.                 }
  3144.                 $paymentIntent = [
  3145.                     "id" => "pi_1DoWjK2eZvKYlo2Csy9J3BHs",
  3146.                     "object" => "payment_intent",
  3147.                     "amount" => 3000,
  3148.                     "amount_capturable" => 0,
  3149.                     "amount_received" => 0,
  3150.                     "application" => null,
  3151.                     "application_fee_amount" => null,
  3152.                     "canceled_at" => null,
  3153.                     "cancellation_reason" => null,
  3154.                     "capture_method" => "automatic",
  3155.                     "charges" => [
  3156.                         "object" => "list",
  3157.                         "data" => [],
  3158.                         "has_more" => false,
  3159.                         "url" => "/v1/charges?payment_intent=pi_1DoWjK2eZvKYlo2Csy9J3BHs"
  3160.                     ],
  3161.                     "client_secret" => "pi_1DoWjK2eZvKYlo2Csy9J3BHs_secret_vmxAcWZxo2kt1XhpWtZtnjDtd",
  3162.                     "confirmation_method" => "automatic",
  3163.                     "created" => 1546523966,
  3164.                     "currency" => $currencyForGateway,
  3165.                     "customer" => null,
  3166.                     "description" => null,
  3167.                     "invoice" => null,
  3168.                     "last_payment_error" => null,
  3169.                     "livemode" => false,
  3170.                     "metadata" => [],
  3171.                     "next_action" => null,
  3172.                     "on_behalf_of" => null,
  3173.                     "payment_method" => null,
  3174.                     "payment_method_options" => [],
  3175.                     "payment_method_types" => [
  3176.                         "card"
  3177.                     ],
  3178.                     "receipt_email" => null,
  3179.                     "review" => null,
  3180.                     "setup_future_usage" => null,
  3181.                     "shipping" => null,
  3182.                     "statement_descriptor" => null,
  3183.                     "statement_descriptor_suffix" => null,
  3184.                     "status" => "requires_payment_method",
  3185.                     "transfer_data" => null,
  3186.                     "transfer_group" => null
  3187.                 ];
  3188.                 $checkout_session = \Stripe\Checkout\Session::create([
  3189.                     'payment_method_types' => ['card'],
  3190.                     'line_items' => $gatewayProductData,
  3191.                     'mode' => 'payment',
  3192.                     'success_url' => $this->generateUrl(
  3193.                         'payment_gateway_success',
  3194.                         ['encData' => $this->get('url_encryptor')->encrypt(json_encode(array(
  3195.                             'invoiceId' => $invoiceId'autoRedirect' => $request->request->get('autoRedirect'1)
  3196.                         ))), 'hbeeSessionToken' => $session->get('token'0)], UrlGenerator::ABSOLUTE_URL
  3197.                     ),
  3198.                     'cancel_url' => $this->generateUrl(
  3199.                         'payment_gateway_cancel', ['invoiceId' => $invoiceId'autoRedirect' => $request->request->get('autoRedirect'1), 'hbeeSessionToken' => $session->get('token'0)], UrlGenerator::ABSOLUTE_URL
  3200.                     ),
  3201.                 ]);
  3202.                 $output = [
  3203.                     'clientSecret' => $paymentIntent['client_secret'],
  3204.                     'id' => $checkout_session->id,
  3205.                     'paymentGateway' => $paymentGatewayFromInvoice,
  3206.                     'proceedToCheckout' => 1
  3207.                 ];
  3208.                 return new JsonResponse($output);
  3209.             }
  3210.             if ($paymentGatewayFromInvoice == 'aamarpay') {
  3211.                 $studentDetails $em_goc->getRepository(EntityApplicantDetails::class)->find($gatewayInvoice->getBillToId());
  3212.                 $url $sandBoxMode == 'https://sandbox.aamarpay.com/request.php' 'https://secure.aamarpay.com/request.php';
  3213.                 $fields = array(
  3214. //                    'store_id' => 'aamarpaytest', //store id will be aamarpay,  contact integration@aamarpay.com for test/live id
  3215.                     'store_id' => $sandBoxMode == 'aamarpaytest' 'buddybee'//store id will be aamarpay,  contact integration@aamarpay.com for test/live id
  3216.                     'amount' => $gatewayInvoice->getGateWayBillamount(), //transaction amount
  3217.                     'payment_type' => 'VISA'//no need to change
  3218.                     'currency' => strtoupper($currencyForGateway),  //currenct will be USD/BDT
  3219.                     'tran_id' => $gatewayInvoice->getDocumentHash(), //transaction id must be unique from your end
  3220.                     'cus_name' => $studentDetails->getFirstname() . ' ' $studentDetails->getLastName(),  //customer name
  3221.                     'cus_email' => $studentDetails->getEmail(), //customer email address
  3222.                     'cus_add1' => $studentDetails->getCurrAddr(),  //customer address
  3223.                     'cus_add2' => $studentDetails->getCurrAddrCity(), //customer address
  3224.                     'cus_city' => $studentDetails->getCurrAddrCity(),  //customer city
  3225.                     'cus_state' => $studentDetails->getCurrAddrState(),  //state
  3226.                     'cus_postcode' => $studentDetails->getCurrAddrZip(), //postcode or zipcode
  3227.                     'cus_country' => 'Bangladesh',  //country
  3228.                     'cus_phone' => ($studentDetails->getPhone() == null || $studentDetails->getPhone() == '') ? '+8801911706483' $studentDetails->getPhone(), //customer phone number
  3229.                     'cus_fax' => '',  //fax
  3230.                     'ship_name' => ''//ship name
  3231.                     'ship_add1' => '',  //ship address
  3232.                     'ship_add2' => '',
  3233.                     'ship_city' => '',
  3234.                     'ship_state' => '',
  3235.                     'ship_postcode' => '',
  3236.                     'ship_country' => 'Bangladesh',
  3237.                     'desc' => $productDescStr,
  3238.                     'success_url' => $this->generateUrl(
  3239.                         'payment_gateway_success',
  3240.                         ['encData' => $this->get('url_encryptor')->encrypt(json_encode(array(
  3241.                             'invoiceId' => $invoiceId'autoRedirect' => $request->request->get('autoRedirect'1)
  3242.                         ))), 'hbeeSessionToken' => $session->get('token'0)], UrlGenerator::ABSOLUTE_URL
  3243.                     ),
  3244.                     'fail_url' => $this->generateUrl(
  3245.                         'payment_gateway_cancel', ['invoiceId' => $invoiceId'autoRedirect' => $request->request->get('autoRedirect'1), 'hbeeSessionToken' => $session->get('token'0)], UrlGenerator::ABSOLUTE_URL
  3246.                     ),
  3247.                     'cancel_url' => $this->generateUrl(
  3248.                         'payment_gateway_cancel', ['invoiceId' => $invoiceId'autoRedirect' => $request->request->get('autoRedirect'1), 'hbeeSessionToken' => $session->get('token'0)], UrlGenerator::ABSOLUTE_URL
  3249.                     ),
  3250. //                    'opt_a' => 'Reshad',  //optional paramter
  3251. //                    'opt_b' => 'Akil',
  3252. //                    'opt_c' => 'Liza',
  3253. //                    'opt_d' => 'Sohel',
  3254. //                    'signature_key' => 'dbb74894e82415a2f7ff0ec3a97e4183',  //sandbox
  3255.                     'signature_key' => $sandBoxMode == 'dbb74894e82415a2f7ff0ec3a97e4183' 'b7304a40e21fe15af3be9a948307f524'  //live
  3256.                 ); //signature key will provided aamarpay, contact integration@aamarpay.com for test/live signature key
  3257.                 $fields_string http_build_query($fields);
  3258. //                $ch = curl_init();
  3259. //                curl_setopt($ch, CURLOPT_VERBOSE, true);
  3260. //                curl_setopt($ch, CURLOPT_URL, $url);
  3261. //
  3262. //                curl_setopt($ch, CURLOPT_POSTFIELDS, $fields_string);
  3263. //                curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
  3264. //                curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
  3265. //                $url_forward = str_replace('"', '', stripslashes(curl_exec($ch)));
  3266. //                curl_close($ch);
  3267. //                $this->redirect_to_merchant($url_forward);
  3268.                 $output = [
  3269. //
  3270. //                    'redirectUrl' => ($sandBoxMode == 1 ? 'https://sandbox.aamarpay.com/' : 'https://secure.aamarpay.com/') . $url_forward, //keeping it off temporarily
  3271. //                    'fields'=>$fields,
  3272. //                    'fields_string'=>$fields_string,
  3273. //                    'redirectUrl' => $this->generateUrl(
  3274. //                        'payment_gateway_success',
  3275. //                        ['encData' => $this->get('url_encryptor')->encrypt(json_encode(array(
  3276. //                            'invoiceId' => $invoiceId, 'autoRedirect' => $request->request->get('autoRedirect', 1)
  3277. //                        ))), 'hbeeSessionToken' => $request->request->get('token', 0)], UrlGenerator::ABSOLUTE_URL
  3278. //                    ),
  3279.                     'paymentGateway' => $paymentGatewayFromInvoice,
  3280.                     'proceedToCheckout' => 1,
  3281.                     'data' => $fields
  3282.                 ];
  3283.                 return new JsonResponse($output);
  3284.             } else if ($paymentGatewayFromInvoice == 'bkash') {
  3285.                 $studentDetails $em_goc->getRepository(EntityApplicantDetails::class)->find($gatewayInvoice->getBillToId());
  3286.                 $baseUrl = ($sandBoxMode == 1) ? 'https://tokenized.sandbox.bka.sh/v1.2.0-beta' 'https://tokenized.pay.bka.sh/v1.2.0-beta';
  3287.                 $username_value = ($sandBoxMode == 1) ? 'sandboxTokenizedUser02' '01891962953';
  3288.                 $password_value = ($sandBoxMode == 1) ? 'sandboxTokenizedUser02@12345' ',a&kPV4deq&';
  3289.                 $app_key_value = ($sandBoxMode == 1) ? '4f6o0cjiki2rfm34kfdadl1eqq' '2ueVHdwz5gH3nxx7xn8wotlztc';
  3290.                 $app_secret_value = ($sandBoxMode == 1) ? '2is7hdktrekvrbljjh44ll3d9l1dtjo4pasmjvs5vl5qr3fug4b' '49Ay3h3wWJMBFD7WF5CassyLrtA1jt6ONhspqjqFx5hTjhqh5dHU';
  3291.                 $request_data = array(
  3292.                     'app_key' => $app_key_value,
  3293.                     'app_secret' => $app_secret_value
  3294.                 );
  3295.                 $url curl_init($baseUrl '/tokenized/checkout/token/grant');
  3296.                 $request_data_json json_encode($request_data);
  3297.                 $header = array(
  3298.                     'Content-Type:application/json',
  3299.                     'username:' $username_value,
  3300.                     'password:' $password_value
  3301.                 );
  3302.                 curl_setopt($urlCURLOPT_HTTPHEADER$header);
  3303.                 curl_setopt($urlCURLOPT_CUSTOMREQUEST"POST");
  3304.                 curl_setopt($urlCURLOPT_RETURNTRANSFERtrue);
  3305.                 curl_setopt($urlCURLOPT_POSTFIELDS$request_data_json);
  3306.                 curl_setopt($urlCURLOPT_FOLLOWLOCATION1);
  3307.                 curl_setopt($urlCURLOPT_IPRESOLVECURL_IPRESOLVE_V4);
  3308.                 $tokenData json_decode(curl_exec($url), true);
  3309.                 curl_close($url);
  3310.                 $id_token $tokenData['id_token'];
  3311.                 $goToBkashPage 0;
  3312.                 if ($tokenData['statusCode'] == '0000') {
  3313.                     $auth $id_token;
  3314.                     $requestbody = array(
  3315.                         "mode" => "0011",
  3316. //                        "payerReference" => "01723888888",
  3317.                         "payerReference" => $invoiceDate->format('U'),
  3318.                         "callbackURL" => $this->generateUrl(
  3319.                             'bkash_callback', [], UrlGenerator::ABSOLUTE_URL
  3320.                         ),
  3321. //                    "merchantAssociationInfo" => "MI05MID54RF09123456One",
  3322.                         "amount" => number_format($gatewayInvoice->getGateWayBillamount(), 2'.'''),
  3323.                         "currency" => "BDT",
  3324.                         "intent" => "sale",
  3325.                         "merchantInvoiceNumber" => $invoiceId
  3326.                     );
  3327.                     $url curl_init($baseUrl '/tokenized/checkout/create');
  3328.                     $requestbodyJson json_encode($requestbody);
  3329.                     $header = array(
  3330.                         'Content-Type:application/json',
  3331.                         'Authorization:' $auth,
  3332.                         'X-APP-Key:' $app_key_value
  3333.                     );
  3334.                     curl_setopt($urlCURLOPT_HTTPHEADER$header);
  3335.                     curl_setopt($urlCURLOPT_CUSTOMREQUEST"POST");
  3336.                     curl_setopt($urlCURLOPT_RETURNTRANSFERtrue);
  3337.                     curl_setopt($urlCURLOPT_POSTFIELDS$requestbodyJson);
  3338.                     curl_setopt($urlCURLOPT_FOLLOWLOCATION1);
  3339.                     curl_setopt($urlCURLOPT_IPRESOLVECURL_IPRESOLVE_V4);
  3340.                     $resultdata curl_exec($url);
  3341. //                    curl_close($url);
  3342. //                    echo $resultdata;
  3343.                     $obj json_decode($resultdatatrue);
  3344.                     $goToBkashPage 1;
  3345.                     $justNow = new \DateTime();
  3346.                     $justNow->modify('+' $tokenData['expires_in'] . ' second');
  3347.                     $gatewayInvoice->setGatewayIdTokenExpireTs($justNow->format('U'));
  3348.                     $gatewayInvoice->setGatewayIdToken($tokenData['id_token']);
  3349.                     $gatewayInvoice->setGatewayPaymentId($obj['paymentID']);
  3350.                     $gatewayInvoice->setGatewayIdRefreshToken($tokenData['refresh_token']);
  3351.                     $em->flush();
  3352.                     $output = [
  3353. //                        'redirectUrl' => $obj['bkashURL'],
  3354.                         'paymentGateway' => $paymentGatewayFromInvoice,
  3355.                         'proceedToCheckout' => $goToBkashPage,
  3356.                         'tokenData' => $tokenData,
  3357.                         'obj' => $obj,
  3358.                         'id_token' => $tokenData['id_token'],
  3359.                         'data' => [
  3360.                             'amount' => $gatewayInvoice->getGateWayBillamount(), //transaction amount
  3361. //                            'payment_type' => 'VISA', //no need to change
  3362.                             'currency' => strtoupper($currencyForGateway),  //currenct will be USD/BDT
  3363.                             'tran_id' => $gatewayInvoice->getDocumentHash(), //transaction id must be unique from your end
  3364.                             'cus_name' => $studentDetails->getFirstname() . ' ' $studentDetails->getLastName(),  //customer name
  3365.                             'cus_email' => $studentDetails->getEmail(), //customer email address
  3366.                             'cus_add1' => $studentDetails->getCurrAddr(),  //customer address
  3367.                             'cus_add2' => $studentDetails->getCurrAddrCity(), //customer address
  3368.                             'cus_city' => $studentDetails->getCurrAddrCity(),  //customer city
  3369.                             'cus_state' => $studentDetails->getCurrAddrState(),  //state
  3370.                             'cus_postcode' => $studentDetails->getCurrAddrZip(), //postcode or zipcode
  3371.                             'cus_country' => 'Bangladesh',  //country
  3372.                             'cus_phone' => ($studentDetails->getPhone() == null || $studentDetails->getPhone() == '') ? '+8801911706483' $studentDetails->getPhone(), //customer phone number
  3373.                             'cus_fax' => '',  //fax
  3374.                             'ship_name' => ''//ship name
  3375.                             'ship_add1' => '',  //ship address
  3376.                             'ship_add2' => '',
  3377.                             'ship_city' => '',
  3378.                             'ship_state' => '',
  3379.                             'ship_postcode' => '',
  3380.                             'ship_country' => 'Bangladesh',
  3381.                             'desc' => $productDescStr,
  3382.                         ]
  3383.                     ];
  3384.                     return new JsonResponse($output);
  3385.                 }
  3386. //                $fields = array(
  3387. //
  3388. //                    "mode" => "0011",
  3389. //                    "payerReference" => "01723888888",
  3390. //                    "callbackURL" => $this->generateUrl(
  3391. //                        'payment_gateway_success',
  3392. //                        ['encData' => $this->get('url_encryptor')->encrypt(json_encode(array(
  3393. //                            'invoiceId' => $invoiceId, 'autoRedirect' => $request->request->get('autoRedirect', 1)
  3394. //                        ))), 'hbeeSessionToken' => $session->get('token', 0)], UrlGenerator::ABSOLUTE_URL
  3395. //                    ),
  3396. //                    "merchantAssociationInfo" => "MI05MID54RF09123456One",
  3397. //                    "amount" => 1*number_format($gatewayInvoice->getGateWayBillamount(),2,'.',''),,
  3398. //                    "currency" => "BDT",
  3399. //                    "intent" => "sale",
  3400. //                    "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)
  3401. //
  3402. //                );
  3403. //                $fields = array(
  3404. ////                    'store_id' => 'aamarpaytest', //store id will be aamarpay,  contact integration@aamarpay.com for test/live id
  3405. //                    'store_id' => $sandBoxMode == 1 ? 'aamarpaytest' : 'buddybee', //store id will be aamarpay,  contact integration@aamarpay.com for test/live id
  3406. //                    'amount' => 1*number_format($gatewayInvoice->getGateWayBillamount(),2,'.',''),, //transaction amount
  3407. //                    'payment_type' => 'VISA', //no need to change
  3408. //                    'currency' => strtoupper($currencyForGateway),  //currenct will be USD/BDT
  3409. //                    '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
  3410. //                    'cus_name' => $studentDetails->getFirstname() . ' ' . $studentDetails->getLastName(),  //customer name
  3411. //                    'cus_email' => $studentDetails->getEmail(), //customer email address
  3412. //                    'cus_add1' => $studentDetails->getCurrAddr(),  //customer address
  3413. //                    'cus_add2' => $studentDetails->getCurrAddrCity(), //customer address
  3414. //                    'cus_city' => $studentDetails->getCurrAddrCity(),  //customer city
  3415. //                    'cus_state' => $studentDetails->getCurrAddrState(),  //state
  3416. //                    'cus_postcode' => $studentDetails->getCurrAddrZip(), //postcode or zipcode
  3417. //                    'cus_country' => 'Bangladesh',  //country
  3418. //                    'cus_phone' => ($studentDetails->getPhone() == null || $studentDetails->getPhone() == '') ? ' + 8801911706483' : $studentDetails->getPhone(), //customer phone number
  3419. //                    'cus_fax' => '',  //fax
  3420. //                    'ship_name' => '', //ship name
  3421. //                    'ship_add1' => '',  //ship address
  3422. //                    'ship_add2' => '',
  3423. //                    'ship_city' => '',
  3424. //                    'ship_state' => '',
  3425. //                    'ship_postcode' => '',
  3426. //                    'ship_country' => 'Bangladesh',
  3427. //                    'desc' => $productDescStr,
  3428. //                    'success_url' => $this->generateUrl(
  3429. //                        'payment_gateway_success',
  3430. //                        ['encData' => $this->get('url_encryptor')->encrypt(json_encode(array(
  3431. //                            'invoiceId' => $invoiceId, 'autoRedirect' => $request->request->get('autoRedirect', 1)
  3432. //                        ))), 'hbeeSessionToken' => $session->get('token', 0)], UrlGenerator::ABSOLUTE_URL
  3433. //                    ),
  3434. //                    'fail_url' => $this->generateUrl(
  3435. //                        'payment_gateway_cancel', ['invoiceId' => $invoiceId, 'autoRedirect' => $request->request->get('autoRedirect', 1), 'hbeeSessionToken' => $session->get('token', 0)], UrlGenerator::ABSOLUTE_URL
  3436. //                    ),
  3437. //                    'cancel_url' => $this->generateUrl(
  3438. //                        'payment_gateway_cancel', ['invoiceId' => $invoiceId, 'autoRedirect' => $request->request->get('autoRedirect', 1), 'hbeeSessionToken' => $session->get('token', 0)], UrlGenerator::ABSOLUTE_URL
  3439. //                    ),
  3440. ////                    'opt_a' => 'Reshad',  //optional paramter
  3441. ////                    'opt_b' => 'Akil',
  3442. ////                    'opt_c' => 'Liza',
  3443. ////                    'opt_d' => 'Sohel',
  3444. ////                    'signature_key' => 'dbb74894e82415a2f7ff0ec3a97e4183',  //sandbox
  3445. //                    'signature_key' => $sandBoxMode == 1 ? 'dbb74894e82415a2f7ff0ec3a97e4183' : 'b7304a40e21fe15af3be9a948307f524'  //live
  3446. //
  3447. //                ); //signature key will provided aamarpay, contact integration@aamarpay.com for test/live signature key
  3448. //
  3449. //                $fields_string = http_build_query($fields);
  3450. //
  3451. //                $ch = curl_init();
  3452. //                curl_setopt($ch, CURLOPT_VERBOSE, true);
  3453. //                curl_setopt($ch, CURLOPT_URL, $url);
  3454. //
  3455. //                curl_setopt($ch, CURLOPT_POSTFIELDS, $fields_string);
  3456. //                curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
  3457. //                curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
  3458. //                $url_forward = str_replace('"', '', stripslashes(curl_exec($ch)));
  3459. //                curl_close($ch);
  3460. //                $this->redirect_to_merchant($url_forward);
  3461.             } else if ($paymentGatewayFromInvoice == 'onsite_pos' || $paymentGatewayFromInvoice == 'onsite_cash' || $paymentGatewayFromInvoice == 'onsite_bkash') {
  3462.                 $meetingId 0;
  3463.                 if ($gatewayInvoice->getId() != 0) {
  3464.                     if ($gatewayInvoice->getDueAmount() <= 0) {
  3465.                         $retData Buddybee::ProcessEntityInvoice($em_goc$gatewayInvoice->getId(), ['stage' => BuddybeeConstant::ENTITY_INVOICE_STAGE_COMPLETED], $this->container->getParameter('kernel.root_dir'), false,
  3466.                             $this->container->getParameter('notification_enabled'),
  3467.                             $this->container->getParameter('notification_server')
  3468.                         );
  3469.                         $meetingId $retData['meetingId'];
  3470.                     }
  3471.                     if (GeneralConstant::EMAIL_ENABLED == 1) {
  3472.                         $billerDetails = [];
  3473.                         $billToDetails = [];
  3474.                         $invoice $gatewayInvoice;
  3475.                         if ($invoice) {
  3476.                             $billerDetails $em->getRepository('CompanyGroupBundle\\Entity\\EntityApplicantDetails')
  3477.                                 ->findOneBy(
  3478.                                     array(
  3479.                                         'applicantId' => $invoice->getBillerId(),
  3480.                                     )
  3481.                                 );
  3482.                             $billToDetails $em->getRepository('CompanyGroupBundle\\Entity\\EntityApplicantDetails')
  3483.                                 ->findOneBy(
  3484.                                     array(
  3485.                                         'applicantId' => $invoice->getBillToId(),
  3486.                                     )
  3487.                                 );
  3488.                         }
  3489.                         $bodyTemplate '@Application/email/templates/buddybeeInvoiceEmail.html.twig';
  3490.                         $bodyData = array(
  3491.                             'page_title' => 'Invoice',
  3492. //            'studentDetails' => $student,
  3493.                             'billerDetails' => $billerDetails,
  3494.                             'billToDetails' => $billToDetails,
  3495.                             'invoice' => $invoice,
  3496.                             'currencyList' => BuddybeeConstant::$currency_List,
  3497.                             'currencyListByMarker' => BuddybeeConstant::$currency_List_by_marker,
  3498.                         );
  3499.                         $attachments = [];
  3500.                         $forwardToMailAddress $billToDetails->getOAuthEmail();
  3501. //                    $upl_dir = $this->container->getParameter('kernel.root_dir') . '/../web/uploads/temp/' . 'ledger' . '.pdf'
  3502.                         $new_mail $this->get('mail_module');
  3503.                         $new_mail->sendMyMail(array(
  3504.                             'senderHash' => '_CUSTOM_',
  3505.                             //                        'senderHash'=>'_CUSTOM_',
  3506.                             'forwardToMailAddress' => $forwardToMailAddress,
  3507.                             '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 ',
  3508. //                        'fileName' => 'Order#' . str_pad($id, 8, '0', STR_PAD_LEFT) . '.pdf',
  3509.                             'attachments' => $attachments,
  3510.                             'toAddress' => $forwardToMailAddress,
  3511.                             'fromAddress' => \ApplicationBundle\Helper\MailerConfig::address(),
  3512.                             'userName' => \ApplicationBundle\Helper\MailerConfig::address(),
  3513.                             'password' => \ApplicationBundle\Helper\MailerConfig::buddybeePassword(),
  3514.                             'smtpServer' => \ApplicationBundle\Helper\MailerConfig::host(),
  3515.                             'smtpPort' => \ApplicationBundle\Helper\MailerConfig::port(),
  3516. //                            'emailBody' => $bodyHtml,
  3517.                             'mailTemplate' => $bodyTemplate,
  3518.                             'templateData' => $bodyData,
  3519.                             'embedCompanyImage' => 0,
  3520.                             'companyId' => 0,
  3521.                             'companyImagePath' => ''
  3522. //                        'embedCompanyImage' => 1,
  3523. //                        'companyId' => $companyId,
  3524. //                        'companyImagePath' => $company_data->getImage()
  3525.                         ));
  3526.                     }
  3527.                 }
  3528.                 MiscActions::RefreshBuddybeeBalanceOnSession($em$request->getSession());
  3529.                 if ($meetingId != 0) {
  3530.                     $url $this->generateUrl(
  3531.                         'consultancy_session'
  3532.                     );
  3533.                     $output = [
  3534.                         'proceedToCheckout' => 0,
  3535.                         'invoiceId' => $gatewayInvoice->getId(),
  3536.                         'meetingId' => $meetingId,
  3537.                         'redirectUrl' => $url '/' $meetingId
  3538.                     ];
  3539.                 } else {
  3540.                     $url $this->generateUrl(
  3541.                         'buddybee_dashboard'
  3542.                     );
  3543.                     $output = [
  3544.                         'proceedToCheckout' => 0,
  3545.                         'invoiceId' => $gatewayInvoice->getId(),
  3546.                         'meetingId' => $meetingId,
  3547.                         'redirectUrl' => $url
  3548.                     ];
  3549.                 }
  3550.                 return new JsonResponse($output);
  3551.             }
  3552.         }
  3553.         $output = [
  3554.             'clientSecret' => 0,
  3555.             'id' => 0,
  3556.             'proceedToCheckout' => 0
  3557.         ];
  3558.         return new JsonResponse($output);
  3559. //        return $this->render('ApplicationBundle:pages/stripe:checkout.html.twig', array(
  3560. //            'page_title' => 'Checkout',
  3561. ////            'stripe' => $stripe,
  3562. //            'stripe' => null,
  3563. ////            'PaymentIntent' => $paymentIntent,
  3564. //
  3565. ////            'consultantDetail' => $consultantDetail,
  3566. ////            'consultantDetails'=> $consultantDetails,
  3567. ////
  3568. ////            'meetingSession' => $meetingSession,
  3569. ////            'packageDetails' => json_decode($meetingSession->getPcakageDetails(),true),
  3570. ////            'packageName' => json_decode($meetingSession->getPackageName(),true),
  3571. ////            'pay' => $payableAmount,
  3572. ////            'balance' => $currStudentBal
  3573. //        ));
  3574.     }
  3575.     public function PaymentGatewaySuccessAction(Request $request$encData '')
  3576.     {
  3577.         $em $this->getDoctrine()->getManager('company_group');
  3578.         $invoiceId 0;
  3579.         $autoRedirect 1;
  3580.         $redirectUrl '';
  3581.         $meetingId 0;
  3582.         $setupOnly 0;
  3583.         $appId 0;
  3584.         $ownerId 0;
  3585.         $activationPending 0;
  3586.         $ownerSyncResult null;
  3587.         $systemType $this->container->hasParameter('system_type') ? $this->container->getParameter('system_type') : '_ERP_';
  3588.         if ($systemType == '_CENTRAL_') {
  3589.             if ($encData != '') {
  3590.                 $encryptedData json_decode($this->get('url_encryptor')->decrypt($encData), true);
  3591.                 if (isset($encryptedData['invoiceId']))
  3592.                     $invoiceId $encryptedData['invoiceId'];
  3593.                 if (isset($encryptedData['autoRedirect']))
  3594.                     $autoRedirect $encryptedData['autoRedirect'];
  3595.                 if (isset($encryptedData['setupOnly']))
  3596.                     $setupOnly = (int)$encryptedData['setupOnly'];
  3597.                 if (isset($encryptedData['appId']))
  3598.                     $appId = (int)$encryptedData['appId'];
  3599.                 if (isset($encryptedData['ownerId']))
  3600.                     $ownerId = (int)$encryptedData['ownerId'];
  3601.                 if (isset($encryptedData['redirectUrl']))
  3602.                     $redirectUrl $encryptedData['redirectUrl'];
  3603.             } else {
  3604.                 $invoiceId $request->query->get('invoiceId'0);
  3605.                 $meetingId 0;
  3606.                 $autoRedirect $request->query->get('autoRedirect'1);
  3607.                 $redirectUrl $request->query->get('redirectUrl''');
  3608.                 $setupOnly = (int)$request->query->get('setupOnly'0);
  3609.                 $appId = (int)$request->query->get('appId'0);
  3610.                 $ownerId = (int)$request->query->get('ownerId'0);
  3611.             }
  3612.             if ($setupOnly === 1) {
  3613.                 $sessionId $request->query->get('session_id');
  3614.                 if (!$sessionId) {
  3615.                     return $this->render('@Application/pages/stripe/cancel.html.twig', array(
  3616.                         'page_title' => 'Failed',
  3617.                     ));
  3618.                 }
  3619.                 $stripeSession = \Stripe\Checkout\Session::retrieve($sessionId);
  3620.                 if (!$stripeSession || !$stripeSession->setup_intent) {
  3621.                     return $this->render('@Application/pages/stripe/cancel.html.twig', array(
  3622.                         'page_title' => 'Failed',
  3623.                     ));
  3624.                 }
  3625.                 $setupIntent = \Stripe\SetupIntent::retrieve($stripeSession->setup_intent);
  3626.                 if ($setupIntent->status !== 'succeeded') {
  3627.                     return $this->render('@Application/pages/stripe/cancel.html.twig', array(
  3628.                         'page_title' => 'Failed',
  3629.                     ));
  3630.                 }
  3631.                 $paymentMethodId $setupIntent->payment_method;
  3632.                 $customerId $setupIntent->customer;
  3633.                 if ($appId === && isset($stripeSession->metadata['app_id'])) {
  3634.                     $appId = (int)$stripeSession->metadata['app_id'];
  3635.                 }
  3636.                 if ($ownerId === && isset($stripeSession->metadata['owner_id'])) {
  3637.                     $ownerId = (int)$stripeSession->metadata['owner_id'];
  3638.                 }
  3639.                 if ($redirectUrl === '' && isset($stripeSession->metadata['redirect_url'])) {
  3640.                     $redirectUrl $stripeSession->metadata['redirect_url'];
  3641.                 }
  3642.                 $companyGroup null;
  3643.                 if ($appId !== 0) {
  3644.                     $companyGroup $em
  3645.                         ->getRepository("CompanyGroupBundle\\Entity\\CompanyGroup")
  3646.                         ->findOneBy([
  3647.                             'appId' => $appId
  3648.                         ]);
  3649.                 }
  3650.                 $existing $em->getRepository(PaymentMethod::class)
  3651.                     ->findOneBy([
  3652.                         'stripePaymentMethodId' => $paymentMethodId,
  3653.                         'appId' => $appId
  3654.                     ]);
  3655.                 if (!$existing) {
  3656.                     if ($companyGroup && !$companyGroup->getStripeCustomerId()) {
  3657.                         $companyGroup->setStripeCustomerId($customerId);
  3658.                     }
  3659.                     $paymentMethod = new PaymentMethod();
  3660.                     $paymentMethod->setAppId($appId);
  3661.                     $paymentMethod->setApplicantId($ownerId);
  3662.                     $paymentMethod->setStripeCustomerId($customerId);
  3663.                     $paymentMethod->setStripePaymentMethodId($paymentMethodId);
  3664.                     $paymentMethod->setIsDefault(1);
  3665.                     $em->persist($paymentMethod);
  3666.                     $em->flush();
  3667.                 }
  3668.                 if ($companyGroup) {
  3669.                     $em->flush();
  3670.                 }
  3671.                 $redirectUrl $redirectUrl !== '' $redirectUrl $this->generateUrl(
  3672.                     'central_landing'
  3673.                 );
  3674.                 return $this->render('@Application/pages/stripe/success.html.twig', array(
  3675.                     'page_title' => 'Success',
  3676.                     'meetingId' => 0,
  3677.                     'autoRedirect' => 0,
  3678.                     'redirectUrl' => $redirectUrl,
  3679.                     'initiateCompany' => 1,
  3680.                     'appId' => $appId,
  3681.                     'ownerId' => $ownerId,
  3682.                     'setupOnly' => 1,
  3683.                 ));
  3684.             }
  3685.             if ($invoiceId != 0) {
  3686.                 $invoice $em
  3687.                     ->getRepository("CompanyGroupBundle\\Entity\\EntityInvoice")
  3688.                     ->findOneBy([
  3689.                         'id' => $invoiceId
  3690.                     ]);
  3691.                 if($invoice->getAmountTransferGateWayHash() == 'stripe') {
  3692.                     $stripeSession = \Stripe\Checkout\Session::retrieve($request->query->get('session_id'));
  3693.                     $paymentIntent = \Stripe\PaymentIntent::retrieve($stripeSession->payment_intent);
  3694.                     if ($paymentIntent->status !== 'succeeded') {
  3695.                         return $this->render('@Application/pages/stripe/cancel.html.twig', array(
  3696.                             'page_title' => 'Failed',
  3697.                         ));
  3698.                     }
  3699.                     $paymentMethodId $paymentIntent->payment_method;
  3700.                     $customerId $paymentIntent->customer;
  3701.                     $companyGroup $this->get('app.quote_company_provisioning_service')
  3702.                         ->ensureCompanyForInvoice($invoice$request->getSession(), $customerId);
  3703.                     if (!isset($companyGroup) || !$companyGroup) {
  3704.                         $companyGroup $em
  3705.                             ->getRepository("CompanyGroupBundle\\Entity\\CompanyGroup")
  3706.                             ->findOneBy([
  3707.                                 'appId' => $invoice->getAppId()
  3708.                             ]);
  3709.                     }
  3710.                     $existing $em->getRepository(PaymentMethod::class)
  3711.                         ->findOneBy([
  3712.                             'stripePaymentMethodId' => $paymentMethodId
  3713.                         ]);
  3714.                     if (!$existing) {
  3715.                         if ($companyGroup) {
  3716.                             // save customer id (safety)
  3717.                             if (!$companyGroup->getStripeCustomerId()) {
  3718.                                 $companyGroup->setStripeCustomerId($customerId);
  3719.                             }
  3720.                             // save payment method
  3721.                             $paymentMethod = new PaymentMethod(); // your entity
  3722.                             $paymentMethod->setAppId($companyGroup->getAppId());;
  3723.                             $paymentMethod->setApplicantId($invoice->getApplicantId());
  3724.                             $paymentMethod->setStripeCustomerId($customerId);
  3725.                             $paymentMethod->setStripePaymentMethodId($paymentMethodId);
  3726.                             $paymentMethod->setIsDefault(1);
  3727.                             $em->persist($paymentMethod);
  3728.                             $em->flush();
  3729.                         }
  3730.                     }
  3731.                 }
  3732.                 $retData Buddybee::ProcessEntityInvoice($em$invoiceId, ['stage' => BuddybeeConstant::ENTITY_INVOICE_STAGE_COMPLETED],
  3733.                     $this->container->getParameter('kernel.root_dir'),
  3734.                     false,
  3735.                     $this->container->getParameter('notification_enabled'),
  3736.                     $this->container->getParameter('notification_server')
  3737.                 );
  3738.                 if (($retData['initiateCompany'] ?? 0) == 1) {
  3739.                     $healthResult $this->get('app.provisioning_health_service')->check($invoicetrue);
  3740.                     if (!($healthResult['success'] ?? false)) {
  3741.                         $activationPending 1;
  3742.                         $autoRedirect 0;
  3743.                         $this->get('logger')->warning('Post-payment ERP health check needs attention.', [
  3744.                             'invoiceId' => (int)$invoice->getId(),
  3745.                             'appId' => (int)$invoice->getAppId(),
  3746.                             'errorCode' => $healthResult['errorCode'] ?? 'health_unverified',
  3747.                         ]);
  3748.                     }
  3749.                 }
  3750.                 $this->get('app.subscription_state_sync_service')->syncFromLegacyInvoice($invoice);
  3751.                 if (($retData['initiateCompany'] ?? 0) == 1) {
  3752.                     if (($retData['ownerId'] ?? 0) != 0) {
  3753.                         $ownerSyncResult $this->get('app.post_payment_company_setup_service')
  3754.                             ->finalizeOwnerServerSync((int)$retData['ownerId'], (int)($retData['appId'] ?? 0), (int)$invoice->getId());
  3755.                     } else {
  3756.                         $ownerSyncResult = [
  3757.                             'success' => false,
  3758.                             'failedServerIds' => [],
  3759.                             'missingAppIds' => [(int)($retData['appId'] ?? 0)],
  3760.                         ];
  3761.                     }
  3762.                     if (!($ownerSyncResult['success'] ?? false)) {
  3763.                         $activationPending 1;
  3764.                         $autoRedirect 0;
  3765.                         $this->get('logger')->warning('Post-payment owner synchronization needs attention.', [
  3766.                             'ownerId' => (int)($retData['ownerId'] ?? 0),
  3767.                             'appId' => (int)($retData['appId'] ?? 0),
  3768.                             'failedServerIds' => $ownerSyncResult['failedServerIds'] ?? [],
  3769.                             'missingAppIds' => $ownerSyncResult['missingAppIds'] ?? [],
  3770.                         ]);
  3771.                     } else {
  3772.                         $readinessResult $this->get('app.provisioning_health_service')->checkOwnerReadiness(
  3773.                             $invoice,
  3774.                             (int)$retData['ownerId'],
  3775.                             $ownerSyncResult,
  3776.                             true
  3777.                         );
  3778.                         if (!($readinessResult['ready'] ?? false)) {
  3779.                             $activationPending 1;
  3780.                             $autoRedirect 0;
  3781.                             $this->get('logger')->warning('Post-payment owner login health needs attention.', [
  3782.                                 'invoiceId' => (int)$invoice->getId(),
  3783.                                 'appId' => (int)($retData['appId'] ?? 0),
  3784.                                 'ownerId' => (int)$retData['ownerId'],
  3785.                                 'blocker' => $readinessResult['blocker'] ?? 'tenant_health_unverified',
  3786.                             ]);
  3787.                         } else {
  3788.                             // This second, owner-aware check is stronger than the
  3789.                             // earlier initialization check and may safely clear a
  3790.                             // transient initialization-pending result.
  3791.                             $activationPending 0;
  3792.                         }
  3793.                     }
  3794.                 }
  3795.                 if ($retData['sendCards'] == 1) {
  3796.                     $cardList = array();
  3797.                     $cards $em->getRepository('CompanyGroupBundle\\Entity\\BeeCode')
  3798.                         ->findBy(
  3799.                             array(
  3800.                                 'id' => $retData['cardIds']
  3801.                             )
  3802.                         );
  3803.                     foreach ($cards as $card) {
  3804.                         $cardList[] = array(
  3805.                             'id' => $card->getId(),
  3806.                             'printed' => $card->getPrinted(),
  3807.                             'amount' => $card->getAmount(),
  3808.                             'coinCount' => $card->getCoinCount(),
  3809.                             'pin' => $card->getPin(),
  3810.                             'serial' => $card->getSerial(),
  3811.                         );
  3812.                     }
  3813.                     $receiverEmail $retData['receiverEmail'];
  3814.                     if (GeneralConstant::EMAIL_ENABLED == 1) {
  3815.                         $bodyHtml '';
  3816.                         $bodyTemplate '@Application/email/templates/beeCodeDigitalDelivery.html.twig';
  3817.                         $bodyData = array(
  3818.                             'cardList' => $cardList,
  3819. //                        'name' => $newApplicant->getFirstname() . ' ' . $newApplicant->getLastname(),
  3820. //                        'email' => $userName,
  3821. //                        'password' => $newApplicant->getPassword(),
  3822.                         );
  3823.                         $attachments = [];
  3824.                         $forwardToMailAddress $receiverEmail;
  3825. //                    $upl_dir = $this->container->getParameter('kernel.root_dir') . '/../web/uploads/temp/' . 'ledger' . '.pdf'
  3826.                         $new_mail $this->get('mail_module');
  3827.                         $new_mail->sendMyMail(array(
  3828.                             'senderHash' => '_CUSTOM_',
  3829.                             //                        'senderHash'=>'_CUSTOM_',
  3830.                             'forwardToMailAddress' => $forwardToMailAddress,
  3831.                             'subject' => 'Digital Bee Card Delivery',
  3832. //                        'fileName' => 'Order#' . str_pad($id, 8, '0', STR_PAD_LEFT) . '.pdf',
  3833.                             'attachments' => $attachments,
  3834.                             'toAddress' => $forwardToMailAddress,
  3835.                             'fromAddress' => 'delivery@buddybee.eu',
  3836.                             'userName' => 'delivery@buddybee.eu',
  3837.                             'password' => \ApplicationBundle\Helper\MailerConfig::buddybeePassword(),
  3838.                             'smtpServer' => \ApplicationBundle\Helper\MailerConfig::host(),
  3839.                             'smtpPort' => \ApplicationBundle\Helper\MailerConfig::port(),
  3840. //                        'encryptionMethod' => 'tls',
  3841.                             'encryptionMethod' => 'ssl',
  3842. //                            'emailBody' => $bodyHtml,
  3843.                             'mailTemplate' => $bodyTemplate,
  3844.                             'templateData' => $bodyData,
  3845. //                        'embedCompanyImage' => 1,
  3846. //                        'companyId' => $companyId,
  3847. //                        'companyImagePath' => $company_data->getImage()
  3848.                         ));
  3849.                         foreach ($cards as $card) {
  3850.                             $card->setPrinted(1);
  3851.                         }
  3852.                         $em->flush();
  3853.                     }
  3854.                     return new JsonResponse(
  3855.                         array(
  3856.                             'success' => true
  3857.                         )
  3858.                     );
  3859.                 }
  3860.                 MiscActions::RefreshBuddybeeBalanceOnSession($em$request->getSession());
  3861.                 $meetingId $retData['meetingId'];
  3862.                 if (GeneralConstant::EMAIL_ENABLED == 1) {
  3863.                     $billerDetails = [];
  3864.                     $billToDetails = [];
  3865.                     $invoice $em->getRepository('CompanyGroupBundle\\Entity\\EntityInvoice')
  3866.                         ->findOneBy(
  3867.                             array(
  3868.                                 'Id' => $invoiceId,
  3869.                             )
  3870.                         );;
  3871.                     if ($invoice) {
  3872.                         $billerDetails $em->getRepository('CompanyGroupBundle\\Entity\\EntityApplicantDetails')
  3873.                             ->findOneBy(
  3874.                                 array(
  3875.                                     'applicantId' => $invoice->getBillerId(),
  3876.                                 )
  3877.                             );
  3878.                         $billToDetails $em->getRepository('CompanyGroupBundle\\Entity\\EntityApplicantDetails')
  3879.                             ->findOneBy(
  3880.                                 array(
  3881.                                     'applicantId' => $invoice->getBillToId(),
  3882.                                 )
  3883.                             );
  3884.                     }
  3885.                     $bodyTemplate '@Application/email/templates/buddybeeInvoiceEmail.html.twig';
  3886.                     $bodyData = array(
  3887.                         'page_title' => 'Invoice',
  3888. //            'studentDetails' => $student,
  3889.                         'billerDetails' => $billerDetails,
  3890.                         'billToDetails' => $billToDetails,
  3891.                         'invoice' => $invoice,
  3892.                         'currencyList' => BuddybeeConstant::$currency_List,
  3893.                         'currencyListByMarker' => BuddybeeConstant::$currency_List_by_marker,
  3894.                     );
  3895.                     $attachments = [];
  3896.                     $forwardToMailAddress $billToDetails->getOAuthEmail();
  3897. //                    $upl_dir = $this->container->getParameter('kernel.root_dir') . '/../web/uploads/temp/' . 'ledger' . '.pdf'
  3898.                     $new_mail $this->get('mail_module');
  3899.                     $new_mail->sendMyMail(array(
  3900.                         'senderHash' => '_CUSTOM_',
  3901.                         //                        'senderHash'=>'_CUSTOM_',
  3902.                         'forwardToMailAddress' => $forwardToMailAddress,
  3903.                         '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 ',
  3904. //                        'fileName' => 'Order#' . str_pad($id, 8, '0', STR_PAD_LEFT) . '.pdf',
  3905.                         'attachments' => $attachments,
  3906.                         'toAddress' => $forwardToMailAddress,
  3907.                         'fromAddress' => \ApplicationBundle\Helper\MailerConfig::address(),
  3908.                         'userName' => \ApplicationBundle\Helper\MailerConfig::address(),
  3909.                         'password' => \ApplicationBundle\Helper\MailerConfig::buddybeePassword(),
  3910.                         'smtpServer' => \ApplicationBundle\Helper\MailerConfig::host(),
  3911.                         'smtpPort' => \ApplicationBundle\Helper\MailerConfig::port(),
  3912. //                            'emailBody' => $bodyHtml,
  3913.                         'mailTemplate' => $bodyTemplate,
  3914.                         'templateData' => $bodyData,
  3915.                         'embedCompanyImage' => 0,
  3916.                         'companyId' => 0,
  3917.                         'companyImagePath' => ''
  3918. //                        'embedCompanyImage' => 1,
  3919. //                        'companyId' => $companyId,
  3920. //                        'companyImagePath' => $company_data->getImage()
  3921.                     ));
  3922.                 }
  3923. //
  3924.                 if ($meetingId != 0) {
  3925.                     $url $this->generateUrl(
  3926.                         'consultancy_session'
  3927.                     );
  3928. //                if($request->query->get('autoRedirect',1))
  3929. //                    return $this->redirect($url . '/' . $meetingId);
  3930.                     $redirectUrl $url '/' $meetingId;
  3931.                 } else {
  3932.                     $url $this->generateUrl(
  3933.                         'central_landing'
  3934.                     );
  3935. //                if($request->query->get('autoRedirect',1))
  3936. //                    return $this->redirect($url);
  3937.                     $redirectUrl $url;
  3938.                     $autoRedirect=0;
  3939.                 }
  3940.                 if (($retData['initiateCompany'] ?? 0) == && $activationPending === && ($retData['appId'] ?? 0) != && ($retData['ownerId'] ?? 0) != 0) {
  3941.                     $redirectUrl $this->generateUrl('activation_center', ['invoice_id' => (int)$invoice->getId()]);
  3942.                     $autoRedirect 1;
  3943.                 }
  3944.             }
  3945.             return $this->render('@Application/pages/stripe/success.html.twig', array(
  3946.                 'page_title' => 'Success',
  3947.                 'meetingId' => $meetingId,
  3948.                 'autoRedirect' => $autoRedirect,
  3949.                 'redirectUrl' => $redirectUrl,
  3950.                 'initiateCompany' => $retData['initiateCompany']??0,
  3951.                 'appId' => $retData['appId']??0,
  3952.                 'ownerId' => $retData['ownerId']??0,
  3953.                 'activationPending' => $activationPending,
  3954.                 'activationCenterUrl' => ($retData['initiateCompany'] ?? 0) == 1
  3955.                     $this->generateUrl('activation_center', ['invoice_id' => (int)$invoice->getId()])
  3956.                     : null,
  3957.             ));
  3958.         }
  3959.         else if ($systemType == '_BUDDYBEE_') {
  3960.             if ($encData != '') {
  3961.                 $encryptedData json_decode($this->get('url_encryptor')->decrypt($encData), true);
  3962.                 if (isset($encryptedData['invoiceId']))
  3963.                     $invoiceId $encryptedData['invoiceId'];
  3964.                 if (isset($encryptedData['autoRedirect']))
  3965.                     $autoRedirect $encryptedData['autoRedirect'];
  3966.             } else {
  3967.                 $invoiceId $request->query->get('invoiceId'0);
  3968.                 $meetingId 0;
  3969.                 $autoRedirect $request->query->get('autoRedirect'1);
  3970.                 $redirectUrl '';
  3971.             }
  3972.             if ($invoiceId != 0) {
  3973.                 $retData Buddybee::ProcessEntityInvoice($em$invoiceId, ['stage' => BuddybeeConstant::ENTITY_INVOICE_STAGE_COMPLETED], false,
  3974.                     $this->container->getParameter('notification_enabled'),
  3975.                     $this->container->getParameter('notification_server')
  3976.                 );
  3977.                 if ($retData['sendCards'] == 1) {
  3978.                     $cardList = array();
  3979.                     $cards $em->getRepository('CompanyGroupBundle\\Entity\\BeeCode')
  3980.                         ->findBy(
  3981.                             array(
  3982.                                 'id' => $retData['cardIds']
  3983.                             )
  3984.                         );
  3985.                     foreach ($cards as $card) {
  3986.                         $cardList[] = array(
  3987.                             'id' => $card->getId(),
  3988.                             'printed' => $card->getPrinted(),
  3989.                             'amount' => $card->getAmount(),
  3990.                             'coinCount' => $card->getCoinCount(),
  3991.                             'pin' => $card->getPin(),
  3992.                             'serial' => $card->getSerial(),
  3993.                         );
  3994.                     }
  3995.                     $receiverEmail $retData['receiverEmail'];
  3996.                     if (GeneralConstant::EMAIL_ENABLED == 1) {
  3997.                         $bodyHtml '';
  3998.                         $bodyTemplate '@Application/email/templates/beeCodeDigitalDelivery.html.twig';
  3999.                         $bodyData = array(
  4000.                             'cardList' => $cardList,
  4001. //                        'name' => $newApplicant->getFirstname() . ' ' . $newApplicant->getLastname(),
  4002. //                        'email' => $userName,
  4003. //                        'password' => $newApplicant->getPassword(),
  4004.                         );
  4005.                         $attachments = [];
  4006.                         $forwardToMailAddress $receiverEmail;
  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' => 'Digital Bee Card Delivery',
  4014. //                        'fileName' => 'Order#' . str_pad($id, 8, '0', STR_PAD_LEFT) . '.pdf',
  4015.                             'attachments' => $attachments,
  4016.                             'toAddress' => $forwardToMailAddress,
  4017.                             'fromAddress' => 'delivery@buddybee.eu',
  4018.                             'userName' => 'delivery@buddybee.eu',
  4019.                             'password' => \ApplicationBundle\Helper\MailerConfig::buddybeePassword(),
  4020.                             'smtpServer' => \ApplicationBundle\Helper\MailerConfig::host(),
  4021.                             'smtpPort' => \ApplicationBundle\Helper\MailerConfig::port(),
  4022. //                        'encryptionMethod' => 'tls',
  4023.                             'encryptionMethod' => 'ssl',
  4024. //                            'emailBody' => $bodyHtml,
  4025.                             'mailTemplate' => $bodyTemplate,
  4026.                             'templateData' => $bodyData,
  4027. //                        'embedCompanyImage' => 1,
  4028. //                        'companyId' => $companyId,
  4029. //                        'companyImagePath' => $company_data->getImage()
  4030.                         ));
  4031.                         foreach ($cards as $card) {
  4032.                             $card->setPrinted(1);
  4033.                         }
  4034.                         $em->flush();
  4035.                     }
  4036.                     return new JsonResponse(
  4037.                         array(
  4038.                             'success' => true
  4039.                         )
  4040.                     );
  4041.                 }
  4042.                 MiscActions::RefreshBuddybeeBalanceOnSession($em$request->getSession());
  4043.                 $meetingId $retData['meetingId'];
  4044.                 if (GeneralConstant::EMAIL_ENABLED == 1) {
  4045.                     $billerDetails = [];
  4046.                     $billToDetails = [];
  4047.                     $invoice $em->getRepository('CompanyGroupBundle\\Entity\\EntityInvoice')
  4048.                         ->findOneBy(
  4049.                             array(
  4050.                                 'Id' => $invoiceId,
  4051.                             )
  4052.                         );;
  4053.                     if ($invoice) {
  4054.                         $billerDetails $em->getRepository('CompanyGroupBundle\\Entity\\EntityApplicantDetails')
  4055.                             ->findOneBy(
  4056.                                 array(
  4057.                                     'applicantId' => $invoice->getBillerId(),
  4058.                                 )
  4059.                             );
  4060.                         $billToDetails $em->getRepository('CompanyGroupBundle\\Entity\\EntityApplicantDetails')
  4061.                             ->findOneBy(
  4062.                                 array(
  4063.                                     'applicantId' => $invoice->getBillToId(),
  4064.                                 )
  4065.                             );
  4066.                     }
  4067.                     $bodyTemplate '@Application/email/templates/buddybeeInvoiceEmail.html.twig';
  4068.                     $bodyData = array(
  4069.                         'page_title' => 'Invoice',
  4070. //            'studentDetails' => $student,
  4071.                         'billerDetails' => $billerDetails,
  4072.                         'billToDetails' => $billToDetails,
  4073.                         'invoice' => $invoice,
  4074.                         'currencyList' => BuddybeeConstant::$currency_List,
  4075.                         'currencyListByMarker' => BuddybeeConstant::$currency_List_by_marker,
  4076.                     );
  4077.                     $attachments = [];
  4078.                     $forwardToMailAddress $billToDetails->getOAuthEmail();
  4079. //                    $upl_dir = $this->container->getParameter('kernel.root_dir') . '/../web/uploads/temp/' . 'ledger' . '.pdf'
  4080.                     $new_mail $this->get('mail_module');
  4081.                     $new_mail->sendMyMail(array(
  4082.                         'senderHash' => '_CUSTOM_',
  4083.                         //                        'senderHash'=>'_CUSTOM_',
  4084.                         'forwardToMailAddress' => $forwardToMailAddress,
  4085.                         '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 ',
  4086. //                        'fileName' => 'Order#' . str_pad($id, 8, '0', STR_PAD_LEFT) . '.pdf',
  4087.                         'attachments' => $attachments,
  4088.                         'toAddress' => $forwardToMailAddress,
  4089.                         'fromAddress' => \ApplicationBundle\Helper\MailerConfig::address(),
  4090.                         'userName' => \ApplicationBundle\Helper\MailerConfig::address(),
  4091.                         'password' => \ApplicationBundle\Helper\MailerConfig::buddybeePassword(),
  4092.                         'smtpServer' => \ApplicationBundle\Helper\MailerConfig::host(),
  4093.                         'smtpPort' => \ApplicationBundle\Helper\MailerConfig::port(),
  4094. //                            'emailBody' => $bodyHtml,
  4095.                         'mailTemplate' => $bodyTemplate,
  4096.                         'templateData' => $bodyData,
  4097.                         'embedCompanyImage' => 0,
  4098.                         'companyId' => 0,
  4099.                         'companyImagePath' => ''
  4100. //                        'embedCompanyImage' => 1,
  4101. //                        'companyId' => $companyId,
  4102. //                        'companyImagePath' => $company_data->getImage()
  4103.                     ));
  4104.                 }
  4105. //
  4106.                 if ($meetingId != 0) {
  4107.                     $url $this->generateUrl(
  4108.                         'consultancy_session'
  4109.                     );
  4110. //                if($request->query->get('autoRedirect',1))
  4111. //                    return $this->redirect($url . '/' . $meetingId);
  4112.                     $redirectUrl $url '/' $meetingId;
  4113.                 } else {
  4114.                     $url $this->generateUrl(
  4115.                         'buddybee_dashboard'
  4116.                     );
  4117. //                if($request->query->get('autoRedirect',1))
  4118. //                    return $this->redirect($url);
  4119.                     $redirectUrl $url;
  4120.                 }
  4121.             }
  4122.             return $this->render('@Application/pages/stripe/success.html.twig', array(
  4123.                 'page_title' => 'Success',
  4124.                 'meetingId' => $meetingId,
  4125.                 'autoRedirect' => $autoRedirect,
  4126.                 'redirectUrl' => $redirectUrl,
  4127.             ));
  4128.         }
  4129.     }
  4130.     public function PaymentGatewayCancelAction(Request $request$msg 'The Payment was unsuccessful'$encData '')
  4131.     {
  4132.         $em $this->getDoctrine()->getManager('company_group');
  4133. //        $consultantDetail = $em->getRepository('CompanyGroupBundle\\Entity\\EntityApplicantDetails')->findOneBy(array());
  4134.         $session $request->getSession();
  4135.         if ($msg == '')
  4136.             $msg $request->query->get('msg'$request->request->get('msg''The Payment was unsuccessful'));
  4137.         return $this->render('@Application/pages/stripe/cancel.html.twig', array(
  4138.             'page_title' => 'Success',
  4139.             'msg' => $msg,
  4140.         ));
  4141.     }
  4142.     public function BkashCallbackAction(Request $request$encData '')
  4143.     {
  4144.         $em $this->getDoctrine()->getManager('company_group');
  4145.         $invoiceId 0;
  4146.         $session $request->getSession();
  4147.         $sandBoxMode $this->container->hasParameter('sand_box_mode') ? $this->container->getParameter('sand_box_mode') : 0;
  4148.         $paymentId $request->query->get('paymentID'0);
  4149.         $status $request->query->get('status'0);
  4150.         if ($status == 'success') {
  4151.             $paymentID $paymentId;
  4152.             $gatewayInvoice $em->getRepository('CompanyGroupBundle\\Entity\\EntityInvoice')->findOneBy(
  4153.                 array(
  4154.                     'gatewayPaymentId' => $paymentId,
  4155.                     'isProcessed' => [02]
  4156.                 ));
  4157.             if ($gatewayInvoice) {
  4158.                 $invoiceId $gatewayInvoice->getId();
  4159.                 $justNow = new \DateTime();
  4160.                 $baseUrl = ($sandBoxMode == 1) ? 'https://tokenized.sandbox.bka.sh/v1.2.0-beta' 'https://tokenized.pay.bka.sh/v1.2.0-beta';
  4161.                 $username_value = ($sandBoxMode == 1) ? 'sandboxTokenizedUser02' '01891962953';
  4162.                 $password_value = ($sandBoxMode == 1) ? 'sandboxTokenizedUser02@12345' ',a&kPV4deq&';
  4163.                 $app_key_value = ($sandBoxMode == 1) ? '4f6o0cjiki2rfm34kfdadl1eqq' '2ueVHdwz5gH3nxx7xn8wotlztc';
  4164.                 $app_secret_value = ($sandBoxMode == 1) ? '2is7hdktrekvrbljjh44ll3d9l1dtjo4pasmjvs5vl5qr3fug4b' '49Ay3h3wWJMBFD7WF5CassyLrtA1jt6ONhspqjqFx5hTjhqh5dHU';
  4165.                 $justNowTs $justNow->format('U');
  4166.                 if ($gatewayInvoice->getGatewayIdTokenExpireTs() <= $justNowTs) {
  4167.                     $refresh_token $gatewayInvoice->getGatewayIdRefreshToken();
  4168.                     $request_data = array(
  4169.                         'app_key' => $app_key_value,
  4170.                         'app_secret' => $app_secret_value,
  4171.                         'refresh_token' => $refresh_token
  4172.                     );
  4173.                     $url curl_init($baseUrl '/tokenized/checkout/token/refresh');
  4174.                     $request_data_json json_encode($request_data);
  4175.                     $header = array(
  4176.                         'Content-Type:application/json',
  4177.                         'username:' $username_value,
  4178.                         'password:' $password_value
  4179.                     );
  4180.                     curl_setopt($urlCURLOPT_HTTPHEADER$header);
  4181.                     curl_setopt($urlCURLOPT_CUSTOMREQUEST"POST");
  4182.                     curl_setopt($urlCURLOPT_RETURNTRANSFERtrue);
  4183.                     curl_setopt($urlCURLOPT_POSTFIELDS$request_data_json);
  4184.                     curl_setopt($urlCURLOPT_FOLLOWLOCATION1);
  4185.                     curl_setopt($urlCURLOPT_IPRESOLVECURL_IPRESOLVE_V4);
  4186.                     $tokenData json_decode(curl_exec($url), true);
  4187.                     curl_close($url);
  4188.                     $justNow = new \DateTime();
  4189.                     $justNow->modify('+' $tokenData['expires_in'] . ' second');
  4190.                     $gatewayInvoice->setGatewayIdTokenExpireTs($justNow->format('U'));
  4191.                     $gatewayInvoice->setGatewayIdToken($tokenData['id_token']);
  4192.                     $gatewayInvoice->setGatewayIdRefreshToken($tokenData['refresh_token']);
  4193.                     $em->flush();
  4194.                 }
  4195.                 $auth $gatewayInvoice->getGatewayIdToken();;
  4196.                 $post_token = array(
  4197.                     'paymentID' => $paymentID
  4198.                 );
  4199. //                $url = curl_init();
  4200.                 $url curl_init($baseUrl '/tokenized/checkout/execute');
  4201.                 $posttoken json_encode($post_token);
  4202.                 $header = array(
  4203.                     'Content-Type:application/json',
  4204.                     'Authorization:' $auth,
  4205.                     'X-APP-Key:' $app_key_value
  4206.                 );
  4207. //                curl_setopt_array($url, array(
  4208. //                    CURLOPT_HTTPHEADER => $header,
  4209. //                    CURLOPT_RETURNTRANSFER => 1,
  4210. //                    CURLOPT_URL => $baseUrl . '/tokenized/checkout/execute',
  4211. //
  4212. //                    CURLOPT_FOLLOWLOCATION => 1,
  4213. //                    CURLOPT_POST => 1,
  4214. //                    CURLOPT_IPRESOLVE => CURL_IPRESOLVE_V4,
  4215. //                    CURLOPT_POSTFIELDS => http_build_query($post_token)
  4216. //                ));
  4217.                 curl_setopt($urlCURLOPT_HTTPHEADER$header);
  4218.                 curl_setopt($urlCURLOPT_CUSTOMREQUEST"POST");
  4219.                 curl_setopt($urlCURLOPT_RETURNTRANSFERtrue);
  4220.                 curl_setopt($urlCURLOPT_POSTFIELDS$posttoken);
  4221.                 curl_setopt($urlCURLOPT_FOLLOWLOCATION1);
  4222.                 curl_setopt($urlCURLOPT_IPRESOLVECURL_IPRESOLVE_V4);
  4223.                 $resultdata curl_exec($url);
  4224.                 curl_close($url);
  4225.                 $obj json_decode($resultdatatrue);
  4226. //                return new JsonResponse(array(
  4227. //                    'obj' => $obj,
  4228. //                    'url' => $baseUrl . '/tokenized/checkout/execute',
  4229. //                    'header' => $header,
  4230. //                    'paymentID' => $paymentID,
  4231. //                    'posttoken' => $posttoken,
  4232. //                ));
  4233. //                                return new JsonResponse($obj);
  4234.                 if (isset($obj['statusCode'])) {
  4235.                     if ($obj['statusCode'] == '0000') {
  4236.                         $gatewayInvoice->setGatewayTransId($obj['trxID']);
  4237.                         $em->flush();
  4238.                         return $this->redirectToRoute("payment_gateway_success", ['encData' => $this->get('url_encryptor')->encrypt(json_encode(array(
  4239.                             'invoiceId' => $invoiceId'autoRedirect' => 1
  4240.                         ))),
  4241.                             'hbeeSessionToken' => $session->get('token'0)]);
  4242.                     } else {
  4243.                         return $this->redirectToRoute("payment_gateway_cancel", [
  4244.                             'msg' => isset($obj['statusMessage']) ? $obj['statusMessage'] : (isset($obj['errorMessage']) ? $obj['errorMessage'] : 'Payment Failed')
  4245.                         ]);
  4246.                     }
  4247.                 }
  4248.             } else {
  4249.                 return $this->redirectToRoute("payment_gateway_cancel", [
  4250.                     'msg' => isset($obj['statusMessage']) ? $obj['statusMessage'] : (isset($obj['errorMessage']) ? $obj['errorMessage'] : 'Payment Failed')
  4251.                 ]);
  4252.             }
  4253.         } else {
  4254.             return $this->redirectToRoute("payment_gateway_cancel", [
  4255.                 'msg' => isset($obj['statusMessage']) ? $obj['statusMessage'] : (isset($obj['errorMessage']) ? $obj['errorMessage'] : 'The Payment was unsuccessful')
  4256.             ]);
  4257.         }
  4258.     }
  4259.     public function MakePaymentOfEntityInvoiceAction(Request $request$encData '')
  4260.     {
  4261.         $em $this->getDoctrine()->getManager('company_group');
  4262.         $em_goc $em;
  4263.         $invoiceId 0;
  4264.         $autoRedirect 1;
  4265.         $redirectUrl '';
  4266.         $meetingId 0;
  4267.         $triggerMiddlePage 0;
  4268.         $session $request->getSession();
  4269.         $sandBoxMode $this->container->hasParameter('sand_box_mode') ? $this->container->getParameter('sand_box_mode') : 0;
  4270.         $refundSuccess 0;
  4271.         $errorMsg '';
  4272.         $errorCode '';
  4273.         if ($encData != '') {
  4274.             $invoiceId $encData;
  4275.             $encryptedData json_decode($this->get('url_encryptor')->decrypt($encData), true);
  4276.             if (isset($encryptedData['invoiceId']))
  4277.                 $invoiceId $encryptedData['invoiceId'];
  4278.             if (isset($encryptedData['triggerMiddlePage']))
  4279.                 $triggerMiddlePage $encryptedData['triggerMiddlePage'];
  4280.             if (isset($encryptedData['autoRedirect']))
  4281.                 $autoRedirect $encryptedData['autoRedirect'];
  4282.         } else {
  4283.             $invoiceId $request->request->get('invoiceId'$request->query->get('invoiceId'0));
  4284.             $triggerMiddlePage $request->request->get('triggerMiddlePage'$request->query->get('triggerMiddlePage'0));
  4285.             $meetingId 0;
  4286.             $autoRedirect $request->query->get('autoRedirect'1);
  4287.             $redirectUrl '';
  4288.         }
  4289.         $meetingId $request->request->get('meetingId'$request->query->get('meetingId'0));
  4290.         $actionDone 0;
  4291.         if ($meetingId != 0) {
  4292.             $dt Buddybee::ConfirmAnyMeetingSessionIfPossible($em0$meetingIdfalse,
  4293.                 $this->container->getParameter('notification_enabled'),
  4294.                 $this->container->getParameter('notification_server'));
  4295.             if ($invoiceId == && $dt['success'] == true) {
  4296.                 $actionDone 1;
  4297.                 return new JsonResponse(array(
  4298.                     'clientSecret' => 0,
  4299.                     'actionDone' => $actionDone,
  4300.                     'id' => 0,
  4301.                     'proceedToCheckout' => 0
  4302.                 ));
  4303.             }
  4304.         }
  4305. //        $invoiceId = $request->request->get('meetingId', $request->query->get('meetingId', 0));
  4306.         $output = [
  4307.             'clientSecret' => 0,
  4308.             'id' => 0,
  4309.             'proceedToCheckout' => 0
  4310.         ];
  4311.         if ($invoiceId != 0) {
  4312.             $gatewayInvoice $em->getRepository('CompanyGroupBundle\\Entity\\EntityInvoice')->findOneBy(
  4313.                 array(
  4314.                     'Id' => $invoiceId,
  4315.                     'isProcessed' => [0]
  4316.                 ));
  4317.         } else {
  4318.             $gatewayInvoice $em->getRepository('CompanyGroupBundle\\Entity\\EntityInvoice')->findOneBy(
  4319.                 array(
  4320.                     'meetingId' => $meetingId,
  4321.                     'isProcessed' => [0]
  4322.                 ));
  4323.         }
  4324.         if ($gatewayInvoice)
  4325.             $invoiceId $gatewayInvoice->getId();
  4326.         $invoiceSessionCount 0;
  4327.         $payableAmount 0;
  4328.         $imageBySessionCount = [
  4329.             => "https://www.buddybee.eu/buddybee_assets/ADULT-BEE.png",
  4330.             100 => "https://www.buddybee.eu/buddybee_assets/ADULT-BEE.png",
  4331.             200 => "https://www.buddybee.eu/buddybee_assets/ADULT-BEE.png",
  4332.             300 => "https://www.buddybee.eu/buddybee_assets/ADULT-BEE.png",
  4333.             400 => "https://www.buddybee.eu/buddybee_assets/ADULT-BEE.png",
  4334.             500 => "https://www.buddybee.eu/buddybee_assets/ADULT-BEE.png",
  4335.             600 => "https://www.buddybee.eu/buddybee_assets/ADULT-BEE.png",
  4336.             700 => "https://www.buddybee.eu/buddybee_assets/ADULT-BEE.png",
  4337.             800 => "https://www.buddybee.eu/buddybee_assets/ADULT-BEE.png",
  4338.             900 => "https://www.buddybee.eu/buddybee_assets/ADULT-BEE.png",
  4339.             1000 => "https://www.buddybee.eu/buddybee_assets/ADULT-BEE.png",
  4340.             1100 => "https://www.buddybee.eu/buddybee_assets/ADULT-BEE.png",
  4341.             1200 => "https://www.buddybee.eu/buddybee_assets/ADULT-BEE.png",
  4342.             1300 => "https://www.buddybee.eu/buddybee_assets/ADULT-BEE.png",
  4343.             1400 => "https://www.buddybee.eu/buddybee_assets/ADULT-BEE.png",
  4344.             1500 => "https://www.buddybee.eu/buddybee_assets/ADULT-BEE.png",
  4345.             1600 => "https://www.buddybee.eu/buddybee_assets/ADULT-BEE.png",
  4346.             1700 => "https://www.buddybee.eu/buddybee_assets/ADULT-BEE.png",
  4347.             1800 => "https://www.buddybee.eu/buddybee_assets/ADULT-BEE.png",
  4348.             1900 => "https://www.buddybee.eu/buddybee_assets/ADULT-BEE.png",
  4349.             2000 => "https://www.buddybee.eu/buddybee_assets/ADULT-BEE.png",
  4350.             2100 => "https://www.buddybee.eu/buddybee_assets/ADULT-BEE.png",
  4351.             2200 => "https://www.buddybee.eu/buddybee_assets/ADULT-BEE.png",
  4352.             2300 => "https://www.buddybee.eu/buddybee_assets/ADULT-BEE.png",
  4353.             2400 => "https://www.buddybee.eu/buddybee_assets/ADULT-BEE.png",
  4354.             2500 => "https://www.buddybee.eu/buddybee_assets/ADULT-BEE.png",
  4355.             2600 => "https://www.buddybee.eu/buddybee_assets/ADULT-BEE.png",
  4356.             2700 => "https://www.buddybee.eu/buddybee_assets/ADULT-BEE.png",
  4357.             2800 => "https://www.buddybee.eu/buddybee_assets/ADULT-BEE.png",
  4358.             2900 => "https://www.buddybee.eu/buddybee_assets/ADULT-BEE.png",
  4359.             3000 => "https://www.buddybee.eu/buddybee_assets/ADULT-BEE.png",
  4360.             3100 => "https://www.buddybee.eu/buddybee_assets/ADULT-BEE.png",
  4361.             3200 => "https://www.buddybee.eu/buddybee_assets/ADULT-BEE.png",
  4362.             3300 => "https://www.buddybee.eu/buddybee_assets/ADULT-BEE.png",
  4363.             3400 => "https://www.buddybee.eu/buddybee_assets/ADULT-BEE.png",
  4364.             3500 => "https://www.buddybee.eu/buddybee_assets/ADULT-BEE.png",
  4365.             3600 => "https://www.buddybee.eu/buddybee_assets/ADULT-BEE.png",
  4366.             3700 => "https://www.buddybee.eu/buddybee_assets/ADULT-BEE.png",
  4367.         ];
  4368.         if ($gatewayInvoice) {
  4369.             $gatewayProductData json_decode($gatewayInvoice->getProductDataForPaymentGateway(), true);
  4370.             if ($gatewayProductData == null$gatewayProductData = [];
  4371.             $gatewayAmount number_format($gatewayInvoice->getGateWayBillamount(), 2'.''');
  4372.             $invoiceSessionCount $gatewayInvoice->getSessionCount();
  4373.             $currencyForGateway $gatewayInvoice->getAmountCurrency();
  4374.             $gatewayAmount round($gatewayAmount2);
  4375.             if (empty($gatewayProductData))
  4376.                 $gatewayProductData = [
  4377.                     [
  4378.                         'price_data' => [
  4379.                             'currency' => 'eur',
  4380.                             'unit_amount' => $gatewayAmount != ? (100 $gatewayAmount) : 200000,
  4381.                             'product_data' => [
  4382. //                            'name' => $request->request->has('packageName') ? $request->request->get('packageName') : 'Advanced Consultancy Package',
  4383.                                 'name' => 'Bee Coins',
  4384. //                                'images' => [$imageBySessionCount[$invoiceSessionCount]],
  4385.                                 'images' => [$imageBySessionCount[0]],
  4386.                             ],
  4387.                         ],
  4388.                         'quantity' => 1,
  4389.                     ]
  4390.                 ];
  4391.             $productDescStr '';
  4392.             $productDescArr = [];
  4393.             foreach ($gatewayProductData as $gpd) {
  4394.                 $productDescArr[] = $gpd['price_data']['product_data']['name'];
  4395.             }
  4396.             $productDescStr implode(','$productDescArr);
  4397.             $paymentGatewayFromInvoice $gatewayInvoice->getAmountTransferGateWayHash();
  4398.             if ($paymentGatewayFromInvoice == 'stripe') {
  4399.                 $stripe = new \Stripe\Stripe();
  4400.                 \Stripe\Stripe::setApiKey('sk_test_51IxYTAJXs21fVb0QMop2Nb0E7u9Da4LwGrym1nGHUHqaSNtT3p9HBgHd7YyDsTKHscgPPECPQniTy79Ab8Sgxfbm00JF2AndUz');
  4401.                 $stripe::setApiKey('sk_test_51IxYTAJXs21fVb0QMop2Nb0E7u9Da4LwGrym1nGHUHqaSNtT3p9HBgHd7YyDsTKHscgPPECPQniTy79Ab8Sgxfbm00JF2AndUz');
  4402.                 {
  4403.                     if ($request->query->has('meetingSessionId'))
  4404.                         $id $request->query->get('meetingSessionId');
  4405.                 }
  4406.                 $paymentIntent = [
  4407.                     "id" => "pi_1DoWjK2eZvKYlo2Csy9J3BHs",
  4408.                     "object" => "payment_intent",
  4409.                     "amount" => 3000,
  4410.                     "amount_capturable" => 0,
  4411.                     "amount_received" => 0,
  4412.                     "application" => null,
  4413.                     "application_fee_amount" => null,
  4414.                     "canceled_at" => null,
  4415.                     "cancellation_reason" => null,
  4416.                     "capture_method" => "automatic",
  4417.                     "charges" => [
  4418.                         "object" => "list",
  4419.                         "data" => [],
  4420.                         "has_more" => false,
  4421.                         "url" => "/v1/charges?payment_intent=pi_1DoWjK2eZvKYlo2Csy9J3BHs"
  4422.                     ],
  4423.                     "client_secret" => "pi_1DoWjK2eZvKYlo2Csy9J3BHs_secret_vmxAcWZxo2kt1XhpWtZtnjDtd",
  4424.                     "confirmation_method" => "automatic",
  4425.                     "created" => 1546523966,
  4426.                     "currency" => $currencyForGateway,
  4427.                     "customer" => null,
  4428.                     "description" => null,
  4429.                     "invoice" => null,
  4430.                     "last_payment_error" => null,
  4431.                     "livemode" => false,
  4432.                     "metadata" => [],
  4433.                     "next_action" => null,
  4434.                     "on_behalf_of" => null,
  4435.                     "payment_method" => null,
  4436.                     "payment_method_options" => [],
  4437.                     "payment_method_types" => [
  4438.                         "card"
  4439.                     ],
  4440.                     "receipt_email" => null,
  4441.                     "review" => null,
  4442.                     "setup_future_usage" => null,
  4443.                     "shipping" => null,
  4444.                     "statement_descriptor" => null,
  4445.                     "statement_descriptor_suffix" => null,
  4446.                     "status" => "requires_payment_method",
  4447.                     "transfer_data" => null,
  4448.                     "transfer_group" => null
  4449.                 ];
  4450.                 $checkout_session = \Stripe\Checkout\Session::create([
  4451.                     'payment_method_types' => ['card'],
  4452.                     'line_items' => $gatewayProductData,
  4453.                     'mode' => 'payment',
  4454.                     'success_url' => $this->generateUrl(
  4455.                         'payment_gateway_success',
  4456.                         ['encData' => $this->get('url_encryptor')->encrypt(json_encode(array(
  4457.                             'invoiceId' => $invoiceId'autoRedirect' => $request->request->get('autoRedirect'1)
  4458.                         ))), 'hbeeSessionToken' => $session->get('token'0)], UrlGenerator::ABSOLUTE_URL
  4459.                     ),
  4460.                     'cancel_url' => $this->generateUrl(
  4461.                         'payment_gateway_cancel', ['invoiceId' => $invoiceId'autoRedirect' => $request->request->get('autoRedirect'1), 'hbeeSessionToken' => $session->get('token'0)], UrlGenerator::ABSOLUTE_URL
  4462.                     ),
  4463.                 ]);
  4464.                 $output = [
  4465.                     'clientSecret' => $paymentIntent['client_secret'],
  4466.                     'id' => $checkout_session->id,
  4467.                     'paymentGateway' => $paymentGatewayFromInvoice,
  4468.                     'proceedToCheckout' => 1
  4469.                 ];
  4470. //                return new JsonResponse($output);
  4471.             }
  4472.             if ($paymentGatewayFromInvoice == 'aamarpay') {
  4473.                 $studentDetails $em_goc->getRepository(EntityApplicantDetails::class)->find($gatewayInvoice->getBillToId());
  4474.                 $url $sandBoxMode == 'https://sandbox.aamarpay.com/request.php' 'https://secure.aamarpay.com/request.php';
  4475.                 $fields = array(
  4476. //                    'store_id' => 'aamarpaytest', //store id will be aamarpay,  contact integration@aamarpay.com for test/live id
  4477.                     'store_id' => $sandBoxMode == 'aamarpaytest' 'buddybee'//store id will be aamarpay,  contact integration@aamarpay.com for test/live id
  4478.                     'amount' => number_format($gatewayInvoice->getGateWayBillamount(), 2'.'''), //transaction amount
  4479.                     'payment_type' => 'VISA'//no need to change
  4480.                     'currency' => strtoupper($currencyForGateway),  //currenct will be USD/BDT
  4481.                     '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
  4482.                     'cus_name' => $studentDetails->getFirstname() . ' ' $studentDetails->getLastName(),  //customer name
  4483.                     'cus_email' => $studentDetails->getEmail(), //customer email address
  4484.                     'cus_add1' => $studentDetails->getCurrAddr(),  //customer address
  4485.                     'cus_add2' => $studentDetails->getCurrAddrCity(), //customer address
  4486.                     'cus_city' => $studentDetails->getCurrAddrCity(),  //customer city
  4487.                     'cus_state' => $studentDetails->getCurrAddrState(),  //state
  4488.                     'cus_postcode' => $studentDetails->getCurrAddrZip(), //postcode or zipcode
  4489.                     'cus_country' => 'Bangladesh',  //country
  4490.                     'cus_phone' => ($studentDetails->getPhone() == null || $studentDetails->getPhone() == '') ? '+8801911706483' $studentDetails->getPhone(), //customer phone number
  4491.                     'cus_fax' => '',  //fax
  4492.                     'ship_name' => ''//ship name
  4493.                     'ship_add1' => '',  //ship address
  4494.                     'ship_add2' => '',
  4495.                     'ship_city' => '',
  4496.                     'ship_state' => '',
  4497.                     'ship_postcode' => '',
  4498.                     'ship_country' => 'Bangladesh',
  4499.                     'desc' => $productDescStr,
  4500.                     'success_url' => $this->generateUrl(
  4501.                         'payment_gateway_success',
  4502.                         ['encData' => $this->get('url_encryptor')->encrypt(json_encode(array(
  4503.                             'invoiceId' => $invoiceId'autoRedirect' => $request->request->get('autoRedirect'1)
  4504.                         ))), 'hbeeSessionToken' => $session->get('token'0)], UrlGenerator::ABSOLUTE_URL
  4505.                     ),
  4506.                     'fail_url' => $this->generateUrl(
  4507.                         'payment_gateway_cancel', ['invoiceId' => $invoiceId'autoRedirect' => $request->request->get('autoRedirect'1), 'hbeeSessionToken' => $session->get('token'0)], UrlGenerator::ABSOLUTE_URL
  4508.                     ),
  4509.                     'cancel_url' => $this->generateUrl(
  4510.                         'payment_gateway_cancel', ['invoiceId' => $invoiceId'autoRedirect' => $request->request->get('autoRedirect'1), 'hbeeSessionToken' => $session->get('token'0)], UrlGenerator::ABSOLUTE_URL
  4511.                     ),
  4512. //                    'opt_a' => 'Reshad',  //optional paramter
  4513. //                    'opt_b' => 'Akil',
  4514. //                    'opt_c' => 'Liza',
  4515. //                    'opt_d' => 'Sohel',
  4516. //                    'signature_key' => 'dbb74894e82415a2f7ff0ec3a97e4183',  //sandbox
  4517.                     'signature_key' => $sandBoxMode == 'dbb74894e82415a2f7ff0ec3a97e4183' 'b7304a40e21fe15af3be9a948307f524'  //live
  4518.                 ); //signature key will provided aamarpay, contact integration@aamarpay.com for test/live signature key
  4519.                 $fields_string http_build_query($fields);
  4520.                 $ch curl_init();
  4521.                 curl_setopt($chCURLOPT_VERBOSEtrue);
  4522.                 curl_setopt($chCURLOPT_URL$url);
  4523.                 curl_setopt($chCURLOPT_POSTFIELDS$fields_string);
  4524.                 curl_setopt($chCURLOPT_RETURNTRANSFERtrue);
  4525.                 curl_setopt($chCURLOPT_SSL_VERIFYPEERfalse);
  4526.                 $url_forward str_replace('"'''stripslashes(curl_exec($ch)));
  4527.                 curl_close($ch);
  4528. //                $this->redirect_to_merchant($url_forward);
  4529.                 $output = [
  4530. //                    'redirectUrl' => 'https://sandbox.aamarpay.com/'.$url_forward, //keeping it off temporarily
  4531.                     'redirectUrl' => ($sandBoxMode == 'https://sandbox.aamarpay.com/' 'https://secure.aamarpay.com/') . $url_forward//keeping it off temporarily
  4532. //                    'fields'=>$fields,
  4533. //                    'fields_string'=>$fields_string,
  4534. //                    'redirectUrl' => $this->generateUrl(
  4535. //                        'payment_gateway_success',
  4536. //                        ['encData' => $this->get('url_encryptor')->encrypt(json_encode(array(
  4537. //                            'invoiceId' => $invoiceId, 'autoRedirect' => $request->request->get('autoRedirect', 1)
  4538. //                        ))), 'hbeeSessionToken' => $request->request->get('token', 0)], UrlGenerator::ABSOLUTE_URL
  4539. //                    ),
  4540.                     'paymentGateway' => $paymentGatewayFromInvoice,
  4541.                     'proceedToCheckout' => 1
  4542.                 ];
  4543. //                return new JsonResponse($output);
  4544.             } else if ($paymentGatewayFromInvoice == 'bkash') {
  4545.                 $studentDetails $em_goc->getRepository(EntityApplicantDetails::class)->find($gatewayInvoice->getBillToId());
  4546.                 $baseUrl = ($sandBoxMode == 1) ? 'https://tokenized.sandbox.bka.sh/v1.2.0-beta' 'https://tokenized.pay.bka.sh/v1.2.0-beta';
  4547.                 $username_value = ($sandBoxMode == 1) ? 'sandboxTokenizedUser02' '01891962953';
  4548.                 $password_value = ($sandBoxMode == 1) ? 'sandboxTokenizedUser02@12345' ',a&kPV4deq&';
  4549.                 $app_key_value = ($sandBoxMode == 1) ? '4f6o0cjiki2rfm34kfdadl1eqq' '2ueVHdwz5gH3nxx7xn8wotlztc';
  4550.                 $app_secret_value = ($sandBoxMode == 1) ? '2is7hdktrekvrbljjh44ll3d9l1dtjo4pasmjvs5vl5qr3fug4b' '49Ay3h3wWJMBFD7WF5CassyLrtA1jt6ONhspqjqFx5hTjhqh5dHU';
  4551.                 $request_data = array(
  4552.                     'app_key' => $app_key_value,
  4553.                     'app_secret' => $app_secret_value
  4554.                 );
  4555.                 $url curl_init($baseUrl '/tokenized/checkout/token/grant');
  4556.                 $request_data_json json_encode($request_data);
  4557.                 $header = array(
  4558.                     'Content-Type:application/json',
  4559.                     'username:' $username_value,
  4560.                     'password:' $password_value
  4561.                 );
  4562.                 curl_setopt($urlCURLOPT_HTTPHEADER$header);
  4563.                 curl_setopt($urlCURLOPT_CUSTOMREQUEST"POST");
  4564.                 curl_setopt($urlCURLOPT_RETURNTRANSFERtrue);
  4565.                 curl_setopt($urlCURLOPT_POSTFIELDS$request_data_json);
  4566.                 curl_setopt($urlCURLOPT_FOLLOWLOCATION1);
  4567.                 curl_setopt($urlCURLOPT_IPRESOLVECURL_IPRESOLVE_V4);
  4568.                 $tokenData json_decode(curl_exec($url), true);
  4569.                 curl_close($url);
  4570.                 $id_token $tokenData['id_token'];
  4571.                 $goToBkashPage 0;
  4572.                 if ($tokenData['statusCode'] == '0000') {
  4573.                     $auth $id_token;
  4574.                     $requestbody = array(
  4575.                         "mode" => "0011",
  4576. //                        "payerReference" => "",
  4577.                         "payerReference" => $gatewayInvoice->getInvoiceDateTs(),
  4578.                         "callbackURL" => $this->generateUrl(
  4579.                             'bkash_callback', [], UrlGenerator::ABSOLUTE_URL
  4580.                         ),
  4581. //                    "merchantAssociationInfo" => "MI05MID54RF09123456One",
  4582.                         "amount" => number_format($gatewayInvoice->getGateWayBillamount(), 2'.'''),
  4583.                         "currency" => "BDT",
  4584.                         "intent" => "sale",
  4585.                         "merchantInvoiceNumber" => $invoiceId
  4586.                     );
  4587.                     $url curl_init($baseUrl '/tokenized/checkout/create');
  4588.                     $requestbodyJson json_encode($requestbody);
  4589.                     $header = array(
  4590.                         'Content-Type:application/json',
  4591.                         'Authorization:' $auth,
  4592.                         'X-APP-Key:' $app_key_value
  4593.                     );
  4594.                     curl_setopt($urlCURLOPT_HTTPHEADER$header);
  4595.                     curl_setopt($urlCURLOPT_CUSTOMREQUEST"POST");
  4596.                     curl_setopt($urlCURLOPT_RETURNTRANSFERtrue);
  4597.                     curl_setopt($urlCURLOPT_POSTFIELDS$requestbodyJson);
  4598.                     curl_setopt($urlCURLOPT_FOLLOWLOCATION1);
  4599.                     curl_setopt($urlCURLOPT_IPRESOLVECURL_IPRESOLVE_V4);
  4600.                     $resultdata curl_exec($url);
  4601.                     curl_close($url);
  4602. //                    return new JsonResponse($resultdata);
  4603.                     $obj json_decode($resultdatatrue);
  4604.                     $goToBkashPage 1;
  4605.                     $justNow = new \DateTime();
  4606.                     $justNow->modify('+' $tokenData['expires_in'] . ' second');
  4607.                     $gatewayInvoice->setGatewayIdTokenExpireTs($justNow->format('U'));
  4608.                     $gatewayInvoice->setGatewayIdToken($tokenData['id_token']);
  4609.                     $gatewayInvoice->setGatewayPaymentId($obj['paymentID']);
  4610.                     $gatewayInvoice->setGatewayIdRefreshToken($tokenData['refresh_token']);
  4611.                     $em->flush();
  4612.                     $output = [
  4613.                         'redirectUrl' => $obj['bkashURL'],
  4614.                         'paymentGateway' => $paymentGatewayFromInvoice,
  4615.                         'proceedToCheckout' => $goToBkashPage,
  4616.                         'tokenData' => $tokenData,
  4617.                         'obj' => $obj,
  4618.                         'id_token' => $tokenData['id_token'],
  4619.                     ];
  4620.                 }
  4621. //                $fields = array(
  4622. //
  4623. //                    "mode" => "0011",
  4624. //                    "payerReference" => "01723888888",
  4625. //                    "callbackURL" => $this->generateUrl(
  4626. //                        'payment_gateway_success',
  4627. //                        ['encData' => $this->get('url_encryptor')->encrypt(json_encode(array(
  4628. //                            'invoiceId' => $invoiceId, 'autoRedirect' => $request->request->get('autoRedirect', 1)
  4629. //                        ))), 'hbeeSessionToken' => $session->get('token', 0)], UrlGenerator::ABSOLUTE_URL
  4630. //                    ),
  4631. //                    "merchantAssociationInfo" => "MI05MID54RF09123456One",
  4632. //                    "amount" => $gatewayInvoice->getGateWayBillamount(),
  4633. //                    "currency" => "BDT",
  4634. //                    "intent" => "sale",
  4635. //                    "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)
  4636. //
  4637. //                );
  4638. //                $fields = array(
  4639. ////                    'store_id' => 'aamarpaytest', //store id will be aamarpay,  contact integration@aamarpay.com for test/live id
  4640. //                    'store_id' => $sandBoxMode == 1 ? 'aamarpaytest' : 'buddybee', //store id will be aamarpay,  contact integration@aamarpay.com for test/live id
  4641. //                    'amount' => $gatewayInvoice->getGateWayBillamount(), //transaction amount
  4642. //                    'payment_type' => 'VISA', //no need to change
  4643. //                    'currency' => strtoupper($currencyForGateway),  //currenct will be USD/BDT
  4644. //                    '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
  4645. //                    'cus_name' => $studentDetails->getFirstname() . ' ' . $studentDetails->getLastName(),  //customer name
  4646. //                    'cus_email' => $studentDetails->getEmail(), //customer email address
  4647. //                    'cus_add1' => $studentDetails->getCurrAddr(),  //customer address
  4648. //                    'cus_add2' => $studentDetails->getCurrAddrCity(), //customer address
  4649. //                    'cus_city' => $studentDetails->getCurrAddrCity(),  //customer city
  4650. //                    'cus_state' => $studentDetails->getCurrAddrState(),  //state
  4651. //                    'cus_postcode' => $studentDetails->getCurrAddrZip(), //postcode or zipcode
  4652. //                    'cus_country' => 'Bangladesh',  //country
  4653. //                    'cus_phone' => ($studentDetails->getPhone() == null || $studentDetails->getPhone() == '') ? ' + 8801911706483' : $studentDetails->getPhone(), //customer phone number
  4654. //                    'cus_fax' => '',  //fax
  4655. //                    'ship_name' => '', //ship name
  4656. //                    'ship_add1' => '',  //ship address
  4657. //                    'ship_add2' => '',
  4658. //                    'ship_city' => '',
  4659. //                    'ship_state' => '',
  4660. //                    'ship_postcode' => '',
  4661. //                    'ship_country' => 'Bangladesh',
  4662. //                    'desc' => $productDescStr,
  4663. //                    'success_url' => $this->generateUrl(
  4664. //                        'payment_gateway_success',
  4665. //                        ['encData' => $this->get('url_encryptor')->encrypt(json_encode(array(
  4666. //                            'invoiceId' => $invoiceId, 'autoRedirect' => $request->request->get('autoRedirect', 1)
  4667. //                        ))), 'hbeeSessionToken' => $session->get('token', 0)], UrlGenerator::ABSOLUTE_URL
  4668. //                    ),
  4669. //                    'fail_url' => $this->generateUrl(
  4670. //                        'payment_gateway_cancel', ['invoiceId' => $invoiceId, 'autoRedirect' => $request->request->get('autoRedirect', 1), 'hbeeSessionToken' => $session->get('token', 0)], UrlGenerator::ABSOLUTE_URL
  4671. //                    ),
  4672. //                    'cancel_url' => $this->generateUrl(
  4673. //                        'payment_gateway_cancel', ['invoiceId' => $invoiceId, 'autoRedirect' => $request->request->get('autoRedirect', 1), 'hbeeSessionToken' => $session->get('token', 0)], UrlGenerator::ABSOLUTE_URL
  4674. //                    ),
  4675. ////                    'opt_a' => 'Reshad',  //optional paramter
  4676. ////                    'opt_b' => 'Akil',
  4677. ////                    'opt_c' => 'Liza',
  4678. ////                    'opt_d' => 'Sohel',
  4679. ////                    'signature_key' => 'dbb74894e82415a2f7ff0ec3a97e4183',  //sandbox
  4680. //                    'signature_key' => $sandBoxMode == 1 ? 'dbb74894e82415a2f7ff0ec3a97e4183' : 'b7304a40e21fe15af3be9a948307f524'  //live
  4681. //
  4682. //                ); //signature key will provided aamarpay, contact integration@aamarpay.com for test/live signature key
  4683. //
  4684. //                $fields_string = http_build_query($fields);
  4685. //
  4686. //                $ch = curl_init();
  4687. //                curl_setopt($ch, CURLOPT_VERBOSE, true);
  4688. //                curl_setopt($ch, CURLOPT_URL, $url);
  4689. //
  4690. //                curl_setopt($ch, CURLOPT_POSTFIELDS, $fields_string);
  4691. //                curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
  4692. //                curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
  4693. //                $url_forward = str_replace('"', '', stripslashes(curl_exec($ch)));
  4694. //                curl_close($ch);
  4695. //                $this->redirect_to_merchant($url_forward);
  4696.             }
  4697.         }
  4698.         if ($triggerMiddlePage == 1) return $this->render('@Buddybee/pages/makePaymentOfEntityInvoiceLandingPage.html.twig', array(
  4699.             'page_title' => 'Invoice Payment',
  4700.             'data' => $output,
  4701.         ));
  4702.         else
  4703.             return new JsonResponse($output);
  4704.     }
  4705.     public function RefundEntityInvoiceAction(Request $request$encData '')
  4706.     {
  4707.         $em $this->getDoctrine()->getManager('company_group');
  4708.         $invoiceId 0;
  4709.         $currIsProcessedFlagValue '_UNSET_';
  4710.         $session $request->getSession();
  4711.         $sandBoxMode $this->container->hasParameter('sand_box_mode') ? $this->container->getParameter('sand_box_mode') : 0;
  4712.         $paymentId $request->query->get('paymentID'0);
  4713.         $status $request->query->get('status'0);
  4714.         $refundSuccess 0;
  4715.         $errorMsg '';
  4716.         $errorCode '';
  4717.         if ($encData != '') {
  4718.             $invoiceId $encData;
  4719.             $encryptedData json_decode($this->get('url_encryptor')->decrypt($encData), true);
  4720.             if (isset($encryptedData['invoiceId']))
  4721.                 $invoiceId $encryptedData['invoiceId'];
  4722.             if (isset($encryptedData['autoRedirect']))
  4723.                 $autoRedirect $encryptedData['autoRedirect'];
  4724.         } else {
  4725.             $invoiceId $request->request->get('invoiceId'$request->query->get('invoiceId'0));
  4726.             $meetingId 0;
  4727.             $autoRedirect $request->query->get('autoRedirect'1);
  4728.             $redirectUrl '';
  4729.         }
  4730.         $gatewayInvoice $em->getRepository('CompanyGroupBundle\\Entity\\EntityInvoice')->findOneBy(
  4731.             array(
  4732.                 'Id' => $invoiceId,
  4733.                 'isProcessed' => [1]
  4734.             ));
  4735.         if ($gatewayInvoice) {
  4736.             $gatewayInvoice->setIsProcessed(3); //pending settlement
  4737.             $currIsProcessedFlagValue $gatewayInvoice->getIsProcessed();
  4738.             $em->flush();
  4739.             if ($gatewayInvoice->getAmountTransferGateWayHash() == 'bkash') {
  4740.                 $invoiceId $gatewayInvoice->getId();
  4741.                 $paymentID $gatewayInvoice->getGatewayPaymentId();
  4742.                 $trxID $gatewayInvoice->getGatewayTransId();
  4743.                 $justNow = new \DateTime();
  4744.                 $baseUrl = ($sandBoxMode == 1) ? 'https://tokenized.sandbox.bka.sh/v1.2.0-beta' 'https://tokenized.pay.bka.sh/v1.2.0-beta';
  4745.                 $username_value = ($sandBoxMode == 1) ? 'sandboxTokenizedUser02' '01891962953';
  4746.                 $password_value = ($sandBoxMode == 1) ? 'sandboxTokenizedUser02@12345' ',a&kPV4deq&';
  4747.                 $app_key_value = ($sandBoxMode == 1) ? '4f6o0cjiki2rfm34kfdadl1eqq' '2ueVHdwz5gH3nxx7xn8wotlztc';
  4748.                 $app_secret_value = ($sandBoxMode == 1) ? '2is7hdktrekvrbljjh44ll3d9l1dtjo4pasmjvs5vl5qr3fug4b' '49Ay3h3wWJMBFD7WF5CassyLrtA1jt6ONhspqjqFx5hTjhqh5dHU';
  4749.                 $justNowTs $justNow->format('U');
  4750.                 if ($gatewayInvoice->getGatewayIdTokenExpireTs() <= $justNowTs) {
  4751.                     $refresh_token $gatewayInvoice->getGatewayIdRefreshToken();
  4752.                     $request_data = array(
  4753.                         'app_key' => $app_key_value,
  4754.                         'app_secret' => $app_secret_value,
  4755.                         'refresh_token' => $refresh_token
  4756.                     );
  4757.                     $url curl_init($baseUrl '/tokenized/checkout/token/refresh');
  4758.                     $request_data_json json_encode($request_data);
  4759.                     $header = array(
  4760.                         'Content-Type:application/json',
  4761.                         'username:' $username_value,
  4762.                         'password:' $password_value
  4763.                     );
  4764.                     curl_setopt($urlCURLOPT_HTTPHEADER$header);
  4765.                     curl_setopt($urlCURLOPT_CUSTOMREQUEST"POST");
  4766.                     curl_setopt($urlCURLOPT_RETURNTRANSFERtrue);
  4767.                     curl_setopt($urlCURLOPT_POSTFIELDS$request_data_json);
  4768.                     curl_setopt($urlCURLOPT_FOLLOWLOCATION1);
  4769.                     curl_setopt($urlCURLOPT_IPRESOLVECURL_IPRESOLVE_V4);
  4770.                     $tokenData json_decode(curl_exec($url), true);
  4771.                     curl_close($url);
  4772.                     $justNow = new \DateTime();
  4773.                     $justNow->modify('+' $tokenData['expires_in'] . ' second');
  4774.                     $gatewayInvoice->setGatewayIdTokenExpireTs($justNow->format('U'));
  4775.                     $gatewayInvoice->setGatewayIdToken($tokenData['id_token']);
  4776.                     $gatewayInvoice->setGatewayIdRefreshToken($tokenData['refresh_token']);
  4777.                     $em->flush();
  4778.                 }
  4779.                 $auth $gatewayInvoice->getGatewayIdToken();;
  4780.                 $post_token = array(
  4781.                     'paymentID' => $paymentID,
  4782.                     'trxID' => $trxID,
  4783.                     'reason' => 'Full Refund Policy',
  4784.                     'sku' => 'RSTR',
  4785.                     'amount' => number_format($gatewayInvoice->getGateWayBillamount(), 2'.'''),
  4786.                 );
  4787.                 $url curl_init($baseUrl '/tokenized/checkout/payment/refund');
  4788.                 $posttoken json_encode($post_token);
  4789.                 $header = array(
  4790.                     'Content-Type:application/json',
  4791.                     'Authorization:' $auth,
  4792.                     'X-APP-Key:' $app_key_value
  4793.                 );
  4794.                 curl_setopt($urlCURLOPT_HTTPHEADER$header);
  4795.                 curl_setopt($urlCURLOPT_CUSTOMREQUEST"POST");
  4796.                 curl_setopt($urlCURLOPT_RETURNTRANSFERtrue);
  4797.                 curl_setopt($urlCURLOPT_POSTFIELDS$posttoken);
  4798.                 curl_setopt($urlCURLOPT_FOLLOWLOCATION1);
  4799.                 curl_setopt($urlCURLOPT_IPRESOLVECURL_IPRESOLVE_V4);
  4800.                 $resultdata curl_exec($url);
  4801.                 curl_close($url);
  4802.                 $obj json_decode($resultdatatrue);
  4803. //                return new JsonResponse($obj);
  4804.                 if (isset($obj['completedTime']))
  4805.                     $refundSuccess 1;
  4806.                 else if (isset($obj['errorCode'])) {
  4807.                     $refundSuccess 0;
  4808.                     $errorCode $obj['errorCode'];
  4809.                     $errorMsg $obj['errorMessage'];
  4810.                 }
  4811. //                    $gatewayInvoice->setGatewayTransId($obj['trxID']);
  4812.                 $em->flush();
  4813.             }
  4814.             if ($refundSuccess == 1) {
  4815.                 Buddybee::RefundEntityInvoice($em$invoiceId);
  4816.                 $currIsProcessedFlagValue 4;
  4817.             }
  4818.         } else {
  4819.         }
  4820.         MiscActions::RefreshBuddybeeBalanceOnSession($em$request->getSession());
  4821.         return new JsonResponse(
  4822.             array(
  4823.                 'success' => $refundSuccess,
  4824.                 'errorCode' => $errorCode,
  4825.                 'isProcessed' => $currIsProcessedFlagValue,
  4826.                 'errorMsg' => $errorMsg,
  4827.             )
  4828.         );
  4829.     }
  4830.     public function ViewEntityInvoiceAction(Request $request$encData '')
  4831.     {
  4832.         $em $this->getDoctrine()->getManager('company_group');
  4833.         $invoiceId 0;
  4834.         $autoRedirect 1;
  4835.         $redirectUrl '';
  4836.         $meetingId 0;
  4837.         $invoice null;
  4838.         if ($encData != '') {
  4839.             $encryptedData json_decode($this->get('url_encryptor')->decrypt($encData), true);
  4840.             $invoiceId $encData;
  4841.             if (isset($encryptedData['invoiceId']))
  4842.                 $invoiceId $encryptedData['invoiceId'];
  4843.             if (isset($encryptedData['autoRedirect']))
  4844.                 $autoRedirect $encryptedData['autoRedirect'];
  4845.         } else {
  4846.             $invoiceId $request->query->get('invoiceId'0);
  4847.             $meetingId 0;
  4848.             $autoRedirect $request->query->get('autoRedirect'1);
  4849.             $redirectUrl '';
  4850.         }
  4851. //    $invoiceList = [];
  4852.         $billerDetails = [];
  4853.         $billToDetails = [];
  4854.         if ($invoiceId != 0) {
  4855.             $invoice $em->getRepository('CompanyGroupBundle\\Entity\\EntityInvoice')
  4856.                 ->findOneBy(
  4857.                     array(
  4858.                         'Id' => $invoiceId,
  4859.                     )
  4860.                 );
  4861.             if ($invoice) {
  4862.                 $billerDetails $em->getRepository('CompanyGroupBundle\\Entity\\EntityApplicantDetails')
  4863.                     ->findOneBy(
  4864.                         array(
  4865.                             'applicantId' => $invoice->getBillerId(),
  4866.                         )
  4867.                     );
  4868.                 $billToDetails $em->getRepository('CompanyGroupBundle\\Entity\\EntityApplicantDetails')
  4869.                     ->findOneBy(
  4870.                         array(
  4871.                             'applicantId' => $invoice->getBillToId(),
  4872.                         )
  4873.                     );
  4874.             }
  4875.             if ($request->query->get('sendMail'0) == && GeneralConstant::EMAIL_ENABLED == 1) {
  4876.                 $billerDetails = [];
  4877.                 $billToDetails = [];
  4878.                 if ($invoice) {
  4879.                     $billerDetails $em->getRepository('CompanyGroupBundle\\Entity\\EntityApplicantDetails')
  4880.                         ->findOneBy(
  4881.                             array(
  4882.                                 'applicantId' => $invoice->getBillerId(),
  4883.                             )
  4884.                         );
  4885.                     $billToDetails $em->getRepository('CompanyGroupBundle\\Entity\\EntityApplicantDetails')
  4886.                         ->findOneBy(
  4887.                             array(
  4888.                                 'applicantId' => $invoice->getBillToId(),
  4889.                             )
  4890.                         );
  4891.                     $bodyTemplate '@Application/email/templates/buddybeeInvoiceEmail.html.twig';
  4892.                     $bodyData = array(
  4893.                         'page_title' => 'Invoice',
  4894. //            'studentDetails' => $student,
  4895.                         'billerDetails' => $billerDetails,
  4896.                         'billToDetails' => $billToDetails,
  4897.                         'invoice' => $invoice,
  4898.                         'currencyList' => BuddybeeConstant::$currency_List,
  4899.                         'currencyListByMarker' => BuddybeeConstant::$currency_List_by_marker,
  4900.                     );
  4901.                     $attachments = [];
  4902.                     $forwardToMailAddress $billToDetails->getOAuthEmail();
  4903. //                    $upl_dir = $this->container->getParameter('kernel.root_dir') . '/../web/uploads/temp/' . 'ledger' . '.pdf'
  4904.                     $new_mail $this->get('mail_module');
  4905.                     $new_mail->sendMyMail(array(
  4906.                         'senderHash' => '_CUSTOM_',
  4907.                         //                        'senderHash'=>'_CUSTOM_',
  4908.                         'forwardToMailAddress' => $forwardToMailAddress,
  4909.                         '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 ',
  4910. //                        'fileName' => 'Order#' . str_pad($id, 8, '0', STR_PAD_LEFT) . '.pdf',
  4911.                         'attachments' => $attachments,
  4912.                         'toAddress' => $forwardToMailAddress,
  4913.                         'fromAddress' => \ApplicationBundle\Helper\MailerConfig::address(),
  4914.                         'userName' => \ApplicationBundle\Helper\MailerConfig::address(),
  4915.                         'password' => \ApplicationBundle\Helper\MailerConfig::buddybeePassword(),
  4916.                         'smtpServer' => \ApplicationBundle\Helper\MailerConfig::host(),
  4917.                         'smtpPort' => \ApplicationBundle\Helper\MailerConfig::port(),
  4918. //                            'emailBody' => $bodyHtml,
  4919.                         'mailTemplate' => $bodyTemplate,
  4920.                         'templateData' => $bodyData,
  4921.                         'embedCompanyImage' => 0,
  4922.                         'companyId' => 0,
  4923.                         'companyImagePath' => ''
  4924. //                        'embedCompanyImage' => 1,
  4925. //                        'companyId' => $companyId,
  4926. //                        'companyImagePath' => $company_data->getImage()
  4927.                     ));
  4928.                 }
  4929.             }
  4930. //            if ($invoice) {
  4931. //
  4932. //            } else {
  4933. //                return $this->render('@Buddybee/pages/404NotFound.html.twig', array(
  4934. //                    'page_title' => '404 Not Found',
  4935. //
  4936. //                ));
  4937. //            }
  4938.             return $this->render('@HoneybeeWeb/pages/views/honeybee_ecosystem_invoice.html.twig', array(
  4939.                 'page_title' => 'Invoice',
  4940. //            'studentDetails' => $student,
  4941.                 'billerDetails' => $billerDetails,
  4942.                 'billToDetails' => $billToDetails,
  4943.                 'invoice' => $invoice,
  4944.                 'currencyList' => BuddybeeConstant::$currency_List,
  4945.                 'currencyListByMarker' => BuddybeeConstant::$currency_List_by_marker,
  4946.             ));
  4947.         }
  4948.     }
  4949.     public function SignatureCheckFromCentralAction(Request $request)
  4950.     {
  4951.         $systemType $this->container->hasParameter('system_type') ? $this->container->getParameter('system_type') : '_ERP_';
  4952.         if ($systemType !== '_CENTRAL_') {
  4953.             return new JsonResponse(['success' => false'message' => 'Only allowed on CENTRAL server.'], 403);
  4954.         }
  4955.         $em $this->getDoctrine()->getManager('company_group');
  4956.         $em->getConnection()->connect();
  4957.         $data json_decode($request->getContent(), true);
  4958.         if (
  4959.             !$data ||
  4960.             !isset($data['userId']) ||
  4961.             !isset($data['companyId']) ||
  4962.             !isset($data['signatureData']) ||
  4963.             !isset($data['approvalHash']) ||
  4964.             !isset($data['applicantId'])
  4965.         ) {
  4966.             return new JsonResponse(['success' => false'message' => 'Missing parameters.'], 400);
  4967.         }
  4968.         $userId $data['userId'];
  4969.         $companyId $data['companyId'];
  4970.         $signatureData $data['signatureData'];
  4971.         $approvalHash $data['approvalHash'];
  4972.         $applicantId $data['applicantId'];
  4973.         try {
  4974.             $centralUser $em
  4975.                 ->getRepository("CompanyGroupBundle\\Entity\\EntityApplicantDetails")
  4976.                 ->findOneBy(['applicantId' => $applicantId]);
  4977.             if (!$centralUser) {
  4978.                 return new JsonResponse(['success' => false'message' => 'Central user not found.'], 404);
  4979.             }
  4980.             $userAppIds json_decode($centralUser->getUserAppIds(), true);
  4981.             if (!is_array($userAppIds)) $userAppIds = [];
  4982.             $companies $em->getRepository('CompanyGroupBundle\\Entity\\CompanyGroup')->findBy([
  4983.                 'appId' => $userAppIds
  4984.             ]);
  4985.             if (count($companies) < 1) {
  4986.                 return new JsonResponse(['success' => false'message' => 'No companies found for userAppIds.'], 404);
  4987.             }
  4988.             $repo $em->getRepository('CompanyGroupBundle\\Entity\\EntitySignature');
  4989.             $record $repo->findOneBy(['userId' => $userId]);
  4990.             if (!$record) {
  4991.                 $record = new \CompanyGroupBundle\Entity\EntitySignature();
  4992.                 $record->setUserId($applicantId);
  4993.                 $record->setCreatedAt(new \DateTime());
  4994.             }
  4995.             $record->setCompanyId($companyId);
  4996.             $record->setApplicantId($applicantId);
  4997.             $record->setData($signatureData);
  4998.             $record->setSigExists(0);
  4999.             $record->setLastDecryptedSigId(0);
  5000.             $record->setUpdatedAt(new \DateTime());
  5001.             $em->persist($record);
  5002.             $em->flush();
  5003.             $dataByServerId = [];
  5004.             $gocDataListByAppId = [];
  5005.             foreach ($companies as $entry) {
  5006.                 $gocDataListByAppId[$entry->getAppId()] = [
  5007.                     'dbName' => $entry->getDbName(),
  5008.                     'dbUser' => $entry->getDbUser(),
  5009.                     'dbPass' => $entry->getDbPass(),
  5010.                     'dbHost' => $entry->getDbHost(),
  5011.                     'serverAddress' => $entry->getCompanyGroupServerAddress(),
  5012.                     'port' => $entry->getCompanyGroupServerPort() ?: 80,
  5013.                     'appId' => $entry->getAppId(),
  5014.                     'serverId' => $entry->getCompanyGroupServerId(),
  5015.                 ];
  5016.                 if (!isset($dataByServerId[$entry->getCompanyGroupServerId()]))
  5017.                     $dataByServerId[$entry->getCompanyGroupServerId()] = array(
  5018.                         'serverId' => $entry->getCompanyGroupServerId(),
  5019.                         'serverAddress' => $entry->getCompanyGroupServerAddress(),
  5020.                         'port' => $entry->getCompanyGroupServerPort() ?: 80,
  5021.                         'payload' => array(
  5022.                             'globalId' => $applicantId,
  5023.                             'companyId' => $userAppIds,
  5024.                             'signatureData' => $signatureData,
  5025. //                                      'approvalHash' => $approvalHash
  5026.                         )
  5027.                     );
  5028.             }
  5029.             $urls = [];
  5030.             foreach ($dataByServerId as $entry) {
  5031.                 $serverAddress $entry['serverAddress'];
  5032.                 if (!$serverAddress) continue;
  5033. //                     $connector = $this->container->get('application_connector');
  5034. //                     $connector->resetConnection(
  5035. //                         'default',
  5036. //                         $entry['dbName'],
  5037. //                         $entry['dbUser'],
  5038. //                         $entry['dbPass'],
  5039. //                         $entry['dbHost'],
  5040. //                         $reset = true
  5041. //                     );
  5042.                 $syncUrl $serverAddress '/ReceiveSignatureFromCentral';
  5043.                 $payload $entry['payload'];
  5044.                 $curl curl_init();
  5045.                 curl_setopt_array($curl, [
  5046.                     CURLOPT_RETURNTRANSFER => true,
  5047.                     CURLOPT_POST => true,
  5048.                     CURLOPT_URL => $syncUrl,
  5049. //                         CURLOPT_PORT => $entry['port'],
  5050.                     CURLOPT_CONNECTTIMEOUT => 10,
  5051.                     CURLOPT_SSL_VERIFYPEER => false,
  5052.                     CURLOPT_SSL_VERIFYHOST => false,
  5053.                     CURLOPT_HTTPHEADER => [
  5054.                         'Accept: application/json',
  5055.                         'Content-Type: application/json'
  5056.                     ],
  5057.                     CURLOPT_POSTFIELDS => json_encode($payload)
  5058.                 ]);
  5059.                 $response curl_exec($curl);
  5060.                 $err curl_error($curl);
  5061.                 $httpCode curl_getinfo($curlCURLINFO_HTTP_CODE);
  5062.                 curl_close($curl);
  5063. //                     if ($err) {
  5064. //                         error_log("ERP Sync Error [AppID $appId]: $err");
  5065. //                          $urls[]=$err;
  5066. //                     } else {
  5067. //                         error_log("ERP Sync Response [AppID $appId] (HTTP $httpCode): $response");
  5068. //                         $res = json_decode($response, true);
  5069. //                         if (!isset($res['success']) || !$res['success']) {
  5070. //                             error_log("❗ ERP Sync error for AppID $appId: " . ($res['message'] ?? 'Unknown'));
  5071. //                         }
  5072. //
  5073. //                      $urls[]=$response;
  5074. //                     }
  5075.             }
  5076.             return new JsonResponse(['success' => true'message' => 'Signature synced successfully.']);
  5077.         } catch (\Exception $e) {
  5078.             return new JsonResponse(['success' => false'message' => 'DB error: ' $e->getMessage()], 500);
  5079.         }
  5080.     }
  5081.  //datev cntroller
  5082.     public function connectDatev(Request $request)
  5083.     {
  5084.         $clientId "51b09bdcf577c5b998cddce7fe7d5c92";
  5085.         $redirectUri "https://ourhoneybee.eu/datev/callback";
  5086.         $state bin2hex(random_bytes(10));
  5087.         $scope "openid profile email accounting:documents accounting:dxso-jobs accounting:clients:read datev:accounting:extf-files-import datev:accounting:clients";
  5088.         $codeVerifier bin2hex(random_bytes(32));
  5089.         $codeChallenge rtrim(strtr(base64_encode(hash('sha256'$codeVerifiertrue)), '+/''-_'), '=');
  5090.         $session $request->getSession();
  5091.         $applicantId $session->get(UserConstants::APPLICANT_ID);
  5092.         $em_goc $this->getDoctrine()->getManager('company_group');
  5093.         $token $em_goc->getRepository('CompanyGroupBundle\\Entity\\EntityDatevToken')
  5094.             ->findOneBy(['userId' => $applicantId]);
  5095.         if (!$token) {
  5096.             $token = new EntityDatevToken();
  5097.             $token->setUserId($applicantId);
  5098.         }
  5099.         $token->setState($state);
  5100.         $token->setCodeChallenge($codeChallenge);
  5101.         $token->setCodeVerifier($codeVerifier);
  5102.         $em_goc->persist($token);
  5103.         $em_goc->flush();
  5104.         $url "https://login.datev.de/openidsandbox/authorize?"
  5105.             ."response_type=code"
  5106.             ."&client_id=".$clientId
  5107.             ."&state=".$state
  5108.             ."&scope=".urlencode($scope)
  5109.             ."&redirect_uri=".urlencode($redirectUri)
  5110.             ."&code_challenge=".$codeChallenge
  5111.             ."&code_challenge_method=S256"
  5112.             ."&prompt=login";
  5113.         return $this->redirect($url);
  5114.     }
  5115.     public function datevCallback(Request $request)
  5116.     {
  5117.         $code  $request->get('code');
  5118.         $state $request->get('state');
  5119.         if (!$code || !$state) {
  5120.             return new Response("Invalid callback request");
  5121.         }
  5122.         $em_goc $this->getDoctrine()->getManager('company_group');
  5123.         $tokenEntity $em_goc->getRepository('CompanyGroupBundle\\Entity\\EntityDatevToken')
  5124.             ->findOneBy(['state' => $state]);
  5125.         if (!$tokenEntity) {
  5126.             return new Response("Invalid or expired state");
  5127.         }
  5128.         $codeVerifier $tokenEntity->getCodeVerifier();
  5129.         if (!$codeVerifier) {
  5130.             return new Response("Code verifier missing");
  5131.         }
  5132.         $clientId "51b09bdcf577c5b998cddce7fe7d5c92";
  5133.         $clientSecret "9b1c4e72a966e9f231584393ff1d3469";
  5134.         // from parameters
  5135. //        $clientId= $this->getContainer()->getParameter('datev_client_id');
  5136. //        $clientSecret= $this->getContainer()->getParameter('datev_client_secret');
  5137.         $authString base64_encode($clientId ":" $clientSecret);
  5138.         $redirectUri "https://ourhoneybee.eu/datev/callback";
  5139.         $postFields http_build_query([
  5140.             "grant_type"    => "authorization_code",
  5141.             "code"          => $code,
  5142.             "redirect_uri"  => $redirectUri,
  5143.             "client_id"     => $clientId,
  5144.             "code_verifier" => $codeVerifier
  5145.         ]);
  5146.         $ch curl_init();
  5147.         curl_setopt_array($ch, [
  5148.             CURLOPT_URL            => "https://sandbox-api.datev.de/token",
  5149.             CURLOPT_POST           => true,
  5150.             CURLOPT_RETURNTRANSFER => true,
  5151.             CURLOPT_POSTFIELDS     => $postFields,
  5152.             CURLOPT_HTTPHEADER     => [
  5153.                 "Content-Type: application/x-www-form-urlencoded",
  5154.                 "Authorization: Basic " $authString
  5155.             ]
  5156.         ]);
  5157.         $response curl_exec($ch);
  5158.         if (curl_errno($ch)) {
  5159.             return new Response("cURL Error: " curl_error($ch), 500);
  5160.         }
  5161.         curl_close($ch);
  5162.         $data json_decode($responsetrue);
  5163.         if (!$data) {
  5164.             return new Response("Invalid token response"500);
  5165.         }
  5166.         if (isset($data['access_token'])) {
  5167.             $tokenEntity->setAccessToken($data['access_token']);
  5168.             $session $request->getSession();  //remove it later
  5169.             $session->set('DATEV_ACCESS_TOKEN'$data['access_token']);
  5170.             if (isset($data['refresh_token'])) {
  5171.                 $tokenEntity->setRefreshToken($data['refresh_token']);
  5172.             }
  5173.             if (isset($data['expires_in'])) {
  5174.                 $tokenEntity->setExpiresAt(time() + $data['expires_in']);
  5175.             }
  5176. //            $tokenEntity->setState(null);
  5177.             $tokenEntity->setCode($code);
  5178.             $em_goc->flush();
  5179.             return $this->redirect("/datev/home");
  5180.         }
  5181.         return new Response(
  5182.             "Token exchange failed: " json_encode($data),
  5183.             400
  5184.         );
  5185.     }
  5186.     public function refreshToken(Request $request)
  5187.     {
  5188.         $em_goc $this->getDoctrine()->getManager('company_group');
  5189.         $session $request->getSession();
  5190.         $applicantId $session->get(UserConstants::APPLICANT_ID);
  5191.         $token $em_goc->getRepository('CompanyGroupBundle\\Entity\\EntityDatevToken')
  5192.             ->findOneBy(['userId' => $applicantId]);
  5193.         if (!$token) {
  5194.             return new JsonResponse([
  5195.                 'status' => false,
  5196.                 'message' => 'User token not found'
  5197.             ]);
  5198.         }
  5199.         if (!$token->getRefreshToken()) {
  5200.             return new JsonResponse([
  5201.                 'status' => false,
  5202.                 'message' => 'No refresh token available'
  5203.             ]);
  5204.         }
  5205.         $clientId "51b09bdcf577c5b998cddce7fe7d5c92";
  5206.         $clientSecret "9b1c4e72a966e9f231584393ff1d3469";
  5207.         $authString base64_encode($clientId ":" $clientSecret);
  5208.         $postFields http_build_query([
  5209.             "grant_type" => "refresh_token",
  5210.             "refresh_token" => $token->getRefreshToken(),
  5211.         ]);
  5212.         $ch curl_init();
  5213.         curl_setopt_array($ch, [
  5214.             CURLOPT_URL => "https://sandbox-api.datev.de/token",
  5215.             CURLOPT_POST => true,
  5216.             CURLOPT_RETURNTRANSFER => true,
  5217.             CURLOPT_POSTFIELDS => $postFields,
  5218.             CURLOPT_HTTPHEADER => [
  5219.                 "Content-Type: application/x-www-form-urlencoded",
  5220.                 "Authorization: Basic " $authString
  5221.             ]
  5222.         ]);
  5223.         $response curl_exec($ch);
  5224.         if (curl_errno($ch)) {
  5225.             return new JsonResponse([
  5226.                 'status' => false,
  5227.                 'message' => curl_error($ch)
  5228.             ]);
  5229.         }
  5230.         curl_close($ch);
  5231.         $data json_decode($responsetrue);
  5232.         if (!isset($data['access_token'])) {
  5233.             return new JsonResponse([
  5234.                 'status' => false,
  5235.                 'message' => 'Refresh failed',
  5236.                 'error' => $data
  5237.             ]);
  5238.         }
  5239.         $token->setAccessToken($data['access_token']);
  5240.         if (isset($data['refresh_token'])) {
  5241.             $token->setRefreshToken($data['refresh_token']);
  5242.         }
  5243.         $token->setExpiresAt(time() + $data['expires_in']);
  5244.         $em_goc->flush();
  5245.         return new JsonResponse([
  5246.             'status' => true,
  5247.             'message' => 'Token refreshed successfully'
  5248.         ]);
  5249.     }
  5250.     public function registerDevice(Request $request)
  5251.     {
  5252.         $em_goc $this->getDoctrine()->getManager('company_group');
  5253.         $data json_decode($request->getContent(), true);
  5254.         if (!$data) {
  5255.             $data $request->request->all();
  5256.         }
  5257.         $deviceSerial $data['device_id'] ?? null;
  5258.         if (!$deviceSerial) {
  5259.             return new JsonResponse([
  5260.                 'success' => false,
  5261.                 'message' => 'Device serial is required',
  5262.                 'data' => null
  5263.             ], 400);
  5264.         }
  5265.         $device =  $em_goc->getRepository('CompanyGroupBundle\\Entity\\Device')
  5266.             ->findOneBy(['deviceSerial' => $deviceSerial]);
  5267.         if (!$device) {
  5268.             $device = new Device();
  5269.             $device->setDeviceSerial($deviceSerial);
  5270.             $message 'Device registered successfully';
  5271.         } else {
  5272.             $message 'Device updated successfully';
  5273.         }
  5274.         if (isset($data['deviceName'])) {
  5275.             $device->setDeviceName($data['deviceName']);
  5276.         }
  5277.         if (isset($data['appId'])) {
  5278.             $device->setAppId($data['appId']);
  5279.         }
  5280.         if (isset($data['deviceType'])) {
  5281.             $device->setDeviceType($data['deviceType']);
  5282.         }
  5283.         if (isset($data['deviceMarker'])) {
  5284.             $device->setDeviceMarker($data['deviceMarker']);
  5285.         }
  5286.         if (isset($data['timezoneStr'])) {
  5287.             $device->setTimezoneStr($data['timezoneStr']);
  5288.         }
  5289.         if (isset($data['hostname'])) {
  5290.             $device->setHostName($data['hostname']);
  5291.         }
  5292.         $em_goc->persist($device);
  5293.         $em_goc->flush();
  5294.         return new JsonResponse([
  5295.             'success' => true,
  5296.             'message' => $message,
  5297.             'data' => [
  5298.                 'id' => $device->getId(),
  5299.                 'deviceSerial' => $device->getDeviceSerial(),
  5300.                 'deviceName' => $device->getDeviceName(),
  5301.                 'deviceType' => $device->getDeviceType(),
  5302.                 'hostName' => $device->getHostName(),
  5303.             ]
  5304.         ]);
  5305.     }
  5306.     public function khorchapatiTermsAndConditions()
  5307.     {
  5308.              return $this->render('@HoneybeeWeb/pages/khorchapati_terms_and_conditions.html.twig', array(
  5309.             'page_title' => 'Terms and Conditions — Khorchapati',
  5310.         ));
  5311.             
  5312.     }
  5313.     public function milkShareTermsAndConditions()
  5314.     {
  5315.         return $this->render('@HoneybeeWeb/pages/milkshare-terms-and-conditions.html.twig', array(
  5316.             'page_title' => 'Terms and Conditions — Milkshare',
  5317.         ));
  5318.     }
  5319. }