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

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