src/ApplicationBundle/Modules/HoneybeeWeb/Controller/HoneybeeWebController.php line 980

Open in your IDE?
  1. <?php
  2. namespace ApplicationBundle\Modules\HoneybeeWeb\Controller;
  3. use ApplicationBundle\Constants\GeneralConstant;
  4. use ApplicationBundle\Constants\HumanResourceConstant;
  5. use ApplicationBundle\Controller\GenericController;
  6. use ApplicationBundle\Entity\EmpLeaveApplication;
  7. use ApplicationBundle\Entity\ReceiptCheck;
  8. use ApplicationBundle\Interfaces\SessionCheckInterface;
  9. use ApplicationBundle\Modules\Authentication\Constants\UserConstants; use ApplicationBundle\Modules\Api\Constants\ApiConstants;
  10. use ApplicationBundle\Modules\HoneybeeWeb\Service\Hb360AccessService;
  11. use ApplicationBundle\Modules\HoneybeeWeb\Service\Hb360ConversionService;
  12. use ApplicationBundle\Modules\HoneybeeWeb\Service\Hb360ExecutionService;
  13. use ApplicationBundle\Modules\HoneybeeWeb\Service\Hb360GridService;
  14. use ApplicationBundle\Modules\HoneybeeWeb\Service\Hb360HybridService;
  15. use ApplicationBundle\Modules\HoneybeeWeb\Service\Hb360ProjectService;
  16. use ApplicationBundle\Modules\HoneybeeWeb\Service\Hb360ReportService;
  17. use ApplicationBundle\Modules\HoneybeeWeb\Support\FunnelManifestCore;
  18. use CompanyGroupBundle\Entity\EntityApplicantDetails;
  19. use CompanyGroupBundle\Entity\EntityCountryConsultantRequirements;
  20. use CompanyGroupBundle\Entity\EntitySkill;
  21. use CompanyGroupBundle\Entity\EntityCreateBlog;
  22. use CompanyGroupBundle\Entity\EntityCreateTopic;
  23. use Ps\PdfBundle\Annotation\Pdf;
  24. use Symfony\Component\HttpFoundation\Request;
  25. use Symfony\Component\HttpFoundation\Response;
  26. use Symfony\Component\HttpFoundation\JsonResponse;
  27. use Symfony\Component\Routing\Generator\UrlGenerator;
  28. use CompanyGroupBundle\Entity\User;
  29. //use Symfony\Bundle\FrameworkBundle\Console\Application;
  30. //use Symfony\Component\Console\Input\ArrayInput;
  31. //use Symfony\Component\Console\Output\NullOutput;
  32. class HoneybeeWebController extends GenericController implements SessionCheckInterface
  33. {
  34.     // ═══ HB360 H1b/H1c — "your saved estimate" behind the signup wall ═══
  35.     /**
  36.      * Tier gate for a package. Returns null when allowed; otherwise a redirect
  37.      * to the estimate page with an upsell notice. SWITCHED OFF by default
  38.      * (Hb360AccessService::DEFAULT_MAP is all-free) until the owner maps tiers.
  39.      */
  40.     private function hb360TierGate(Request $requeststring $packageint $projectId)
  41.     {
  42.         $check = (new Hb360AccessService($this->container))
  43.             ->check($package, (int) $this->loggedUserId($request));
  44.         if ($check['allowed']) {
  45.             return null;
  46.         }
  47.         return $this->redirectToRoute('hb360_my_estimate', [
  48.             'p' => $projectId'locked' => $package'tier' => $check['required_tier'],
  49.         ]);
  50.     }
  51.     /** The saved-estimate home: latest project + Package B report (if generated). */
  52.     public function Hb360MyEstimateAction(Request $request)
  53.     {
  54.         if ((int) $this->loggedUserType($request) !== UserConstants::USER_TYPE_APPLICANT) {
  55.             return $this->redirectToRoute('central_login');
  56.         }
  57.         $em $this->getDoctrine()->getManager('company_group');
  58.         $svc = new Hb360ProjectService($em);
  59.         $applicantId = (int) $this->loggedUserId($request);
  60.         // Safety net for the login-time attach (e.g. the estimate was made in
  61.         // another tab AFTER logging in): claim anon rows for this cookie now.
  62.         try {
  63.             $anon = (string) $request->cookies->get('hb360_anon''');
  64.             if ($anon !== '') {
  65.                 $svc->attachToken($anon$applicantId, (string) $request->getSession()->get(UserConstants::USER_EMAIL));
  66.             }
  67.         } catch (\Throwable $e) { /* best-effort */ }
  68.         $projects = []; $storageReady true;
  69.         try {
  70.             $projects $svc->listForApplicant($applicantId);
  71.         } catch (\Throwable $e) {
  72.             $storageReady false// hb360_project table not migrated yet
  73.         }
  74.         $current null;
  75.         $pid = (int) $request->query->get('p'0);
  76.         foreach ($projects as $p) {
  77.             if ((int) $p->getId() === $pid) { $current $p; break; }
  78.         }
  79.         if (!$current && $projects) { $current $projects[0]; }
  80.         // FUNNEL-1: the attached studio design card for the CURRENT estimate. Best-effort.
  81.         $design null;
  82.         try {
  83.             if ($current && $current->getDesignJson()) {
  84.                 $dj json_decode((string) $current->getDesignJson(), true);
  85.                 if (is_array($dj) && isset($dj['payload']) && is_array($dj['payload'])) {
  86.                     $design = array(
  87.                         'summary'  => FunnelManifestCore::summary($dj['payload']),
  88.                         'hash'     => isset($dj['hash']) ? (string) $dj['hash'] : '',
  89.                         'saved_at' => isset($dj['saved_at']) ? (string) $dj['saved_at'] : null,
  90.                     );
  91.                 }
  92.             }
  93.         } catch (\Throwable $e) { $design null; }
  94.         // ── FUNNEL-3: "My designs" — every attached row carrying a studio design, with
  95.         // summary figures + the HONEST handoff status line (read from CENTRAL only —
  96.         // sds_funnel_handoff lives where the applicant lives; no tenant DB is touched).
  97.         $myDesigns = array();
  98.         try {
  99.             $handoffByProject = array();
  100.             $tenantNames = array();
  101.             try {
  102.                 $conn $em->getConnection();
  103.                 if ($conn->getSchemaManager()->tablesExist(array('sds_funnel_handoff'))) {
  104.                     $rows $conn->fetchAllAssociative(
  105.                         'SELECT project_id, target_app_id, status, created_at FROM sds_funnel_handoff'
  106.                         ' WHERE project_id IS NOT NULL ORDER BY id ASC');
  107.                     foreach ($rows as $r) { // ASC ⇒ the LATEST handoff per project wins
  108.                         $handoffByProject[(int) $r['project_id']] = $r;
  109.                     }
  110.                     foreach ($em->getRepository('CompanyGroupBundle\\Entity\\CompanyGroup')->findAll() as $g) {
  111.                         $tenantNames[(int) $g->getAppId()] = (string) $g->getName();
  112.                     }
  113.                 }
  114.             } catch (\Throwable $e) { /* status lines are an extra, never a gate */ }
  115.             foreach ($projects as $p) {
  116.                 if (!$p->getDesignJson()) { continue; }
  117.                 $dj json_decode((string) $p->getDesignJson(), true);
  118.                 if (!is_array($dj) || !isset($dj['payload']) || !is_array($dj['payload'])) { continue; }
  119.                 $entry = array(
  120.                     'id'       => (int) $p->getId(),
  121.                     'title'    => (string) ($p->getTitle() ?: ('Design #' $p->getId())),
  122.                     'address'  => (string) $p->getAddress(),
  123.                     'summary'  => FunnelManifestCore::summary($dj['payload']),
  124.                     'saved_at' => isset($dj['saved_at']) ? (string) $dj['saved_at'] : null,
  125.                     'updated'  => $p->getUpdatedAt() ? $p->getUpdatedAt()->format('d M Y H:i') : '',
  126.                     'offer'    => null,
  127.                 );
  128.                 if (isset($handoffByProject[(int) $p->getId()])) {
  129.                     $h $handoffByProject[(int) $p->getId()];
  130.                     $label = \ApplicationBundle\Modules\HoneybeeWeb\Support\FunnelWireCore::applicantStatusLabel((string) $h['status']);
  131.                     if ($label !== '') {
  132.                         $entry['offer'] = array(
  133.                             'label'     => $label,
  134.                             'recipient' => isset($tenantNames[(int) $h['target_app_id']])
  135.                                 ? $tenantNames[(int) $h['target_app_id']] : null,
  136.                             'when'      => (string) $h['created_at'],
  137.                         );
  138.                     }
  139.                 }
  140.                 $myDesigns[] = $entry;
  141.             }
  142.         } catch (\Throwable $e) { $myDesigns = array(); }
  143.         return $this->render('@HoneybeeWeb/pages/tools/hb360_my_estimate.html.twig', array(
  144.             'page_title'    => 'My Solar Estimates | HoneyBee 360',
  145.             'projects'      => $projects,
  146.             'current'       => $current,
  147.             'estimate'      => $current json_decode($current->getEstimateJson(), true) : null,
  148.             'report'        => ($current && $current->getReportJson()) ? json_decode($current->getReportJson(), true) : null,
  149.             'design'        => $design,
  150.             'my_designs'    => $myDesigns,
  151.             'storage_ready' => $storageReady,
  152.         ));
  153.     }
  154.     /** H1c: turn the saved estimate into a Package B feasibility report. */
  155.     public function Hb360GenerateReportAction(Request $request$id)
  156.     {
  157.         if ((int) $this->loggedUserType($request) !== UserConstants::USER_TYPE_APPLICANT) {
  158.             return $this->redirectToRoute('central_login');
  159.         }
  160.         $em $this->getDoctrine()->getManager('company_group');
  161.         $svc = new Hb360ProjectService($em);
  162.         $project $svc->findOwned((int) $id, (int) $this->loggedUserId($request));
  163.         if (!$project) {
  164.             return $this->redirectToRoute('hb360_my_estimate');
  165.         }
  166.         $estimate json_decode($project->getEstimateJson(), true) ?: [];
  167.         $report = (new Hb360ReportService())->report($estimate, [
  168.             'lat' => $project->getLat() ?: 50,
  169.             // Equipment refinement: an explicit config pick from the report form.
  170.             'inverterModel' => (string) $request->request->get('inverter_model'''),
  171.         ]);
  172.         if (!empty($report['ok'])) {
  173.             // A refresh recomputes Package B but keeps existing deeper packages.
  174.             $old json_decode((string) $project->getReportJson(), true);
  175.             foreach (['package_c''package_d''package_e''package_f'] as $pk) {
  176.                 if (!empty($old[$pk])) { $report[$pk] = $old[$pk]; }
  177.             }
  178.             $svc->saveReport($project$report);
  179.         }
  180.         return $this->redirectToRoute('hb360_my_estimate', ['p' => $project->getId()]);
  181.     }
  182.     // ═══ HB360-CONV — "Convert this estimate to an EPC project" (web wire) ═══
  183.     //
  184.     // Wraps the EXISTING Hb360ConversionService (no re-implementation). Hard
  185.     // rules: anonymous visitors hit the wall (the applicant gate below); the
  186.     // target tenant resolves ONLY from the authenticated session's app-id list
  187.     // (Hb360ConversionService::resolveTenant — a request-supplied id that is
  188.     // not in the session list resolves to null); conversion is confirm-before-
  189.     // commit, DRAFT-only (existing approval funnel), and idempotent (a stamped
  190.     // converted_ref shows the existing document, never a duplicate).
  191.     /** The session's workspace list — the ONLY source of a conversion target. */
  192.     private function hb360AllowedAppIds(Request $request): array
  193.     {
  194.         return Hb360ConversionService::allowedAppIds(
  195.             $request->getSession()->get(UserConstants::USER_APP_ID_LIST)
  196.         );
  197.     }
  198.     /** Connect a tenant DB (the application_connector reset pattern). */
  199.     private function hb360TenantConnect(int $appId): array
  200.     {
  201.         $emGoc $this->getDoctrine()->getManager('company_group');
  202.         $goc $emGoc->getRepository('CompanyGroupBundle\\Entity\\CompanyGroup')->findOneBy(['appId' => $appId]);
  203.         if (!$goc) {
  204.             return [nullnull];
  205.         }
  206.         $this->container->get('application_connector')->resetConnection(
  207.             'default'$goc->getDbName(), $goc->getDbUser(), $goc->getDbPass(), $goc->getDbHost(), true
  208.         );
  209.         return [$this->getDoctrine()->getManager(), $goc];
  210.     }
  211.     /** Workspace labels + the best-effort ERP deep-link base, from CENTRAL data only. */
  212.     private function hb360WorkspaceMeta(array $appIds): array
  213.     {
  214.         $meta = [];
  215.         try {
  216.             $emGoc $this->getDoctrine()->getManager('company_group');
  217.             foreach ($appIds as $appId) {
  218.                 $goc $emGoc->getRepository('CompanyGroupBundle\\Entity\\CompanyGroup')->findOneBy(['appId' => $appId]);
  219.                 $addr $goc trim((string) ($goc->getCurrentServerAddress() ?: $goc->getCompanyGroupServerAddress())) : '';
  220.                 if ($addr !== '' && strpos($addr'http') !== 0) { $addr 'https://' $addr; }
  221.                 $meta[$appId] = [
  222.                     'name' => $goc ? (string) $goc->getName() : ('Workspace #' $appId),
  223.                     'erp_base' => $addr !== '' rtrim($addr'/') : null,
  224.                 ];
  225.             }
  226.         } catch (\Throwable $e) { /* labels are cosmetic — never block the flow */ }
  227.         return $meta;
  228.     }
  229.     /** GET — the confirm step (also the "already converted" landing). */
  230.     public function Hb360ConvertConfirmAction(Request $request$id)
  231.     {
  232.         if ((int) $this->loggedUserType($request) !== UserConstants::USER_TYPE_APPLICANT) {
  233.             return $this->redirectToRoute('central_login'); // the wall — anon never converts
  234.         }
  235.         $em $this->getDoctrine()->getManager('company_group');
  236.         $project = (new Hb360ProjectService($em))->findOwned((int) $id, (int) $this->loggedUserId($request));
  237.         if (!$project) {
  238.             return $this->redirectToRoute('hb360_my_estimate');
  239.         }
  240.         $allowed $this->hb360AllowedAppIds($request);
  241.         $estimate json_decode($project->getEstimateJson(), true) ?: [];
  242.         // Idempotent landing: already converted → link the existing document.
  243.         $existing null;
  244.         if ($project->getConvertedRef()) {
  245.             [$docHash$proposalId] = array_pad(explode('#', (string) $project->getConvertedRef(), 2), 2'');
  246.             $wsMeta $this->hb360WorkspaceMeta([(int) $project->getConvertedAppId()]);
  247.             $base $wsMeta[(int) $project->getConvertedAppId()]['erp_base'] ?? null;
  248.             $existing = [
  249.                 'doc_hash' => $docHash'proposal_id' => (int) $proposalId,
  250.                 'app_id' => (int) $project->getConvertedAppId(),
  251.                 'workspace' => $wsMeta[(int) $project->getConvertedAppId()]['name'] ?? ('Workspace #' $project->getConvertedAppId()),
  252.                 'deep_link' => $base && $proposalId $base '/view_sales_proposal/' . (int) $proposalId null,
  253.                 'converted_at' => $project->getConvertedAt(),
  254.             ];
  255.         }
  256.         return $this->render('@HoneybeeWeb/pages/tools/hb360_convert.html.twig', array(
  257.             'page_title' => 'Convert to EPC project | HoneyBee 360',
  258.             'project'    => $project,
  259.             'estimate'   => $estimate,
  260.             'allowed'    => $allowed,
  261.             'workspaces' => $this->hb360WorkspaceMeta($allowed),
  262.             'existing'   => $existing,
  263.             'error'      => (string) $request->query->get('e'''),
  264.         ));
  265.     }
  266.     /** POST — the commit: create ONE draft proposal in the session-resolved tenant. */
  267.     public function Hb360ConvertCommitAction(Request $request$id)
  268.     {
  269.         if ((int) $this->loggedUserType($request) !== UserConstants::USER_TYPE_APPLICANT) {
  270.             return $this->redirectToRoute('central_login');
  271.         }
  272.         $emGoc $this->getDoctrine()->getManager('company_group');
  273.         $project = (new Hb360ProjectService($emGoc))->findOwned((int) $id, (int) $this->loggedUserId($request));
  274.         if (!$project) {
  275.             return $this->redirectToRoute('hb360_my_estimate');
  276.         }
  277.         // Idempotent replay: a second POST lands on the existing document.
  278.         if ($project->getConvertedRef()) {
  279.             return $this->redirectToRoute('hb360_convert_confirm', ['id' => $project->getId()]);
  280.         }
  281.         // Tenant from the SESSION list only — a foreign id resolves to null.
  282.         $appId Hb360ConversionService::resolveTenant(
  283.             $this->hb360AllowedAppIds($request), $request->request->get('workspace')
  284.         );
  285.         if ($appId === null) {
  286.             return $this->redirectToRoute('hb360_convert_confirm', ['id' => $project->getId(), 'e' => 'workspace']);
  287.         }
  288.         [$tenantEm$goc] = $this->hb360TenantConnect($appId);
  289.         if (!$tenantEm) {
  290.             return $this->redirectToRoute('hb360_convert_confirm', ['id' => $project->getId(), 'e' => 'workspace']);
  291.         }
  292.         $session $request->getSession();
  293.         $res = (new Hb360ConversionService())->convert($project$tenantEm$emGoc$appIdfalse, [
  294.             'clientName' => trim((string) ($session->get(UserConstants::USER_NAME) ?: $session->get(UserConstants::USER_EMAIL) ?: '')),
  295.         ]);
  296.         if (empty($res['ok'])) {
  297.             return $this->redirectToRoute('hb360_convert_confirm', ['id' => $project->getId(), 'e' => 'convert']);
  298.         }
  299.         return $this->redirectToRoute('hb360_convert_confirm', ['id' => $project->getId()]);
  300.     }
  301.     // ── FUNNEL-3: design management on the applicant surface. All three are POST-only,
  302.     //    applicant-gated, and OWN-SCOPED through findOwned (a foreign id is a redirect,
  303.     //    never a touch). Delete is SOFT — the retention cron purges it after 30 days. ──
  304.     /** The own-scoped project or a safe redirect (shared guard for the three actions). */
  305.     private function hb360OwnedOrNull(Request $request$id)
  306.     {
  307.         if ((int) $this->loggedUserType($request) !== UserConstants::USER_TYPE_APPLICANT) {
  308.             return null;
  309.         }
  310.         $em $this->getDoctrine()->getManager('company_group');
  311.         return (new Hb360ProjectService($em))->findOwned((int) $id, (int) $this->loggedUserId($request));
  312.     }
  313.     public function Hb360DesignRenameAction(Request $request$id)
  314.     {
  315.         try {
  316.             $project $this->hb360OwnedOrNull($request$id);
  317.             if ($project) {
  318.                 (new Hb360ProjectService($this->getDoctrine()->getManager('company_group')))
  319.                     ->rename($project, (string) $request->request->get('title'''));
  320.             }
  321.         } catch (\Throwable $e) { /* fall through to the list */ }
  322.         return $this->redirectToRoute('hb360_my_estimate');
  323.     }
  324.     public function Hb360DesignDuplicateAction(Request $request$id)
  325.     {
  326.         try {
  327.             $project $this->hb360OwnedOrNull($request$id);
  328.             if ($project) {
  329.                 $copy = (new Hb360ProjectService($this->getDoctrine()->getManager('company_group')))
  330.                     ->duplicateForApplicant($project);
  331.                 return $this->redirectToRoute('hb360_my_estimate', array('p' => $copy->getId()));
  332.             }
  333.         } catch (\Throwable $e) { /* fall through to the list */ }
  334.         return $this->redirectToRoute('hb360_my_estimate');
  335.     }
  336.     public function Hb360DesignDeleteAction(Request $request$id)
  337.     {
  338.         try {
  339.             $project $this->hb360OwnedOrNull($request$id);
  340.             if ($project) {
  341.                 (new Hb360ProjectService($this->getDoctrine()->getManager('company_group')))
  342.                     ->softDelete($project);
  343.             }
  344.         } catch (\Throwable $e) { /* fall through to the list */ }
  345.         return $this->redirectToRoute('hb360_my_estimate');
  346.     }
  347.     /** HB360-2: add/refresh the Package C hybrid design (BESS + genset + EVSE + finance). */
  348.     public function Hb360GenerateHybridAction(Request $request$id)
  349.     {
  350.         if ((int) $this->loggedUserType($request) !== UserConstants::USER_TYPE_APPLICANT) {
  351.             return $this->redirectToRoute('central_login');
  352.         }
  353.         $em $this->getDoctrine()->getManager('company_group');
  354.         $svc = new Hb360ProjectService($em);
  355.         $project $svc->findOwned((int) $id, (int) $this->loggedUserId($request));
  356.         if (!$project) {
  357.             return $this->redirectToRoute('hb360_my_estimate');
  358.         }
  359.         if ($gate $this->hb360TierGate($request'C', (int) $project->getId())) {
  360.             return $gate;
  361.         }
  362.         $estimate json_decode($project->getEstimateJson(), true) ?: [];
  363.         $report   json_decode((string) $project->getReportJson(), true) ?: [];
  364.         if (empty($report['ok'])) {
  365.             return $this->redirectToRoute('hb360_my_estimate', ['p' => $project->getId()]);
  366.         }
  367.         $packageC = (new Hb360HybridService())->design($estimate$report, [
  368.             'dayShare'        => (float) $request->request->get('day_share'60),
  369.             'criticalLoadPct' => (float) $request->request->get('critical_load_pct'30),
  370.             'outageHoursYr'   => (float) $request->request->get('outage_hours_yr'0),
  371.             'chargers'        => [
  372.                 'ac11'  => (int) $request->request->get('ev_ac11'0),
  373.                 'ac22'  => (int) $request->request->get('ev_ac22'0),
  374.                 'dc50'  => (int) $request->request->get('ev_dc50'0),
  375.                 'dc150' => (int) $request->request->get('ev_dc150'0),
  376.             ],
  377.         ]);
  378.         if (!empty($packageC['ok'])) {
  379.             $report['package_c'] = $packageC;
  380.             $svc->saveReport($project$report);
  381.         }
  382.         return $this->redirectToRoute('hb360_my_estimate', ['p' => $project->getId()]);
  383.     }
  384.     /** HB360-3: add/refresh the Package D grid & connection concept. */
  385.     public function Hb360GenerateGridAction(Request $request$id)
  386.     {
  387.         if ((int) $this->loggedUserType($request) !== UserConstants::USER_TYPE_APPLICANT) {
  388.             return $this->redirectToRoute('central_login');
  389.         }
  390.         $em $this->getDoctrine()->getManager('company_group');
  391.         $svc = new Hb360ProjectService($em);
  392.         $project $svc->findOwned((int) $id, (int) $this->loggedUserId($request));
  393.         if (!$project) {
  394.             return $this->redirectToRoute('hb360_my_estimate');
  395.         }
  396.         if ($gate $this->hb360TierGate($request'D', (int) $project->getId())) {
  397.             return $gate;
  398.         }
  399.         $estimate json_decode($project->getEstimateJson(), true) ?: [];
  400.         $report   json_decode((string) $project->getReportJson(), true) ?: [];
  401.         if (empty($report['ok'])) {
  402.             return $this->redirectToRoute('hb360_my_estimate', ['p' => $project->getId()]);
  403.         }
  404.         $packageD = (new Hb360GridService())->design($estimate$report, [
  405.             'exportCapPct'          => (float) $request->request->get('export_cap_pct'100),
  406.             'existingConnectionKva' => (float) $request->request->get('existing_connection_kva'0),
  407.         ], [
  408.             'lat' => (float) $project->getLat(), 'lng' => (float) $project->getLng(),
  409.             'address' => (string) $project->getAddress(),
  410.         ]);
  411.         if (!empty($packageD['ok'])) {
  412.             $report['package_d'] = $packageD;
  413.             $svc->saveReport($project$report);
  414.         }
  415.         return $this->redirectToRoute('hb360_my_estimate', ['p' => $project->getId()]);
  416.     }
  417.     /** HB360-4: add/refresh Packages E (execution briefing) + F (operate plan). */
  418.     public function Hb360GenerateExecutionAction(Request $request$id)
  419.     {
  420.         if ((int) $this->loggedUserType($request) !== UserConstants::USER_TYPE_APPLICANT) {
  421.             return $this->redirectToRoute('central_login');
  422.         }
  423.         $em $this->getDoctrine()->getManager('company_group');
  424.         $svc = new Hb360ProjectService($em);
  425.         $project $svc->findOwned((int) $id, (int) $this->loggedUserId($request));
  426.         if (!$project) {
  427.             return $this->redirectToRoute('hb360_my_estimate');
  428.         }
  429.         if ($gate $this->hb360TierGate($request'E', (int) $project->getId())) {
  430.             return $gate;
  431.         }
  432.         $estimate json_decode($project->getEstimateJson(), true) ?: [];
  433.         $report   json_decode((string) $project->getReportJson(), true) ?: [];
  434.         if (empty($report['ok'])) {
  435.             return $this->redirectToRoute('hb360_my_estimate', ['p' => $project->getId()]);
  436.         }
  437.         $exec = (new Hb360ExecutionService())->design($estimate$report);
  438.         if (!empty($exec['ok'])) {
  439.             $report['package_e'] = $exec['package_e'];
  440.             $report['package_f'] = $exec['package_f'];
  441.             $svc->saveReport($project$report);
  442.         }
  443.         return $this->redirectToRoute('hb360_my_estimate', ['p' => $project->getId()]);
  444.     }
  445.     // My Freelancer Profile
  446.     public function CentralMyApplicantProfilePageAction(Request $request)
  447.     {
  448.         $em $this->getDoctrine()->getManager('company_group');
  449.         $session $request->getSession();
  450.         $details $em->getRepository(EntityApplicantDetails::class)->find($session->get(UserConstants::USER_ID));
  451.         $employmentByCompany = [];
  452.         if ($details) {
  453.             $employmentByCompany $this->get('app.applicant_employment_aggregator')->getForApplicant($details);
  454.         }
  455.         return $this->render('@HoneybeeWeb/pages/my_freelancer_profile.html.twig', array(
  456.             'page_title' => 'My Freelancer Profile',
  457.             'details' => $details,
  458.             'skillDetails' => $em->getRepository(EntitySkill::class)->findAll(),
  459.             'employmentByCompany' => $employmentByCompany,
  460.         ));
  461.     }
  462.     public function AccountMergePageAction(Request $request)
  463.     {
  464.         if ((int)$this->loggedUserType($request) !== UserConstants::USER_TYPE_APPLICANT) {
  465.             return $this->redirectToRoute('central_login');
  466.         }
  467.         return $this->render('@HoneybeeWeb/pages/merge_accounts.html.twig', [
  468.             'page_title' => 'Merge Accounts',
  469.         ]);
  470.     }
  471.     public function RequestAccountMergeCodeAction(Request $request): JsonResponse
  472.     {
  473.         if ((int)$this->loggedUserType($request) !== UserConstants::USER_TYPE_APPLICANT) {
  474.             return new JsonResponse(['success' => false'message' => 'Please sign in first.'], 403);
  475.         }
  476.         $em $this->getDoctrine()->getManager('company_group');
  477.         $requester $em->getRepository(EntityApplicantDetails::class)->find((int)$this->loggedUserId($request));
  478.         if (!$requester) {
  479.             return new JsonResponse(['success' => false'message' => 'Applicant account not found.'], 404);
  480.         }
  481.         $result $this->get('app.account_merge_service')->requestMergeCode(
  482.             $requester,
  483.             (string)$request->request->get('email'$request->query->get('email'''))
  484.         );
  485.         return new JsonResponse($result$result['success'] ? 200 422);
  486.     }
  487.     public function ConfirmAccountMergeAction(Request $request): JsonResponse
  488.     {
  489.         if ((int)$this->loggedUserType($request) !== UserConstants::USER_TYPE_APPLICANT) {
  490.             return new JsonResponse(['success' => false'message' => 'Please sign in first.'], 403);
  491.         }
  492.         $em $this->getDoctrine()->getManager('company_group');
  493.         $requester $em->getRepository(EntityApplicantDetails::class)->find((int)$this->loggedUserId($request));
  494.         if (!$requester) {
  495.             return new JsonResponse(['success' => false'message' => 'Applicant account not found.'], 404);
  496.         }
  497.         $result $this->get('app.account_merge_service')->confirmMerge(
  498.             $requester,
  499.             (string)$request->request->get('email'$request->query->get('email''')),
  500.             (string)$request->request->get('code'$request->query->get('code''')),
  501.             $request->getSession()
  502.         );
  503.         return new JsonResponse($result$result['success'] ? 200 422);
  504.     }
  505.     public function viewAsUserAction(Request $request$id)
  506.     {
  507.         $session $request->getSession();
  508.         $em_goc $this->getDoctrine()->getManager('company_group');
  509.         $userType $session->get(UserConstants::USER_TYPE);
  510.         $actualUserId $session->get('actualUserId'$session->get(UserConstants::USER_ID));
  511.         $actualUserName $session->get('actualUserName'$session->get(UserConstants::USER_NAME));
  512.         $actualUserType $session->get('actualUserType'$session->get(UserConstants::USER_TYPE));
  513.         $actualUserAdminLevel $session->get('actualUserAdminLevel'$session->get(UserConstants::BUDDYBEE_ADMIN_LEVEL));
  514.         $actualUserIsAdmin $session->get('actualUserIsAdmin'$session->get(UserConstants::IS_BUDDYBEE_ADMIN));
  515.         $actualUserIsModerator $session->get('actualUserIsModerator'$session->get(UserConstants::IS_BUDDYBEE_MODERATOR));
  516.         $switchToUserId $request->query->get('id'$request->request->get('id'$id));
  517.         if ($userType == UserConstants::USER_TYPE_APPLICANT) {
  518.             $user $em_goc->getRepository('CompanyGroupBundle\\Entity\\EntityApplicantDetails')->findOneBy(
  519.                 array(
  520.                     'applicantId' => $switchToUserId
  521.                 )
  522.             );
  523.             $session->set(UserConstants::USER_ID$user->getApplicantId());
  524.             $session->set(UserConstants::IS_CONSULTANT$user->getIsConsultant() == 0);
  525.             $session->set('BUDDYBEE_BALANCE'$user->getAccountBalance());
  526.             $session->set('BUDDYBEE_COIN_BALANCE'$user->getSessionCountBalance());
  527.             $session->set(UserConstants::IS_BUDDYBEE_RETAILER$user->getIsRetailer() == 0);
  528.             $session->set(UserConstants::BUDDYBEE_RETAILER_LEVEL$user->getRetailerLevel() == 0);
  529.             $session->set(UserConstants::BUDDYBEE_ADMIN_LEVEL$user->getIsAdmin() == ? (($user->getAdminLevel() != null && $user->getAdminLevel() != 0) ? $user->getAdminLevel() : 1) : ($user->getIsModerator() == 0));
  530.             $session->set(UserConstants::IS_BUDDYBEE_MODERATOR$user->getIsModerator() == 0);
  531.             $session->set(UserConstants::IS_BUDDYBEE_ADMIN$user->getIsAdmin() == 0);
  532.             // $session->set(UserConstants::SUPPLIER_ID, $user->getSupplierId());
  533.             $session->set(UserConstants::USER_TYPEUserConstants::USER_TYPE_APPLICANT);
  534.             $session->set(UserConstants::USER_EMAIL$user->getOauthEmail());
  535.             $session->set(UserConstants::USER_IMAGE$user->getImage());
  536.             $session->set(UserConstants::USER_NAME$user->getFirstName() . ' ' $user->getLastName());
  537.             $session->set(UserConstants::USER_DEFAULT_ROUTE'');
  538.             $session->set(UserConstants::USER_COMPANY_ID1);
  539.             $session->set(UserConstants::USER_COMPANY_ID_LISTjson_encode([]));
  540.             $session->set(UserConstants::USER_COMPANY_NAME_LISTjson_encode([]));
  541.             $session->set(UserConstants::USER_COMPANY_IMAGE_LISTjson_encode([]));
  542.             $session->set('userCompanyDarkVibrantList'json_encode([]));
  543.             $session->set('userCompanyVibrantList'json_encode([]));
  544.             $session->set('userCompanyLightVibrantList'json_encode([]));
  545.             $session->set(UserConstants::USER_COMPANY_IMAGE_LISTjson_encode([]));
  546.             $session->set(UserConstants::USER_APP_ID0);
  547.             $session->set(UserConstants::USER_POSITION_LIST'[]');
  548.             $session->set(UserConstants::ALL_MODULE_ACCESS_FLAG0);
  549.             $session->set(UserConstants::SESSION_SALTuniqid(mt_rand()));
  550.             $session->set(UserConstants::APPLICATION_SECRET$this->container->getParameter('secret'));
  551.             $session->set(UserConstants::USER_NOTIFICATION_ENABLEDGeneralConstant::NOTIFICATION_ENABLED == ? ($this->getParameter('notification_enabled') == 0) : 0);
  552.             $session->set(UserConstants::USER_NOTIFICATION_SERVER$this->getParameter('notification_server'));
  553.             $session->set('oAuthToken'$request->request->get('oAuthToken'''));
  554.             $session->set('locale'$request->request->get('locale'''));
  555.             $session->set('firebaseToken'$request->request->get('firebaseToken'''));
  556.             $session->set('actualUserId'$actualUserId);
  557.             $session->set('actualUserName'$actualUserName);
  558.             $session->set('actualUserType'$actualUserType);
  559.             $session->set('actualUserAdminLevel'$actualUserAdminLevel);
  560.             $session->set('actualUserIsAdmin'$actualUserIsAdmin);
  561.             $session->set('actualUserIsModerator'$actualUserIsModerator);
  562.             $route_list_array = [];
  563.             $session->set(UserConstants::USER_CURRENT_POSITION0);
  564. //            $userAppIds = json_decode($user->getUserAppIds(), true);
  565.             $userAppIds = [];
  566.             $userSuspendedAppIds json_decode($user->getUserSuspendedAppIds(), true);
  567.             $userTypesByAppIds json_decode($user->getUserTypesByAppIds(), true);
  568.             if ($userAppIds == null$userAppIds = [];
  569.             if ($userSuspendedAppIds == null$userSuspendedAppIds = [];
  570.             if ($userTypesByAppIds == null$userTypesByAppIds = [];
  571.             foreach ($userTypesByAppIds as $aid => $accData)
  572.                 if (in_array($aid$userSuspendedAppIds))
  573.                     unset($userTypesByAppIds[$aid]);
  574.                 else
  575.                     $userAppIds[]=$aid;
  576. //            $userAppIds=array_diff($userAppIds,$userSuspendedAppIds);
  577.             $gocList $em_goc
  578.                 ->getRepository("CompanyGroupBundle\\Entity\\CompanyGroup")
  579.                 ->findBy(
  580.                     array(//                        'active' => 1
  581.                         'appId'=>$userAppIds
  582.                     )
  583.                 );
  584.             $gocDataList = [];
  585.             $gocDataListForLoginWeb = [];
  586.             $gocDataListByAppId = [];
  587.             $accessList=[];
  588.             foreach ($gocList as $entry) {
  589.                 $d = array(
  590.                     'name' => $entry->getName(),
  591.                     'image' => $entry->getImage(),
  592.                     'id' => $entry->getId(),
  593.                     'appId' => $entry->getAppId(),
  594.                     'skipInWebFlag' => $entry->getSkipInWebFlag(),
  595.                     'skipInAppFlag' => $entry->getSkipInAppFlag(),
  596.                     'dbName' => $entry->getDbName(),
  597.                     'dbUser' => $entry->getDbUser(),
  598.                     'dbPass' => $entry->getDbPass(),
  599.                     'dbHost' => $entry->getDbHost(),
  600.                     'companyGroupServerAddress' => $entry->getCompanyGroupServerAddress(),
  601.                     'companyGroupServerId' => $entry->getCompanyGroupServerId(),
  602.                     'companyGroupServerPort' => $entry->getCompanyGroupServerPort(),
  603.                     'companyRemaining' => $entry->getCompanyRemaining(),
  604.                     'companyAllowed' => $entry->getCompanyAllowed(),
  605.                 );
  606.                 $gocDataList[$entry->getId()] = $d;
  607.                 if (in_array($entry->getSkipInWebFlag(), [0null]))
  608.                     $gocDataListForLoginWeb[$entry->getId()] = $d;
  609.                 $gocDataListByAppId[$entry->getAppId()] = $d;
  610.             }
  611.             foreach ($userTypesByAppIds as $thisUserAppId => $thisUserUserTypes) {
  612.                 foreach ($thisUserUserTypes as $thisUserUserType) {
  613.                     if (isset($gocDataListByAppId[$thisUserAppId])) {
  614.                         $userTypeName = isset(UserConstants::$userTypeName[$thisUserUserType]) ? UserConstants::$userTypeName[$thisUserUserType] : 'Unknown';
  615.                         $d = array(
  616.                             'userType' => $thisUserUserType,
  617. //                                        'userTypeName' => UserConstants::$userTypeName[$thisUserUserType],
  618.                             'userTypeName' => $userTypeName,
  619.                             'globalId' => $user->getApplicantId(),
  620.                             'serverId' => $gocDataListByAppId[$thisUserAppId]['companyGroupServerId'],
  621.                             'serverUrl' => $gocDataListByAppId[$thisUserAppId]['companyGroupServerAddress'],
  622.                             'serverPort' => $gocDataListByAppId[$thisUserAppId]['companyGroupServerPort'],
  623.                             'systemType' => '_ERP_',
  624.                             'companyId' => 1,
  625.                             'appId' => $thisUserAppId,
  626.                             'companyLogoUrl' => $gocDataListByAppId[$thisUserAppId]['image'],
  627.                             'companyName' => $gocDataListByAppId[$thisUserAppId]['name'],
  628.                             'authenticationStr' => $this->get('url_encryptor')->encrypt(json_encode(
  629.                                     array(
  630.                                         'globalId' => $user->getApplicantId(),
  631.                                         'appId' => $thisUserAppId,
  632.                                         'authenticate' => 1,
  633.                                         'userType' => $thisUserUserType,
  634.                                         'userTypeName' => $userTypeName
  635.                                     )
  636.                                 )
  637.                             ),
  638.                             'userCompanyList' => [
  639.                             ]
  640.                         );
  641.                         $accessList[] = $d;
  642.                     }
  643.                 }
  644.             }
  645.             $session_data['userAccessList'] = $accessList;
  646.             $session->set('userAccessList',$accessList);
  647.             $loginID 0;
  648. //            $loginID = MiscActions::addEntityUserLoginLog(
  649. //                $em_goc,
  650. //                $session->get(UserConstants::USER_ID),
  651. //                $session->get(UserConstants::USER_ID),
  652. //                1,
  653. //                $request->server->get("REMOTE_ADDR"),
  654. //                0,
  655. //                $request->request->get('deviceId', ''),
  656. //                $request->request->get('oAuthToken', ''),
  657. //                $request->request->get('oAuthType', ''),
  658. //                $request->request->get('locale', ''),
  659. //                $request->request->get('firebaseToken', '')
  660. //
  661. //            );
  662. //            $session->set(UserConstants::USER_LOGIN_ID, $loginID);
  663.             if ($request->request->has('referer_path')) {
  664.                 if ($request->request->get('referer_path') != '/' && $request->request->get('referer_path') != '') {
  665.                     return $this->redirect($request->request->get('referer_path'));
  666.                 }
  667.             }
  668.             $redirectRoute 'central_landing';
  669.             return $this->redirectToRoute($redirectRoute);
  670.         }
  671.     }
  672.     public function CentralGetHirePageAction(Request $request,$id=0)
  673.     {
  674.         $em $this->getDoctrine()->getManager('company_group');
  675.         $session $request->getSession();
  676.         $consultantDetails $em->getRepository(EntityApplicantDetails::class)->find($session->get(UserConstants::USER_ID));
  677.         $consultantRequirementsQry $em->getRepository(EntityCountryConsultantRequirements::class)->findAll();
  678.         $subscribed false;
  679.         $consultantRequirementsByCountryId = [];
  680.         foreach ($consultantRequirementsQry as $value) {
  681.             $docList json_decode($value->getDocumentList(), true);
  682.             $requiredFields json_decode($value->getRequiredFields(), true);
  683.             if ($docList == null$docList = [];
  684.             if ($requiredFields == null$requiredFields = [];
  685.             $consultantRequirementsByCountryId[$value->getCountryId()] = array(
  686.                 'documentList' => $docList,
  687.                 'requiredFields' => $requiredFields,
  688.                 'contractLetterHtml' => $value->getContractLetterHtml(),
  689.             );
  690.         }
  691.         $documentLists $em->getRepository('CompanyGroupBundle\\Entity\\EntityCreateDocument')->findAll();;
  692.         $docListArray = [];
  693.         foreach ($documentLists as $document) {
  694.             $docListArray [$document->getId()] = array(
  695.                 'id' => $document->getId(),
  696.                 'docName' => $document->getDocumentName(),
  697.                 'expiryDays' => $document->getExpiryDays(),
  698.                 'processingDays' => $document->getProcessingDays(),
  699.                 'emergencyProcessingDays' => $document->getEmergencyProcessingDays(),
  700.                 'checklist' => json_decode($document->getCheckList()),
  701.             );
  702.         }
  703.         $skillDetails $em->getRepository(EntitySkill::class)->findAll();
  704.         $companyId $this->getLoggedUserCompanyId($request);
  705.         $gender HumanResourceConstant::$sex;
  706.         $blood HumanResourceConstant::$BloodGroup;
  707.         $userId $session->get(UserConstants::USER_ID);
  708.         $education = array(
  709.             'instituteName' => $request->get('instituteName'),
  710.             'courseOfStudy' => $request->get('courseOfStudy'),
  711.             'courseStartDate' => $request->get('courseStartDate'),
  712.             'courseEndDate' => $request->get('courseEndDate'),
  713.             'result' => $request->get('result'),
  714.             'grade' => $request->get('grade'),
  715.             'degree' => $request->get('degree'),
  716.         );
  717.         $workExperience = array(
  718.             'title' => $request->get('title'),
  719.             'companyName' => $request->get('companyName'),
  720.             'jobStartDate' => $request->get('jobStartDate'),
  721.             'jobEndDate' => $request->get('jobEndDate'),
  722.             'description' => $request->get('workDescription'),
  723.         );
  724.         $certificate = array(
  725.             'certificatename' => $request->get('certificatename'),
  726.             'issuedDate' => $request->get('issuedDate'),
  727.         );
  728.         $courses = array(
  729.             'courseName' => $request->get('courseName'),
  730.             'date' => $request->get('date'),
  731.             'duration' => $request->get('duration')
  732.         );
  733.         if ($request->isMethod('POST')) {
  734.             if ($consultantDetails)
  735.                 $consultant $consultantDetails;
  736.             else
  737.                 $consultant = new EntityApplicantDetails();
  738.             $consultant->setApplicationText($request->request->get('applicationText'));
  739.             $consultant->setFirstname($request->request->get('firstname'));
  740.             $consultant->setLastname($request->request->get('lastname'));
  741.             $consultant->setIsImgLegal($request->request->get('is_img_legal'));
  742.             $consultant->setNid($request->request->get('nid'));
  743.             $consultant->setDob(new \DateTime($request->get('dob')));
  744.             $consultant->setSex($request->request->get('sex'));
  745.             $consultant->setFather($request->request->get('father'));
  746.             $consultant->setMother($request->request->get('mother'));
  747.             $consultant->setBlood($request->request->get('blood'));
  748.             $consultant->setPhone($request->request->get('phone'));
  749.             $consultant->setCountry($request->request->get('country'));
  750.             $consultant->setCurrentCountryId($request->request->get('currentCountryId'));
  751.             $consultant->setCountryId($request->request->get('currentCountryId'));
  752.             $consultant->setPostalCode($request->request->get('postalCode'));
  753.             $consultant->setDescription($request->request->get('description'));
  754.             $consultant->setCurrAddr($request->request->get('curr_addr'));
  755.             $consultant->setSkill(json_encode($request->request->get('skill')));
  756.             $consultant->setEmergencyContactNumber($request->request->get('emm_contact'));
  757.             $consultant->setEmail($request->request->get('oauth_email'));
  758.             $consultant->setCurrentEmployment($request->request->get('currentEmployment'));
  759.             $consultant->setTin($request->request->get('tin'));
  760.             $consultant->setEducationData(json_encode($education));
  761.             $consultant->setWorkExperienceData(json_encode($workExperience));
  762.             $consultant->setCertificateData(json_encode($certificate));
  763.             $consultant->setCoursesData(json_encode($courses));
  764.             $consultant->setWorkExperienceText($request->request->get('workExperience'));
  765.             $consultant->setUniversityText($request->request->get('universityText'));
  766.             $consultant->setEducationText($request->request->get('educationText'));
  767.             $consultant->setExperienceText($request->request->get('experienceText'));
  768.             $consultant->setSkillstext($request->request->get('skillText'));
  769.             $consultant->setSpeciality($request->request->get('speciality'));
  770.             $consultant->setDescription($request->request->get('aboutMe'));
  771.             $consultant->setApplyForConsultant(1);
  772.             $consultant->setApplyForConsultantDate(new \DateTime());
  773.             $em->persist($consultant);
  774.             $em->flush();
  775.             $subscribed true;
  776.         }
  777.         return $this->render('@HoneybeeWeb/pages/get_hire.html.twig', array(
  778.             'page_title' => 'Get Hired',
  779.             'gender' => $gender,
  780.             'blood' => $blood,
  781.             'consultantDetails' => $consultantDetails,
  782.             'consultantRequirementsByCountryId' => $consultantRequirementsByCountryId,
  783.             'docListArray' => $docListArray,
  784.             'education' => json_decode($consultantDetails->getEducationData(), true),
  785.             'workExperience' => json_decode($consultantDetails->getWorkExperienceData(), true),
  786.             'certificate' => json_decode($consultantDetails->getCertificateData(), true),
  787.             'courses' => json_decode($consultantDetails->getCoursesData(), true),
  788.             'languages' => json_decode($consultantDetails->getLanguagesData(), true),
  789.             'skillDetails' => $skillDetails,
  790.             'subscribed' => $subscribed,
  791.         ));
  792.     }
  793.     public function createTopicAction(Request $request,$id =0){
  794.         $em $this->getDoctrine()->getManager('company_group');
  795.         if ($request->isMethod('POST')) {
  796.             $entityTopic = new EntityCreateTopic();
  797.             $entityTopic->setTopicName($request->request->get('catName'));
  798.             $em->persist($entityTopic);
  799.             $em->flush();
  800.         }
  801.         $topicDetails =  $em->getRepository('CompanyGroupBundle\\Entity\\EntityCreateTopic')->findAll();
  802.         return $this->render('@HoneybeeWeb/pages/create_topic.html.twig', [
  803.             'page_title' => 'Create Category',
  804.             'topics' => $topicDetails
  805.         ]);
  806.     }
  807.     public function createBlogAction(Request $request$id 0)
  808.     {
  809.         $em $this->getDoctrine()->getManager('company_group');
  810.         // ── Soft Delete ──────────────────────────────────────────────────
  811.         if ($request->isMethod('POST') && $request->request->get('_action') === 'delete') {
  812.             $blog $em->getRepository('CompanyGroupBundle\Entity\EntityCreateBlog')->find($id);
  813.             if (!$blog) {
  814.                 throw $this->createNotFoundException('Blog not found');
  815.             }
  816.             $blog->setDeleteFlag(true);
  817.             $em->flush();
  818.             return $this->redirectToRoute('honeybee_blog', ['action' => 'create']);
  819.         }
  820.         // ── Find or new ───────────────────────────────────────────────────
  821.         if ($id 0) {
  822.             $new $em->getRepository('CompanyGroupBundle\Entity\EntityCreateBlog')->find($id);
  823.             if (!$new || $new->getDeleteFlag()) {
  824.                 throw $this->createNotFoundException('Blog not found');
  825.             }
  826.         } else {
  827.             $new = new \CompanyGroupBundle\Entity\EntityCreateBlog();
  828.         }
  829.         $topicDetails $em->getRepository('CompanyGroupBundle\Entity\EntityCreateTopic')->findAll();
  830.         if ($request->isMethod('POST')) {
  831.             $new->setTopicId($request->request->get('topicId'));
  832.             $new->setTitle($request->request->get('blogTitle'));
  833.             $new->setContent($request->request->get('blogContent'));
  834.             if ($id == 0) {
  835.                 $session $request->getSession();
  836.                 $userName $session->get(UserConstants::USER_NAME);
  837.                 if ($userName) {
  838.                     $new->setAuthorName($userName);
  839.                 }
  840.             }
  841.             $em->persist($new);
  842.             $em->flush();
  843.             $upl_dir $this->container->getParameter('kernel.root_dir') . '/../web/uploads/BlogImages/';
  844.             $uploadedFile $request->files->get('blogImage'null);
  845.             if ($uploadedFile != null) {
  846.                 $fileName 'p' $new->getId() . '.' $uploadedFile->guessExtension();
  847.                 if (!file_exists($upl_dir)) {
  848.                     mkdir($upl_dir0777true);
  849.                 }
  850.                 $uploadedFile->move($upl_dir$fileName);
  851.                 $new->setMainImage('uploads/BlogImages/' $fileName);
  852.                 $em->flush();
  853.             }
  854.             return $this->redirectToRoute($request->attributes->get('_route'), ['id' => $new->getId()]);
  855.         }
  856.         // ── List: exclude soft-deleted ────────────────────────────────────
  857.         $blogDetails $em->getRepository('CompanyGroupBundle\Entity\EntityCreateBlog')
  858.             ->createQueryBuilder('b')
  859.             ->where('b.deleteFlag != :status')
  860.             ->orWhere('b.deleteFlag IS NULL')
  861.             ->setParameter('status'true)
  862.             ->getQuery()
  863.             ->getResult();
  864.         return $this->render('@HoneybeeWeb/pages/create_blog.html.twig', [
  865.             'page_title' => ($id 0) ? 'Edit Blog' 'Create Blog',
  866.             'blogs'  => $blogDetails,
  867.             'topics' => $topicDetails,
  868.             'blog'   => $new,
  869.         ]);
  870.     }
  871.     public function LoggedInUserAction(Request $request): JsonResponse
  872.     {
  873.         $session $request->getSession();
  874.         $userId $session->get(UserConstants::APPLICANT_ID);
  875.         $token $session->get(UserConstants::USER_TOKEN);
  876. //        $providedToken = $request->headers->get('auth-token');
  877. //        return new JsonResponse([$token,$providedToken,$userId]);
  878. //        if (empty($providedToken) || $providedToken !== $token) {
  879. //            return new JsonResponse([
  880. //                'status' => 'error',
  881. //                'message' => 'Token mismatched or missing',
  882. //            ], 401);
  883. //        }
  884.         try {
  885.             $em_goc $this->getDoctrine()->getManager('company_group');
  886.             $applicant $em_goc->getRepository('CompanyGroupBundle\\Entity\\EntityApplicantDetails')
  887.                 ->findOneBy(
  888.                     array(
  889.                         'applicantId' => $userId
  890.                     )
  891.                 );
  892.             if (!$applicant->getApplicantId()) {
  893.                 return new JsonResponse([
  894.                     'success' => false,
  895.                     'error' => [
  896.                         'code' => 'USER_NOT_FOUND',
  897.                         'message' => 'Applicant not found for the current session',
  898.                         'statusCode' => 404,
  899.                     ]
  900.                 ], 404);
  901.             }
  902.             $educationDataRaw json_decode($applicant->getEducationData(), true);
  903.             $workExperienceDataRaw json_decode($applicant->getWorkExperienceData(), true);
  904.             $certificateDataRaw json_decode($applicant->getCertificateData(), true);
  905.             $absoluteUrl $this->generateUrl('dashboard', [], UrlGenerator::ABSOLUTE_URL);
  906.             $userImage $session->get(UserConstants::USER_IMAGE);
  907.             $educationData = [];
  908.             if ($educationDataRaw && isset($educationDataRaw['instituteName'])) {
  909.                 $count count($educationDataRaw['instituteName']);
  910.                 for ($i 0$i $count$i++) {
  911.                     $educationData[] = [
  912.                         'instituteName' => $educationDataRaw['instituteName'][$i] ?? '',
  913.                         'courseOfStudy' => $educationDataRaw['courseOfStudy'][$i] ?? '',
  914.                         'courseStartDate' => $educationDataRaw['courseStartDate'][$i] ?? '',
  915.                         'courseEndDate' => $educationDataRaw['courseEndDate'][$i] ?? '',
  916.                         'result' => $educationDataRaw['result'][$i] ?? '',
  917.                         'grade' => $educationDataRaw['grade'][$i] ?? '',
  918.                         'degree' => $educationDataRaw['degree'][$i] ?? '',
  919.                     ];
  920.                 }
  921.             }
  922.             $workExperienceData = [];
  923.             if ($workExperienceDataRaw && isset($workExperienceDataRaw['title'])) {
  924.                 $count count($workExperienceDataRaw['title']);
  925.                 for ($i 0$i $count$i++) {
  926.                     $workExperienceData[] = [
  927.                         'title' => $workExperienceDataRaw['title'][$i] ?? '',
  928.                         'companyName' => $workExperienceDataRaw['companyName'][$i] ?? '',
  929.                         'jobStartDate' => $workExperienceDataRaw['jobStartDate'][$i] ?? '',
  930.                         'jobEndDate' => $workExperienceDataRaw['jobEndDate'][$i] ?? '',
  931.                         'description' => $workExperienceDataRaw['description'][$i] ?? '',
  932.                     ];
  933.                 }
  934.             }
  935.             $certificateData = [];
  936.             if ($certificateDataRaw && isset($certificateDataRaw['certificatename'])) {
  937.                 $count count($certificateDataRaw['certificatename']);
  938.                 for ($i 0$i $count$i++) {
  939.                     $certificateData[] = [
  940.                         'certificatename' => $certificateDataRaw['certificatename'][$i] ?? '',
  941.                         'issuedDate' => $certificateDataRaw['issuedDate'][$i] ?? '',
  942.                     ];
  943.                 }
  944.             }
  945.             $data = [
  946.                 'id' => $applicant->getApplicantId(),
  947.                 'username' => $applicant->getUsername(),
  948.                 'email' => $applicant->getEmail(),
  949.                 'firstname' => $applicant->getFirstname(),
  950.                 'lastname' => $applicant->getLastname(),
  951.                 'phone' => $applicant->getPhone(),
  952.                 'accountStatus' => $applicant->getAccountStatus(),
  953.                 'educationData' => $educationData,
  954.                 'workExperienceData' => $workExperienceData,
  955.                 'certificateData' => $certificateData,
  956.                 'skill' => [
  957.                     'php',
  958.                     'java'
  959.                 ],
  960.                 'jobDone' => 3,
  961.                 'pointsEarned' => 200,
  962.                 'reviews' => 4.8,
  963.                 'userImage' => $absoluteUrl '' $userImage
  964.             ];
  965.             $data['Contract'] = [
  966.                 'supplierName' => 'test',
  967.                 'Date' => '25-10-2025',
  968.                 'Summary' => 'summary'
  969.             ];
  970.             return new JsonResponse([
  971.                 'success' => true,
  972.                 'data' => $data,
  973.             ]);
  974.         }
  975.         catch (\Exception $e) {
  976.             return new JsonResponse([
  977.                 'success' => false,
  978.                 'error' => [
  979.                     'code' => 'INTERNAL_ERROR',
  980.                     'message' => 'Something went wrong',
  981.                     'statusCode' => 500,
  982.                 ]
  983.             ], 500);
  984.         }
  985.     }
  986.     public function summaryPlanAction(Request $request)
  987.     {
  988.         $em_goc $this->getDoctrine()->getManager('company_group');
  989.         $session $request->getSession();
  990.         $userId $session->get(UserConstants::USER_ID);
  991.         $invoiceDetails $em_goc->getRepository('CompanyGroupBundle\Entity\EntityInvoice')->findBy(
  992.             [
  993.                 'applicantId' => $userId,
  994.             ]
  995.         );
  996.         return $this->render('@HoneybeeWeb/pages/summaryPlan.html.twig', [
  997.             'page_title' => 'Invoice Summary',
  998.             'invoiceDetails' => $invoiceDetails,
  999.         ]);
  1000.     }
  1001. }