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

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