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

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