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

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