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

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