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

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