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

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