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

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