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

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