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

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