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

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