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

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