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

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