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

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