src/ApplicationBundle/Controller/HumanResourceController.php line 3038

Open in your IDE?
  1. <?php
  2. namespace ApplicationBundle\Controller;
  3. use ApplicationBundle\Constants\BuddybeeConstant;
  4. use ApplicationBundle\Constants\GeneralConstant;
  5. use ApplicationBundle\Constants\HumanResourceConstant;
  6. use ApplicationBundle\Constants\MeetingSchedulingConstant;
  7. use ApplicationBundle\Entity\AttendanceAmendment;
  8. use ApplicationBundle\Entity\BankList;
  9. use ApplicationBundle\Entity\BonusPolicy;
  10. use ApplicationBundle\Entity\Branch;
  11. use ApplicationBundle\Entity\ConsultancyTopic;
  12. use ApplicationBundle\Entity\EducationQualification;
  13. use ApplicationBundle\Entity\Employee;
  14. use ApplicationBundle\Entity\EmployeeAttendance;
  15. use ApplicationBundle\Entity\EmployeeAttendanceLog;
  16. use ApplicationBundle\Entity\EmployeeDetails;
  17. use ApplicationBundle\Entity\EmployeeLeaveApplication;
  18. use ApplicationBundle\Entity\EvaluationCategory;
  19. use ApplicationBundle\Entity\HolidayCalendar;
  20. use ApplicationBundle\Entity\HolidayCalendarDates;
  21. use ApplicationBundle\Entity\IncrementPolicy;
  22. use ApplicationBundle\Entity\LeaveSettings;
  23. use ApplicationBundle\Entity\PayrollPolicy;
  24. use ApplicationBundle\Entity\PlanningItem;
  25. use ApplicationBundle\Entity\Questionnaire;
  26. use ApplicationBundle\Entity\ScheduledMeeting;
  27. use ApplicationBundle\Entity\Skill;
  28. use ApplicationBundle\Entity\SysDepartment;
  29. use ApplicationBundle\Entity\SysDepartmentPosition;
  30. use ApplicationBundle\Entity\SysUser;
  31. use ApplicationBundle\Entity\TrainingCourse;
  32. use ApplicationBundle\Entity\WorkHourPolicy;
  33. use ApplicationBundle\Helper\ResponseStructure;
  34. use ApplicationBundle\Interfaces\SessionCheckInterface;
  35. use ApplicationBundle\Modules\Accounts\Accounts;
  36. use ApplicationBundle\Modules\Authentication\Constants\UserConstants;
  37. use ApplicationBundle\Modules\Buddybee\Buddybee;
  38. use ApplicationBundle\Modules\HumanResource\HumanResource;
  39. use ApplicationBundle\Modules\HumanResource\HumanResourceHelper;
  40. use ApplicationBundle\Modules\Inventory\Inventory;
  41. use ApplicationBundle\Modules\Sales\Client;
  42. use ApplicationBundle\Modules\System\DeleteDocument;
  43. use ApplicationBundle\Modules\System\DocValidation;
  44. use ApplicationBundle\Modules\System\MiscActions;
  45. use ApplicationBundle\Modules\System\System;
  46. use ApplicationBundle\Modules\User\Company;
  47. use CompanyGroupBundle\Entity\EntityApplicantDetails;
  48. use CompanyGroupBundle\Entity\EntityCountryConsultantRequirements;
  49. use CompanyGroupBundle\Entity\EntityCreateBlog;
  50. use CompanyGroupBundle\Entity\EntityCreateDocument;
  51. use CompanyGroupBundle\Entity\EntityCreateTopic;
  52. use CompanyGroupBundle\Entity\EntityFile;
  53. use CompanyGroupBundle\Entity\EntityInvoice;
  54. use CompanyGroupBundle\Entity\EntitySkill;
  55. use CompanyGroupBundle\Entity\PromoCode;
  56. use CompanyGroupBundle\Modules\ApplicantM;
  57. use DateTime;
  58. use Ps\PdfBundle\Annotation\Pdf;
  59. use Symfony\Component\HttpFoundation\JsonResponse;
  60. use Symfony\Component\HttpFoundation\Request;
  61. use Symfony\Component\HttpFoundation\Response;
  62. use Symfony\Component\Routing\Generator\UrlGenerator;
  63. use Throwable;
  64. //use Symfony\Bundle\FrameworkBundle\Console\Application;
  65. //use Symfony\Component\Console\Input\ArrayInput;
  66. //use Symfony\Component\Console\Output\NullOutput;
  67. class HumanResourceController extends GenericController implements SessionCheckInterface
  68. {
  69. //temporary for adding session
  70.     public function CheckoutPageAction(Request $request$encData '')
  71.     {
  72.         $em $this->getDoctrine()->getManager('company_group');
  73.         $em_goc $this->getDoctrine()->getManager('company_group');
  74.         $sandBoxMode $this->container->hasParameter('sand_box_mode') ? $this->container->getParameter('sand_box_mode') : 0;
  75.         $systemType $this->container->getParameter('system_type') ?: '_CENTRAL_';
  76.         $invoiceId $request->request->get('invoiceId'$request->query->get('invoiceId'0));
  77.         if ($encData != "") {
  78.             $encryptedData json_decode($this->get('url_encryptor')->decrypt($encData), true);
  79.             if ($encryptedData == null$encryptedData = [];
  80.             if (isset($encryptedData['invoiceId'])) $invoiceId $encryptedData['invoiceId'];
  81.         }
  82.         $session $request->getSession();
  83.         $currencyForGateway 'eur';
  84.         $gatewayInvoice null;
  85.         if ($invoiceId != 0)
  86.             $gatewayInvoice $em->getRepository(EntityInvoice::class)->find($invoiceId);
  87.         $paymentGateway $request->request->get('paymentGateway''stripe'); //aamarpay,bkash
  88.         $paymentType $request->request->get('paymentType''credit');
  89.         $retailerId $request->request->get('retailerId'0);
  90.         if ($request->query->has('currency'))
  91.             $currencyForGateway $request->query->get('currency');
  92.         else
  93.             $currencyForGateway $request->request->get('currency''eur');
  94. //        {
  95. //            if ($request->query->has('meetingSessionId'))
  96. //                $id = $request->query->get('meetingSessionId');
  97. //        }
  98.         $currentUserBalance 0;
  99.         $currentUserCoinBalance 0;
  100.         $gatewayAmount 0;
  101.         $redeemedAmount 0;
  102.         $redeemedSessionCount 0;
  103.         $toConsumeSessionCount 0;
  104.         $invoiceSessionCount 0;
  105.         $payableAmount 0;
  106.         $promoClaimedAmount 0;
  107.         $promoCodeId 0;
  108.         $promoClaimedSession 0;
  109.         $bookingExpireTime null;
  110.         $bookingExpireTs 0;
  111.         $imageBypackageId = [
  112.             => "https://www.buddybee.eu/buddybee_assets/ADULT-BEE.png",
  113.             => "https://www.buddybee.eu/buddybee_assets/ADULT-BEE.png",
  114.             => "https://www.buddybee.eu/buddybee_assets/ADULT-BEE.png",
  115.             => "https://www.buddybee.eu/buddybee_assets/ADULT-BEE.png",
  116.             => "https://www.buddybee.eu/buddybee_assets/ADULT-BEE.png",
  117.             => "https://www.buddybee.eu/buddybee_assets/ADULT-BEE.png",
  118.         ];
  119.         $imageBySessionCount = [
  120.             => "https://www.buddybee.eu/buddybee_assets/ADULT-BEE.png",
  121.             100 => "https://www.buddybee.eu/buddybee_assets/ADULT-BEE.png",
  122.             200 => "https://www.buddybee.eu/buddybee_assets/ADULT-BEE.png",
  123.             300 => "https://www.buddybee.eu/buddybee_assets/ADULT-BEE.png",
  124.             400 => "https://www.buddybee.eu/buddybee_assets/ADULT-BEE.png",
  125.             500 => "https://www.buddybee.eu/buddybee_assets/ADULT-BEE.png",
  126.             600 => "https://www.buddybee.eu/buddybee_assets/ADULT-BEE.png",
  127.             700 => "https://www.buddybee.eu/buddybee_assets/ADULT-BEE.png",
  128.             800 => "https://www.buddybee.eu/buddybee_assets/ADULT-BEE.png",
  129.             900 => "https://www.buddybee.eu/buddybee_assets/ADULT-BEE.png",
  130.             1000 => "https://www.buddybee.eu/buddybee_assets/ADULT-BEE.png",
  131.             1100 => "https://www.buddybee.eu/buddybee_assets/ADULT-BEE.png",
  132.             1200 => "https://www.buddybee.eu/buddybee_assets/ADULT-BEE.png",
  133.             1300 => "https://www.buddybee.eu/buddybee_assets/ADULT-BEE.png",
  134.             1400 => "https://www.buddybee.eu/buddybee_assets/ADULT-BEE.png",
  135.             1500 => "https://www.buddybee.eu/buddybee_assets/ADULT-BEE.png",
  136.             1600 => "https://www.buddybee.eu/buddybee_assets/ADULT-BEE.png",
  137.             1700 => "https://www.buddybee.eu/buddybee_assets/ADULT-BEE.png",
  138.             1800 => "https://www.buddybee.eu/buddybee_assets/ADULT-BEE.png",
  139.             1900 => "https://www.buddybee.eu/buddybee_assets/ADULT-BEE.png",
  140.             2000 => "https://www.buddybee.eu/buddybee_assets/ADULT-BEE.png",
  141.             2100 => "https://www.buddybee.eu/buddybee_assets/ADULT-BEE.png",
  142.             2200 => "https://www.buddybee.eu/buddybee_assets/ADULT-BEE.png",
  143.             2300 => "https://www.buddybee.eu/buddybee_assets/ADULT-BEE.png",
  144.             2400 => "https://www.buddybee.eu/buddybee_assets/ADULT-BEE.png",
  145.             2500 => "https://www.buddybee.eu/buddybee_assets/ADULT-BEE.png",
  146.             2600 => "https://www.buddybee.eu/buddybee_assets/ADULT-BEE.png",
  147.             2700 => "https://www.buddybee.eu/buddybee_assets/ADULT-BEE.png",
  148.             2800 => "https://www.buddybee.eu/buddybee_assets/ADULT-BEE.png",
  149.             2900 => "https://www.buddybee.eu/buddybee_assets/ADULT-BEE.png",
  150.             3000 => "https://www.buddybee.eu/buddybee_assets/ADULT-BEE.png",
  151.             3100 => "https://www.buddybee.eu/buddybee_assets/ADULT-BEE.png",
  152.             3200 => "https://www.buddybee.eu/buddybee_assets/ADULT-BEE.png",
  153.             3300 => "https://www.buddybee.eu/buddybee_assets/ADULT-BEE.png",
  154.             3400 => "https://www.buddybee.eu/buddybee_assets/ADULT-BEE.png",
  155.             3500 => "https://www.buddybee.eu/buddybee_assets/ADULT-BEE.png",
  156.             3600 => "https://www.buddybee.eu/buddybee_assets/ADULT-BEE.png",
  157.             3700 => "https://www.buddybee.eu/buddybee_assets/ADULT-BEE.png",
  158.         ];
  159.         if (!$gatewayInvoice) {
  160.             if ($request->isMethod('POST')) {
  161.                 $totalAmount 0;
  162.                 $totalSessionCount 0;
  163.                 $consumedAmount 0;
  164.                 $consumedSessionCount 0;
  165.                 $bookedById 0;
  166.                 $bookingRefererId 0;
  167.                 if ($session->get(UserConstants::USER_ID)) {
  168.                     $bookedById $session->get(UserConstants::USER_ID);
  169.                     $bookingRefererId 0;
  170. //                    $toConsumeSessionCount = 1 * $request->request->get('meetingSessionConsumeCount', 0);
  171.                     $invoiceSessionCount * ($request->request->get('sessionCount'0) == '' $request->request->get('sessionCount'0));
  172.                     //1st do the necessary
  173.                     $extMeeting null;
  174.                     $meetingSessionId 0;
  175.                     $dataAppId $request->request->get('appId'$session->get(UserConstants::USER_APP_ID));
  176.                     $expireTsAddition $request->request->get('expireTsAddition',
  177.                         $request->request->get('billingFrequency'2) == 30 24 3600 365 24 2600
  178.                     );
  179.                     $expireTsModification $request->request->get('expireTsModification'0);
  180.                     $userAddition $request->request->get('userAddition'0);
  181.                     $userModification $request->request->get('userModification'0);
  182.                     $adminAddition $request->request->get('adminAddition'0);
  183.                     $adminModification $request->request->get('adminModification'0);
  184.                     $packageId $request->request->get('packageId'1);
  185.                     $successActionData = [
  186.                         'appId' => $dataAppId,
  187.                         'packageId' => $packageId,
  188.                         'expireTsAddition' => $expireTsAddition,/// can also be - if needed
  189.                         'expireTsModification' => $expireTsModification,/// can also be - if needed
  190.                         'userAddition' => $userAddition,/// can also be - if needed
  191.                         'userModification' => $userModification,/// can also be - if needed
  192.                         'adminAddition' => $adminAddition,/// can also be - if needed
  193.                         'adminModification' => $adminModification,/// can also be - if needed
  194.                     ];
  195.                     $expireActonData = [
  196.                     ];
  197.                     if ($request->request->has('purchasePackage')) {
  198.                         //1. check if any bee card if yes try to claim it , modify current balance then
  199.                         $beeCodeSerial $request->request->get('beeCodeSerial''');
  200.                         $promoCode $request->request->get('promoCode''');
  201.                         $beeCodePin $request->request->get('beeCodePin''');
  202.                         $userId $request->request->get('userId'$session->get(UserConstants::USER_ID));
  203.                         $studentDetails null;
  204.                         $studentDetails $em_goc->getRepository(EntityApplicantDetails::class)->find($userId);
  205.                         if ($studentDetails) {
  206.                             $currentUserBalance $studentDetails->getAccountBalance();
  207.                         }
  208.                         if ($beeCodeSerial != '' && $beeCodePin != '') {
  209.                             $claimData MiscActions::ClaimBeeCode($em,
  210.                                 [
  211.                                     'claimFlag' => 1,
  212.                                     'pin' => $beeCodePin,
  213.                                     'serial' => $beeCodeSerial,
  214.                                     'userId' => $userId,
  215.                                 ]);
  216.                             if ($userId == $session->get(UserConstants::USER_ID)) {
  217.                                 MiscActions::RefreshBuddybeeBalanceOnSession($em$request->getSession());
  218.                                 $claimData['newCoinBalance'] = $session->get('BUDDYBEE_COIN_BALANCE');
  219.                                 $claimData['newBalance'] = $session->get('BUDDYBEE_BALANCE');
  220.                             }
  221.                             $redeemedAmount $claimData['data']['claimedAmount'];
  222.                             $redeemedSessionCount $claimData['data']['claimedCoin'];
  223.                         } else
  224.                             if ($userId == $session->get(UserConstants::USER_ID)) {
  225.                                 MiscActions::RefreshBuddybeeBalanceOnSession($em$request->getSession());
  226.                             }
  227.                         $payableAmount round($request->request->get('payableAmount'0), 0);
  228.                         $totalAmountWoDiscount round($request->request->get('totalAmountWoDiscount'0), 0);
  229.                         //now claim and process promocode
  230.                         if ($promoCode != '') {
  231.                             $claimData MiscActions::ClaimPromoCode($em,
  232.                                 [
  233.                                     'claimFlag' => 1,
  234.                                     'promoCode' => $promoCode,
  235.                                     'decryptedPromoCodeData' => json_decode($this->get('url_encryptor')->decrypt($promoCode), true),
  236.                                     'orderValue' => $totalAmountWoDiscount,
  237.                                     'currency' => $currencyForGateway,
  238.                                     'orderCoin' => $invoiceSessionCount,
  239.                                     'userId' => $userId,
  240.                                 ]);
  241.                             $promoClaimedAmount 0;
  242. //                            $promoClaimedAmount = $claimData['data']['claimedAmount']*(BuddybeeConstant::$convMultFromTo['eur'][$currencyForGateway]);
  243.                             $promoCodeId $claimData['promoCodeId'];
  244.                             $promoClaimedSession $claimData['data']['claimedCoin'];
  245.                         }
  246.                         if ($userId == $session->get(UserConstants::USER_ID)) {
  247.                             MiscActions::RefreshBuddybeeBalanceOnSession($em$request->getSession());
  248.                             $currentUserBalance $session->get('BUDDYBEE_BALANCE');
  249.                             $currentUserCoinBalance $session->get('BUDDYBEE_COIN_BALANCE');
  250.                         } else {
  251.                             if ($bookingRefererId == 0)
  252.                                 $bookingRefererId $session->get(UserConstants::USER_ID);
  253.                             $studentDetails $em_goc->getRepository(EntityApplicantDetails::class)->find($userId);
  254.                             if ($studentDetails) {
  255.                                 $currentUserBalance $studentDetails->getAccountBalance();
  256.                                 $currentUserCoinBalance $studentDetails->getSessionCountBalance();
  257.                                 if ($bookingRefererId != $userId && $bookingRefererId != 0) {
  258.                                     $bookingReferer $em_goc->getRepository(EntityApplicantDetails::class)->find($bookingRefererId);
  259.                                     if ($bookingReferer)
  260.                                         if ($bookingReferer->getIsAdmin()) {
  261.                                             $studentDetails->setAssignedSalesRepresentativeId($bookingRefererId);
  262.                                             $em_goc->flush();
  263.                                         }
  264.                                 }
  265.                             }
  266.                         }
  267.                         //2. check if any promo code  if yes add it to promo discount
  268.                         //3. check if scheule is still temporarily booked if not return that you cannot book it
  269.                         Buddybee::ExpireAnyMeetingSessionIfNeeded($em);
  270.                         Buddybee::ExpireAnyEntityInvoiceIfNeeded($em);
  271. //                        if ($request->request->get('autoAssignMeetingSession', 0) == 1
  272. //                            && $request->request->get('consultancyScheduleId', 0) != 0
  273. //                            && $request->request->get('consultancyScheduleId', 0) != ''
  274. //                        )
  275.                         {
  276.                             //1st check if a meeting session exxists with same TS, student id , consultant id
  277. //                            $scheduledStartTime = new \DateTime('@' . $request->request->get('consultancyScheduleId', ''));
  278. //                            $extMeeting = $em->getRepository('CompanyGroupBundle:EntityMeetingSession')
  279. //                                ->findOneBy(
  280. //                                    array(
  281. //                                        'scheduledTimeTs' => $scheduledStartTime->format('U'),
  282. //                                        'consultantId' => $request->request->get('consultantId', 0),
  283. //                                        'studentId' => $request->request->get('studentId', 0),
  284. //                                        'durationAllowedMin' => $request->request->get('meetingSessionScheduledDuration', BuddybeeConstant::PER_SESSION_MINUTE),
  285. //                                    )
  286. //                                );
  287. //                            if ($extMeeting) {
  288. //                                $new = $extMeeting;
  289. //                                $meetingSessionId = $new->getSessionId();
  290. //                                $periodMarker = $scheduledStartTime->format('Ym');
  291. //
  292. //                            }
  293. //                            else {
  294. //
  295. //
  296. //                                $scheduleValidity = MiscActions::CheckIfScheduleCanBeConfirmed(
  297. //                                    $em,
  298. //                                    $request->request->get('consultantId', 0),
  299. //                                    $request->request->get('studentId', 0),
  300. //                                    $scheduledStartTime->format('U'),
  301. //                                    $request->request->get('meetingSessionScheduledDuration', BuddybeeConstant::PER_SESSION_MINUTE),
  302. //                                    1
  303. //                                );
  304. //
  305. //                                if (!$scheduleValidity) {
  306. //                                    $url = $this->generateUrl(
  307. //                                        'consultant_profile'
  308. //                                    );
  309. //                                    $output = [
  310. //
  311. //                                        'proceedToCheckout' => 0,
  312. //                                        'message' => 'Session Booking Expired or not Found!',
  313. //                                        'errorFlag' => 1,
  314. //                                        'redirectUrl' => $url . '/' . $request->request->get('consultantId', 0)
  315. //                                    ];
  316. //                                    return new JsonResponse($output);
  317. //                                }
  318. //                                $new = new EntityMeetingSession();
  319. //
  320. //                                $new->setTopicId($request->request->get('consultancyTopic', 0));
  321. //                                $new->setConsultantId($request->request->get('consultantId', 0));
  322. //                                $new->setStudentId($request->request->get('studentId', 0));
  323. //                                $consultancyTopic = $em_goc->getRepository(EntityCreateTopic::class)->find($request->request->get('consultancyTopic', 0));
  324. //                                $new->setMeetingType($consultancyTopic ? $consultancyTopic->getMeetingType() : 0);
  325. //                                $new->setConsultantCanUpload($consultancyTopic ? $consultancyTopic->getConsultantCanUpload() : 0);
  326. //
  327. //
  328. //                                $scheduledEndTime = new \DateTime($request->request->get('scheduledTime', ''));
  329. //                                $scheduledEndTime = $scheduledEndTime->modify('+' . $request->request->get('meetingSessionScheduledDuration', 30) . ' minute');
  330. //
  331. //                                //$new->setScheduledTime($request->request->get('setScheduledTime'));
  332. //                                $new->setScheduledTime($scheduledStartTime);
  333. //                                $new->setDurationAllowedMin($request->request->get('meetingSessionScheduledDuration', 30));
  334. //                                $new->setDurationLeftMin($request->request->get('meetingSessionScheduledDuration', 30));
  335. //                                $new->setSessionExpireDate($scheduledEndTime);
  336. //                                $new->setSessionExpireDateTs($scheduledEndTime->format('U'));
  337. //                                $new->setEquivalentSessionCount($request->request->get('meetingSessionConsumeCount', 0));
  338. //                                $new->setMeetingSpecificNote($request->request->get('meetingSpecificNote', ''));
  339. //
  340. //                                $new->setUsableSessionCount($request->request->get('meetingSessionConsumeCount', 0));
  341. //                                $new->setRedeemSessionCount($request->request->get('meetingSessionConsumeCount', 0));
  342. //                                $new->setMeetingActionFlag(0);// no action waiting for meeting
  343. //                                $new->setScheduledTime($scheduledStartTime);
  344. //                                $new->setScheduledTimeTs($scheduledStartTime->format('U'));
  345. //                                $new->setPayableAmount($request->request->get('payableAmount', 0));
  346. //                                $new->setDueAmount($request->request->get('dueAmount', 0));
  347. //                                //$new->setScheduledTime(new \DateTime($request->get('setScheduledTime')));
  348. //                                //$new->setPcakageDetails(json_encode(($request->request->get('packageData'))));
  349. //                                $new->setPackageName(($request->request->get('packageName', '')));
  350. //                                $new->setPcakageDetails(($request->request->get('packageData', '')));
  351. //                                $new->setScheduleId(($request->request->get('consultancyScheduleId', 0)));
  352. //                                $currentUnixTime = new \DateTime();
  353. //                                $currentUnixTimeStamp = $currentUnixTime->format('U');
  354. //                                $studentId = $request->request->get('studentId', 0);
  355. //                                $consultantId = $request->request->get('consultantId', 0);
  356. //                                $new->setMeetingRoomId(str_pad($consultantId, 4, STR_PAD_LEFT) . $currentUnixTimeStamp . str_pad($studentId, 4, STR_PAD_LEFT));
  357. //                                $new->setSessionValue(($request->request->get('sessionValue', 0)));
  358. ////                        $new->setIsPayment(0);
  359. //                                $new->setConsultantIsPaidFull(0);
  360. //
  361. //                                if ($bookingExpireTs == 0) {
  362. //
  363. //                                    $bookingExpireTime = new \DateTime();
  364. //                                    $currTime = new \DateTime();
  365. //                                    $currTimeTs = $currTime->format('U');
  366. //                                    $bookingExpireTs = (1 * $scheduledStartTime->format('U')) - (24 * 3600);
  367. //                                    if ($bookingExpireTs < $currTimeTs) {
  368. //                                        if ((1 * $scheduledStartTime->format('U')) - $currTimeTs > (12 * 3600))
  369. //                                            $bookingExpireTs = (1 * $scheduledStartTime->format('U')) - (2 * 3600);
  370. //                                        else
  371. //                                            $bookingExpireTs = (1 * $scheduledStartTime->format('U'));
  372. //                                    }
  373. //
  374. ////                                    $bookingExpireTs = $bookingExpireTime->format('U');
  375. //                                }
  376. //
  377. //                                $new->setPaidSessionCount(0);
  378. //                                $new->setBookedById($bookedById);
  379. //                                $new->setBookingRefererId($bookingRefererId);
  380. //                                $new->setDueSessionCount($request->request->get('meetingSessionConsumeCount', 0));
  381. //                                $new->setExpireIfUnpaidTs($bookingExpireTs);
  382. //                                $new->setBookingExpireTs($bookingExpireTs);
  383. //                                $new->setConfirmationExpireTs($bookingExpireTs);
  384. //                                $new->setIsPaidFull(0);
  385. //                                $new->setIsExpired(0);
  386. //
  387. //
  388. //                                $em_goc->persist($new);
  389. //                                $em_goc->flush();
  390. //                                $meetingSessionId = $new->getSessionId();
  391. //                                $periodMarker = $scheduledStartTime->format('Ym');
  392. //                                MiscActions::UpdateSchedulingRestrictions($em_goc, $consultantId, $periodMarker, (($request->request->get('meetingSessionScheduledDuration', 30)) / 60), -(($request->request->get('meetingSessionScheduledDuration', 30)) / 60));
  393. //                            }
  394.                         }
  395.                         //4. if after all this stages passed then calcualte gateway payable
  396.                         if ($request->request->get('isRecharge'0) == 1) {
  397.                             if (($redeemedAmount $promoClaimedAmount) >= $payableAmount) {
  398.                                 $payableAmount = ($redeemedAmount $promoClaimedAmount);
  399.                                 $gatewayAmount 0;
  400.                             } else
  401.                                 $gatewayAmount $payableAmount - ($redeemedAmount $promoClaimedAmount);
  402.                         } else {
  403. //                            if ($toConsumeSessionCount <= $currentUserCoinBalance && $invoiceSessionCount <= $toConsumeSessionCount) {
  404. //                                $payableAmount = 0;
  405. //                                $gatewayAmount = 0;
  406. //                            } else if (($redeemedAmount + $promoClaimedAmount) >= $payableAmount) {
  407. //                                $payableAmount = ($redeemedAmount + $promoClaimedAmount);
  408. //                                $gatewayAmount = 0;
  409. //                            } else
  410.                             $gatewayAmount $payableAmount <= ($currentUserBalance + ($redeemedAmount $promoClaimedAmount)) ? : ($payableAmount $currentUserBalance - ($redeemedAmount $promoClaimedAmount));
  411.                         }
  412.                         $gatewayAmount round($gatewayAmount2);
  413.                         $dueAmount round($request->request->get('dueAmount'$payableAmount), 0);
  414.                         if ($request->request->has('gatewayProductData'))
  415.                             $gatewayProductData $request->request->get('gatewayProductData');
  416.                         $gatewayProductData = [[
  417.                             'price_data' => [
  418.                                 'currency' => $currencyForGateway,
  419.                                 'unit_amount' => $gatewayAmount != ? ((100 $gatewayAmount) / 1) : 200000,
  420.                                 'product_data' => [
  421. //                            'name' => $request->request->has('packageName') ? $request->request->get('packageName') : 'Advanced Consultancy Package',
  422.                                     'name' => 'HoneyBee Hive Subscription- '.GeneralConstant::$packageDetails[$packageId]['packageName'],
  423.                                     'images' => [$imageBypackageId[$packageId]],
  424.                                 ],
  425.                             ],
  426.                             'quantity' =>  1,
  427.                         ]];
  428.                         $new_invoice null;
  429. //                        if ($extMeeting) {
  430. //                            $new_invoice = $em->getRepository('CompanyGroupBundle:EntityInvoice')
  431. //                                ->findOneBy(
  432. //                                    array(
  433. //                                        'invoiceType' => $request->request->get('invoiceType', BuddybeeConstant::ENTITY_INVOICE_TYPE_PAYMENT_TO_HONEYBEE),
  434. //                                        'meetingId' => $extMeeting->getSessionId(),
  435. //                                    )
  436. //                                );
  437. //                        }
  438.                         if ($new_invoice) {
  439.                         } else {
  440.                             $new_invoice = new EntityInvoice();
  441.                             $invoiceDate = new \DateTime();
  442.                             $new_invoice->setInvoiceDate($invoiceDate);
  443.                             $new_invoice->setInvoiceDateTs($invoiceDate->format('U'));
  444.                             $new_invoice->setStudentId($userId);
  445.                             $new_invoice->setBillerId($retailerId == $retailerId);
  446.                             $new_invoice->setRetailerId($retailerId);
  447.                             $new_invoice->setBillToId($userId);
  448.                             $new_invoice->setAmountTransferGateWayHash($paymentGateway);
  449.                             $new_invoice->setAmountCurrency($currencyForGateway);
  450.                             $cardIds $request->request->get('cardIds', []);
  451.                             $new_invoice->setMeetingId($meetingSessionId);
  452.                             $new_invoice->setGatewayBillAmount($gatewayAmount);
  453.                             $new_invoice->setRedeemedAmount($redeemedAmount);
  454.                             $new_invoice->setPromoDiscountAmount($promoClaimedAmount);
  455.                             $new_invoice->setPromoCodeId($promoCodeId);
  456.                             $new_invoice->setRedeemedSessionCount($redeemedSessionCount);
  457.                             $new_invoice->setPaidAmount($payableAmount $dueAmount);
  458.                             $new_invoice->setProductDataForPaymentGateway(json_encode($gatewayProductData));
  459.                             $new_invoice->setDueAmount($dueAmount);
  460.                             $new_invoice->setInvoiceType($request->request->get('invoiceType'BuddybeeConstant::ENTITY_INVOICE_TYPE_PAYMENT_TO_HONEYBEE));
  461.                             $new_invoice->setDocumentHash(MiscActions::GenerateRandomCrypto('BEI' microtime(true)));
  462.                             $new_invoice->setCardIds(json_encode($cardIds));
  463.                             $new_invoice->setAmountType($request->request->get('amountType'1));
  464.                             $new_invoice->setAmount($payableAmount);
  465.                             $new_invoice->setConsumeAmount($payableAmount);
  466.                             $new_invoice->setSessionCount($invoiceSessionCount);
  467.                             $new_invoice->setConsumeSessionCount($toConsumeSessionCount);
  468.                             $new_invoice->setIsPaidfull(0);
  469.                             $new_invoice->setIsProcessed(0);
  470.                             $new_invoice->setApplicantId($userId);
  471.                             $new_invoice->setBookedById($bookedById);
  472.                             $new_invoice->setBookingRefererId($bookingRefererId);
  473.                             $new_invoice->setIsRecharge($request->request->get('isRecharge'0));
  474.                             $new_invoice->setAutoConfirmTaggedMeeting($request->request->get('autoConfirmTaggedMeeting'0));
  475.                             $new_invoice->setAutoConfirmOtherMeeting($request->request->get('autoConfirmOtherMeeting'0));
  476.                             $new_invoice->setAutoClaimPurchasedCards($request->request->get('autoClaimPurchasedCards'0));
  477.                             $new_invoice->setIsPayment(0); //0 means receive
  478.                             $new_invoice->setStatus(GeneralConstant::ACTIVE); //0 means receive
  479.                             $new_invoice->setStage(BuddybeeConstant::ENTITY_INVOICE_STAGE_INITIATED); //0 means receive
  480.                             $new_invoice->setSuccessActionData(json_encode($successActionData)); //0 means receive
  481.                             if ($bookingExpireTs == 0) {
  482.                                 $bookingExpireTime = new \DateTime();
  483.                                 $bookingExpireTime->modify('+30 day');
  484.                                 $bookingExpireTs $bookingExpireTime->format('U');
  485.                             }
  486.                             $new_invoice->setExpireIfUnpaidTs($bookingExpireTs);
  487.                             $new_invoice->setBookingExpireTs($bookingExpireTs);
  488.                             $new_invoice->setConfirmationExpireTs($bookingExpireTs);
  489. //            $new_invoice->setStatus($request->request->get(0));
  490.                             $em_goc->persist($new_invoice);
  491.                             $em_goc->flush();
  492.                         }
  493.                         $invoiceId $new_invoice->getId();
  494.                         $gatewayInvoice $new_invoice;
  495.                         if ($request->request->get('isRecharge'0) == 1) {
  496.                         } else {
  497.                             if ($gatewayAmount <= 0) {
  498.                                 $meetingId 0;
  499.                                 if ($invoiceId != 0) {
  500.                                     $retData Buddybee::ProcessEntityInvoice($em_goc$invoiceId, ['stage' => BuddybeeConstant::ENTITY_INVOICE_STAGE_COMPLETED],
  501.                                         $this->container->getParameter('kernel.root_dir'),
  502.                                         false,
  503.                                         $this->container->getParameter('notification_enabled'),
  504.                                         $this->container->getParameter('notification_server')
  505.                                     );
  506.                                     $meetingId $retData['meetingId'];
  507.                                 }
  508.                                 MiscActions::RefreshBuddybeeBalanceOnSession($em$request->getSession());
  509.                                 if (GeneralConstant::EMAIL_ENABLED == 1) {
  510.                                     $billerDetails = [];
  511.                                     $billToDetails = [];
  512.                                     $invoice $gatewayInvoice;
  513.                                     if ($invoice) {
  514.                                         $billerDetails $em->getRepository('CompanyGroupBundle:EntityApplicantDetails')
  515.                                             ->findOneBy(
  516.                                                 array(
  517.                                                     'applicantId' => $invoice->getBillerId(),
  518.                                                 )
  519.                                             );
  520.                                         $billToDetails $em->getRepository('CompanyGroupBundle:EntityApplicantDetails')
  521.                                             ->findOneBy(
  522.                                                 array(
  523.                                                     'applicantId' => $invoice->getBillToId(),
  524.                                                 )
  525.                                             );
  526.                                     }
  527.                                     $bodyTemplate 'ApplicationBundle:email/templates:buddybeeInvoiceEmail.html.twig';
  528.                                     $bodyData = array(
  529.                                         'page_title' => 'Invoice',
  530. //            'studentDetails' => $student,
  531.                                         'billerDetails' => $billerDetails,
  532.                                         'billToDetails' => $billToDetails,
  533.                                         'invoice' => $invoice,
  534.                                         'currencyList' => BuddybeeConstant::$currency_List,
  535.                                         'currencyListByMarker' => BuddybeeConstant::$currency_List_by_marker,
  536.                                     );
  537.                                     $attachments = [];
  538.                                     $forwardToMailAddress $billToDetails->getOAuthEmail();
  539. //                    $upl_dir = $this->container->getParameter('kernel.root_dir') . '/../web/uploads/temp/' . 'ledger' . '.pdf'
  540.                                     $new_mail $this->get('mail_module');
  541.                                     $new_mail->sendMyMail(array(
  542.                                         'senderHash' => '_CUSTOM_',
  543.                                         //                        'senderHash'=>'_CUSTOM_',
  544.                                         'forwardToMailAddress' => $forwardToMailAddress,
  545.                                         '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 ',
  546. //                        'fileName' => 'Order#' . str_pad($id, 8, '0', STR_PAD_LEFT) . '.pdf',
  547.                                         'attachments' => $attachments,
  548.                                         'toAddress' => $forwardToMailAddress,
  549.                                         'fromAddress' => 'no-reply@buddybee.eu',
  550.                                         'userName' => 'no-reply@buddybee.eu',
  551.                                         'password' => 'Honeybee@0112',
  552.                                         'smtpServer' => 'smtp.hostinger.com',
  553.                                         'smtpPort' => 465,
  554. //                            'emailBody' => $bodyHtml,
  555.                                         'mailTemplate' => $bodyTemplate,
  556.                                         'templateData' => $bodyData,
  557.                                         'embedCompanyImage' => 0,
  558.                                         'companyId' => 0,
  559.                                         'companyImagePath' => ''
  560. //                        'embedCompanyImage' => 1,
  561. //                        'companyId' => $companyId,
  562. //                        'companyImagePath' => $company_data->getImage()
  563.                                     ));
  564.                                 }
  565.                                 if ($meetingId != 0) {
  566.                                     $url $this->generateUrl(
  567.                                         'consultancy_session'
  568.                                     );
  569.                                     $output = [
  570.                                         'invoiceId' => $gatewayInvoice->getId(),
  571.                                         'meetingId' => $meetingId,
  572.                                         'proceedToCheckout' => 0,
  573.                                         'redirectUrl' => $url '/' $meetingId
  574.                                     ];
  575.                                 } else {
  576.                                     $url $this->generateUrl(
  577.                                         $systemType == '_BUDDYBEE_' 'buddybee_dashboard' 'central_landing'
  578.                                     );
  579.                                     $output = [
  580.                                         'invoiceId' => $gatewayInvoice->getId(),
  581.                                         'meetingId' => 0,
  582.                                         'proceedToCheckout' => 0,
  583.                                         'redirectUrl' => $url
  584.                                     ];
  585.                                 }
  586.                                 return new JsonResponse($output);
  587. //                return $this->redirect($url);
  588.                             } else {
  589.                             }
  590. //                $url = $this->generateUrl(
  591. //                    'checkout_page'
  592. //                );
  593. //
  594. //                return $this->redirect($url."?meetingSessionId=".$new->getSessionId().'&invoiceId='.$invoiceId);
  595.                         }
  596.                     }
  597.                 } else {
  598.                     $url $this->generateUrl(
  599.                         'user_login'
  600.                     );
  601.                     $session->set('LAST_REQUEST_URI_BEFORE_LOGIN'$this->generateUrl(
  602.                         'pricing_plan_page', [
  603.                         'autoRedirected' => 1
  604.                     ],
  605.                         UrlGenerator::ABSOLUTE_URL
  606.                     ));
  607.                     $output = [
  608.                         'proceedToCheckout' => 0,
  609.                         'redirectUrl' => $url,
  610.                         'clearLs' => 0
  611.                     ];
  612.                     return new JsonResponse($output);
  613.                 }
  614.                 //now proceed to checkout page if the user has lower balance or recharging
  615.                 //$invoiceDetails = $em->getRepository('CompanyGroupBundle:EntityInvoice')->
  616.             }
  617.         }
  618.         if ($gatewayInvoice) {
  619.             $gatewayProductData json_decode($gatewayInvoice->getProductDataForPaymentGateway(), true);
  620.             if ($gatewayProductData == null$gatewayProductData = [];
  621.             if (empty($gatewayProductData))
  622.                 $gatewayProductData = [
  623.                     [
  624.                         'price_data' => [
  625.                             'currency' => 'eur',
  626.                             'unit_amount' => $gatewayAmount != ? (100 $gatewayAmount) : 200000,
  627.                             'product_data' => [
  628. //                            'name' => $request->request->has('packageName') ? $request->request->get('packageName') : 'Advanced Consultancy Package',
  629.                                 'name' => 'Bee Coins',
  630.                                 'images' => [$imageBySessionCount[0]],
  631.                             ],
  632.                         ],
  633.                         'quantity' => 1,
  634.                     ]
  635.                 ];
  636.             $productDescStr '';
  637.             $productDescArr = [];
  638.             foreach ($gatewayProductData as $gpd) {
  639.                 $productDescArr[] = $gpd['price_data']['product_data']['name'];
  640.             }
  641.             $productDescStr implode(','$productDescArr);
  642.             $paymentGatewayFromInvoice $gatewayInvoice->getAmountTransferGateWayHash();
  643. //            return new JsonResponse(
  644. //                [
  645. //                    'paymentGateway' => $paymentGatewayFromInvoice,
  646. //                    'gateWayData' => $gatewayProductData[0]
  647. //                ]
  648. //            );
  649.             if ($paymentGateway == null$paymentGatewayFromInvoice 'stripe';
  650.             if ($paymentGatewayFromInvoice == 'stripe' || $paymentGatewayFromInvoice == 'aamarpay' || $paymentGatewayFromInvoice == 'bkash') {
  651.                 if (GeneralConstant::EMAIL_ENABLED == 1) {
  652.                     $billerDetails = [];
  653.                     $billToDetails = [];
  654.                     $invoice $gatewayInvoice;
  655.                     if ($invoice) {
  656.                         $billerDetails $em->getRepository('CompanyGroupBundle:EntityApplicantDetails')
  657.                             ->findOneBy(
  658.                                 array(
  659.                                     'applicantId' => $invoice->getBillerId(),
  660.                                 )
  661.                             );
  662.                         $billToDetails $em->getRepository('CompanyGroupBundle:EntityApplicantDetails')
  663.                             ->findOneBy(
  664.                                 array(
  665.                                     'applicantId' => $invoice->getBillToId(),
  666.                                 )
  667.                             );
  668.                     }
  669.                     $bodyTemplate 'ApplicationBundle:email/templates:buddybeeInvoiceEmail.html.twig';
  670.                     $bodyData = array(
  671.                         'page_title' => 'Invoice',
  672. //            'studentDetails' => $student,
  673.                         'billerDetails' => $billerDetails,
  674.                         'billToDetails' => $billToDetails,
  675.                         'invoice' => $invoice,
  676.                         'currencyList' => BuddybeeConstant::$currency_List,
  677.                         'currencyListByMarker' => BuddybeeConstant::$currency_List_by_marker,
  678.                     );
  679.                     $attachments = [];
  680.                     $forwardToMailAddress $billToDetails->getOAuthEmail();
  681. //                    $upl_dir = $this->container->getParameter('kernel.root_dir') . '/../web/uploads/temp/' . 'ledger' . '.pdf'
  682.                     $new_mail $this->get('mail_module');
  683.                     $new_mail->sendMyMail(array(
  684.                         'senderHash' => '_CUSTOM_',
  685.                         //                        'senderHash'=>'_CUSTOM_',
  686.                         'forwardToMailAddress' => $forwardToMailAddress,
  687.                         '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 ',
  688. //                        'fileName' => 'Order#' . str_pad($id, 8, '0', STR_PAD_LEFT) . '.pdf',
  689.                         'attachments' => $attachments,
  690.                         'toAddress' => $forwardToMailAddress,
  691.                         'fromAddress' => 'no-reply@buddybee.eu',
  692.                         'userName' => 'no-reply@buddybee.eu',
  693.                         'password' => 'Honeybee@0112',
  694.                         'smtpServer' => 'smtp.hostinger.com',
  695.                         'smtpPort' => 465,
  696. //                            'emailBody' => $bodyHtml,
  697.                         'mailTemplate' => $bodyTemplate,
  698.                         'templateData' => $bodyData,
  699.                         'embedCompanyImage' => 0,
  700.                         'companyId' => 0,
  701.                         'companyImagePath' => ''
  702. //                        'embedCompanyImage' => 1,
  703. //                        'companyId' => $companyId,
  704. //                        'companyImagePath' => $company_data->getImage()
  705.                     ));
  706.                 }
  707.             }
  708.             if ($paymentGatewayFromInvoice == 'stripe') {
  709.                 $stripe = new \Stripe\Stripe();
  710.                 \Stripe\Stripe::setApiKey('sk_test_51IxYTAJXs21fVb0QMop2Nb0E7u9Da4LwGrym1nGHUHqaSNtT3p9HBgHd7YyDsTKHscgPPECPQniTy79Ab8Sgxfbm00JF2AndUz');
  711.                 $stripe::setApiKey('sk_test_51IxYTAJXs21fVb0QMop2Nb0E7u9Da4LwGrym1nGHUHqaSNtT3p9HBgHd7YyDsTKHscgPPECPQniTy79Ab8Sgxfbm00JF2AndUz');
  712.                 {
  713.                     if ($request->query->has('meetingSessionId'))
  714.                         $id $request->query->get('meetingSessionId');
  715.                 }
  716.                 $paymentIntent = [
  717.                     "id" => "pi_1DoWjK2eZvKYlo2Csy9J3BHs",
  718.                     "object" => "payment_intent",
  719.                     "amount" => 3000,
  720.                     "amount_capturable" => 0,
  721.                     "amount_received" => 0,
  722.                     "application" => null,
  723.                     "application_fee_amount" => null,
  724.                     "canceled_at" => null,
  725.                     "cancellation_reason" => null,
  726.                     "capture_method" => "automatic",
  727.                     "charges" => [
  728.                         "object" => "list",
  729.                         "data" => [],
  730.                         "has_more" => false,
  731.                         "url" => "/v1/charges?payment_intent=pi_1DoWjK2eZvKYlo2Csy9J3BHs"
  732.                     ],
  733.                     "client_secret" => "pi_1DoWjK2eZvKYlo2Csy9J3BHs_secret_vmxAcWZxo2kt1XhpWtZtnjDtd",
  734.                     "confirmation_method" => "automatic",
  735.                     "created" => 1546523966,
  736.                     "currency" => $currencyForGateway,
  737.                     "customer" => null,
  738.                     "description" => null,
  739.                     "invoice" => null,
  740.                     "last_payment_error" => null,
  741.                     "livemode" => false,
  742.                     "metadata" => [],
  743.                     "next_action" => null,
  744.                     "on_behalf_of" => null,
  745.                     "payment_method" => null,
  746.                     "payment_method_options" => [],
  747.                     "payment_method_types" => [
  748.                         "card"
  749.                     ],
  750.                     "receipt_email" => null,
  751.                     "review" => null,
  752.                     "setup_future_usage" => null,
  753.                     "shipping" => null,
  754.                     "statement_descriptor" => null,
  755.                     "statement_descriptor_suffix" => null,
  756.                     "status" => "requires_payment_method",
  757.                     "transfer_data" => null,
  758.                     "transfer_group" => null
  759.                 ];
  760.                 $stripeDataForPaymentIntent=[
  761.                     'payment_method_types' => ['card'],
  762.                     "currency" => $currencyForGateway,
  763.                     'amount' => $gatewayAmount != ? ((100 $gatewayAmount) / 1) : 0,
  764.                 ];
  765.                 $stripeDataForCheckOut=[
  766.                     'payment_method_types' => ['card'],
  767.                     'line_items' => $gatewayProductData,
  768.                     'mode' => 'payment',
  769.                     'success_url' => $this->generateUrl(
  770.                         'payment_gateway_success',
  771.                         ['encData' => $this->get('url_encryptor')->encrypt(json_encode(array(
  772.                             'invoiceId' => $invoiceId'autoRedirect' => $request->request->get('autoRedirect'1)
  773.                         ))), 'hbeeSessionToken' => $session->get('token'0)], UrlGenerator::ABSOLUTE_URL
  774.                     ),
  775.                     'cancel_url' => $this->generateUrl(
  776.                         'payment_gateway_cancel', ['invoiceId' => $invoiceId'autoRedirect' => $request->request->get('autoRedirect'1), 'hbeeSessionToken' => $session->get('token'0)], UrlGenerator::ABSOLUTE_URL
  777.                     ),
  778.                 ];
  779.                 if( $request->attributes->get('_route')=='app_checkout_page_api') {
  780.                     $paymentIntent = \Stripe\PaymentIntent::create($stripeDataForPaymentIntent);
  781.                     $output = [
  782.                         'clientSecret' => $paymentIntent->client_secret,
  783.                         'id' => $paymentIntent->id,
  784.                         'paymentGateway' => $paymentGatewayFromInvoice,
  785.                         'proceedToCheckout' => 1,
  786.                         'paymentIntentId' =>$paymentIntent->id
  787.                     ];
  788.                 }
  789.                 else{
  790.                     $checkout_session = \Stripe\Checkout\Session::create($stripeDataForCheckOut);
  791.                     $output = [
  792.                         'clientSecret' => $checkout_session['payment_intent'],
  793.                         'id' => $checkout_session->id,
  794.                         'paymentGateway' => $paymentGatewayFromInvoice,
  795.                         'proceedToCheckout' => 1,
  796.                     ];
  797.                 }
  798.                 return new JsonResponse($output);
  799.             }
  800.             if ($paymentGatewayFromInvoice == 'aamarpay') {
  801.                 $studentDetails $em_goc->getRepository(EntityApplicantDetails::class)->find($gatewayInvoice->getBillToId());
  802.                 $url $sandBoxMode == 'https://sandbox.aamarpay.com/request.php' 'https://secure.aamarpay.com/request.php';
  803.                 $fields = array(
  804. //                    'store_id' => 'aamarpaytest', //store id will be aamarpay,  contact integration@aamarpay.com for test/live id
  805.                     'store_id' => $sandBoxMode == 'aamarpaytest' 'buddybee'//store id will be aamarpay,  contact integration@aamarpay.com for test/live id
  806.                     'amount' => $gatewayInvoice->getGateWayBillamount(), //transaction amount
  807.                     'payment_type' => 'VISA'//no need to change
  808.                     'currency' => strtoupper($currencyForGateway),  //currenct will be USD/BDT
  809.                     'tran_id' => $gatewayInvoice->getDocumentHash(), //transaction id must be unique from your end
  810.                     'cus_name' => $studentDetails->getFirstname() . ' ' $studentDetails->getLastName(),  //customer name
  811.                     'cus_email' => $studentDetails->getEmail(), //customer email address
  812.                     'cus_add1' => $studentDetails->getCurrAddr(),  //customer address
  813.                     'cus_add2' => $studentDetails->getCurrAddrCity(), //customer address
  814.                     'cus_city' => $studentDetails->getCurrAddrCity(),  //customer city
  815.                     'cus_state' => $studentDetails->getCurrAddrState(),  //state
  816.                     'cus_postcode' => $studentDetails->getCurrAddrZip(), //postcode or zipcode
  817.                     'cus_country' => 'Bangladesh',  //country
  818.                     'cus_phone' => ($studentDetails->getPhone() == null || $studentDetails->getPhone() == '') ? '+8801911706483' $studentDetails->getPhone(), //customer phone number
  819.                     'cus_fax' => '',  //fax
  820.                     'ship_name' => ''//ship name
  821.                     'ship_add1' => '',  //ship address
  822.                     'ship_add2' => '',
  823.                     'ship_city' => '',
  824.                     'ship_state' => '',
  825.                     'ship_postcode' => '',
  826.                     'ship_country' => 'Bangladesh',
  827.                     'desc' => $productDescStr,
  828.                     'success_url' => $this->generateUrl(
  829.                         'payment_gateway_success',
  830.                         ['encData' => $this->get('url_encryptor')->encrypt(json_encode(array(
  831.                             'invoiceId' => $invoiceId'autoRedirect' => $request->request->get('autoRedirect'1)
  832.                         ))), 'hbeeSessionToken' => $session->get('token'0)], UrlGenerator::ABSOLUTE_URL
  833.                     ),
  834.                     'fail_url' => $this->generateUrl(
  835.                         'payment_gateway_cancel', ['invoiceId' => $invoiceId'autoRedirect' => $request->request->get('autoRedirect'1), 'hbeeSessionToken' => $session->get('token'0)], UrlGenerator::ABSOLUTE_URL
  836.                     ),
  837.                     'cancel_url' => $this->generateUrl(
  838.                         'payment_gateway_cancel', ['invoiceId' => $invoiceId'autoRedirect' => $request->request->get('autoRedirect'1), 'hbeeSessionToken' => $session->get('token'0)], UrlGenerator::ABSOLUTE_URL
  839.                     ),
  840. //                    'opt_a' => 'Reshad',  //optional paramter
  841. //                    'opt_b' => 'Akil',
  842. //                    'opt_c' => 'Liza',
  843. //                    'opt_d' => 'Sohel',
  844. //                    'signature_key' => 'dbb74894e82415a2f7ff0ec3a97e4183',  //sandbox
  845.                     'signature_key' => $sandBoxMode == 'dbb74894e82415a2f7ff0ec3a97e4183' 'b7304a40e21fe15af3be9a948307f524'  //live
  846.                 ); //signature key will provided aamarpay, contact integration@aamarpay.com for test/live signature key
  847.                 $fields_string http_build_query($fields);
  848. //                $ch = curl_init();
  849. //                curl_setopt($ch, CURLOPT_VERBOSE, true);
  850. //                curl_setopt($ch, CURLOPT_URL, $url);
  851. //
  852. //                curl_setopt($ch, CURLOPT_POSTFIELDS, $fields_string);
  853. //                curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
  854. //                curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
  855. //                $url_forward = str_replace('"', '', stripslashes(curl_exec($ch)));
  856. //                curl_close($ch);
  857. //                $this->redirect_to_merchant($url_forward);
  858.                 $output = [
  859. //
  860. //                    'redirectUrl' => ($sandBoxMode == 1 ? 'https://sandbox.aamarpay.com/' : 'https://secure.aamarpay.com/') . $url_forward, //keeping it off temporarily
  861. //                    'fields'=>$fields,
  862. //                    'fields_string'=>$fields_string,
  863. //                    'redirectUrl' => $this->generateUrl(
  864. //                        'payment_gateway_success',
  865. //                        ['encData' => $this->get('url_encryptor')->encrypt(json_encode(array(
  866. //                            'invoiceId' => $invoiceId, 'autoRedirect' => $request->request->get('autoRedirect', 1)
  867. //                        ))), 'hbeeSessionToken' => $request->request->get('token', 0)], UrlGenerator::ABSOLUTE_URL
  868. //                    ),
  869.                     'paymentGateway' => $paymentGatewayFromInvoice,
  870.                     'proceedToCheckout' => 1,
  871.                     'data' => $fields
  872.                 ];
  873.                 return new JsonResponse($output);
  874.             } else if ($paymentGatewayFromInvoice == 'bkash') {
  875.                 $studentDetails $em_goc->getRepository(EntityApplicantDetails::class)->find($gatewayInvoice->getBillToId());
  876.                 $baseUrl = ($sandBoxMode == 1) ? 'https://tokenized.sandbox.bka.sh/v1.2.0-beta' 'https://tokenized.pay.bka.sh/v1.2.0-beta';
  877.                 $username_value = ($sandBoxMode == 1) ? 'sandboxTokenizedUser02' '01891962953';
  878.                 $password_value = ($sandBoxMode == 1) ? 'sandboxTokenizedUser02@12345' ',a&kPV4deq&';
  879.                 $app_key_value = ($sandBoxMode == 1) ? '4f6o0cjiki2rfm34kfdadl1eqq' '2ueVHdwz5gH3nxx7xn8wotlztc';
  880.                 $app_secret_value = ($sandBoxMode == 1) ? '2is7hdktrekvrbljjh44ll3d9l1dtjo4pasmjvs5vl5qr3fug4b' '49Ay3h3wWJMBFD7WF5CassyLrtA1jt6ONhspqjqFx5hTjhqh5dHU';
  881.                 $request_data = array(
  882.                     'app_key' => $app_key_value,
  883.                     'app_secret' => $app_secret_value
  884.                 );
  885.                 $url curl_init($baseUrl '/tokenized/checkout/token/grant');
  886.                 $request_data_json json_encode($request_data);
  887.                 $header = array(
  888.                     'Content-Type:application/json',
  889.                     'username:' $username_value,
  890.                     'password:' $password_value
  891.                 );
  892.                 curl_setopt($urlCURLOPT_HTTPHEADER$header);
  893.                 curl_setopt($urlCURLOPT_CUSTOMREQUEST"POST");
  894.                 curl_setopt($urlCURLOPT_RETURNTRANSFERtrue);
  895.                 curl_setopt($urlCURLOPT_POSTFIELDS$request_data_json);
  896.                 curl_setopt($urlCURLOPT_FOLLOWLOCATION1);
  897.                 curl_setopt($urlCURLOPT_IPRESOLVECURL_IPRESOLVE_V4);
  898.                 $tokenData json_decode(curl_exec($url), true);
  899.                 curl_close($url);
  900.                 $id_token $tokenData['id_token'];
  901.                 $goToBkashPage 0;
  902.                 if ($tokenData['statusCode'] == '0000') {
  903.                     $auth $id_token;
  904.                     $requestbody = array(
  905.                         "mode" => "0011",
  906. //                        "payerReference" => "01723888888",
  907.                         "payerReference" => $invoiceDate->format('U'),
  908.                         "callbackURL" => $this->generateUrl(
  909.                             'bkash_callback', [], UrlGenerator::ABSOLUTE_URL
  910.                         ),
  911. //                    "merchantAssociationInfo" => "MI05MID54RF09123456One",
  912.                         "amount" => number_format($gatewayInvoice->getGateWayBillamount(), 2'.'''),
  913.                         "currency" => "BDT",
  914.                         "intent" => "sale",
  915.                         "merchantInvoiceNumber" => $invoiceId
  916.                     );
  917.                     $url curl_init($baseUrl '/tokenized/checkout/create');
  918.                     $requestbodyJson json_encode($requestbody);
  919.                     $header = array(
  920.                         'Content-Type:application/json',
  921.                         'Authorization:' $auth,
  922.                         'X-APP-Key:' $app_key_value
  923.                     );
  924.                     curl_setopt($urlCURLOPT_HTTPHEADER$header);
  925.                     curl_setopt($urlCURLOPT_CUSTOMREQUEST"POST");
  926.                     curl_setopt($urlCURLOPT_RETURNTRANSFERtrue);
  927.                     curl_setopt($urlCURLOPT_POSTFIELDS$requestbodyJson);
  928.                     curl_setopt($urlCURLOPT_FOLLOWLOCATION1);
  929.                     curl_setopt($urlCURLOPT_IPRESOLVECURL_IPRESOLVE_V4);
  930.                     $resultdata curl_exec($url);
  931. //                    curl_close($url);
  932. //                    echo $resultdata;
  933.                     $obj json_decode($resultdatatrue);
  934.                     $goToBkashPage 1;
  935.                     $justNow = new \DateTime();
  936.                     $justNow->modify('+' $tokenData['expires_in'] . ' second');
  937.                     $gatewayInvoice->setGatewayIdTokenExpireTs($justNow->format('U'));
  938.                     $gatewayInvoice->setGatewayIdToken($tokenData['id_token']);
  939.                     $gatewayInvoice->setGatewayPaymentId($obj['paymentID']);
  940.                     $gatewayInvoice->setGatewayIdRefreshToken($tokenData['refresh_token']);
  941.                     $em->flush();
  942.                     $output = [
  943. //                        'redirectUrl' => $obj['bkashURL'],
  944.                         'paymentGateway' => $paymentGatewayFromInvoice,
  945.                         'proceedToCheckout' => $goToBkashPage,
  946.                         'tokenData' => $tokenData,
  947.                         'obj' => $obj,
  948.                         'id_token' => $tokenData['id_token'],
  949.                         'data' => [
  950.                             'amount' => $gatewayInvoice->getGateWayBillamount(), //transaction amount
  951. //                            'payment_type' => 'VISA', //no need to change
  952.                             'currency' => strtoupper($currencyForGateway),  //currenct will be USD/BDT
  953.                             'tran_id' => $gatewayInvoice->getDocumentHash(), //transaction id must be unique from your end
  954.                             'cus_name' => $studentDetails->getFirstname() . ' ' $studentDetails->getLastName(),  //customer name
  955.                             'cus_email' => $studentDetails->getEmail(), //customer email address
  956.                             'cus_add1' => $studentDetails->getCurrAddr(),  //customer address
  957.                             'cus_add2' => $studentDetails->getCurrAddrCity(), //customer address
  958.                             'cus_city' => $studentDetails->getCurrAddrCity(),  //customer city
  959.                             'cus_state' => $studentDetails->getCurrAddrState(),  //state
  960.                             'cus_postcode' => $studentDetails->getCurrAddrZip(), //postcode or zipcode
  961.                             'cus_country' => 'Bangladesh',  //country
  962.                             'cus_phone' => ($studentDetails->getPhone() == null || $studentDetails->getPhone() == '') ? '+8801911706483' $studentDetails->getPhone(), //customer phone number
  963.                             'cus_fax' => '',  //fax
  964.                             'ship_name' => ''//ship name
  965.                             'ship_add1' => '',  //ship address
  966.                             'ship_add2' => '',
  967.                             'ship_city' => '',
  968.                             'ship_state' => '',
  969.                             'ship_postcode' => '',
  970.                             'ship_country' => 'Bangladesh',
  971.                             'desc' => $productDescStr,
  972.                         ]
  973.                     ];
  974.                     return new JsonResponse($output);
  975.                 }
  976. //                $fields = array(
  977. //
  978. //                    "mode" => "0011",
  979. //                    "payerReference" => "01723888888",
  980. //                    "callbackURL" => $this->generateUrl(
  981. //                        'payment_gateway_success',
  982. //                        ['encData' => $this->get('url_encryptor')->encrypt(json_encode(array(
  983. //                            'invoiceId' => $invoiceId, 'autoRedirect' => $request->request->get('autoRedirect', 1)
  984. //                        ))), 'hbeeSessionToken' => $session->get('token', 0)], UrlGenerator::ABSOLUTE_URL
  985. //                    ),
  986. //                    "merchantAssociationInfo" => "MI05MID54RF09123456One",
  987. //                    "amount" => 1*number_format($gatewayInvoice->getGateWayBillamount(),2,'.',''),,
  988. //                    "currency" => "BDT",
  989. //                    "intent" => "sale",
  990. //                    "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)
  991. //
  992. //                );
  993. //                $fields = array(
  994. ////                    'store_id' => 'aamarpaytest', //store id will be aamarpay,  contact integration@aamarpay.com for test/live id
  995. //                    'store_id' => $sandBoxMode == 1 ? 'aamarpaytest' : 'buddybee', //store id will be aamarpay,  contact integration@aamarpay.com for test/live id
  996. //                    'amount' => 1*number_format($gatewayInvoice->getGateWayBillamount(),2,'.',''),, //transaction amount
  997. //                    'payment_type' => 'VISA', //no need to change
  998. //                    'currency' => strtoupper($currencyForGateway),  //currenct will be USD/BDT
  999. //                    '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
  1000. //                    'cus_name' => $studentDetails->getFirstname() . ' ' . $studentDetails->getLastName(),  //customer name
  1001. //                    'cus_email' => $studentDetails->getEmail(), //customer email address
  1002. //                    'cus_add1' => $studentDetails->getCurrAddr(),  //customer address
  1003. //                    'cus_add2' => $studentDetails->getCurrAddrCity(), //customer address
  1004. //                    'cus_city' => $studentDetails->getCurrAddrCity(),  //customer city
  1005. //                    'cus_state' => $studentDetails->getCurrAddrState(),  //state
  1006. //                    'cus_postcode' => $studentDetails->getCurrAddrZip(), //postcode or zipcode
  1007. //                    'cus_country' => 'Bangladesh',  //country
  1008. //                    'cus_phone' => ($studentDetails->getPhone() == null || $studentDetails->getPhone() == '') ? ' + 8801911706483' : $studentDetails->getPhone(), //customer phone number
  1009. //                    'cus_fax' => '',  //fax
  1010. //                    'ship_name' => '', //ship name
  1011. //                    'ship_add1' => '',  //ship address
  1012. //                    'ship_add2' => '',
  1013. //                    'ship_city' => '',
  1014. //                    'ship_state' => '',
  1015. //                    'ship_postcode' => '',
  1016. //                    'ship_country' => 'Bangladesh',
  1017. //                    'desc' => $productDescStr,
  1018. //                    'success_url' => $this->generateUrl(
  1019. //                        'payment_gateway_success',
  1020. //                        ['encData' => $this->get('url_encryptor')->encrypt(json_encode(array(
  1021. //                            'invoiceId' => $invoiceId, 'autoRedirect' => $request->request->get('autoRedirect', 1)
  1022. //                        ))), 'hbeeSessionToken' => $session->get('token', 0)], UrlGenerator::ABSOLUTE_URL
  1023. //                    ),
  1024. //                    'fail_url' => $this->generateUrl(
  1025. //                        'payment_gateway_cancel', ['invoiceId' => $invoiceId, 'autoRedirect' => $request->request->get('autoRedirect', 1), 'hbeeSessionToken' => $session->get('token', 0)], UrlGenerator::ABSOLUTE_URL
  1026. //                    ),
  1027. //                    'cancel_url' => $this->generateUrl(
  1028. //                        'payment_gateway_cancel', ['invoiceId' => $invoiceId, 'autoRedirect' => $request->request->get('autoRedirect', 1), 'hbeeSessionToken' => $session->get('token', 0)], UrlGenerator::ABSOLUTE_URL
  1029. //                    ),
  1030. ////                    'opt_a' => 'Reshad',  //optional paramter
  1031. ////                    'opt_b' => 'Akil',
  1032. ////                    'opt_c' => 'Liza',
  1033. ////                    'opt_d' => 'Sohel',
  1034. ////                    'signature_key' => 'dbb74894e82415a2f7ff0ec3a97e4183',  //sandbox
  1035. //                    'signature_key' => $sandBoxMode == 1 ? 'dbb74894e82415a2f7ff0ec3a97e4183' : 'b7304a40e21fe15af3be9a948307f524'  //live
  1036. //
  1037. //                ); //signature key will provided aamarpay, contact integration@aamarpay.com for test/live signature key
  1038. //
  1039. //                $fields_string = http_build_query($fields);
  1040. //
  1041. //                $ch = curl_init();
  1042. //                curl_setopt($ch, CURLOPT_VERBOSE, true);
  1043. //                curl_setopt($ch, CURLOPT_URL, $url);
  1044. //
  1045. //                curl_setopt($ch, CURLOPT_POSTFIELDS, $fields_string);
  1046. //                curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
  1047. //                curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
  1048. //                $url_forward = str_replace('"', '', stripslashes(curl_exec($ch)));
  1049. //                curl_close($ch);
  1050. //                $this->redirect_to_merchant($url_forward);
  1051.             } else if ($paymentGatewayFromInvoice == 'onsite_pos' || $paymentGatewayFromInvoice == 'onsite_cash' || $paymentGatewayFromInvoice == 'onsite_bkash') {
  1052.                 $meetingId 0;
  1053.                 if ($gatewayInvoice->getId() != 0) {
  1054.                     if ($gatewayInvoice->getDueAmount() <= 0) {
  1055.                         $retData Buddybee::ProcessEntityInvoice($em_goc$gatewayInvoice->getId(), ['stage' => BuddybeeConstant::ENTITY_INVOICE_STAGE_COMPLETED], $this->container->getParameter('kernel.root_dir'), false,
  1056.                             $this->container->getParameter('notification_enabled'),
  1057.                             $this->container->getParameter('notification_server')
  1058.                         );
  1059.                         $meetingId $retData['meetingId'];
  1060.                     }
  1061.                     if (GeneralConstant::EMAIL_ENABLED == 1) {
  1062.                         $billerDetails = [];
  1063.                         $billToDetails = [];
  1064.                         $invoice $gatewayInvoice;
  1065.                         if ($invoice) {
  1066.                             $billerDetails $em->getRepository('CompanyGroupBundle:EntityApplicantDetails')
  1067.                                 ->findOneBy(
  1068.                                     array(
  1069.                                         'applicantId' => $invoice->getBillerId(),
  1070.                                     )
  1071.                                 );
  1072.                             $billToDetails $em->getRepository('CompanyGroupBundle:EntityApplicantDetails')
  1073.                                 ->findOneBy(
  1074.                                     array(
  1075.                                         'applicantId' => $invoice->getBillToId(),
  1076.                                     )
  1077.                                 );
  1078.                         }
  1079.                         $bodyTemplate 'ApplicationBundle:email/templates:buddybeeInvoiceEmail.html.twig';
  1080.                         $bodyData = array(
  1081.                             'page_title' => 'Invoice',
  1082. //            'studentDetails' => $student,
  1083.                             'billerDetails' => $billerDetails,
  1084.                             'billToDetails' => $billToDetails,
  1085.                             'invoice' => $invoice,
  1086.                             'currencyList' => BuddybeeConstant::$currency_List,
  1087.                             'currencyListByMarker' => BuddybeeConstant::$currency_List_by_marker,
  1088.                         );
  1089.                         $attachments = [];
  1090.                         $forwardToMailAddress $billToDetails->getOAuthEmail();
  1091. //                    $upl_dir = $this->container->getParameter('kernel.root_dir') . '/../web/uploads/temp/' . 'ledger' . '.pdf'
  1092.                         $new_mail $this->get('mail_module');
  1093.                         $new_mail->sendMyMail(array(
  1094.                             'senderHash' => '_CUSTOM_',
  1095.                             //                        'senderHash'=>'_CUSTOM_',
  1096.                             'forwardToMailAddress' => $forwardToMailAddress,
  1097.                             '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 ',
  1098. //                        'fileName' => 'Order#' . str_pad($id, 8, '0', STR_PAD_LEFT) . '.pdf',
  1099.                             'attachments' => $attachments,
  1100.                             'toAddress' => $forwardToMailAddress,
  1101.                             'fromAddress' => 'no-reply@buddybee.eu',
  1102.                             'userName' => 'no-reply@buddybee.eu',
  1103.                             'password' => 'Honeybee@0112',
  1104.                             'smtpServer' => 'smtp.hostinger.com',
  1105.                             'smtpPort' => 465,
  1106. //                            'emailBody' => $bodyHtml,
  1107.                             'mailTemplate' => $bodyTemplate,
  1108.                             'templateData' => $bodyData,
  1109.                             'embedCompanyImage' => 0,
  1110.                             'companyId' => 0,
  1111.                             'companyImagePath' => ''
  1112. //                        'embedCompanyImage' => 1,
  1113. //                        'companyId' => $companyId,
  1114. //                        'companyImagePath' => $company_data->getImage()
  1115.                         ));
  1116.                     }
  1117.                 }
  1118.                 MiscActions::RefreshBuddybeeBalanceOnSession($em$request->getSession());
  1119.                 if ($meetingId != 0) {
  1120.                     $url $this->generateUrl(
  1121.                         'consultancy_session'
  1122.                     );
  1123.                     $output = [
  1124.                         'proceedToCheckout' => 0,
  1125.                         'invoiceId' => $gatewayInvoice->getId(),
  1126.                         'meetingId' => $meetingId,
  1127.                         'redirectUrl' => $url '/' $meetingId
  1128.                     ];
  1129.                 } else {
  1130.                     $url $this->generateUrl(
  1131.                         'buddybee_dashboard'
  1132.                     );
  1133.                     $output = [
  1134.                         'proceedToCheckout' => 0,
  1135.                         'invoiceId' => $gatewayInvoice->getId(),
  1136.                         'meetingId' => $meetingId,
  1137.                         'redirectUrl' => $url
  1138.                     ];
  1139.                 }
  1140.                 return new JsonResponse($output);
  1141.             }
  1142.         }
  1143.         $output = [
  1144.             'clientSecret' => 0,
  1145.             'id' => 0,
  1146.             'proceedToCheckout' => 0
  1147.         ];
  1148.         return new JsonResponse($output);
  1149. //        return $this->render('ApplicationBundle:pages/stripe:checkout.html.twig', array(
  1150. //            'page_title' => 'Checkout',
  1151. ////            'stripe' => $stripe,
  1152. //            'stripe' => null,
  1153. ////            'PaymentIntent' => $paymentIntent,
  1154. //
  1155. ////            'consultantDetail' => $consultantDetail,
  1156. ////            'consultantDetails'=> $consultantDetails,
  1157. ////
  1158. ////            'meetingSession' => $meetingSession,
  1159. ////            'packageDetails' => json_decode($meetingSession->getPcakageDetails(),true),
  1160. ////            'packageName' => json_decode($meetingSession->getPackageName(),true),
  1161. ////            'pay' => $payableAmount,
  1162. ////            'balance' => $currStudentBal
  1163. //        ));
  1164.     }
  1165.     //changes dev
  1166.     public function AddEmployeeAction(Request $data$id 0)
  1167.     {
  1168.         $em $this->getDoctrine()->getManager();
  1169.         $connection $em->getConnection();
  1170.         $connection->beginTransaction();
  1171.         $skills $em->getRepository(Skill::class)->findAll();
  1172.         $session $data->getSession();
  1173.         $ownOnly 0;
  1174.         $consultancyLevel HumanResourceConstant::$consultantLevel;
  1175.         $systemType $this->container->hasParameter('system_type') ? $this->container->getParameter('system_type') : '_ERP_';
  1176.         $banks $em->getRepository(BankList::class)->findAll();
  1177.         $bankListObj = [];
  1178.         $id $data->request->get('employeeId'$id);
  1179.         foreach ($banks as $bank) {
  1180.             $bankListObj[$bank->getBankId()] = $bank->getName();
  1181.         }
  1182.         if ($id === "my") {
  1183.             $id $session->get(UserConstants::USER_EMPLOYEE_ID);
  1184.             $ownOnly 1;
  1185.             if ($id == || $id == null) {
  1186.                 return $this->redirectToRoute('permission_denied_page');
  1187.             }
  1188.         }
  1189.         if ($id) {
  1190.             if ($data->isMethod('GET')) {
  1191.                 $Employee $this->getDoctrine()->getRepository(EmployeeDetails::class)->find($id);
  1192.                 if (!$Employee) {
  1193.                     $this->addFlash(
  1194.                         'error',
  1195.                         'Invalid User ID!'
  1196.                     );
  1197.                     return $this->redirectToRoute('add_employee');
  1198.                 } else {
  1199.                     $EmployeeRes HumanResource::TwigDataForAddEmployee($em$id);
  1200.                     $Employee $EmployeeRes['employee'];
  1201.                     $EmployeeMain $EmployeeRes['employeeMain'];
  1202.                     $sysUserId $EmployeeRes['sysId'];
  1203.                     $existingSysUser $sysUserId $em->getRepository('ApplicationBundle:SysUser')->find($sysUserId) : [];
  1204.                     $regionIdsArray json_decode($EmployeeMain->getRegionIds(), true) ?: [];
  1205.                     $regionLeaderFlagsArray json_decode($EmployeeMain->getRegionLeaderFlags(), true) ?: [];
  1206.                     $existingRegionAssociations = [];
  1207.                     if (!empty($regionIdsArray)) {
  1208.                         $regionRepo $this->getDoctrine()->getRepository('ApplicationBundle:Region');
  1209.                         $regions $regionRepo->findBy(['id' => $regionIdsArray]);
  1210.                         $regionMap = [];
  1211.                         foreach ($regions as $region) {
  1212.                             $regionMap[$region->getId()] = $region;
  1213.                         }
  1214.                         foreach ($regionIdsArray as $index => $regionId) {
  1215.                             if (!isset($regionMap[$regionId])) continue;
  1216.                             $region $regionMap[$regionId];
  1217.                             $existingRegionAssociations[] = [
  1218.                                 'regionLevelId' => $region->getRegionLevelId(),
  1219.                                 'regionId' => $region->getId(),
  1220.                                 'isLeader' => isset($regionLeaderFlagsArray[$index]) ? (int)$regionLeaderFlagsArray[$index] : 0
  1221.                             ];
  1222.                         }
  1223.                     }
  1224.                     $TwigData HumanResource::TwigDataForAddEmployee($em0);
  1225.                     return $this->render(
  1226.                         'ApplicationBundle:pages/human_resource/input_forms:add_employee.html.twig',
  1227.                         array(
  1228.                             'page_title' => 'Update Employee',
  1229.                             'ownOnly' => $ownOnly,
  1230.                             'branches' => $TwigData['branches'],
  1231.                             'bankListObj' => $bankListObj,
  1232.                             'heads' => Accounts::getLedgerHeadsWithParents($em),
  1233.                             'departments' => $TwigData['departments'],
  1234.                             'departmentPositions' => $TwigData['departmentPositions'],
  1235.                             'regions' => $TwigData['regions'],
  1236.                             'supervisors' => $TwigData['supervisors'],
  1237.                             'sysUsers' => $TwigData['sysUser'],
  1238.                             'EmploymentStatus' => $TwigData['EmploymentStatus'],
  1239.                             'sex' => $TwigData['sex'],
  1240.                             'BloodGroup' => $TwigData['BloodGroup'],
  1241.                             'days' => $TwigData['days'],
  1242.                             'employeeMain' => $EmployeeMain,
  1243.                             'employee' => $Employee,
  1244.                             'skills' => $skills,
  1245.                             'existingSysUser' => $existingSysUser,
  1246.                             'id' => $id,
  1247.                             'default_route' => $EmployeeRes['defaultRoute'],
  1248.                             'user_type' => $EmployeeRes['userType'],
  1249.                             'user_type_data' => HumanResourceConstant::$userType,
  1250.                             'AccountTypes' => $TwigData['AccountType'],
  1251.                             'weekends' => explode(','$Employee->getWeeklyHoliday()),
  1252.                             'consultancyLevel' => $consultancyLevel,
  1253.                             'module_data_array' => $TwigData['module_data_array'],
  1254.                             'HasUpdateMode' => true,
  1255.                             'brand_list' => Inventory::GetBrandList($em$this->getLoggedUserCompanyId($data)),
  1256.                             'branch_list' => Client::BranchList($this->getDoctrine()->getManager(), $this->getLoggedUserCompanyId($data)),
  1257.                             'region_data' => Client::RegionList($this->getDoctrine()->getManager(), $this->getLoggedUserCompanyId($data)),
  1258.                             'leaveSettings' => $TwigData['leaveSettings'],
  1259.                             'leaveData' => $EmployeeRes['leaveData'],
  1260.                             'positions' => $EmployeeRes['positions'],
  1261.                             'existing_region_associations' => $existingRegionAssociations
  1262.                         )
  1263.                     );
  1264.                 }
  1265.             } else {
  1266.                 $approveHash $data->request->get('approvalHash');
  1267.                 $loginId $data->getSession()->get(UserConstants::USER_LOGIN_ID);
  1268.                 $isSignatureOk DocValidation::isSignatureOk($em$loginId$approveHash);
  1269.                 $upl_dir $this->container->getParameter('kernel.root_dir') . '/../web/uploads/Users/';
  1270.                 $image $data->files->get('img');
  1271.                 $profileImage $this->uploadImage($image$data);
  1272.                 $path '';
  1273.                 if ($isSignatureOk) {
  1274.                     $CompanyId $this->getLoggedUserCompanyId($data);
  1275.                     $user $em->getRepository('ApplicationBundle:SysUser')->findOneBy(['email' => $data->get('email')]);
  1276.                     if ($user) {
  1277.                         $sysUserId $user->getUserId();
  1278.                         $message $this->get('user_module')->updateUser(
  1279.                             $sysUserId,
  1280.                             $data->request->get('firstname') . " " $data->request->get('lastname'),
  1281.                             $data->request->has('email') ? $data->request->get('email') : '_UNCHANGED_',
  1282.                             $data->request->has('username') ? $data->request->get('username') : '_UNCHANGED_',
  1283.                             $data->request->get('password'),
  1284.                             1,
  1285.                             $data->request->get('user_type''_UNCHANGED_'),
  1286.                             $data->request->get('supervisor'),
  1287.                             $data->request->get('default_route'),
  1288.                             $data->request->get('branch'),
  1289.                             $data->request->has('access_module') ? 0,
  1290.                             $data->getSession()->get(UserConstants::USER_LOGIN_ID),
  1291.                             $data->request->get('global_user_id'null),
  1292.                             $profileImage,
  1293.                             $upl_dir
  1294.                         );
  1295.                         if (isset($message[0]) && $message[0] === 'success') {
  1296.                             HumanResource::StoreDataForAddEmployee($em$data$id$CompanyId$profileImage);
  1297.                             $connection->commit();
  1298.                             if ($systemType == '_CENTRAL_') {
  1299.                             } else {
  1300.                                 $Employee $em->getRepository(Employee::class)->find($id);
  1301.                                 $EmployeeDetails $em->getRepository(EmployeeDetails::class)->findOneBy(
  1302.                                     array(
  1303.                                         'id' => $id
  1304.                                     )
  1305.                                 );
  1306.                                 $em_goc $this->getDoctrine()->getManager('company_group');
  1307.                                 $em_goc->getConnection()->connect();
  1308.                                 $connected $em_goc->getConnection()->isConnected();
  1309.                                 $gocDataList = [];
  1310.                                 $gocDataListByAppId = [];
  1311.                                 $retDataDebug = array();
  1312.                                 $appIds $message[3]->getUserAppId();
  1313.                                 $userIds $message[3]->getUserId();
  1314.                                 if ($connected) {
  1315.                                     $findByQuery = array(
  1316.                                         'active' => 1
  1317.                                     );
  1318.                                     if ($appIds !== '_UNSET_')
  1319.                                         $findByQuery['appId'] = $appIds;
  1320.                                     $gocList $this->getDoctrine()->getManager('company_group')
  1321.                                         ->getRepository("CompanyGroupBundle:CompanyGroup")
  1322.                                         ->findBy($findByQuery);
  1323.                                     foreach ($gocList as $entry) {
  1324.                                         $d = array(
  1325.                                             'name' => $entry->getName(),
  1326.                                             'id' => $entry->getId(),
  1327.                                             'image' => $entry->getImage(),
  1328.                                             'companyGroupHash' => $entry->getCompanyGroupHash(),
  1329.                                             'dbName' => $entry->getDbName(),
  1330.                                             'dbUser' => $entry->getDbUser(),
  1331.                                             'dbPass' => $entry->getDbPass(),
  1332.                                             'dbHost' => $entry->getDbHost(),
  1333.                                             'appId' => $entry->getAppId(),
  1334.                                             'companyRemaining' => $entry->getCompanyRemaining(),
  1335.                                             'companyAllowed' => $entry->getCompanyAllowed(),
  1336.                                         );
  1337.                                         $gocDataList[$entry->getId()] = $d;
  1338.                                         $gocDataListByAppId[$entry->getAppId()] = $d;
  1339.                                     }
  1340.                                     $debugCount 0;
  1341.                                     foreach ($gocDataList as $gocId => $entry) {
  1342.                                         $skipSend 1;
  1343.                                         $connector $this->container->get('application_connector');
  1344.                                         $connector->resetConnection(
  1345.                                             'default',
  1346.                                             $gocDataList[$gocId]['dbName'],
  1347.                                             $gocDataList[$gocId]['dbUser'],
  1348.                                             $gocDataList[$gocId]['dbPass'],
  1349.                                             $gocDataList[$gocId]['dbHost'],
  1350.                                             $reset true);
  1351.                                         $em $this->getDoctrine()->getManager();
  1352.                                         if ($userIds !== '_UNSET_')
  1353.                                             $users $this->getDoctrine()
  1354.                                                 ->getRepository('ApplicationBundle:SysUser')
  1355.                                                 ->findBy(
  1356.                                                     array(
  1357.                                                         'userId' => $userIds
  1358.                                                     )
  1359.                                                 );
  1360.                                         else
  1361.                                             $users $this->getDoctrine()
  1362.                                                 ->getRepository('ApplicationBundle:SysUser')
  1363.                                                 ->findBy(
  1364.                                                     array()
  1365.                                                 );
  1366.                                         $output '';
  1367.                                         $userData = array();
  1368.                                         $userFiles = array();
  1369.                                         foreach ($users as $user) {
  1370.                                             $file $this->container->getParameter('kernel.root_dir') . '/../web/' $user->getImage();
  1371.                                             if ($user->getImage() != '' && $user->getImage() != null && file_exists($file)) {
  1372.                                                 $mime mime_content_type($file);
  1373.                                                 $info pathinfo($file);
  1374.                                                 $name $info['basename'];
  1375.                                                 if (strpos($mime'image') !== false) {
  1376.                                                     $output = new \CURLFile($file$mime$name);
  1377.                                                 }
  1378.                                                 $skipSend 0;
  1379.                                                 $userFiles['file_' $user->getUserAppId() . '_' $user->getUserId()] = $output;
  1380.                                             } else {
  1381.                                                 $user->setImage(null);
  1382.                                                 $userFiles['file_' $user->getUserAppId() . '_' $user->getUserId()] = 'pika';
  1383.                                                 $em->flush();
  1384.                                             }
  1385.                                             $getters array_filter(get_class_methods($user), function ($method) {
  1386.                                                 return 'get' === substr($method03);
  1387.                                             });
  1388.                                             $userDataSingle = array();
  1389.                                             foreach ($getters as $getter) {
  1390.                                                 if ($getter == 'getCreatedAt' || $getter == 'getUpdatedAt' || $getter == 'getImage')
  1391.                                                     continue;
  1392.                                                 if ($user->{$getter}() instanceof \DateTime) {
  1393.                                                     $ggtd $user->{$getter}();
  1394.                                                     $userDataSingle[$getter] = $ggtd->format('Y-m-d');
  1395.                                                 } else
  1396.                                                     $userDataSingle[$getter] = $user->{$getter}();
  1397.                                             }
  1398.                                             $employeeGetters = array(
  1399.                                                 'getFirstname''getLastname''getImage''getIsImgLegal''getNid''getDob''getSex''getReligion''getFather',
  1400.                                                 'getMother''getSpouse''getChild1''getChild2''getBlood''getPhone''getOfficailPhone''getCurrAddr',
  1401.                                                 'getCurrAddrLat''getCurrAddrLng''getPermAddr''getEmmContact''getUsername''getEmail''getPassword',
  1402.                                                 'getUserId''getJoiningDate''getEmpValidTill''getEmpStatus''getEmpType''getEmpCode''getEmpLabel''getTin',
  1403.                                                 'getTinValidTill''getMedIns''getMedInsValidTill''getDocs''getNocApproval''getInst1''getYr1''getDur1',
  1404.                                                 'getInst2''getYr2''getDur2''getInst3''getYr3''getDur3''getEinst1''getEyr1''getEdeg1''getEinst2',
  1405.                                                 'getEyr2''getEdeg2''getEinst3''getEyr3''getEdeg3''getBankAcc''getBankAccType''getBankAccValidFrom',
  1406.                                                 'getBankAccValidTo''getRoutingCode''getSwiftCode''getEar1''getEar2''getEar3''getEar4''getEar5''getEar6',
  1407.                                                 'getEart''getDed1''getDed2''getDed3''getDed4''getDedt''getPayable''getHandCash''getBankTransfer',
  1408.                                                 'getSecDep''getSecDepSpan''getSecDepRemMon''getSecDepRemAmount''getSlQty''getSlTkn''getSlFreq''getMlQty',
  1409.                                                 'getMlTkn''getMlFreq''getElQty''getElTkn''getElFreq''getClQty''getClTkn''getClFreq''getLevt',
  1410.                                                 'getWeeklyHoliday''getFiles''getSupervisor''getDept''getDesg''getBranch''getDivision''getCreatedAt',
  1411.                                                 'getUpdatedAt''getEmployeeLevel''getSkill''getProbationaryPeriod''getDocBookedFlag''getTimeStampOfForm',
  1412.                                                 'getIsConsultant''getConsultantLevel''getApplicationText''getCurrentEmployment''getEmergencyContactNumber',
  1413.                                                 'getPostalCode''getCountry''getEducationData''getWorkExperienceData''getCertificateData''getLanguagesData',
  1414.                                                 'getBeneficiaryName''getBankName''getBranchName''getClockedIn'
  1415.                                             );
  1416.                                             foreach ($employeeGetters as $getter) {
  1417.                                                 if (!method_exists($EmployeeDetails$getter)) continue;
  1418.                                                 try {
  1419.                                                     $value $EmployeeDetails->{$getter}();
  1420.                                                     if ($value instanceof \DateTime) {
  1421.                                                         $userDataSingle[$getter] = $value->format('Y-m-d');
  1422.                                                     } elseif (is_object($value)) {
  1423.                                                         continue;
  1424.                                                     } else {
  1425.                                                         $userDataSingle[$getter] = $value;
  1426.                                                     }
  1427.                                                 } catch (\Exception $e) {
  1428.                                                     continue;
  1429.                                                 }
  1430.                                             }
  1431.                                             $userData[] = $userDataSingle;
  1432.                                         }
  1433.                                         $retDataDebug[$debugCount] = array(
  1434.                                             'skipSend' => $skipSend
  1435.                                         );
  1436.                                         {
  1437.                                             $urlToCall GeneralConstant::HONEYBEE_CENTRAL_SERVER '/SyncUserToCentralUser';
  1438.                                             $userFiles['userData'] = json_encode($userData);
  1439.                                             $curl curl_init();
  1440.                                             curl_setopt_array($curl, array(
  1441.                                                 CURLOPT_RETURNTRANSFER => 1,
  1442.                                                 CURLOPT_POST => 1,
  1443.                                                 CURLOPT_URL => $urlToCall,
  1444.                                                 CURLOPT_CONNECTTIMEOUT => 10,
  1445.                                                 CURLOPT_SSL_VERIFYPEER => false,
  1446.                                                 CURLOPT_SSL_VERIFYHOST => false,
  1447.                                                 CURLOPT_HTTPHEADER => array(),
  1448.                                                 CURLOPT_POSTFIELDS => $userFiles
  1449.                                             ));
  1450.                                             $retData curl_exec($curl);
  1451.                                             $errData curl_error($curl);
  1452.                                             curl_close($curl);
  1453.                                             $retDataObj json_decode($retDatatrue);
  1454.                                             $retDataDebug[$debugCount] = $retDataObj;
  1455.                                             if (isset($retDataObj['globalIdsData']))
  1456.                                                 foreach ($retDataObj['globalIdsData'] as $app_id => $usrList) {
  1457.                                                     $connector $this->container->get('application_connector');
  1458.                                                     $connector->resetConnection(
  1459.                                                         'default',
  1460.                                                         $gocDataListByAppId[$app_id]['dbName'],
  1461.                                                         $gocDataListByAppId[$app_id]['dbUser'],
  1462.                                                         $gocDataListByAppId[$app_id]['dbPass'],
  1463.                                                         $gocDataListByAppId[$app_id]['dbHost'],
  1464.                                                         $reset true);
  1465.                                                     $em $this->getDoctrine()->getManager();
  1466.                                                     foreach ($usrList as $sys_id => $globaldata) {
  1467.                                                         $user $this->getDoctrine()
  1468.                                                             ->getRepository('ApplicationBundle:SysUser')
  1469.                                                             ->findOneBy(
  1470.                                                                 array(
  1471.                                                                     'userId' => $sys_id
  1472.                                                                 )
  1473.                                                             );
  1474.                                                         if ($user) {
  1475.                                                             $user->setGlobalId($globaldata['gid']);
  1476.                                                             $em->flush();
  1477.                                                         }
  1478.                                                     }
  1479.                                                 }
  1480.                                         }
  1481.                                         $debugCount++;
  1482.                                     }
  1483.                                 }
  1484.                             }
  1485.                         } else {
  1486.                             $errorMsg $message['message'] ?? 'Unknown error occurred.';
  1487.                             $this->addFlash('error'$errorMsg);
  1488.                             return $this->redirectToRoute('add_employee');
  1489.                         }
  1490.                         $userType $data->getSession()->get(UserConstants::USER_TYPE);
  1491.                         $redirctUrl $this->generateUrl('employee_list', [], UrlGenerator::ABSOLUTE_URL);
  1492.                         if ($userType == 1) {
  1493.                             $redirctUrl $this->generateUrl('employee_list', [], UrlGenerator::ABSOLUTE_URL);
  1494.                         } else {
  1495.                             $redirctUrl $this->generateUrl('edit_employee', [], UrlGenerator::ABSOLUTE_URL) . '/my';
  1496.                         }
  1497.                         return new JsonResponse(array(
  1498.                             'employeeId' => $Employee->getEmployeeId(),
  1499.                             'redirectToNew' => 0,
  1500.                             'success' => true,
  1501.                             'redirectUrl' => $redirctUrl,
  1502.                         ));
  1503.                     }
  1504.                 } else {
  1505.                     $this->addFlash(
  1506.                         'error',
  1507.                         'Invalid Approval Hash!'
  1508.                     );
  1509.                     return $this->redirectToRoute('add_employee');
  1510.                 }
  1511.             }
  1512.         } else {
  1513.             if ($data->isMethod('GET')) {
  1514.                 $TwigData HumanResource::TwigDataForAddEmployee($em0);
  1515.                 $existingRegionAssociations = [];
  1516.                 return $this->render(
  1517.                     'ApplicationBundle:pages/human_resource/input_forms:add_employee.html.twig',
  1518.                     array(
  1519.                         'page_title' => 'Add Employee',
  1520.                         'ownOnly' => $ownOnly,
  1521.                         'heads' => Accounts::getLedgerHeadsWithParents($em),
  1522.                         'bankListObj' => $bankListObj,
  1523.                         'branches' => $TwigData['branches'],
  1524.                         'departments' => $TwigData['departments'],
  1525.                         'departmentPositions' => $TwigData['departmentPositions'],
  1526.                         'regions' => $TwigData['regions'],
  1527.                         'supervisors' => $TwigData['supervisors'],
  1528.                         'sysUsers' => $TwigData['sysUser'],
  1529.                         'EmploymentStatus' => $TwigData['EmploymentStatus'],
  1530.                         'sex' => $TwigData['sex'],
  1531.                         'skills' => $skills,
  1532.                         'id' => $id,
  1533.                         'consultancyLevel' => $consultancyLevel,
  1534.                         'existingSysUser' => null,
  1535.                         'BloodGroup' => $TwigData['BloodGroup'],
  1536.                         'days' => $TwigData['days'],
  1537.                         'AccountTypes' => $TwigData['AccountType'],
  1538.                         'module_data_array' => $TwigData['module_data_array'],
  1539.                         'user_type_data' => HumanResourceConstant::$userType,
  1540.                         'HasUpdateMode' => false,
  1541.                         'brand_list' => Inventory::GetBrandList($em$this->getLoggedUserCompanyId($data)),
  1542.                         'leaveSettings' => $TwigData['leaveSettings'],
  1543.                         'employee' => [],
  1544.                         'positions' => $TwigData['positions'],
  1545.                         'existing_region_associations' => $existingRegionAssociations ?? [],
  1546.                         'branch_list' => Client::BranchList($this->getDoctrine()->getManager(), $this->getLoggedUserCompanyId($data)),
  1547.                         'region_data' => Client::RegionList($this->getDoctrine()->getManager(), $this->getLoggedUserCompanyId($data)),
  1548.                     )
  1549.                 );
  1550.             } else {
  1551.                 try {
  1552.                     $approveHash $data->request->get('approvalHash');
  1553.                     $loginId $data->getSession()->get(UserConstants::USER_LOGIN_ID);
  1554.                     $CompanyId $this->getLoggedUserCompanyId($data);
  1555.                     $isSignatureOk DocValidation::isSignatureOk($em$loginId$approveHash);
  1556.                     if (!$isSignatureOk) {
  1557.                         $this->addFlash('error''Invalid Approval Hash!');
  1558.                         return $this->redirectToRoute('add_employee');
  1559.                     }
  1560.                     $message $this->get('user_module')->addNewUser(
  1561.                         $data->request->get('firstname') . " " $data->request->get('lastname'),
  1562.                         $data->request->get('email'),
  1563.                         $data->request->get('username'),
  1564.                         $data->request->get('password'),
  1565.                         $data->request->get('desg'),
  1566.                         $this->getLoggedUserLoginId($data),
  1567.                         $data->request->get('company'),
  1568.                         $data->request->get('user_type'),
  1569.                         $data->request->get('companyIdList'),
  1570.                         $data->request->get('branch'),
  1571.                         $data->request->get('supervisor'),
  1572.                         $data->request->get('default_route'),
  1573.                         $data->request->has('access_module') ? 0,
  1574.                         "",
  1575.                         $data->files->get('img'),
  1576.                         '',
  1577.                         00,
  1578.                         ''''''0''0,
  1579.                         $data->request->get('global_user_id'null)
  1580.                     );
  1581.                     if ($message[0] === 'error') {
  1582.                         $this->addFlash('error''Invalid Approval Hash!');
  1583.                         return $this->redirectToRoute('add_employee');
  1584.                     }
  1585.                     $isSuccess HumanResource::StoreDataForAddEmployee($em$datafalse$CompanyId);
  1586.                     $Employee $isSuccess;
  1587.                     $EmployeeDetails $em->getRepository(EmployeeDetails::class)->findOneBy(['id' => $id]);
  1588.                     $Employee->setUserId($message[3]->getUserId());
  1589.                     $em->persist($Employee);
  1590.                     if ($EmployeeDetails) {
  1591.                         $EmployeeDetails->setUserId($message[3]->getUserId());
  1592.                         $em->persist($EmployeeDetails);
  1593.                     }
  1594.                     $em->flush();
  1595.                     $connection->commit();
  1596.                 } catch (Throwable $e) {
  1597.                     $connection->rollBack();
  1598.                     $em->close();
  1599.                     $this->addFlash('error''Failed to save employee: ' $e->getMessage());
  1600.                     return $this->redirectToRoute('add_employee');
  1601.                 }
  1602.                 if ($systemType !== '_CENTRAL_') {
  1603.                     $em_goc $this->getDoctrine()->getManager('company_group');
  1604.                     $em_goc->getConnection()->connect();
  1605.                     $connected $em_goc->getConnection()->isConnected();
  1606.                     if ($connected) {
  1607.                         $appIds $message[2]->getAppId();
  1608.                         $userIds $message[3]->getUserId();
  1609.                         $findByQuery = ['active' => 1];
  1610.                         if ($appIds !== '_UNSET_'$findByQuery['appId'] = $appIds;
  1611.                         $gocList $em_goc->getRepository("CompanyGroupBundle:CompanyGroup")->findBy($findByQuery);
  1612.                         $gocDataList $gocDataListByAppId = [];
  1613.                         foreach ($gocList as $entry) {
  1614.                             $d = [
  1615.                                 'name' => $entry->getName(),
  1616.                                 'id' => $entry->getId(),
  1617.                                 'image' => $entry->getImage(),
  1618.                                 'companyGroupHash' => $entry->getCompanyGroupHash(),
  1619.                                 'dbName' => $entry->getDbName(),
  1620.                                 'dbUser' => $entry->getDbUser(),
  1621.                                 'dbPass' => $entry->getDbPass(),
  1622.                                 'dbHost' => $entry->getDbHost(),
  1623.                                 'appId' => $entry->getAppId(),
  1624.                                 'companyRemaining' => $entry->getCompanyRemaining(),
  1625.                                 'companyAllowed' => $entry->getCompanyAllowed(),
  1626.                             ];
  1627.                             $gocDataList[$entry->getId()] = $d;
  1628.                             $gocDataListByAppId[$entry->getAppId()] = $d;
  1629.                         }
  1630.                         $debugCount 0;
  1631.                         foreach ($gocDataList as $gocId => $entry) {
  1632.                             $skipSend 1;
  1633.                             $connector $this->container->get('application_connector');
  1634.                             $connector->resetConnection(
  1635.                                 'default',
  1636.                                 $entry['dbName'],
  1637.                                 $entry['dbUser'],
  1638.                                 $entry['dbPass'],
  1639.                                 $entry['dbHost'],
  1640.                                 $reset true
  1641.                             );
  1642.                             $em $this->getDoctrine()->getManager();
  1643.                             $users = ($userIds !== '_UNSET_')
  1644.                                 ? $this->getDoctrine()->getRepository('ApplicationBundle:SysUser')->findBy(['userId' => $userIds])
  1645.                                 : $this->getDoctrine()->getRepository('ApplicationBundle:SysUser')->findBy([]);
  1646.                             $userData $userFiles = [];
  1647.                             foreach ($users as $user) {
  1648.                                 $filePath $this->container->getParameter('kernel.root_dir') . '/../web/' $user->getImage();
  1649.                                 if ($user->getImage() && file_exists($filePath)) {
  1650.                                     $mime mime_content_type($filePath);
  1651.                                     $info pathinfo($filePath);
  1652.                                     $name $info['basename'];
  1653.                                     if (strpos($mime'image') !== false) {
  1654.                                         $userFiles['file_' $user->getUserAppId() . '_' $user->getUserId()] = new \CURLFile($filePath$mime$name);
  1655.                                         $skipSend 0;
  1656.                                     }
  1657.                                 } else {
  1658.                                     $user->setImage(null);
  1659.                                     $userFiles['file_' $user->getUserAppId() . '_' $user->getUserId()] = 'pika';
  1660.                                     $em->flush();
  1661.                                 }
  1662.                                 $getters array_filter(get_class_methods($user), function ($m) {
  1663.                                     return substr($m03) === 'get';
  1664.                                 });
  1665.                                 $userDataSingle = [];
  1666.                                 foreach ($getters as $getter) {
  1667.                                     if (in_array($getter, ['getCreatedAt''getUpdatedAt''getImage'])) continue;
  1668.                                     $val $user->{$getter}();
  1669.                                     $userDataSingle[$getter] = $val instanceof \DateTime $val->format('Y-m-d') : $val;
  1670.                                 }
  1671.                                 $employeeGetters = [
  1672.                                     'getFirstname''getLastname''getImage''getIsImgLegal''getNid''getDob''getSex''getReligion',
  1673.                                     'getFather''getMother''getSpouse''getChild1''getChild2''getBlood''getPhone''getOfficailPhone',
  1674.                                     'getCurrAddr''getCurrAddrLat''getCurrAddrLng''getPermAddr''getEmmContact''getUsername''getEmail',
  1675.                                     'getPassword''getUserId''getJoiningDate''getEmpValidTill''getEmpStatus''getEmpType''getEmpCode',
  1676.                                     'getEmpLabel''getTin''getTinValidTill''getMedIns''getMedInsValidTill''getDocs''getNocApproval',
  1677.                                     'getInst1''getYr1''getDur1''getInst2''getYr2''getDur2''getInst3''getYr3''getDur3''getEinst1',
  1678.                                     'getEyr1''getEdeg1''getEinst2''getEyr2''getEdeg2''getEinst3''getEyr3''getEdeg3''getBankAcc',
  1679.                                     'getBankAccType''getBankAccValidFrom''getBankAccValidTo''getRoutingCode''getSwiftCode''getEar1',
  1680.                                     'getEar2''getEar3''getEar4''getEar5''getEar6''getEart''getDed1''getDed2''getDed3''getDed4',
  1681.                                     'getDedt''getPayable''getHandCash''getBankTransfer''getSecDep''getSecDepSpan''getSecDepRemMon',
  1682.                                     'getSecDepRemAmount''getSlQty''getSlTkn''getSlFreq''getMlQty''getMlTkn''getMlFreq''getElQty',
  1683.                                     'getElTkn''getElFreq''getClQty''getClTkn''getClFreq''getLevt''getWeeklyHoliday''getFiles',
  1684.                                     'getSupervisor''getDept''getDesg''getBranch''getDivision''getCreatedAt''getUpdatedAt',
  1685.                                     'getEmployeeLevel''getSkill''getProbationaryPeriod''getDocBookedFlag''getTimeStampOfForm',
  1686.                                     'getIsConsultant''getConsultantLevel''getApplicationText''getCurrentEmployment''getEmergencyContactNumber',
  1687.                                     'getPostalCode''getCountry''getEducationData''getWorkExperienceData''getCertificateData''getLanguagesData',
  1688.                                     'getBeneficiaryName''getBankName''getBranchName''getClockedIn'
  1689.                                 ];
  1690.                                 foreach ($employeeGetters as $getter) {
  1691.                                     if (!method_exists($EmployeeDetails$getter)) continue;
  1692.                                     $value $EmployeeDetails->{$getter}();
  1693.                                     if ($value instanceof \DateTime$userDataSingle[$getter] = $value->format('Y-m-d');
  1694.                                     elseif (!is_object($value)) $userDataSingle[$getter] = $value;
  1695.                                 }
  1696.                                 $userData[] = $userDataSingle;
  1697.                             }
  1698.                             $retDataDebug[$debugCount] = ['skipSend' => $skipSend];
  1699.                             $urlToCall GeneralConstant::HONEYBEE_CENTRAL_SERVER '/SyncUserToCentralUser';
  1700.                             $userFiles['userData'] = json_encode($userData);
  1701.                             $curl curl_init();
  1702.                             curl_setopt_array($curl, [
  1703.                                 CURLOPT_RETURNTRANSFER => 1,
  1704.                                 CURLOPT_POST => 1,
  1705.                                 CURLOPT_URL => $urlToCall,
  1706.                                 CURLOPT_CONNECTTIMEOUT => 10,
  1707.                                 CURLOPT_SSL_VERIFYPEER => false,
  1708.                                 CURLOPT_SSL_VERIFYHOST => false,
  1709.                                 CURLOPT_POSTFIELDS => $userFiles
  1710.                             ]);
  1711.                             $retData curl_exec($curl);
  1712.                             $errData curl_error($curl);
  1713.                             curl_close($curl);
  1714.                             $retDataObj $errData ? ['status' => 'error''message' => 'cURL Error: ' $errData] : json_decode($retDatatrue);
  1715.                             $retDataDebug[$debugCount] = $retDataObj;
  1716.                             if (isset($retDataObj['globalIdsData'])) {
  1717.                                 foreach ($retDataObj['globalIdsData'] as $app_id => $usrList) {
  1718.                                     $connector->resetConnection(
  1719.                                         'default',
  1720.                                         $gocDataListByAppId[$app_id]['dbName'],
  1721.                                         $gocDataListByAppId[$app_id]['dbUser'],
  1722.                                         $gocDataListByAppId[$app_id]['dbPass'],
  1723.                                         $gocDataListByAppId[$app_id]['dbHost'],
  1724.                                         $reset true
  1725.                                     );
  1726.                                     $em $this->getDoctrine()->getManager();
  1727.                                     foreach ($usrList as $sys_id => $globaldata) {
  1728.                                         $user $this->getDoctrine()->getRepository('ApplicationBundle:SysUser')->findOneBy(['userId' => $sys_id]);
  1729.                                         if ($user) {
  1730.                                             $user->setGlobalId($globaldata['gid']);
  1731.                                             $em->persist($user);
  1732.                                             $em->flush();
  1733.                                         }
  1734.                                     }
  1735.                                 }
  1736.                             }
  1737.                             $debugCount++;
  1738.                         }
  1739.                     }
  1740.                 }
  1741.                 $companyData $message[2];
  1742.                 if ($message[0] === 'success' && GeneralConstant::EMAIL_ENABLED == 1) {
  1743.                     $bodyTemplate 'ApplicationBundle:email/user:registration.html.twig';
  1744.                     $bodyData = [
  1745.                         'name' => $data->request->get('name'),
  1746.                         'companyData' => $companyData,
  1747.                         'userName' => $data->request->get('username'),
  1748.                         'password' => $data->request->get('password'),
  1749.                     ];
  1750.                     $new_mail $this->get('mail_module');
  1751.                     $new_mail->sendMyMail([
  1752.                         'senderHash' => '_CUSTOM_',
  1753.                         'forwardToMailAddress' => $data->request->get('email'),
  1754.                         'subject' => 'User Registration on HoneyBee Ecosystem under Entity ' $companyData->getName(),
  1755.                         'fileName' => '',
  1756.                         'attachments' => [],
  1757.                         'toAddress' => $data->request->get('email'),
  1758.                         'fromAddress' => 'no-reply@ourhoneybee.eu',
  1759.                         'userName' => 'no-reply@ourhoneybee.eu',
  1760.                         'password' => 'Honeybee@0112',
  1761.                         'smtpServer' => 'smtp.hostinger.com',
  1762.                         'smtpPort' => 465,
  1763.                         'mailTemplate' => $bodyTemplate,
  1764.                         'templateData' => $bodyData,
  1765.                         'embedCompanyImage' => 1,
  1766.                         'companyId' => $data->request->get('company'),
  1767.                         'companyImagePath' => $companyData->getImage()
  1768.                     ]);
  1769.                 }
  1770.                 $this->addFlash('success''New Employee Successfully Added!');
  1771.                 $userType $data->getSession()->get(UserConstants::USER_TYPE);
  1772.                 $redirectUrl $userType == 1
  1773.                     $this->generateUrl('employee_list', [], UrlGenerator::ABSOLUTE_URL)
  1774.                     : $this->generateUrl('add_employee', [], UrlGenerator::ABSOLUTE_URL);
  1775.                 return new JsonResponse([
  1776.                     'employeeId' => $Employee->getEmployeeId(),
  1777.                     'redirectToNew' => 1,
  1778.                     'success' => true,
  1779.                     'redirectUrl' => $redirectUrl,
  1780.                 ]);
  1781.             }
  1782.         }
  1783.     }
  1784.     public function AddNewEmployeeAction(Request $request$id)
  1785.     {
  1786.         $em $this->getDoctrine()->getManager();
  1787.         $systemType $this->container->hasParameter('system_type') ? $this->container->getParameter('system_type') : '_ERP_';
  1788.         $approveHash $request->request->get('approvalHash');
  1789.         $loginId $request->getSession()->get(UserConstants::USER_LOGIN_ID);
  1790.         $CompanyId $this->getLoggedUserCompanyId($request);
  1791.         $isSignatureOk DocValidation::isSignatureOk($em$loginId$approveHash);
  1792.         $employee HumanResource::StoreDataForAddEmployee($em$requestfalse$CompanyId);
  1793.         $isUserExist $em->getRepository(EmployeeDetails::class);
  1794.         if ($isSignatureOk) {
  1795.             if ($isUserExist) {
  1796.                 if ($employee) {
  1797.                     $message $this->get('user_module')->addNewUser(
  1798.                         $request->request->get('firstname') . " " $request->request->get('lastname'),
  1799.                         $request->request->get('email'),
  1800.                         $request->request->get('username'),
  1801.                         $request->request->get('password'),
  1802.                         $request->request->get('desg'),
  1803.                         $request->getLoggedUserLoginId($request),
  1804.                         $request->request->get('company'),
  1805.                         $request->request->get('user_type'),
  1806.                         $request->request->get('companyIdList'),
  1807.                         $request->request->get('branch'),
  1808.                         $request->request->get('supervisor'),
  1809.                         $request->request->get('default_route'),
  1810.                         $request->request->has('access_module') ? 0
  1811.                     );
  1812.                     if ($message[0] == 'success') {
  1813.                         $employee->setUserId($message[3]->getUserId());
  1814.                         $em->flush();
  1815.                         if ($systemType == '_CENTRAL_') {
  1816.                         } else {
  1817.                             $em_goc $this->getDoctrine()->getManager('company_group');
  1818.                             $em_goc->getConnection()->connect();
  1819.                             $connected $em_goc->getConnection()->isConnected();
  1820.                             $gocDataList = [];
  1821.                             $gocDataListByAppId = [];
  1822.                             $retDataDebug = array();
  1823.                             $appIds $message[2]->getAppId();
  1824.                             $userIds $message[3]->getUserId();
  1825.                             if ($connected) {
  1826.                                 $findByQuery = array(
  1827.                                     'active' => 1
  1828.                                 );
  1829.                                 if ($appIds !== '_UNSET_')
  1830.                                     $findByQuery['appId'] = $appIds;
  1831.                                 $gocList $this->getDoctrine()->getManager('company_group')
  1832.                                     ->getRepository("CompanyGroupBundle:CompanyGroup")
  1833.                                     ->findBy($findByQuery);
  1834.                                 foreach ($gocList as $entry) {
  1835.                                     $d = array(
  1836.                                         'name' => $entry->getName(),
  1837.                                         'id' => $entry->getId(),
  1838.                                         'image' => $entry->getImage(),
  1839.                                         'companyGroupHash' => $entry->getCompanyGroupHash(),
  1840.                                         'dbName' => $entry->getDbName(),
  1841.                                         'dbUser' => $entry->getDbUser(),
  1842.                                         'dbPass' => $entry->getDbPass(),
  1843.                                         'dbHost' => $entry->getDbHost(),
  1844.                                         'appId' => $entry->getAppId(),
  1845.                                         'companyRemaining' => $entry->getCompanyRemaining(),
  1846.                                         'companyAllowed' => $entry->getCompanyAllowed(),
  1847.                                     );
  1848.                                     $gocDataList[$entry->getId()] = $d;
  1849.                                     $gocDataListByAppId[$entry->getAppId()] = $d;
  1850.                                 }
  1851.                                 $debugCount 0;
  1852.                                 foreach ($gocDataList as $gocId => $entry) {
  1853.                                     $skipSend 1;
  1854.                                     $connector $this->container->get('application_connector');
  1855.                                     $connector->resetConnection(
  1856.                                         'default',
  1857.                                         $gocDataList[$gocId]['dbName'],
  1858.                                         $gocDataList[$gocId]['dbUser'],
  1859.                                         $gocDataList[$gocId]['dbPass'],
  1860.                                         $gocDataList[$gocId]['dbHost'],
  1861.                                         $reset true);
  1862.                                     $em $this->getDoctrine()->getManager();
  1863.                                     if ($userIds !== '_UNSET_')
  1864.                                         $users $this->getDoctrine()
  1865.                                             ->getRepository('ApplicationBundle:SysUser')
  1866.                                             ->findBy(
  1867.                                                 array(
  1868.                                                     'userId' => $userIds
  1869.                                                 )
  1870.                                             );
  1871.                                     else
  1872.                                         $users $this->getDoctrine()
  1873.                                             ->getRepository('ApplicationBundle:SysUser')
  1874.                                             ->findBy(
  1875.                                                 array()
  1876.                                             );
  1877.                                     $output '';
  1878.                                     $userData = array();
  1879.                                     $userFiles = array();
  1880.                                     foreach ($users as $user) {
  1881.                                         $file $this->container->getParameter('kernel.root_dir') . '/../web/' $user->getImage();
  1882.                                         if ($user->getImage() != '' && $user->getImage() != null && file_exists($file)) {
  1883.                                             $mime mime_content_type($file);
  1884.                                             $info pathinfo($file);
  1885.                                             $name $info['basename'];
  1886.                                             if (strpos($mime'image') !== false) {
  1887.                                                 $output = new \CURLFile($file$mime$name);
  1888.                                             }
  1889.                                             $skipSend 0;
  1890.                                             $userFiles['file_' $user->getUserAppId() . '_' $user->getUserId()] = $output;
  1891.                                         } else {
  1892.                                             $user->setImage(null);
  1893.                                             $userFiles['file_' $user->getUserAppId() . '_' $user->getUserId()] = 'pika';
  1894.                                             $em->flush();
  1895.                                         }
  1896.                                         $getters array_filter(get_class_methods($user), function ($method) {
  1897.                                             return 'get' === substr($method03);
  1898.                                         });
  1899.                                         $userDataSingle = array();
  1900.                                         foreach ($getters as $getter) {
  1901.                                             if ($getter == 'getCreatedAt' || $getter == 'getUpdatedAt' || $getter == 'getImage')
  1902.                                                 continue;
  1903. //                                if(is_string($user->{$getter}())|| is_numeric($user->{$getter}()))
  1904. //                                {
  1905. //                                    $userDataSingle[$getter]= $user->{$getter}();
  1906. //                                }
  1907.                                             if ($user->{$getter}() instanceof \DateTime) {
  1908.                                                 $ggtd $user->{$getter}();
  1909.                                                 $userDataSingle[$getter] = $ggtd->format('Y-m-d');
  1910.                                             } else
  1911.                                                 $userDataSingle[$getter] = $user->{$getter}();
  1912.                                         }
  1913. //                                                    $userDataSingle['getNid']=$Employee->getNid();
  1914. //                                                    $userDataSingle['getCurrAddr'] = $Employee->getCurrAddr();
  1915.                                         $userData[] = $userDataSingle;
  1916.                                     }
  1917.                                     $retDataDebug[$debugCount] = array(
  1918.                                         'skipSend' => $skipSend
  1919.                                     );
  1920.                                     {
  1921.                                         $urlToCall GeneralConstant::HONEYBEE_CENTRAL_SERVER '/SyncUserToCentralUser';
  1922.                                         $userFiles['userData'] = json_encode($userData);
  1923.                                         $curl curl_init();
  1924.                                         curl_setopt_array($curl, array(
  1925.                                             CURLOPT_RETURNTRANSFER => 1,
  1926.                                             CURLOPT_POST => 1,
  1927.                                             CURLOPT_URL => $urlToCall,
  1928.                                             CURLOPT_CONNECTTIMEOUT => 10,
  1929.                                             CURLOPT_SSL_VERIFYPEER => false,
  1930.                                             CURLOPT_SSL_VERIFYHOST => false,
  1931. //                            CURLOPT_SAFE_UPLOAD => false,
  1932.                                             CURLOPT_HTTPHEADER => array(//                                "Accept: multipart/form-data",
  1933.                                             ),
  1934.                                             //                        CURLOPT_USERAGENT => 'InnoPM',
  1935. //                            CURLOPT_POSTFIELDS => array(
  1936. //                                'userData'=>json_encode($userData),
  1937. //                                'userFiles'=>$userFiles
  1938. //                            ),
  1939.                                             CURLOPT_POSTFIELDS => $userFiles
  1940.                                         ));
  1941.                                         $retData curl_exec($curl);
  1942.                                         $errData curl_error($curl);
  1943.                                         curl_close($curl);
  1944.                                         $response = [];
  1945.                                         if ($errData) {
  1946.                                             $response['status'] = 'error';
  1947.                                             $response['message'] = 'cURL Error: ' $errData;
  1948.                                         } else {
  1949.                                             $retDataObj json_decode($retDatatrue);
  1950.                                             if (!$retDataObj) {
  1951.                                                 $response['status'] = 'error';
  1952.                                                 $response['message'] = 'Invalid response from central server';
  1953.                                                 $response['raw_response'] = $retData;
  1954.                                             } else {
  1955.                                                 $response['status'] = 'success';
  1956.                                                 $response['data'] = $retDataObj;
  1957.                                             }
  1958.                                         }
  1959. // Return JSON response
  1960. //                                                    return new JsonResponse($response);
  1961.                                         $retDataDebug[$debugCount] = $retDataObj;
  1962.                                         if (isset($retDataObj['globalIdsData']))
  1963.                                             foreach ($retDataObj['globalIdsData'] as $app_id => $usrList) {
  1964.                                                 $connector $this->container->get('application_connector');
  1965.                                                 $connector->resetConnection(
  1966.                                                     'default',
  1967.                                                     $gocDataListByAppId[$app_id]['dbName'],
  1968.                                                     $gocDataListByAppId[$app_id]['dbUser'],
  1969.                                                     $gocDataListByAppId[$app_id]['dbPass'],
  1970.                                                     $gocDataListByAppId[$app_id]['dbHost'],
  1971.                                                     $reset true);
  1972.                                                 $em $this->getDoctrine()->getManager();
  1973.                                                 foreach ($usrList as $sys_id => $globaldata) {
  1974.                                                     $user $this->getDoctrine()
  1975.                                                         ->getRepository('ApplicationBundle:SysUser')
  1976.                                                         ->findOneBy(
  1977.                                                             array(
  1978.                                                                 'userId' => $sys_id
  1979.                                                             )
  1980.                                                         );
  1981.                                                     if ($user) {
  1982.                                                         $user->setGlobalId($globaldata['gid']);
  1983.                                                         $em->persist($user);
  1984.                                                         $em->flush();
  1985.                                                     }
  1986.                                                 }
  1987.                                             }
  1988.                                     }
  1989.                                     $debugCount++;
  1990.                                 }
  1991.                             }
  1992. //                    return new JsonResponse($retDataDebug);
  1993.                         }
  1994.                     }
  1995. //                                    if($message[0]=='success'){
  1996. //                                        $SysUserRepo = $em->getRepository('ApplicationBundle:SysUser');
  1997. //                                        $SysUser = $SysUserRepo->findOneBy([
  1998. //                                            'email' => $data->request->get('email')
  1999. //                                        ]);
  2000. //
  2001. //                                        if ($SysUser === null) {
  2002. //                                            throw new \Exception("User with email " . $data->request->get('email') . " not found.");
  2003. //                                        }
  2004. //
  2005. //                                        $isSuccess->setUserId($SysUser->getUserId());
  2006. //                                        $em->persist($isSuccess);
  2007. //                                        $em->flush();
  2008. //                                    }
  2009.                     $companyData $message[2];
  2010.                     if ($message[0] == 'success' && GeneralConstant::EMAIL_ENABLED == 1) {
  2011.                         $bodyHtml '';
  2012.                         $bodyTemplate 'ApplicationBundle:email/user:registration.html.twig';
  2013.                         $bodyData = array(
  2014.                             'name' => $request->request->get('name'),
  2015.                             'companyData' => $companyData,
  2016.                             'userName' => $request->request->get('username'),
  2017.                             'password' => $request->request->get('password'),
  2018.                         );
  2019.                         $attachments = [];
  2020.                         $new_mail $this->get('mail_module');
  2021.                         $new_mail->sendMyMail(array(
  2022.                             'senderHash' => '_CUSTOM_',
  2023.                             //                        'senderHash'=>'_CUSTOM_',
  2024.                             'forwardToMailAddress' => $request->request->get('email'),
  2025.                             'fromAddress' => 'no-reply@ourhoneybee.eu',
  2026.                             'userName' => 'no-reply@ourhoneybee.eu',
  2027.                             'password' => 'Honeybee@0112',
  2028.                             'smtpServer' => 'smtp.hostinger.com',
  2029.                             'smtpPort' => 465,
  2030.                             'subject' => 'User Registration on HoneyBee Ecosystem under Entity ' $companyData->getName(),
  2031.                             'fileName' => '',
  2032.                             'attachments' => $attachments,
  2033.                             'toAddress' => $request->request->get('email'),
  2034.                             'mailTemplate' => $bodyTemplate,
  2035.                             'templateData' => $bodyData,
  2036.                             'embedCompanyImage' => 1,
  2037.                             'companyId' => $request->request->get('company'),
  2038.                             'companyImagePath' => $companyData->getImage()
  2039.                         ));
  2040.                     }
  2041.                 }
  2042.                 $this->addFlash(
  2043.                     'success',
  2044.                     'New Employee Successfully Added!'
  2045.                 );
  2046.                 return $this->redirectToRoute('add_employee');
  2047.             } else {
  2048. //                        $requiredFields = [
  2049. //                            'email', 'username', 'password', 'firstname', 'lastname', 'nid', 'dob',
  2050. //                            'sex', 'blood', 'phone', 'perm_addr', 'dept', 'desg', 'branch',
  2051. //                            'emp_type', 'tin'
  2052. //                        ];
  2053. //
  2054. //                        $missingFields = [];
  2055. //
  2056. //                        foreach ($requiredFields as $field) {
  2057. //                            if (!$data->request->get($field)) {
  2058. //                                $missingFields[] = $field;
  2059. //                            }
  2060. //                        }
  2061. //                        if (!empty($missingFields)) {
  2062. //                            $this->addFlash('error', 'Missing fields: ' . implode(', ', $missingFields));
  2063. //                            return $this->redirectToRoute('add_employee');
  2064. //                        }
  2065. //                        $password = $data->request->get('password');
  2066. //                        $passwordPattern = '/^(?=.*[A-Z])(?=.*[a-z])(?=.*\d)(?=.*[\W_]).{8,}$/';
  2067. //                        if (!preg_match($passwordPattern, $password)) {
  2068. //                            $this->addFlash('error', 'Password must be at least 8 characters long, contain at least one uppercase letter, one lowercase letter, one special character, and one number. ' . implode(', ', $missingFields));
  2069. //                            return $this->redirectToRoute('add_employee');
  2070. //                        }
  2071.                 $CompanyId $this->getLoggedUserCompanyId($request);
  2072.                 $isSuccess HumanResource::StoreDataForAddEmployee($em$requestfalse$CompanyId);
  2073.                 if ($isSuccess) {
  2074.                     if ($request->request->has('send_appointment')) {
  2075.                         $email $request->request->get('email');
  2076.                         $bodyHtml '';
  2077.                         $bodyTemplate 'ApplicationBundle:email/general:appointment_letter_test.html.twig';
  2078.                         $bodyData = [];
  2079.                         $attachments = [];
  2080.                         $forwardToMailAddress $email;
  2081.                         $new_mail $this->get('mail_module');
  2082.                         $new_mail->sendMyMail(array(
  2083.                             'senderHash' => '_CUSTOM_',
  2084.                             'forwardToMailAddress' => $forwardToMailAddress,
  2085.                             'subject' => 'Appointment Letter',
  2086.                             'attachments' => $attachments,
  2087.                             'toAddress' => $forwardToMailAddress,
  2088.                             'fromAddress' => 'no-reply@ourhoneybee.eu',
  2089.                             'userName' => 'no-reply@ourhoneybee.eu',
  2090.                             'password' => 'Honeybee@0112',
  2091.                             'smtpServer' => 'smtp.hostinger.com',
  2092.                             'smtpPort' => 465,
  2093.                             'emailBody' => $bodyHtml,
  2094.                             'mailTemplate' => $bodyTemplate,
  2095.                             'templateData' => $bodyData,
  2096.                         ));
  2097.                     }
  2098.                     // Mailer function
  2099.                     if ($request->get("send_mail") && empty($request->get('sys_user'))) {
  2100.                         $message $this->get('user_module')->addNewUser(
  2101.                             $request->request->get('firstname') . " " $request->request->get('lastname'),
  2102.                             $request->request->get('email'),
  2103.                             $request->request->get('username'),
  2104.                             $request->request->get('password'),
  2105.                             $request->request->get('desg'),
  2106.                             $request->getLoggedUserLoginId($request),
  2107.                             $request->request->get('company'),
  2108.                             $request->request->get('user_type'),
  2109.                             $request->request->get('companyIdList'),
  2110.                             $request->request->get('branch'),
  2111.                             $request->request->get('supervisor'),
  2112.                             $request->request->get('default_route'),
  2113.                             $request->request->has('access_module') ? 0
  2114.                         );
  2115.                         if ($message[0] == 'success') {
  2116.                             if ($systemType == '_CENTRAL_') {
  2117.                             } else {
  2118.                                 $em_goc $this->getDoctrine()->getManager('company_group');
  2119.                                 $em_goc->getConnection()->connect();
  2120.                                 $connected $em_goc->getConnection()->isConnected();
  2121.                                 $gocDataList = [];
  2122.                                 $gocDataListByAppId = [];
  2123.                                 $retDataDebug = array();
  2124.                                 $appIds $message[2]->getAppId();
  2125.                                 $userIds $message[3]->getUserId();
  2126.                                 if ($connected) {
  2127.                                     $findByQuery = array(
  2128.                                         'active' => 1
  2129.                                     );
  2130.                                     if ($appIds !== '_UNSET_')
  2131.                                         $findByQuery['appId'] = $appIds;
  2132.                                     $gocList $this->getDoctrine()->getManager('company_group')
  2133.                                         ->getRepository("CompanyGroupBundle:CompanyGroup")
  2134.                                         ->findBy($findByQuery);
  2135.                                     foreach ($gocList as $entry) {
  2136.                                         $d = array(
  2137.                                             'name' => $entry->getName(),
  2138.                                             'id' => $entry->getId(),
  2139.                                             'image' => $entry->getImage(),
  2140.                                             'companyGroupHash' => $entry->getCompanyGroupHash(),
  2141.                                             'dbName' => $entry->getDbName(),
  2142.                                             'dbUser' => $entry->getDbUser(),
  2143.                                             'dbPass' => $entry->getDbPass(),
  2144.                                             'dbHost' => $entry->getDbHost(),
  2145.                                             'appId' => $entry->getAppId(),
  2146.                                             'companyRemaining' => $entry->getCompanyRemaining(),
  2147.                                             'companyAllowed' => $entry->getCompanyAllowed(),
  2148.                                         );
  2149.                                         $gocDataList[$entry->getId()] = $d;
  2150.                                         $gocDataListByAppId[$entry->getAppId()] = $d;
  2151.                                     }
  2152.                                     $debugCount 0;
  2153.                                     foreach ($gocDataList as $gocId => $entry) {
  2154.                                         $skipSend 1;
  2155.                                         $connector $this->container->get('application_connector');
  2156.                                         $connector->resetConnection(
  2157.                                             'default',
  2158.                                             $gocDataList[$gocId]['dbName'],
  2159.                                             $gocDataList[$gocId]['dbUser'],
  2160.                                             $gocDataList[$gocId]['dbPass'],
  2161.                                             $gocDataList[$gocId]['dbHost'],
  2162.                                             $reset true);
  2163.                                         $em $this->getDoctrine()->getManager();
  2164.                                         if ($userIds !== '_UNSET_')
  2165.                                             $users $this->getDoctrine()
  2166.                                                 ->getRepository('ApplicationBundle:SysUser')
  2167.                                                 ->findBy(
  2168.                                                     array(
  2169.                                                         'userId' => $userIds
  2170.                                                     )
  2171.                                                 );
  2172.                                         else
  2173.                                             $users $this->getDoctrine()
  2174.                                                 ->getRepository('ApplicationBundle:SysUser')
  2175.                                                 ->findBy(
  2176.                                                     array()
  2177.                                                 );
  2178.                                         $output '';
  2179.                                         $userData = array();
  2180.                                         $userFiles = array();
  2181.                                         foreach ($users as $user) {
  2182.                                             $file $this->container->getParameter('kernel.root_dir') . '/../web/' $user->getImage();
  2183.                                             if ($user->getImage() != '' && $user->getImage() != null && file_exists($file)) {
  2184.                                                 $mime mime_content_type($file);
  2185.                                                 $info pathinfo($file);
  2186.                                                 $name $info['basename'];
  2187.                                                 if (strpos($mime'image') !== false) {
  2188.                                                     $output = new \CURLFile($file$mime$name);
  2189.                                                 }
  2190.                                                 $skipSend 0;
  2191.                                                 $userFiles['file_' $user->getUserAppId() . '_' $user->getUserId()] = $output;
  2192.                                             } else {
  2193.                                                 $user->setImage(null);
  2194.                                                 $userFiles['file_' $user->getUserAppId() . '_' $user->getUserId()] = 'pika';
  2195.                                                 $em->flush();
  2196.                                             }
  2197.                                             $getters array_filter(get_class_methods($user), function ($method) {
  2198.                                                 return 'get' === substr($method03);
  2199.                                             });
  2200.                                             $userDataSingle = array();
  2201.                                             foreach ($getters as $getter) {
  2202.                                                 if ($getter == 'getCreatedAt' || $getter == 'getUpdatedAt' || $getter == 'getImage')
  2203.                                                     continue;
  2204. //                                if(is_string($user->{$getter}())|| is_numeric($user->{$getter}()))
  2205. //                                {
  2206. //                                    $userDataSingle[$getter]= $user->{$getter}();
  2207. //                                }
  2208.                                                 if ($user->{$getter}() instanceof \DateTime) {
  2209.                                                     $ggtd $user->{$getter}();
  2210.                                                     $userDataSingle[$getter] = $ggtd->format('Y-m-d');
  2211.                                                 } else
  2212.                                                     $userDataSingle[$getter] = $user->{$getter}();
  2213.                                             }
  2214. //                                                    $userDataSingle['getNid']=$Employee->getNid();
  2215. //                                                    $userDataSingle['getCurrAddr'] = $Employee->getCurrAddr();
  2216.                                             $userData[] = $userDataSingle;
  2217.                                         }
  2218.                                         $retDataDebug[$debugCount] = array(
  2219.                                             'skipSend' => $skipSend
  2220.                                         );
  2221.                                         {
  2222.                                             $urlToCall GeneralConstant::HONEYBEE_CENTRAL_SERVER '/SyncUserToCentralUser';
  2223.                                             $userFiles['userData'] = json_encode($userData);
  2224.                                             $curl curl_init();
  2225.                                             curl_setopt_array($curl, array(
  2226.                                                 CURLOPT_RETURNTRANSFER => 1,
  2227.                                                 CURLOPT_POST => 1,
  2228.                                                 CURLOPT_URL => $urlToCall,
  2229.                                                 CURLOPT_CONNECTTIMEOUT => 10,
  2230.                                                 CURLOPT_SSL_VERIFYPEER => false,
  2231.                                                 CURLOPT_SSL_VERIFYHOST => false,
  2232. //                            CURLOPT_SAFE_UPLOAD => false,
  2233.                                                 CURLOPT_HTTPHEADER => array(//                                "Accept: multipart/form-data",
  2234.                                                 ),
  2235.                                                 //                        CURLOPT_USERAGENT => 'InnoPM',
  2236. //                            CURLOPT_POSTFIELDS => array(
  2237. //                                'userData'=>json_encode($userData),
  2238. //                                'userFiles'=>$userFiles
  2239. //                            ),
  2240.                                                 CURLOPT_POSTFIELDS => $userFiles
  2241.                                             ));
  2242.                                             $retData curl_exec($curl);
  2243.                                             $errData curl_error($curl);
  2244.                                             curl_close($curl);
  2245.                                             $response = [];
  2246.                                             if ($errData) {
  2247.                                                 $response['status'] = 'error';
  2248.                                                 $response['message'] = 'cURL Error: ' $errData;
  2249.                                             } else {
  2250.                                                 $retDataObj json_decode($retDatatrue);
  2251.                                                 if (!$retDataObj) {
  2252.                                                     $response['status'] = 'error';
  2253.                                                     $response['message'] = 'Invalid response from central server';
  2254.                                                     $response['raw_response'] = $retData;
  2255.                                                 } else {
  2256.                                                     $response['status'] = 'success';
  2257.                                                     $response['data'] = $retDataObj;
  2258.                                                 }
  2259.                                             }
  2260. // Return JSON response
  2261. //                                                    return new JsonResponse($response);
  2262.                                             $retDataDebug[$debugCount] = $retDataObj;
  2263.                                             if (isset($retDataObj['globalIdsData']))
  2264.                                                 foreach ($retDataObj['globalIdsData'] as $app_id => $usrList) {
  2265.                                                     $connector $this->container->get('application_connector');
  2266.                                                     $connector->resetConnection(
  2267.                                                         'default',
  2268.                                                         $gocDataListByAppId[$app_id]['dbName'],
  2269.                                                         $gocDataListByAppId[$app_id]['dbUser'],
  2270.                                                         $gocDataListByAppId[$app_id]['dbPass'],
  2271.                                                         $gocDataListByAppId[$app_id]['dbHost'],
  2272.                                                         $reset true);
  2273.                                                     $em $this->getDoctrine()->getManager();
  2274.                                                     foreach ($usrList as $sys_id => $globaldata) {
  2275.                                                         $user $this->getDoctrine()
  2276.                                                             ->getRepository('ApplicationBundle:SysUser')
  2277.                                                             ->findOneBy(
  2278.                                                                 array(
  2279.                                                                     'userId' => $sys_id
  2280.                                                                 )
  2281.                                                             );
  2282.                                                         if ($user) {
  2283.                                                             $user->setGlobalId($globaldata['gid']);
  2284.                                                             $em->persist($user);
  2285.                                                             $em->flush();
  2286.                                                         }
  2287.                                                     }
  2288.                                                 }
  2289.                                         }
  2290.                                         $debugCount++;
  2291.                                     }
  2292.                                 }
  2293. //                    return new JsonResponse($retDataDebug);
  2294.                             }
  2295.                         }
  2296.                         $SysUserRepo $em->getRepository(SysUser::class);
  2297.                         $SysUser $SysUserRepo->findOneBy(array(
  2298.                             'email' => $request->request->get('email')
  2299.                         ));
  2300.                         $isSuccess->setUserId($SysUser->getUserId());
  2301.                         $em->persist($isSuccess);
  2302.                         $em->flush();
  2303.                         $companyData $message[2];
  2304.                         if ($message[0] == 'success' && GeneralConstant::EMAIL_ENABLED == 1) {
  2305.                             $bodyHtml '';
  2306.                             $bodyTemplate 'ApplicationBundle:email/user:registration.html.twig';
  2307.                             $bodyData = array(
  2308.                                 'name' => $request->request->get('name'),
  2309.                                 'companyData' => $companyData,
  2310.                                 'userName' => $request->request->get('username'),
  2311.                                 'password' => $request->request->get('password'),
  2312.                             );
  2313.                             $attachments = [];
  2314. //                    $upl_dir = $this->container->getParameter('kernel.root_dir') . '/../web/uploads/temp/' . 'ledger' . '.pdf'
  2315.                             $new_mail $this->get('mail_module');
  2316.                             $new_mail->sendMyMail(array(
  2317.                                 'senderHash' => '_CUSTOM_',
  2318.                                 //                        'senderHash'=>'_CUSTOM_',
  2319.                                 'forwardToMailAddress' => $request->request->get('email'),
  2320.                                 'subject' => 'User Registration on HoneyBee Ecosystem under Entity ' $companyData->getName(),
  2321.                                 'fileName' => '',
  2322.                                 'attachments' => $attachments,
  2323.                                 'toAddress' => $request->request->get('email'),
  2324.                                 'fromAddress' => 'no-reply@ourhoneybee.eu',
  2325.                                 'userName' => 'no-reply@ourhoneybee.eu',
  2326.                                 'password' => 'Honeybee@0112',
  2327.                                 'smtpServer' => 'smtp.hostinger.com',
  2328.                                 'smtpPort' => 465,
  2329. //                        'fromAddress'=>'sales@entity.innobd.com',
  2330. //                        'userName'=>'sales@entity.innobd.com',
  2331. //                        'password'=>'Y41dh8g0112',
  2332. //                        'smtpServer'=>'smtp.hostinger.com',
  2333. //                        'smtpPort'=>587,
  2334. //                        'emailBody'=>$bodyHtml,
  2335.                                 'mailTemplate' => $bodyTemplate,
  2336.                                 'templateData' => $bodyData,
  2337.                                 'embedCompanyImage' => 1,
  2338.                                 'companyId' => $request->request->get('company'),
  2339.                                 'companyImagePath' => $companyData->getImage()
  2340.                             ));
  2341. //                  $emailmessage = (new \Swift_Message('Registration to Entity'))
  2342. //                    ->setFrom('registration@entity.innobd.com')
  2343. //                    ->setTo($data->request->get('email'))
  2344. //                    ->setBody(
  2345. //                      $this->renderView(
  2346. //                        'ApplicationBundle:email/user:registration.html.twig',
  2347. //                        array(
  2348. //                          'name' => $data->request->get('name'),
  2349. //                          'companyData' => $companyData,
  2350. //                          'userName' => $data->request->get('email'),
  2351. //                          'password' => $data->request->get('password'),
  2352. //                        )
  2353. //                      ),
  2354. //                      'text/html'
  2355. //                    );
  2356. //                  $this->get('mailer')->send($emailmessage);
  2357.                         }
  2358.                     }
  2359.                     // End Mailer function
  2360.                     $this->addFlash(
  2361.                         'success',
  2362.                         'New Employee Successfully Added!'
  2363.                     );
  2364.                     return $this->redirectToRoute('employee_list');
  2365.                 } else {
  2366.                     $this->addFlash(
  2367.                         'error',
  2368.                         'Something Went Wrong!'
  2369.                     );
  2370.                     return $this->redirectToRoute('add_employee');
  2371.                 }
  2372.             }
  2373.         } else {
  2374.             $this->addFlash(
  2375.                 'error',
  2376.                 'Invalid Approval Hash!'
  2377.             );
  2378.             return $this->redirectToRoute('add_employee');
  2379.         }
  2380.     }
  2381.     public function UpdateEmployeeAction(Request $request$id)
  2382.     {
  2383.     }
  2384.     private function uploadImage($image$request)
  2385.     {
  2386.         $upl_dir $this->container->getParameter('kernel.root_dir') . '/../web/uploads/Users/';
  2387.         $profileImage '';
  2388.         if ($image != null) {
  2389.             $fileName $request->request->get('firstname') . '.' $request->request->get('global_user_id') . '.' $image->guessExtension();
  2390.             $path $fileName;
  2391.             if (!file_exists($upl_dir)) {
  2392.                 mkdir($upl_dir0777true);
  2393.             }
  2394.             $image->move($upl_dir$path);
  2395.             $profileImage 'uploads/Users/' $path;
  2396.         }
  2397.         return $profileImage;
  2398.     }
  2399.     private function uploadMeetingFile($file$request)
  2400.     {
  2401.         $upl_dir $this->container->getParameter('kernel.root_dir') . '/../web/uploads/meeting/';
  2402.         $uploadedFilePath '';
  2403.         if ($file != null) {
  2404.             $fileName uniqid() . '.' $file->guessExtension();
  2405.             if (!file_exists($upl_dir)) {
  2406.                 mkdir($upl_dir0777true);
  2407.             }
  2408.             $file->move($upl_dir$fileName);
  2409.             $uploadedFilePath 'uploads/meeting/' $fileName;
  2410.         }
  2411.         return $uploadedFilePath;
  2412.     }
  2413.     public function OnboardEmployeeAction(Request $request)
  2414.     {
  2415.         $systemType $this->container->hasParameter('system_type') ? $this->container->getParameter('system_type') : '_ERP_';
  2416.         $email $request->request->get('email');
  2417.         $applicantId $request->request->get('applicant_id');
  2418.         $em_goc $this->getDoctrine()->getManager('company_group');
  2419.         $em $this->getDoctrine()->getManager();
  2420.         $session $request->getSession();
  2421.         $companyId $session->get('userCompanyId');
  2422.         $appId $session->get('userAppId');
  2423.         $urlToCall GeneralConstant::HONEYBEE_CENTRAL_SERVER '/get_applicant_data_central';
  2424.         $applicantFiles = [
  2425.             'email' => $email,
  2426.             'applicantId' => $applicantId
  2427.         ];
  2428.         $entityToken $em_goc->getRepository('CompanyGroupBundle:EntityTokenStorage')
  2429.             ->findOneBy(['userId' => $applicantId]);
  2430.         $curl curl_init();
  2431.         curl_setopt_array($curl, array(
  2432.             CURLOPT_RETURNTRANSFER => 1,
  2433.             CURLOPT_POST => 1,
  2434.             CURLOPT_URL => $urlToCall,
  2435.             CURLOPT_CONNECTTIMEOUT => 10,
  2436.             CURLOPT_SSL_VERIFYPEER => false,
  2437.             CURLOPT_SSL_VERIFYHOST => false,
  2438.             CURLOPT_HTTPHEADER => array(),
  2439.             CURLOPT_POSTFIELDS => $applicantFiles
  2440.         ));
  2441.         $retData curl_exec($curl);
  2442.         $errData curl_error($curl);
  2443.         curl_close($curl);
  2444.         $retDataObj json_decode($retDatatrue);
  2445.         if (!isset($retDataObj['status']) || $retDataObj['status'] !== 'success') {
  2446.             return new JsonResponse([
  2447.                 'status' => 'error',
  2448.                 'message' => 'Failed to get applicant data from central server',
  2449.                 'response' => $retDataObj
  2450.             ]);
  2451.         }
  2452.         $centralData $retDataObj['centralData'];
  2453.         $em $this->getDoctrine()->getManager();
  2454.         $existingUser $em->getRepository('ApplicationBundle:SysUser')->findOneBy([
  2455.             'globalId' => $centralData['globalId']
  2456.         ]);
  2457.         if ($existingUser) {
  2458.             return new JsonResponse([
  2459.                 'status' => 'info',
  2460.                 'message' => 'User is already onboarded',
  2461.                 'userId' => $existingUser->getUserId(),
  2462.                 'redirectUrl' => 'dashboard'
  2463.             ]);
  2464.         }
  2465.         $sysUser = new SysUser();
  2466.         $sysUser->setGlobalId($centralData['globalId'] ?? '');
  2467.         $sysUser->setUsername($centralData['username'] ?? '');
  2468.         $sysUser->setEmail($centralData['email'] ?? '');
  2469.         $sysUser->setName($centralData['firstname'] ?? '');
  2470.         $sysUser->setUserType(1);
  2471.         $sysUser->setUserAppId($appId);
  2472.         $sysUser->setUserCompanyId($companyId);
  2473.         $sysUser->setStatus(1);
  2474.         $sysUser->setDefaultRoute('sales_dashboard');
  2475.         $em->persist($sysUser);
  2476.         $em->flush();
  2477.         $employee $em->getRepository('ApplicationBundle:Employee')
  2478.             ->findOneBy(
  2479.                 array(
  2480.                     'userId' => $sysUser->getUserId(),
  2481.                 )
  2482.             );
  2483.         if (!$employee) {
  2484.             $employee = new Employee();
  2485.             if ($sysUser->getUserId()) {
  2486.                 $employee->setEmail($sysUser->getEmail());
  2487.                 $employee->setFirstName($sysUser->getUsername());
  2488.                 $employee->setLastName($sysUser->getName());
  2489.                 $employee->setCompanyId($sysUser->getUserCompanyId());
  2490.                 $employee->setStatus(1);
  2491.                 $employee->setUserId($sysUser->getUserId());
  2492.                 $em->persist($employee);
  2493.                 $em->flush();
  2494.             } else {
  2495.                 return new JsonResponse([
  2496.                     'status' => 'error',
  2497.                     'message' => 'Missing employee data',
  2498.                 ]);
  2499.             }
  2500.         }
  2501.         $employeeDetails $em->getRepository('ApplicationBundle:EmployeeDetails')
  2502.             ->findOneBy([
  2503.                 'userId' => $sysUser->getUserId(),
  2504.             ]);
  2505.         if (!$employeeDetails) {
  2506.             $employeeDetails = new EmployeeDetails();
  2507.             if ($sysUser->getUserId() && $employee->getEmployeeId()) {
  2508.                 $employeeDetails->setId($employee->getEmployeeId());
  2509.                 $employeeDetails->setEmail($sysUser->getEmail());
  2510.                 $employeeDetails->setFirstName($sysUser->getUsername());
  2511.                 $employeeDetails->setLastName($sysUser->getName());
  2512.                 $employeeDetails->setUsername($sysUser->getUsername());
  2513.                 $employeeDetails->setUserId($sysUser->getUserId());
  2514.                 $employeeDetails->setEmpStatus(1);
  2515.                 $em->persist($employeeDetails);
  2516.                 $em->flush();
  2517.             } else {
  2518.                 return new JsonResponse([
  2519.                     'status' => 'error',
  2520.                     'message' => 'Missing employee details data',
  2521.                 ]);
  2522.             }
  2523.         }
  2524.         $company $em->getRepository('ApplicationBundle:Company')->find($companyId);
  2525.         $companyName $company $company->getName() : '';
  2526.         $newAccess = [
  2527.             'userType' => 2,
  2528.             'userTypeName' => UserConstants::$userTypeName[2],
  2529.             'globalId' => $applicantId,
  2530.             'serverId' => 1,
  2531.             'serverUrl' => $request->getSchemeAndHttpHost(),
  2532.             'serverPort' => 80,
  2533.             'systemType' => '_ERP_',
  2534.             'companyId' => 1,
  2535.             'appId' => $appId,
  2536.             'companyLogoUrl' => '/uploads/CompanyImage/company_image' $request->request->get('appId') . '.png',
  2537.             'companyName' => $companyName,
  2538.             'authenticationStr' => $this->get('url_encryptor')->encrypt(json_encode(
  2539.                     array(
  2540.                         'globalId' => $applicantId,
  2541.                         'appId' => $appId,
  2542.                         'authenticate' => 1,
  2543.                         'userType' => 2,
  2544.                         'userTypeName' => UserConstants::$userTypeName[2]
  2545.                     )
  2546.                 )
  2547.             ),
  2548.             'userCompanyList' => [],
  2549.         ];
  2550.         $urlToCall GeneralConstant::HONEYBEE_CENTRAL_SERVER '/update_token_storage';
  2551.         $curl curl_init();
  2552.         curl_setopt_array($curl, array(
  2553.             CURLOPT_RETURNTRANSFER => 1,
  2554.             CURLOPT_POST => 1,
  2555.             CURLOPT_URL => $urlToCall,
  2556.             CURLOPT_CONNECTTIMEOUT => 10,
  2557.             CURLOPT_SSL_VERIFYPEER => false,
  2558.             CURLOPT_SSL_VERIFYHOST => false,
  2559.             CURLOPT_HTTPHEADER => array(),
  2560.             CURLOPT_POSTFIELDS => json_encode($newAccess)
  2561.         ));
  2562.         $retData curl_exec($curl);
  2563.         $errData curl_error($curl);
  2564.         return new JsonResponse([
  2565.             'status' => 'success',
  2566.             'message' => 'User onboarded successfully',
  2567.             'redirectUlr' => 'dashboard',
  2568.             'returnData' => $retData,
  2569.             'errorData' => $errData
  2570.         ]);
  2571.     }
  2572.     public function DecodeQrAction(Request $request)
  2573.     {
  2574.         $applicantId $request->request->get('applicant_id');
  2575.         $urlToCall GeneralConstant::HONEYBEE_CENTRAL_SERVER '/get_applicant_data_central';
  2576.         $applicantFiles = [
  2577.             'applicantId' => $applicantId
  2578.         ];
  2579.         $curl curl_init();
  2580.         curl_setopt_array($curl, array(
  2581.             CURLOPT_RETURNTRANSFER => 1,
  2582.             CURLOPT_POST => 1,
  2583.             CURLOPT_URL => $urlToCall,
  2584.             CURLOPT_CONNECTTIMEOUT => 10,
  2585.             CURLOPT_SSL_VERIFYPEER => false,
  2586.             CURLOPT_SSL_VERIFYHOST => false,
  2587.             CURLOPT_HTTPHEADER => array(),
  2588.             CURLOPT_POSTFIELDS => $applicantFiles
  2589.         ));
  2590.         $retData curl_exec($curl);
  2591.         $errData curl_error($curl);
  2592.         curl_close($curl);
  2593.         $retDataObj json_decode($retDatatrue);
  2594.         return new JsonResponse($retDataObj['centralData']);
  2595.     }
  2596.     public function GetApplicantDataForErpAction(Request $request)
  2597.     {
  2598.         $applicantId $request->request->get('applicantId');
  2599.         if (!$applicantId) {
  2600.             return new JsonResponse([
  2601.                 'status' => 'error',
  2602.                 'message' => 'Missing applicantId in request.'
  2603.             ]);
  2604.         }
  2605.         $em_goc $this->getDoctrine()->getManager('company_group');
  2606.         $entityApplicant $em_goc->getRepository("CompanyGroupBundle:EntityApplicantDetails")
  2607.             ->findOneBy(['applicantId' => $applicantId]);
  2608.         if (!$entityApplicant) {
  2609.             return new JsonResponse([
  2610.                 'status' => 'error',
  2611.                 'message' => 'Applicant not found.'
  2612.             ]);
  2613.         }
  2614.         return new JsonResponse([
  2615.             'status' => 'success',
  2616.             'centralData' => [
  2617.                 'globalId' => $entityApplicant->getApplicantId(),
  2618.                 'username' => $entityApplicant->getUsername(),
  2619.                 'email' => $entityApplicant->getEmail(),
  2620.                 'firstname' => $entityApplicant->getFirstname(),
  2621.                 'lastname' => $entityApplicant->getLastname(),
  2622.                 'image' => $entityApplicant->getImage(),
  2623.                 'phone' => $entityApplicant->getPhone(),
  2624.                 'address' => $entityApplicant->getPermAddr()
  2625.             ]
  2626.         ]);
  2627.     }
  2628.     public function UpdateTokenStorageAction(Request $request)
  2629.     {
  2630.         $em_goc $this->getDoctrine()->getManager('company_group');
  2631.         $newAccess $request->request->all();
  2632.         $appId = isset($newAccess['appId']) ? $newAccess['appId'] : null;
  2633.         $globalId = isset($newAccess['globalId']) ? $newAccess['globalId'] : null;
  2634.         $sesssionData MiscActions::UpdateCompanyListInSession(
  2635.             $em_goc,
  2636.             $globalId,
  2637.             1,
  2638.             1,
  2639.             1,
  2640.             $newAccess
  2641.         );
  2642.         return new JsonResponse([
  2643.             'status' => 'success',
  2644.             'message' => 'Token storage updated',
  2645.             'newaccess' => $newAccess
  2646.         ]);
  2647.     }
  2648.     public function EmployeeListAction(Request $data)
  2649.     {
  2650.         $em $this->getDoctrine()->getManager();
  2651.         if ($data->isMethod('GET')) {
  2652.             return $this->render("ApplicationBundle:pages/human_resource/list:list_employee.html.twig", array(
  2653.                 'page_title' => 'Employee List',
  2654.             ));
  2655.         }
  2656.     }
  2657.     public function OrganizationChartAction()
  2658.     {
  2659.         $em $this->getDoctrine()->getManager();
  2660.         $Reponse HumanResource::TwigDataForOrgChart($em);
  2661.         return $this->render('ApplicationBundle:pages/human_resource/views:org_chart.html.twig', array(
  2662.             'page_title' => 'Organization Chart',
  2663.             'supervisors' => $Reponse['TreantJsData'],
  2664.             'alluser' => $Reponse['TreantJsInitUser']
  2665.         ));
  2666.     }
  2667.     public function EmployeeListSelectizeAjaxAction(Request $request$str '_EMPTY_')
  2668.     {
  2669.         $em $this->getDoctrine()->getManager();
  2670.         $companyId $this->getLoggedUserCompanyId($request);
  2671.         $company_data Company::getCompanyData($em$companyId);
  2672.         $data = [];
  2673.         $html '';
  2674.         $qryStrs explode(' '$str);
  2675.         $qryStrAddedForSpacedName "";
  2676.         if ($str == '_EMPTY_') {
  2677.             $query "SELECT *
  2678. from  employee  order by employee_id asc limit 10";
  2679.         } else {
  2680.             foreach ($qryStrs as $qryStr) {
  2681.                 $qryStrAddedForSpacedName .= "or first_name like '%$qryStr%' or last_name like '%$qryStr%' ";
  2682.             }
  2683.             $query "SELECT  *
  2684. from  employee  where" . (is_numeric($str) ? " employee_id =$str " " 1=0 ") . $qryStrAddedForSpacedName " or `name` like '%$str%' or employee_code like '%$str%' order by employee_id asc limit 10";
  2685.         }
  2686.         $stmt $em->getConnection()->prepare($query);
  2687.         $stmt->execute();
  2688.         $res $stmt->fetchAll();
  2689. //    if(!empty($res)) {
  2690.         foreach ($res as $i => $r) {
  2691.             $res[$i]['id_padded'] = str_pad($r['employee_id'], 8'0'STR_PAD_LEFT);
  2692.         }
  2693. //    }
  2694.         return new JsonResponse(
  2695.             array(
  2696.                 'success' => true,
  2697.                 'data' => $res,
  2698.             )
  2699.         );
  2700.     }
  2701.     public function AttendanceAction(Request $data$remoteVerify 0)
  2702.     {
  2703.         $em $this->getDoctrine()->getManager();
  2704.         $em_goc $this->getDoctrine()->getManager('company_group');
  2705.         $session $data->getSession();
  2706. //        $token = $session->get(UserConstants::USER_TOKEN);
  2707. //        $providedToken = $data->headers->get('auth-token');
  2708. //
  2709. //        if (empty($providedToken) || $providedToken !== $token) {
  2710. //            return new JsonResponse([
  2711. //                'status' => 'error',
  2712. //                'message' => 'Token not match or missing',
  2713. //            ], 401);
  2714. //        }
  2715.         $workHourPolicy $em->getRepository('ApplicationBundle:WorkHourPolicy')->findAll();
  2716.         $options = array(
  2717.             'notification_enabled' => $this->container->getParameter('notification_enabled'),
  2718.             'notification_server' => $this->container->getParameter('notification_server'),
  2719.         );
  2720.         if ($data->get('DataTable')) {
  2721.             $response HumanResource::HandelAjaxRequestForManualAttendance($em$data);
  2722.             return new JsonResponse($response);
  2723.         }
  2724.         if ($data->request->get('getAttendanceStatus')) {
  2725.             $response HumanResource::getAttendanceStatus($em$data);
  2726.             return new JsonResponse($response);
  2727.         }
  2728. //        if ($session->get('devAdminMode', 0) != 1 && $data->get('returnJson', 0) == 0)
  2729. //            return $this->redirectToRoute('permission_denied_page');
  2730.         // Auto attendance
  2731.         if ($data->get('autoAttendance') && $data->request->has('position_array')) {
  2732. //            $empId = $data->query->get('id');
  2733.             $empId $data->request->get('id'$session->get(UserConstants::USER_EMPLOYEE_ID));
  2734.             $positionsArray $data->request->get('position_array', []);
  2735.             if (is_string($positionsArray)) $positionsArray json_decode($positionsArraytrue);
  2736.             if ($positionsArray == null$positionsArray = [];
  2737.             $dataByAttId = [];
  2738.             $workPlaceType '_UNSET_';
  2739.             foreach ($positionsArray as $d) {
  2740.                 $sysUserId 0;
  2741.                 $userId 0;
  2742.                 $empId 0;
  2743.                 $dtTs 0;
  2744.                 $timeZoneStr '+0000';
  2745. //                $timeZoneStr = '+0600';
  2746.                 $token '_unset_';
  2747.                 if (isset($d['token'])) $token $d['token'];
  2748.                 if (isset($d['employeeId'])) $empId $d['employeeId'];
  2749.                 if (isset($d['userId'])) $userId $d['userId'];
  2750.                 if (isset($d['sysUserId'])) $sysUserId $d['sysUserId'];
  2751.                 if (isset($d['tsMilSec'])) {
  2752.                     $dtTs ceil(($d['tsMilSec']) / 1000);
  2753.                 }
  2754.                 if ($token != '_unset_') {
  2755.                     $sessionData MiscActions::GetSessionDataFromToken($em_goc$token)['sessionData'];
  2756.                     if (isset($sessionData[UserConstants::USER_EMPLOYEE_ID]))
  2757.                         $empId $sessionData[UserConstants::USER_EMPLOYEE_ID];
  2758.                 }
  2759.                 if ($sysUserId == 0)
  2760.                     $sysUserId $userId;
  2761.                 if ($sysUserId == 0)
  2762.                     $sysUserId $em->getRepository(Employee::class)
  2763.                         ->findOneBy(['employeeId' => $empId])->getUserId();
  2764.                 if ($dtTs == 0) {
  2765.                     $currTsTime = new \DateTime();
  2766.                     $dtTs $currTsTime->format('U');
  2767.                 } else {
  2768.                     $currTsTime = new \DateTime('@' $dtTs);
  2769.                 }
  2770.                 $currTsTime->setTimezone(new \DateTimeZone('UTC'));
  2771.                 $attDate = new \DateTime($currTsTime->format('Y-m-d') . ' 00:00:00' $timeZoneStr);
  2772.                 $EmployeeAttendance $this->getDoctrine()
  2773.                     ->getRepository(EmployeeAttendance::class)
  2774.                     ->findOneBy(array('employeeId' => $empId'date' => $attDate));
  2775.                 if (!$EmployeeAttendance)
  2776.                     $EmployeeAttendance = new EmployeeAttendance;
  2777.                 $attendanceInfo HumanResource::StoreAttendance($em$empId$sysUserId$data$EmployeeAttendance$attDate$dtTs$timeZoneStr$d['markerId']);
  2778.                 if ($d['markerId'] == HumanResourceConstant::ATTENDANCE_MARKER_CLOCK_IN) {
  2779.                     if ($empId == 24)
  2780.                         $workPlaceType '_HYBRID_';
  2781.                     else
  2782.                         $workPlaceType '_STATIC_';
  2783.                 }
  2784.                 if (!isset($dataByAttId[$attendanceInfo->getId()]))
  2785.                     $dataByAttId[$attendanceInfo->getId()] = array(
  2786.                         'attendanceInfo' => $attendanceInfo,
  2787.                         'empId' => $empId,
  2788.                         'lat' => 0,
  2789.                         'lng' => 0,
  2790.                         'address' => 0,
  2791.                         'sysUserId' => $sysUserId,
  2792.                         'companyId' => $data->getSession()->get(UserConstants::USER_COMPANY_ID),
  2793.                         'appId' => $data->getSession()->get(UserConstants::USER_APP_ID),
  2794.                         'positionArray' => []
  2795.                     );
  2796.                 $posData = array(
  2797.                     'ts' => $dtTs,
  2798.                     'lat' => $d['lat'],
  2799.                     'lng' => $d['lng'],
  2800.                     'marker' => $d['markerId'],
  2801.                     'src' => 2,
  2802.                 );
  2803.                 $posDataArray = array(
  2804.                     $dtTs,
  2805.                     $d['lat'],
  2806.                     $d['lng'],
  2807.                     $d['markerId'],
  2808.                     2
  2809.                 );
  2810.                 $dataByAttId[$attendanceInfo->getId()]['markerId'] = $d['markerId'];
  2811.                 //this markerId will be calclulted and modified to check if user is in our out of office/workplace later
  2812.                 $dataByAttId[$attendanceInfo->getId()]['attendanceInfo'] = $attendanceInfo;
  2813.                 $dataByAttId[$attendanceInfo->getId()]['positionArray'][] = $posData;
  2814.                 $dataByAttId[$attendanceInfo->getId()]['lat'] = $d['lat'];  //for last lat lng etc
  2815.                 $dataByAttId[$attendanceInfo->getId()]['lng'] = $d['lng'];  //for last lat lng etc
  2816.                 if (isset($d['address']))
  2817.                     $dataByAttId[$attendanceInfo->getId()]['address'] = $d['address'];  //for last lat lng etc
  2818. //                $dataByAttId[$attendanceInfo->getId()]['positionArray'][]=$posDataArray;
  2819.             }
  2820.             $response = array(
  2821.                 'success' => true,
  2822.             );
  2823.             foreach ($dataByAttId as $attInfoId => $d) {
  2824.                 $response HumanResource::setAttendanceLogFlutterApp($em,
  2825.                     $d['empId'],
  2826.                     $d['sysUserId'],
  2827.                     $d['companyId'],
  2828.                     $d['appId'],
  2829.                     $data,
  2830.                     $d['attendanceInfo'],
  2831.                     $options,
  2832.                     $d['positionArray'],
  2833.                     $d['lat'],
  2834.                     $d['lng'],
  2835.                     $d['address'],
  2836.                     $d['markerId']
  2837.                 );
  2838.             }
  2839.             if ($data->request->get('requestFromMobile')) {
  2840.                 $today = new \DateTime(date('y-m-d'));
  2841.                 $repository $this->getDoctrine()->getRepository(EmployeeAttendance::class);
  2842.                 $ActivitiesTemplate HumanResource::getCurrentStatusFromDb($repository$empId$today);
  2843.                 return new JsonResponse(array(
  2844.                     'success' => $response['success'] == true true false,
  2845.                     'msg' => $response['success'] == true 'Employee activities successfully updated.' 'Action Failed',
  2846.                     'workPlaceType' => $workPlaceType,
  2847.                     'data' => $ActivitiesTemplate
  2848.                 ));
  2849.             }
  2850.             return new JsonResponse(
  2851.                 array(
  2852.                     'success' => true,
  2853.                     'msg' => 'Employee activities successfully updated.',
  2854.                     'workPlaceType' => $workPlaceType,
  2855.                 )
  2856.             );
  2857.         } else if ($data->get('autoAttendance')) {
  2858.             $sysUserId 0;
  2859.             $userId 0;
  2860.             $empId 0;
  2861.             $dtTs 0;
  2862. //            $timeZoneStr = '+0600';
  2863.             $timeZoneStr '+0000';
  2864.             if ($data->request->get('requestFromMobile')) {
  2865.                 $empId $data->request->get('employeeId');
  2866.                 $userId $data->request->get('userId'0);
  2867.                 $sysUserId $data->request->get('id'0);
  2868. //        $empId = $em->getRepository(Employee::class)
  2869. //            ->findOneBy(['userId' => $userId])->getEmployeeId();
  2870.             } else {
  2871.                 $empId $data->request->get('employeeId'0);
  2872.                 $sysUserId $data->request->get('userId'0);
  2873.             }
  2874.             $dtTs $data->request->get('timeTs'0);
  2875.             if ($sysUserId == 0)
  2876.                 $sysUserId $userId;
  2877.             if ($sysUserId == 0)
  2878.                 $sysUserId $em->getRepository(Employee::class)
  2879.                     ->findOneBy(['employeeId' => $empId])->getUserId();
  2880.             if ($dtTs == 0) {
  2881.                 $currTsTime = new \DateTime();
  2882.                 $dtTs $currTsTime->format('U');
  2883.             } else {
  2884.                 $currTsTime = new \DateTime('@' $dtTs);
  2885.             }
  2886.             if ($sysUserId == 0)
  2887.                 $sysUserId $userId;
  2888.             if ($sysUserId == 0)
  2889.                 $sysUserId $em->getRepository(Employee::class)
  2890.                     ->findOneBy(['employeeId' => $empId])->getUserId();
  2891.             $today = new \DateTime(date('y-m-d'));
  2892.             $currTsTime->setTimezone(new \DateTimeZone('UTC'));
  2893.             $attDate = new \DateTime($currTsTime->format('Y-m-d') . ' 00:00:00' $timeZoneStr);
  2894.             $EmployeeAttendance $this->getDoctrine()
  2895.                 ->getRepository(EmployeeAttendance::class)
  2896.                 ->findOneBy(array('employeeId' => $empId'date' => $attDate));
  2897.             if (!$EmployeeAttendance)
  2898.                 $EmployeeAttendance = new EmployeeAttendance;
  2899. //            return new JsonResponse(["success" => true, "data" => $ActivitiesTemplate]);
  2900. //            $attendanceInfo = HumanResource::StoreAttendance($em, $empId, $sysUserId, $data, $EmployeeAttendance, $customTime);
  2901.             $attendanceInfo HumanResource::StoreAttendance($em$empId$sysUserId$data$EmployeeAttendance$attDate$dtTs$timeZoneStrHumanResourceConstant::ATTENDANCE_MARKER_START_WORKING_FORCED);
  2902.             if (!isset($dataByAttId[$attendanceInfo->getId()]))
  2903.                 $dataByAttId[$attendanceInfo->getId()] = array(
  2904.                     'attendanceInfo' => $attendanceInfo,
  2905.                     'empId' => $empId,
  2906.                     'lat' => 0,
  2907.                     'lng' => 0,
  2908.                     'address' => 0,
  2909.                     'sysUserId' => $sysUserId,
  2910.                     'companyId' => $data->getSession()->get(UserConstants::USER_COMPANY_ID),
  2911.                     'appId' => $data->getSession()->get(UserConstants::USER_APP_ID),
  2912.                     'positionArray' => []
  2913.                 );
  2914.             $posData = array(
  2915.                 'ts' => $dtTs,
  2916.                 'lat' => 0,
  2917.                 'lng' => 0,
  2918.                 'marker' => HumanResourceConstant::ATTENDANCE_MARKER_START_WORKING_FORCED,
  2919.                 'src' => 1,
  2920.             );
  2921.             $posDataArray = array(
  2922.                 $dtTs,
  2923.                 0,
  2924.                 0,
  2925.                 HumanResourceConstant::ATTENDANCE_MARKER_START_WORKING_FORCED,
  2926.                 1
  2927.             );
  2928.             $dataByAttId[$attendanceInfo->getId()]['markerId'] = HumanResourceConstant::ATTENDANCE_MARKER_START_WORKING_FORCED;
  2929.             //this markerId will be calclulted and modified to check if user is in our out of office/workplace later
  2930.             $dataByAttId[$attendanceInfo->getId()]['attendanceInfo'] = $attendanceInfo;
  2931.             $dataByAttId[$attendanceInfo->getId()]['positionArray'][] = $posData;
  2932.             $dataByAttId[$attendanceInfo->getId()]['lat'] = 0;  //for last lat lng etc
  2933.             $dataByAttId[$attendanceInfo->getId()]['lng'] = 0;  //for last lat lng etc
  2934.             if (isset($d['address']))
  2935.                 $dataByAttId[$attendanceInfo->getId()]['address'] = '';  //for last lat lng etc
  2936.             $response = array(
  2937.                 'success' => true
  2938.             );
  2939.             foreach ($dataByAttId as $attInfoId => $d) {
  2940.                 $response HumanResource::setAttendanceLogFlutterApp($em,
  2941.                     $d['empId'],
  2942.                     $d['sysUserId'],
  2943.                     $d['companyId'],
  2944.                     $d['appId'],
  2945.                     $data,
  2946.                     $d['attendanceInfo'],
  2947.                     $options,
  2948.                     $d['positionArray'],
  2949.                     $d['lat'],
  2950.                     $d['lng'],
  2951.                     $d['address'],
  2952.                     $d['markerId']
  2953.                 );
  2954.             }
  2955.             if ($data->request->get('requestFromMobile')) {
  2956.                 return new JsonResponse(array(
  2957.                     'success' => $response['success'] == true true false,
  2958.                     'msg' => $response['success'] == true 'Employee activities successfully updated.' 'Action Failed',
  2959.                 ));
  2960.             }
  2961.             return new JsonResponse(
  2962.                 array(
  2963.                     'success' => true,
  2964.                     'dtTs' => $dtTs,
  2965.                     'attDate' => $attDate->format(DATE_RFC822),
  2966.                     'currTsTime' => $currTsTime->format(DATE_RFC822),
  2967.                     'msg' => 'Employee activities successfully updated.',
  2968.                 )
  2969.             );
  2970. //
  2971. //
  2972. //            $response = HumanResource::setAttendanceLog($em, $empId, $sysUserId,
  2973. //                $data->getSession()->get(UserConstants::USER_COMPANY_ID),
  2974. //                $data->getSession()->get(UserConstants::USER_APP_ID),
  2975. //                $data, $attendanceInfo, $options);
  2976. //
  2977. //            if ($data->request->get('requestFromMobile')) {
  2978. //                return new JsonResponse($response);
  2979. //            }
  2980. //
  2981. //            return new JsonResponse(
  2982. //                array(
  2983. //                    'success' => true,
  2984. //                    'msg' => 'Employee activities successfully updated.'
  2985. //                )
  2986. //            );
  2987.             // }
  2988.             // else {
  2989.             //   return new JsonResponse(
  2990.             //     array(
  2991.             //       'success' => false,
  2992.             //       'msg' => "Invalid employee ID"
  2993.             //     )
  2994.             //   );
  2995.             // }
  2996.         } else {
  2997.             if ($data->get('manualAttendance')) {
  2998.                 return $this->render(
  2999.                     'ApplicationBundle:pages/human_resource/input_forms:manual_attendance.html.twig',
  3000.                     array(
  3001.                         'page_title' => 'Manual Attendance',
  3002.                         'workPolicy' => $workHourPolicy,
  3003. //                        'workTime' => json_decode($workHourPolicy->getRepeatationData()),
  3004. //                        'workTime' => json_decode($workHourPolicy->getRepeatationData()),
  3005. //                        'workTime' => json_decode($workHourPolicy->getEmployeeTypeIds(),true),
  3006.                     )
  3007.                 );
  3008.             }
  3009.             // Show all matching employee list during ajax request
  3010.             // Show current location according to id
  3011.             if ($data->get('getCurrLocById')) {
  3012.                 $Id $data->get("id");
  3013.                 $options = array(
  3014.                     'employeeId' => $Id,
  3015.                     'entityDbaseName' => 'work_hour_policy',
  3016.                     'entityDbaseIdField' => 'id',
  3017.                     'entityDbaseEmployeeIdsField' => 'employeeIds',
  3018.                     'entityDesignationIdsField' => 'designationIds',
  3019.                     'entityDepartmentIdsField' => 'departmentIds',
  3020.                     'entityEmployeeTypeIdsField' => 'employee_types',
  3021.                     'limit' => 1,
  3022.                     'single' => 1,
  3023.                 );
  3024.                 $workHourPolicyData HumanResource::getApplicableSettingsDataForEmployee($em$options);
  3025.                 $today = new \DateTime(date('y-m-d'));
  3026.                 $repository $this->getDoctrine()->getRepository(EmployeeAttendance::class);
  3027.                 $ActivitiesTemplate HumanResource::getActivitiesTemplate($repository$Id$today);
  3028.                 return new JsonResponse(["success" => true"workHourPolicyData" => $workHourPolicyData"template" => $ActivitiesTemplate]);
  3029.             }
  3030.         }
  3031.     }
  3032.     public function AttendanceForAppAction(Request $data$remoteVerify 0)
  3033.     {
  3034.         $em $this->getDoctrine()->getManager();
  3035.         $em_goc $this->getDoctrine()->getManager('company_group');
  3036.         $session $data->getSession();
  3037.         $token $session->get(UserConstants::USER_TOKEN);
  3038.         $providedToken $data->headers->get('auth-token');
  3039.         if (empty($providedToken) || $providedToken !== $token) {
  3040.             return new JsonResponse([
  3041.                 'status' => 'error',
  3042.                 'message' => 'Token not match or missing',
  3043.             ], 401);
  3044.         }
  3045.         $workHourPolicy $em->getRepository('ApplicationBundle:WorkHourPolicy')->findAll();
  3046.         $options = array(
  3047.             'notification_enabled' => $this->container->getParameter('notification_enabled'),
  3048.             'notification_server' => $this->container->getParameter('notification_server'),
  3049.         );
  3050.         if ($data->get('DataTable')) {
  3051.             $response HumanResource::HandelAjaxRequestForManualAttendance($em$data);
  3052.             return new JsonResponse($response);
  3053.         }
  3054.         if ($data->request->get('getAttendanceStatus')) {
  3055.             $response HumanResource::getAttendanceStatus($em$data);
  3056.             return new JsonResponse($response);
  3057.         }
  3058. //        if ($session->get('devAdminMode', 0) != 1 && $data->get('returnJson', 0) == 0)
  3059. //            return $this->redirectToRoute('permission_denied_page');
  3060.         // Auto attendance
  3061.         if ($data->get('autoAttendance') && $data->request->has('position_array')) {
  3062. //            $empId = $data->query->get('id');
  3063.             $empId $data->request->get('id'$session->get(UserConstants::USER_EMPLOYEE_ID));
  3064.             $positionsArray $data->request->get('position_array', []);
  3065.             if (is_string($positionsArray)) $positionsArray json_decode($positionsArraytrue);
  3066.             if ($positionsArray == null$positionsArray = [];
  3067.             $dataByAttId = [];
  3068.             $workPlaceType '_UNSET_';
  3069.             foreach ($positionsArray as $d) {
  3070.                 $sysUserId 0;
  3071.                 $userId 0;
  3072.                 $empId 0;
  3073.                 $dtTs 0;
  3074.                 $timeZoneStr '+0000';
  3075. //                $timeZoneStr = '+0600';
  3076.                 $token '_unset_';
  3077.                 if (isset($d['token'])) $token $d['token'];
  3078.                 if (isset($d['employeeId'])) $empId $d['employeeId'];
  3079.                 if (isset($d['userId'])) $userId $d['userId'];
  3080.                 if (isset($d['sysUserId'])) $sysUserId $d['sysUserId'];
  3081.                 if (isset($d['tsMilSec'])) {
  3082.                     $dtTs ceil(($d['tsMilSec']) / 1000);
  3083.                 }
  3084.                 if ($token != '_unset_') {
  3085.                     $sessionData MiscActions::GetSessionDataFromToken($em_goc$token)['sessionData'];
  3086.                     if (isset($sessionData[UserConstants::USER_EMPLOYEE_ID]))
  3087.                         $empId $sessionData[UserConstants::USER_EMPLOYEE_ID];
  3088.                 }
  3089.                 if ($sysUserId == 0)
  3090.                     $sysUserId $userId;
  3091.                 if ($sysUserId == 0)
  3092.                     $sysUserId $em->getRepository(Employee::class)
  3093.                         ->findOneBy(['employeeId' => $empId])->getUserId();
  3094.                 if ($dtTs == 0) {
  3095.                     $currTsTime = new \DateTime();
  3096.                     $dtTs $currTsTime->format('U');
  3097.                 } else {
  3098.                     $currTsTime = new \DateTime('@' $dtTs);
  3099.                 }
  3100.                 $currTsTime->setTimezone(new \DateTimeZone('UTC'));
  3101.                 $attDate = new \DateTime($currTsTime->format('Y-m-d') . ' 00:00:00' $timeZoneStr);
  3102.                 $EmployeeAttendance $this->getDoctrine()
  3103.                     ->getRepository(EmployeeAttendance::class)
  3104.                     ->findOneBy(array('employeeId' => $empId'date' => $attDate));
  3105.                 if (!$EmployeeAttendance)
  3106.                     $EmployeeAttendance = new EmployeeAttendance;
  3107.                 $attendanceInfo HumanResource::StoreAttendance($em$empId$sysUserId$data$EmployeeAttendance$attDate$dtTs$timeZoneStr$d['markerId']);
  3108.                 if ($d['markerId'] == HumanResourceConstant::ATTENDANCE_MARKER_CLOCK_IN) {
  3109.                     if ($empId == 24)
  3110.                         $workPlaceType '_HYBRID_';
  3111.                     else
  3112.                         $workPlaceType '_STATIC_';
  3113.                 }
  3114.                 if (!isset($dataByAttId[$attendanceInfo->getId()]))
  3115.                     $dataByAttId[$attendanceInfo->getId()] = array(
  3116.                         'attendanceInfo' => $attendanceInfo,
  3117.                         'empId' => $empId,
  3118.                         'lat' => 0,
  3119.                         'lng' => 0,
  3120.                         'address' => 0,
  3121.                         'sysUserId' => $sysUserId,
  3122.                         'companyId' => $data->getSession()->get(UserConstants::USER_COMPANY_ID),
  3123.                         'appId' => $data->getSession()->get(UserConstants::USER_APP_ID),
  3124.                         'positionArray' => []
  3125.                     );
  3126.                 $posData = array(
  3127.                     'ts' => $dtTs,
  3128.                     'lat' => $d['lat'],
  3129.                     'lng' => $d['lng'],
  3130.                     'marker' => $d['markerId'],
  3131.                     'src' => 2,
  3132.                 );
  3133.                 $posDataArray = array(
  3134.                     $dtTs,
  3135.                     $d['lat'],
  3136.                     $d['lng'],
  3137.                     $d['markerId'],
  3138.                     2
  3139.                 );
  3140.                 $dataByAttId[$attendanceInfo->getId()]['markerId'] = $d['markerId'];
  3141.                 //this markerId will be calclulted and modified to check if user is in our out of office/workplace later
  3142.                 $dataByAttId[$attendanceInfo->getId()]['attendanceInfo'] = $attendanceInfo;
  3143.                 $dataByAttId[$attendanceInfo->getId()]['positionArray'][] = $posData;
  3144.                 $dataByAttId[$attendanceInfo->getId()]['lat'] = $d['lat'];  //for last lat lng etc
  3145.                 $dataByAttId[$attendanceInfo->getId()]['lng'] = $d['lng'];  //for last lat lng etc
  3146.                 if (isset($d['address']))
  3147.                     $dataByAttId[$attendanceInfo->getId()]['address'] = $d['address'];  //for last lat lng etc
  3148. //                $dataByAttId[$attendanceInfo->getId()]['positionArray'][]=$posDataArray;
  3149.             }
  3150.             $response = array(
  3151.                 'success' => true,
  3152.             );
  3153.             foreach ($dataByAttId as $attInfoId => $d) {
  3154.                 $response HumanResource::setAttendanceLogFlutterApp($em,
  3155.                     $d['empId'],
  3156.                     $d['sysUserId'],
  3157.                     $d['companyId'],
  3158.                     $d['appId'],
  3159.                     $data,
  3160.                     $d['attendanceInfo'],
  3161.                     $options,
  3162.                     $d['positionArray'],
  3163.                     $d['lat'],
  3164.                     $d['lng'],
  3165.                     $d['address'],
  3166.                     $d['markerId']
  3167.                 );
  3168.             }
  3169.             if ($data->request->get('requestFromMobile')) {
  3170.                 $today = new \DateTime(date('y-m-d'));
  3171.                 $repository $this->getDoctrine()->getRepository(EmployeeAttendance::class);
  3172.                 $ActivitiesTemplate HumanResource::getCurrentStatusFromDb($repository$empId$today);
  3173.                 return new JsonResponse(array(
  3174.                     'success' => $response['success'] == true true false,
  3175.                     'msg' => $response['success'] == true 'Employee activities successfully updated.' 'Action Failed',
  3176.                     'workPlaceType' => $workPlaceType,
  3177.                     'data' => $ActivitiesTemplate
  3178.                 ));
  3179.             }
  3180.             return new JsonResponse(
  3181.                 array(
  3182.                     'success' => true,
  3183.                     'msg' => 'Employee activities successfully updated.',
  3184.                     'workPlaceType' => $workPlaceType,
  3185.                 )
  3186.             );
  3187.         } else if ($data->get('autoAttendance')) {
  3188.             $sysUserId 0;
  3189.             $userId 0;
  3190.             $empId 0;
  3191.             $dtTs 0;
  3192. //            $timeZoneStr = '+0600';
  3193.             $timeZoneStr '+0000';
  3194.             if ($data->request->get('requestFromMobile')) {
  3195.                 $empId $data->request->get('employeeId');
  3196.                 $userId $data->request->get('userId'0);
  3197.                 $sysUserId $data->request->get('id'0);
  3198. //        $empId = $em->getRepository(Employee::class)
  3199. //            ->findOneBy(['userId' => $userId])->getEmployeeId();
  3200.             } else {
  3201.                 $empId $data->request->get('employeeId'0);
  3202.                 $sysUserId $data->request->get('userId'0);
  3203.             }
  3204.             $dtTs $data->request->get('timeTs'0);
  3205.             if ($sysUserId == 0)
  3206.                 $sysUserId $userId;
  3207.             if ($sysUserId == 0)
  3208.                 $sysUserId $em->getRepository(Employee::class)
  3209.                     ->findOneBy(['employeeId' => $empId])->getUserId();
  3210.             if ($dtTs == 0) {
  3211.                 $currTsTime = new \DateTime();
  3212.                 $dtTs $currTsTime->format('U');
  3213.             } else {
  3214.                 $currTsTime = new \DateTime('@' $dtTs);
  3215.             }
  3216.             if ($sysUserId == 0)
  3217.                 $sysUserId $userId;
  3218.             if ($sysUserId == 0)
  3219.                 $sysUserId $em->getRepository(Employee::class)
  3220.                     ->findOneBy(['employeeId' => $empId])->getUserId();
  3221.             $today = new \DateTime(date('y-m-d'));
  3222.             $currTsTime->setTimezone(new \DateTimeZone('UTC'));
  3223.             $attDate = new \DateTime($currTsTime->format('Y-m-d') . ' 00:00:00' $timeZoneStr);
  3224.             $EmployeeAttendance $this->getDoctrine()
  3225.                 ->getRepository(EmployeeAttendance::class)
  3226.                 ->findOneBy(array('employeeId' => $empId'date' => $attDate));
  3227.             if (!$EmployeeAttendance)
  3228.                 $EmployeeAttendance = new EmployeeAttendance;
  3229. //            return new JsonResponse(["success" => true, "data" => $ActivitiesTemplate]);
  3230. //            $attendanceInfo = HumanResource::StoreAttendance($em, $empId, $sysUserId, $data, $EmployeeAttendance, $customTime);
  3231.             $attendanceInfo HumanResource::StoreAttendance($em$empId$sysUserId$data$EmployeeAttendance$attDate$dtTs$timeZoneStrHumanResourceConstant::ATTENDANCE_MARKER_START_WORKING_FORCED);
  3232.             if (!isset($dataByAttId[$attendanceInfo->getId()]))
  3233.                 $dataByAttId[$attendanceInfo->getId()] = array(
  3234.                     'attendanceInfo' => $attendanceInfo,
  3235.                     'empId' => $empId,
  3236.                     'lat' => 0,
  3237.                     'lng' => 0,
  3238.                     'address' => 0,
  3239.                     'sysUserId' => $sysUserId,
  3240.                     'companyId' => $data->getSession()->get(UserConstants::USER_COMPANY_ID),
  3241.                     'appId' => $data->getSession()->get(UserConstants::USER_APP_ID),
  3242.                     'positionArray' => []
  3243.                 );
  3244.             $posData = array(
  3245.                 'ts' => $dtTs,
  3246.                 'lat' => 0,
  3247.                 'lng' => 0,
  3248.                 'marker' => HumanResourceConstant::ATTENDANCE_MARKER_START_WORKING_FORCED,
  3249.                 'src' => 1,
  3250.             );
  3251.             $posDataArray = array(
  3252.                 $dtTs,
  3253.                 0,
  3254.                 0,
  3255.                 HumanResourceConstant::ATTENDANCE_MARKER_START_WORKING_FORCED,
  3256.                 1
  3257.             );
  3258.             $dataByAttId[$attendanceInfo->getId()]['markerId'] = HumanResourceConstant::ATTENDANCE_MARKER_START_WORKING_FORCED;
  3259.             //this markerId will be calclulted and modified to check if user is in our out of office/workplace later
  3260.             $dataByAttId[$attendanceInfo->getId()]['attendanceInfo'] = $attendanceInfo;
  3261.             $dataByAttId[$attendanceInfo->getId()]['positionArray'][] = $posData;
  3262.             $dataByAttId[$attendanceInfo->getId()]['lat'] = 0;  //for last lat lng etc
  3263.             $dataByAttId[$attendanceInfo->getId()]['lng'] = 0;  //for last lat lng etc
  3264.             if (isset($d['address']))
  3265.                 $dataByAttId[$attendanceInfo->getId()]['address'] = '';  //for last lat lng etc
  3266.             $response = array(
  3267.                 'success' => true
  3268.             );
  3269.             foreach ($dataByAttId as $attInfoId => $d) {
  3270.                 $response HumanResource::setAttendanceLogFlutterApp($em,
  3271.                     $d['empId'],
  3272.                     $d['sysUserId'],
  3273.                     $d['companyId'],
  3274.                     $d['appId'],
  3275.                     $data,
  3276.                     $d['attendanceInfo'],
  3277.                     $options,
  3278.                     $d['positionArray'],
  3279.                     $d['lat'],
  3280.                     $d['lng'],
  3281.                     $d['address'],
  3282.                     $d['markerId']
  3283.                 );
  3284.             }
  3285.             if ($data->request->get('requestFromMobile')) {
  3286.                 return new JsonResponse(array(
  3287.                     'success' => $response['success'] == true true false,
  3288.                     'msg' => $response['success'] == true 'Employee activities successfully updated.' 'Action Failed',
  3289.                 ));
  3290.             }
  3291.             return new JsonResponse(
  3292.                 array(
  3293.                     'success' => true,
  3294.                     'dtTs' => $dtTs,
  3295.                     'attDate' => $attDate->format(DATE_RFC822),
  3296.                     'currTsTime' => $currTsTime->format(DATE_RFC822),
  3297.                     'msg' => 'Employee activities successfully updated.',
  3298.                 )
  3299.             );
  3300. //
  3301. //
  3302. //            $response = HumanResource::setAttendanceLog($em, $empId, $sysUserId,
  3303. //                $data->getSession()->get(UserConstants::USER_COMPANY_ID),
  3304. //                $data->getSession()->get(UserConstants::USER_APP_ID),
  3305. //                $data, $attendanceInfo, $options);
  3306. //
  3307. //            if ($data->request->get('requestFromMobile')) {
  3308. //                return new JsonResponse($response);
  3309. //            }
  3310. //
  3311. //            return new JsonResponse(
  3312. //                array(
  3313. //                    'success' => true,
  3314. //                    'msg' => 'Employee activities successfully updated.'
  3315. //                )
  3316. //            );
  3317.             // }
  3318.             // else {
  3319.             //   return new JsonResponse(
  3320.             //     array(
  3321.             //       'success' => false,
  3322.             //       'msg' => "Invalid employee ID"
  3323.             //     )
  3324.             //   );
  3325.             // }
  3326.         } else {
  3327.             if ($data->get('manualAttendance')) {
  3328.                 return $this->render(
  3329.                     'ApplicationBundle:pages/human_resource/input_forms:manual_attendance.html.twig',
  3330.                     array(
  3331.                         'page_title' => 'Manual Attendance',
  3332.                         'workPolicy' => $workHourPolicy,
  3333. //                        'workTime' => json_decode($workHourPolicy->getRepeatationData()),
  3334. //                        'workTime' => json_decode($workHourPolicy->getRepeatationData()),
  3335. //                        'workTime' => json_decode($workHourPolicy->getEmployeeTypeIds(),true),
  3336.                     )
  3337.                 );
  3338.             }
  3339.             // Show all matching employee list during ajax request
  3340.             // Show current location according to id
  3341.             if ($data->get('getCurrLocById')) {
  3342.                 $Id $data->get("id");
  3343.                 $options = array(
  3344.                     'employeeId' => $Id,
  3345.                     'entityDbaseName' => 'work_hour_policy',
  3346.                     'entityDbaseIdField' => 'id',
  3347.                     'entityDbaseEmployeeIdsField' => 'employeeIds',
  3348.                     'entityDesignationIdsField' => 'designationIds',
  3349.                     'entityDepartmentIdsField' => 'departmentIds',
  3350.                     'entityEmployeeTypeIdsField' => 'employee_types',
  3351.                     'limit' => 1,
  3352.                     'single' => 1,
  3353.                 );
  3354.                 $workHourPolicyData HumanResource::getApplicableSettingsDataForEmployee($em$options);
  3355.                 $today = new \DateTime(date('y-m-d'));
  3356.                 $repository $this->getDoctrine()->getRepository(EmployeeAttendance::class);
  3357.                 $ActivitiesTemplate HumanResource::getActivitiesTemplate($repository$Id$today);
  3358.                 return new JsonResponse(["success" => true"workHourPolicyData" => $workHourPolicyData"template" => $ActivitiesTemplate]);
  3359.             }
  3360.         }
  3361.     }
  3362.     public function getCurrentStatusAction($id)
  3363.     {
  3364.         $today = new \DateTime(date('y-m-d'));
  3365.         $repository $this->getDoctrine()->getRepository(EmployeeAttendance::class);
  3366.         $ActivitiesTemplate HumanResource::getCurrentStatusFromDb($repository$id$today);
  3367.         return new JsonResponse(["success" => true"data" => $ActivitiesTemplate]);
  3368.     }
  3369.     public function CurrentAttendanceAction(Request $data)
  3370.     {
  3371.         $em $this->getDoctrine()->getManager();
  3372.         $options = array(
  3373.             'notification_enabled' => $this->container->getParameter('notification_enabled'),
  3374.             'notification_server' => $this->container->getParameter('notification_server'),
  3375.         );
  3376.         if ($data->get('DataTable')) {
  3377.             $response HumanResource::HandelAjaxRequestForManualAttendance($em$data);
  3378.             return new JsonResponse($response);
  3379.         }
  3380.         if ($data->request->get('getAttendanceStatus')) {
  3381.             $response HumanResource::getAttendanceStatus($em$data);
  3382.             return new JsonResponse($response);
  3383.         }
  3384.         // Auto attendance
  3385.         if ($data->get('autoAttendance')) {
  3386.             $empId $data->query->get('id');
  3387.             $sysUserId 0;
  3388.             if ($data->get('requestFromMobile')) {
  3389.                 $sysUserId $data->request->get('id');
  3390.                 $empId $em->getRepository(Employee::class)
  3391.                     ->findOneBy(['userId' => $sysUserId])->getEmployeeId();
  3392.             } else {
  3393.                 $sysUserId $em->getRepository(Employee::class)
  3394.                     ->findOneBy(['employeeId' => $empId])->getUserId();
  3395.             }
  3396.             $customTime $data->get('time');
  3397.             $today = new \DateTime(date('y-m-d'));
  3398.             $EmployeeAttendance $this->getDoctrine()
  3399.                 ->getRepository(EmployeeAttendance::class)
  3400.                 ->findOneBy(array('employeeId' => $empId'date' => $today));
  3401.             if (!$EmployeeAttendance)
  3402.                 $EmployeeAttendance = new EmployeeAttendance;
  3403.             $attendanceInfo HumanResource::StoreAttendance($em$empId$sysUserId$data$EmployeeAttendance$customTime);
  3404.             $response HumanResource::setAttendanceLog($em$empId$sysUserId,
  3405.                 $data->getSession()->get(UserConstants::USER_COMPANY_ID),
  3406.                 $data->getSession()->get(UserConstants::USER_APP_ID),
  3407.                 $data$attendanceInfo$options);
  3408.             if ($data->get('requestFromMobile')) {
  3409.                 return new JsonResponse([$response]);
  3410.             }
  3411.             return new JsonResponse(
  3412.                 array(
  3413.                     'success' => true,
  3414.                     'msg' => 'Employee activities successfully updated.'
  3415.                 )
  3416.             );
  3417.             // }
  3418.             // else {
  3419.             //   return new JsonResponse(
  3420.             //     array(
  3421.             //       'success' => false,
  3422.             //       'msg' => "Invalid employee ID"
  3423.             //     )
  3424.             //   );
  3425.             // }
  3426.         } else {
  3427.             if ($data->get('manualAttendance')) {
  3428.                 return $this->render(
  3429.                     'ApplicationBundle:pages/human_resource/report:current_attendance.html.twig',
  3430.                     array(
  3431.                         'page_title' => 'Current Attendance Status',
  3432.                     )
  3433.                 );
  3434.             }
  3435.             // Show all matching employee list during ajax request
  3436.             // Show current location according to id
  3437.             if ($data->get('getCurrLocById')) {
  3438.                 $Id $data->get("id");
  3439.                 $today = new \DateTime(date('y-m-d'));
  3440.                 $repository $this->getDoctrine()->getRepository(EmployeeAttendance::class);
  3441.                 $ActivitiesTemplate HumanResource::getActivitiesTemplate($repository$Id$today);
  3442.                 return new JsonResponse(["success" => true"template" => $ActivitiesTemplate]);
  3443.             }
  3444.         }
  3445.     }
  3446.     public function EmployeeLeaveAction(Request $data$id 0)
  3447.     {
  3448.         $em $this->getDoctrine()->getManager();
  3449.         $request $data;
  3450.         if (!$id) {
  3451.             if ($data->isMethod('GET')) {
  3452.                 $EmpID $data->query->get('id');
  3453.                 $LeaveType $data->query->get('leaveType');
  3454.                 if ($data->query->has('id') && $data->query->has('leaveType')) {
  3455.                     $response HumanResource::HandelAjaxRequestForLeaveApp($em$EmpID$LeaveType);
  3456.                     return new JsonResponse($response);
  3457.                 }
  3458.                 if ($data->query->has('id')) {
  3459.                     $Response HumanResource::HandelAjaxRequestForLeaveApp($em$EmpID);
  3460.                     return new JsonResponse($Response);
  3461.                 }
  3462.                 $TemplateData HumanResource::TwigDataForLeaveApp($emFalse);
  3463.                 return $this->render(
  3464.                     'ApplicationBundle:pages/human_resource/input_forms:employee_leave.html.twig',
  3465.                     array(
  3466.                         'page_title' => $TemplateData['Title'],
  3467.                         'EmployeeList' => $TemplateData['EmployeeList'],
  3468.                         'DesignationList' => $TemplateData['DesignationList'],
  3469.                         'HasUpdateMode' => false
  3470.                     )
  3471.                 );
  3472.             } else {
  3473.                 $CompanyId $this->getLoggedUserCompanyId($data);
  3474.                 $Response HumanResource::StoreDataForLeaveApplication($em$id$datafalse$CompanyId);
  3475.                 if ($Response['HasErr']) {
  3476.                     $this->addFlash('error'$Response['msg']);
  3477.                     if ($data->request->has('returnJson')) {
  3478.                         return new JsonResponse(array(
  3479.                             'success' => false,
  3480.                             'errorStr' => $Response['msg'],
  3481.                         ));
  3482.                     } else {
  3483.                         return $this->redirectToRoute('employee_leave');
  3484.                     }
  3485.                 }
  3486.                 $applicationId $Response['applicationId'];
  3487.                 $em_goc $this->getDoctrine()->getManager('company_group');
  3488.                 $file_path_list = [];
  3489.                 if ($applicationId != 0) {
  3490.                     if (!empty($request->files)) {
  3491.                         MiscActions::RemoveFilesForEntityDoc($em_goc'EmployeeLeaveApplication'$applicationId);
  3492.                         $storePath 'uploads/LeaveDoc/';
  3493.                         $path "";
  3494.                         $file_path "";
  3495.                         $session $request->getSession();
  3496.                         MiscActions::RemoveExpiredFiles($em_goc);
  3497.                         foreach ($request->files as $uploadedFileGG) {
  3498.                             //            if($uploadedFile->getImage())
  3499.                             //                var_dump($uploadedFile->getFile());
  3500.                             //                var_dump($uploadedFile);
  3501.                             $tempD $uploadedFileGG;
  3502.                             if (!is_array($uploadedFileGG)) {
  3503.                                 $uploadedFileGG = array();
  3504.                                 $uploadedFileGG[] = $tempD;
  3505.                             }
  3506.                             foreach ($uploadedFileGG as $uploadedFile) {
  3507.                                 if ($uploadedFile != null) {
  3508.                                     $extension $uploadedFile->guessExtension();
  3509.                                     $size $uploadedFile->getSize();
  3510.                                     $fileName 'LDOC_' $applicationId '_' . (md5(uniqid())) . '.' $uploadedFile->guessExtension();
  3511.                                     $path $fileName;
  3512.                                     $upl_dir $this->container->getParameter('kernel.root_dir') . '/../web/' $storePath;
  3513.                                     if (!file_exists($upl_dir)) {
  3514.                                         mkdir($upl_dir0777true);
  3515.                                     }
  3516.                                     if (file_exists($upl_dir '' $path)) {
  3517.                                         chmod($upl_dir '' $path0755);
  3518.                                         unlink($upl_dir '' $path);
  3519.                                     }
  3520.                                     $file $uploadedFile->move($upl_dir$path);
  3521.                                     $expireNever 1;
  3522.                                     $expireTs 0;
  3523.                                     $EntityFile = new EntityFile();
  3524.                                     $EntityFile->setPath($this->container->getParameter('kernel.root_dir') . '/../web/' $storePath $path);
  3525.                                     $EntityFile->setMarker('_GEN_');
  3526.                                     $EntityFile->setExtension($extension);
  3527.                                     $EntityFile->setExpireTs($expireTs);
  3528.                                     $EntityFile->setSize($size);
  3529.                                     $EntityFile->setRelativePath($storePath $path);
  3530.                                     $EntityFile->setEntityName('EmployeeLeaveApplication');
  3531.                                     $EntityFile->setEntityBundle('EmployeeLeaveApplication');
  3532.                                     $EntityFile->setEntityId($applicationId);
  3533.                                     $EntityFile->setEntityIdField('employeeLeaveApplicationId');
  3534.                                     $EntityFile->setModifyFieldSetter('setFiles');
  3535.                                     $EntityFile->setDocIdForApplicant(0);
  3536.                                     $EntityFile->setUserId($session->get(UserConstants::USER_ID0));
  3537.                                     $EntityFile->setAppId($session->get(UserConstants::USER_APP_ID0));
  3538.                                     $EntityFile->setEmployeeId($session->get(UserConstants::USER_EMPLOYEE_ID0));
  3539.                                     $EntityFile->setUserType($session->get(UserConstants::USER_TYPE0));
  3540.                                     $em_goc->persist($EntityFile);
  3541.                                     $em_goc->flush();
  3542.                                     $EntityFileId $EntityFile->getId();
  3543.                                 }
  3544.                                 if ($path != "")
  3545.                                     $file_path_list[] = ($storePath $path);
  3546.                             }
  3547.                         }
  3548.                         $g_path $this->container->getParameter('kernel.root_dir') . '/../web/' $storePath $path;
  3549.                         $v $em->getRepository('ApplicationBundle:EmployeeLeaveApplication')->findOneBy(array(
  3550.                             'employeeLeaveApplicationId' => $applicationId,
  3551.                         ));
  3552.                         if ($v) {
  3553.                             $v->setFiles(implode(','$file_path_list));
  3554.                             $em->flush();
  3555.                         } else {
  3556.                         }
  3557.                     }
  3558.                 }
  3559.                 // $this->addFlash('success', 'Application submitted successfully!');
  3560.                 // return $this->redirectToRoute('leave_application_list');
  3561.                 if ($data->request->has('returnJson')) {
  3562.                     return new JsonResponse(array(
  3563.                         'success' => true,
  3564.                     ));
  3565.                 } else {
  3566.                     return $this->redirectToRoute('view_employee_leave_application', array('id' => $applicationId));
  3567.                 }
  3568.             }
  3569.         } else {
  3570.             if ($data->isMethod('GET')) {
  3571.                 $ApplicationRepo $em->getRepository(EmployeeLeaveApplication::class);
  3572.                 $OldData $ApplicationRepo->find(array('employeeLeaveApplicationId' => $id));
  3573.                 $TemplateData HumanResource::TwigDataForLeaveApp($em$OldData);
  3574.                 return $this->render(
  3575.                     'ApplicationBundle:pages/human_resource/input_forms:employee_leave.html.twig',
  3576.                     array(
  3577.                         'page_title' => $TemplateData['Title'],
  3578.                         'EmployeeList' => $TemplateData['EmployeeList'],
  3579.                         'DesignationList' => $TemplateData['DesignationList'],
  3580.                         'OldData' => $TemplateData['OldData'],
  3581.                         'AvailableLeave' => $TemplateData['AvailableLeave'],
  3582.                         'HasUpdateMode' => true
  3583.                     )
  3584.                 );
  3585.             } else {
  3586.                 $CompanyId $this->getLoggedUserCompanyId($data);
  3587.                 $Response HumanResource::StoreDataForLeaveApplication($em$id$datatrue$CompanyId);
  3588.                 if ($Response['HasErr']) {
  3589.                     $this->addFlash('error'$Response['msg']);
  3590.                     return $this->redirectToRoute('employee_leave');
  3591.                 }
  3592.                 $this->addFlash('success'"Application updated successfully!");
  3593.                 return $this->redirectToRoute('leave_application_list');
  3594.             }
  3595.         }
  3596.     }
  3597.     public function ViewLeaveApplicationAction(Request $request$id)
  3598.     {
  3599.         $em $this->getDoctrine()->getManager();
  3600.         if ($id) {
  3601.             $TwigData HumanResource::TwigDataForViewLeaveApplication($em$request$id);
  3602.             if ($TwigData['HasErr']) {
  3603.                 return new JsonResponse(array(
  3604.                     'success' => false,
  3605.                     'msg' => $TwigData['Msg']
  3606.                 ));
  3607.             }
  3608.             return $this->render(
  3609.                 'ApplicationBundle:pages/human_resource/views:leave_application_view.html.twig',
  3610.                 array(
  3611.                     'page_title' => 'View Leave Application',
  3612.                     'Applicant' => $TwigData['Applicant'],
  3613.                     'Application' => $TwigData['Application'],
  3614.                     'LeaveType' => $TwigData['LeaveType'],
  3615.                     'LeaveCategory' => $TwigData['LeaveCategory'],
  3616.                     'leaveDataArray' => $TwigData['leaveDataArray'],
  3617.                     'FrwdEmp' => $TwigData['FrwdEmp'],
  3618.                     'ApplicantDesg' => $TwigData['ApplicantDesg'],
  3619.                     'approval_status' => $TwigData['approval_status'],
  3620.                     'approval_data' => $TwigData['approval_data'],
  3621.                     'document_log' => $TwigData['document_log'],
  3622.                     'auto_created' => 0,
  3623.                 )
  3624.             );
  3625.         }
  3626.         return new JsonResponse(array(
  3627.             'success' => false,
  3628.             'msg' => 'Wrong URL format! Please try with application ID'
  3629.         ));
  3630.     }
  3631.     public function PrintLeaveApplicationAction(Request $request$id)
  3632.     {
  3633.         if ($id) {
  3634.             $em $this->getDoctrine()->getManager();
  3635.             $company_data Company::getCompanyData($em1);
  3636.             $Authorizations System::getSignatureListForDocumentPrint($emarray_flip(GeneralConstant::$Entity_list)['EmployeeLeaveApplication'], $id);
  3637.             $TwigData HumanResource::TwigDataForViewLeaveApplication($em$request$id);
  3638.             if ($TwigData['HasErr']) {
  3639.                 return new JsonResponse(array(
  3640.                     'success' => false,
  3641.                     'msg' => $TwigData['Msg']
  3642.                 ));
  3643.             }
  3644.             $ApplicationCategory $TwigData['Application']->getLeaveCategory();
  3645.             $ApplicationType = ($ApplicationCategory != && $ApplicationCategory != 2) ? $TwigData['LeaveType'] : '';
  3646.             return $this->render(
  3647.                 'ApplicationBundle:pages/human_resource/print:leave_application_print.html.twig',
  3648.                 array(
  3649.                     'page_title' => 'Print Leave Application',
  3650.                     'export' => 'pdf,print',
  3651.                     'company_name' => $company_data->getName(),
  3652.                     'company_data' => $company_data,
  3653.                     'company_address' => $company_data->getAddress(),
  3654.                     'company_image' => $company_data->getImage(),
  3655.                     'Authorizations' => $Authorizations,
  3656.                     'ApplicationType' => $ApplicationType,
  3657.                     'ApplicationCategory' => $ApplicationCategory,
  3658.                     'Applicant' => $TwigData['Applicant'],
  3659.                     'Application' => $TwigData['Application'],
  3660.                     'LeaveType' => $TwigData['LeaveType'],
  3661.                     'LeaveCategory' => $TwigData['LeaveCategory'],
  3662.                     'leaveDataArray' => $TwigData['leaveDataArray'],
  3663.                     'FrwdEmp' => $TwigData['FrwdEmp'],
  3664.                     'ApplicantDesg' => $TwigData['ApplicantDesg'],
  3665.                     'approval_status' => $TwigData['approval_status'],
  3666.                     'approval_data' => $TwigData['approval_data'],
  3667.                     'document_log' => $TwigData['document_log'],
  3668.                     'red' => 0,
  3669.                     'invoice_footer' => 0
  3670.                 )
  3671.             );
  3672.         }
  3673.         return new JsonResponse(array(
  3674.             'success' => false,
  3675.             'msg' => 'Wrong URL format! Please try with application ID'
  3676.         ));
  3677.     }
  3678.     public function LeaveApplicationListAction(Request $request)
  3679.     {
  3680.         $em $this->getDoctrine()->getManager();
  3681.         $response HumanResource::GetEmployeeLeaveApplicationList($em$request);
  3682.         if ($request->isMethod('GET')) {
  3683.             return $this->render("ApplicationBundle:pages/human_resource/list:leave_application_list.html.twig", array(
  3684.                 'page_title' => 'Leave Application List',
  3685.                 'application_data' => $response,
  3686.             ));
  3687.         }
  3688.     }
  3689.     public function PayrollPolicySettingsAction(Request $request$id)
  3690.     {
  3691.         $em $this->getDoctrine()->getManager();
  3692.         $CompanyId $this->getLoggedUserCompanyId($request);
  3693.         if ($id) {
  3694.             if ($request->isMethod('GET')) {
  3695.                 $Row $em->getRepository(PayrollPolicy::class)->find($id);
  3696.                 if (!$Row) {
  3697.                     $this->addFlash('error''Invalid Payroll Policy Id');
  3698.                     return $this->redirectToRoute('payroll_policy_settings');
  3699.                 }
  3700.                 $TwigData HumanResource::GetPayrollPolicyTwigData($em);
  3701.                 $OldData HumanResource::GetPayrollPolicyTwigData($em$id);
  3702.                 return $this->render('ApplicationBundle:pages/human_resource/input_forms:payroll_policy_settings.html.twig', array(
  3703.                     'page_title' => 'Update Payroll Policy Settings',
  3704.                     'EmployeeIds' => $TwigData['EmployeeIds'],
  3705.                     'EmployeeType' => $TwigData['EmployeeType'],//
  3706.                     'department' => $TwigData['department'],
  3707.                     'Designation' => $TwigData['Designation'],
  3708.                     'WorkingDays' => $TwigData['WorkingDays'],
  3709.                     'OldData' => $OldData['Row'],
  3710.                     'earningAspects' => HumanResourceConstant::$earningAspectsForPayrollPolicy,
  3711.                     'leaveTypes' => HumanResourceConstant::$LeaveTypeForPayrollPolicy,
  3712.                     'leaveTypesArray' => HumanResourceConstant::$LeaveTypeArrayForPayrollPolicy,
  3713.                     'deductionAspects' => HumanResourceConstant::$deductionAspects,
  3714.                     'deductionCondition' => json_decode($Row->getDeductionCondition(), true),
  3715.                     'HasUpdateMode' => true,
  3716.                 ));
  3717.             } else {
  3718.                 $Response HumanResource::StorePayrollPolicyData($em$id$CompanyId$request);
  3719.                 if ($Response['HasErr']) {
  3720.                     $this->addFlash('error'$Response['msg']);
  3721.                     return $this->redirectToRoute('payroll_policy_settings');
  3722.                 }
  3723.                 return $this->redirectToRoute('payroll_policy_settings');
  3724. //        if ($Response['isSuccess']) {
  3725. //          return new JsonResponse(array('success' => true, 'msg' => 'don\'t forget to redirect'));
  3726. //        }
  3727. //        return new JsonResponse(array('success' => false, 'msg' => 'Sorry something went wrong'));
  3728.             }
  3729.         } else {
  3730.             if ($request->isMethod('GET')) {
  3731.                 if ($request->query->get('GetDocHash')) {
  3732.                     $Dochash HumanResource::GenerateDocHashForPayrollSettings($em$request);
  3733.                     return new JsonResponse($Dochash);
  3734.                 }
  3735.                 $TwigData HumanResource::GetPayrollPolicyTwigData($em);
  3736.                 return $this->render(
  3737.                     'ApplicationBundle:pages/human_resource/input_forms:payroll_policy_settings.html.twig',
  3738.                     array(
  3739.                         'page_title' => 'Create Payroll Policy Settings',
  3740.                         'EmployeeIds' => $TwigData['EmployeeIds'],
  3741.                         'EmployeeType' => $TwigData['EmployeeType'],
  3742.                         'WorkingDays' => $TwigData['WorkingDays'],
  3743.                         'Designation' => $TwigData['Designation'],
  3744.                         'department' => $TwigData['department'],
  3745.                         'earningAspects' => HumanResourceConstant::$earningAspectsForPayrollPolicy,
  3746.                         'leaveTypes' => HumanResourceConstant::$LeaveTypeForPayrollPolicy,
  3747.                         'leaveTypesArray' => HumanResourceConstant::$LeaveTypeArrayForPayrollPolicy,
  3748.                         'deductionAspects' => HumanResourceConstant::$deductionAspects,
  3749.                         'HasUpdateMode' => false
  3750.                     )
  3751.                 );
  3752.             } else {
  3753.                 $Response HumanResource::StorePayrollPolicyData($em$id$CompanyId$request);
  3754.                 if ($Response['HasErr']) {
  3755.                     $this->addFlash('error'$Response['msg']);
  3756.                     return $this->redirectToRoute('payroll_policy_settings');
  3757.                 }
  3758.                 return $this->redirectToRoute('payroll_policy_settings');
  3759. //        return new JsonResponse(array("success" => true, 'msg' => 'Dont forget to redirect!'));
  3760.             }
  3761.         }
  3762.     }
  3763.     public function AttendanceReportAction(Request $request$apiKey 'impose')
  3764.     {
  3765.         $em $this->getDoctrine()->getManager();
  3766.         $attendanceSource HumanResourceConstant::$attendanceSources;
  3767.         $routeName $request->attributes->get('_route');
  3768.         if ($routeName == 'app_get_attendendance_data') {
  3769.             $ReportData HumanResource::GenerateAttendanceReport($em$request$request->get('considerCurrTsIfNoOut'1));
  3770.             $newReports = [];
  3771.             foreach ($ReportData['Reports'] as $gg) {
  3772.                 foreach ($gg as $d) {
  3773.                     $newReports[] = $d;
  3774. //                if(!isset($newReports[$d['id']]))
  3775. //                    $newReports[$d['id']]=array();
  3776. //                    $newReports[$d['id']][]=$d;
  3777.                 }
  3778.             }
  3779.             return new JsonResponse (array(
  3780.                 'attendanceSource' => $attendanceSource,
  3781. //                'Reports' => $ReportData['Reports'],
  3782.                 'Reports' => $newReports,
  3783.                 'from_date' => $ReportData['from_date'],
  3784.                 'to_date' => $ReportData['to_date'],
  3785.                 'report_for' => $ReportData['generated_for'],
  3786.                 'attendance' => $ReportData['attendance'],
  3787.             ));
  3788.         } else {
  3789.             $EmployeeIds $em->getRepository(EmployeeDetails::class)->findAll();
  3790.             $Departments $em->getRepository(SysDepartment::class)->findAll();
  3791.             if ($request->isMethod('GET')) {
  3792.                 return $this->render('ApplicationBundle:pages/human_resource/report:attendance_report.html.twig', array(
  3793.                     'page_title' => 'Attendance Report',
  3794.                     'employes' => $EmployeeIds,
  3795.                     'departments' => $Departments,
  3796.                     'isMethodGet' => true,
  3797.                     'from_date' => '',
  3798.                     'to_date' => '',
  3799.                     'report_for' => '',
  3800.                     'attendance' => [],
  3801.                     'Reports' => [],
  3802.                     'qry' => ''
  3803.                 ));
  3804.             }
  3805.             $ReportData HumanResource::GenerateAttendanceReport($em$request$request->request->get('considerCurrTsIfNoOut'0));
  3806.             if ($request->request->get('returnJson'0) == 1) {
  3807.                 return new JsonResponse($ReportData);
  3808.             }
  3809.             $Qry "start_date=" $ReportData['from_date'] . '&' "end_date=" $ReportData['to_date'] . '&' "period_type=" $ReportData['period_type'] . '&' "show_all=" $ReportData['show_all'] . '&' "department=" $request->get('department') . '&' "employes=" implode(',', ($request->get('employes') ? $request->get('employes') : []));
  3810.             return $this->render('ApplicationBundle:pages/human_resource/report:attendance_report.html.twig', array(
  3811.                 'page_title' => 'Attendance Report',
  3812.                 'isMethodGet' => false,
  3813.                 'departments' => $Departments,
  3814.                 'employes' => $EmployeeIds,
  3815.                 'attendanceSource' => $attendanceSource,
  3816.                 'Reports' => $ReportData['Reports'],
  3817.                 'from_date' => $ReportData['from_date'],
  3818.                 'to_date' => $ReportData['to_date'],
  3819.                 'report_for' => $ReportData['generated_for'],
  3820.                 'attendance' => $ReportData['attendance'],
  3821.                 'qry' => $Qry
  3822.             ));
  3823.         }
  3824.     }
  3825.     public function PrintAttendanceReportAction(Request $request)
  3826.     {
  3827.         $em $this->getDoctrine()->getManager();
  3828.         $company_data Company::getCompanyData($em1);
  3829.         $ReportData HumanResource::GenerateAttendanceReport($em$request);
  3830.         return $this->render(
  3831.             'ApplicationBundle:pages/human_resource/print:print_attendance_report.html.twig',
  3832.             array(
  3833.                 'page_title' => 'Print Attendance Report',
  3834.                 'export' => 'pdf,print',
  3835.                 'company_name' => $company_data->getName(),
  3836.                 'company_data' => $company_data,
  3837.                 'company_address' => $company_data->getAddress(),
  3838.                 'company_image' => $company_data->getImage(),
  3839.                 'Reports' => $ReportData['Reports'],
  3840.                 'from_date' => $ReportData['from_date'],
  3841.                 'to_date' => $ReportData['to_date'],
  3842.                 'report_for' => $ReportData['generated_for'],
  3843.                 'attendance' => $ReportData['attendance'],
  3844.                 'red' => 0
  3845.             )
  3846.         );
  3847.     }
  3848.     public function DisburseSalaryAction(Request $request)
  3849.     {
  3850.         $em $this->getDoctrine()->getManager();
  3851.         $EmployeeIds $em->getRepository(EmployeeDetails::class)->findBy(
  3852.             array(
  3853.                 'emp_status' => 1
  3854.             )
  3855.         );
  3856.         $startDate $request->get('salary_start_date''');
  3857.         $endDate $request->get('salary_till_date''');
  3858.         $filterType $request->get('filterType'1);
  3859.         $filterBranchIds $request->get('branchIds', []);
  3860.         $filterBankIds $request->get('bankIds', []);
  3861.         $filterDepartmentIds $request->get('departmentIds', []);
  3862.         $filterEmployeeIds $request->get('employeeIds', []);
  3863.         $Departments $em->getRepository(SysDepartment::class)->findAll();
  3864.         $attendance $em->getRepository(EmployeeAttendanceLog::class)->findAll();
  3865.         $banks $em->getRepository(BankList::class)->findAll();
  3866.         $branches $em->getRepository(Branch::class)->findAll();
  3867.         if ($request->isMethod('GET')) {
  3868.             return $this->render('ApplicationBundle:pages/human_resource/report:disburse_salary.html.twig', array(
  3869.                 'page_title' => 'Disburse Salary',
  3870.                 'EmployeeIds' => $EmployeeIds,
  3871.                 'departments' => $Departments,
  3872.                 'attendance' => $attendance,
  3873.                 'branches' => $branches,
  3874.                 'banks' => $banks,
  3875.                 'SalaryReports' => [],
  3876.                 'from_date' => '',
  3877.                 'to_date' => '',
  3878.                 'Qry' => '',
  3879.                 'isMethodGet' => true,
  3880.                 'filterType' => $filterType,
  3881.                 'startDate' => $startDate,
  3882.                 'endDate' => $endDate,
  3883.                 'filterBranchIds' => $filterBranchIds,
  3884.                 'filterBankIds' => $filterBankIds,
  3885.                 'filterDepartmentIds' => $filterDepartmentIds,
  3886.                 'filterEmployeeIds' => $filterEmployeeIds,
  3887.             ));
  3888.         }
  3889.         $SalaryReports HumanResource::BasicDeduction($em$request);
  3890. //        $SalaryReportsNew = HumanResource::calculateSalary($em,
  3891. //            array(
  3892. //                'startDate' => $request->get('salary_start_date', ''),
  3893. //                'endDate' => $request->get('salary_end_date', ''),
  3894. //                'timeZone' => $request->get('time_zone', '+0600'),
  3895. //                'employeeIds' => $request->get('employeeIds', []),
  3896. //                'departmentIds' => $request->get('department', []),
  3897. //                'allFlag' => $request->get('show_all', 0),
  3898. //
  3899. //            )
  3900. //        );
  3901.         $Qry "salary_till_date=" $endDate '&' "departmentIds=" implode(','$filterDepartmentIds) . '&' "employeeIds=" implode(','$filterEmployeeIds) .
  3902.             '&' "salary_start_date=" $startDate .
  3903.             '&' "filterType=" $filterType .
  3904.             '&' "branchIds=" implode(','$filterBranchIds) .
  3905.             '&' "bankIds=" implode(','$filterBankIds);
  3906. //        if ($request->get('returnJson', 0) == 1) {
  3907.         if ($request->get('returnJson'0) == 1) {
  3908.             return new JsonResponse(array(
  3909.                 'SalaryReports' => $SalaryReports,
  3910.             ));
  3911.         } else {
  3912.             return $this->render('ApplicationBundle:pages/human_resource/report:disburse_salary.html.twig', array(
  3913.                 'page_title' => 'Disburse Salary',
  3914.                 'EmployeeIds' => $EmployeeIds,
  3915.                 'departments' => $Departments,
  3916.                 'branches' => $branches,
  3917.                 'banks' => $banks,
  3918.                 'SalaryReports' => $SalaryReports,
  3919.                 'for_month' => $SalaryReports[0]['for_month'],
  3920.                 'from_date' => $SalaryReports[0]['from_date'],
  3921.                 'to_date' => $SalaryReports[0]['to_date'],
  3922.                 'Qry' => $Qry,
  3923.                 'isMethodGet' => false,
  3924.                 'startDate' => $startDate,
  3925.                 'endDate' => $endDate,
  3926.                 'filterType' => $filterType,
  3927.                 'filterBranchIds' => $filterBranchIds,
  3928.                 'filterBankIds' => $filterBankIds,
  3929.                 'filterDepartmentIds' => $filterDepartmentIds,
  3930.                 'filterEmployeeIds' => $filterEmployeeIds,
  3931.             ));
  3932.         }
  3933.     }
  3934.     public function PrintDisburseSalaryAction(Request $Req)
  3935.     {
  3936.         $em $this->getDoctrine()->getManager();
  3937.         $company_data Company::getCompanyData($em1);
  3938.         $SalaryReports HumanResource::BasicDeduction($em$Req);
  3939.         return $this->render(
  3940.             'ApplicationBundle:pages/human_resource/print:print_disburse_salary.html.twig',
  3941.             array(
  3942.                 'page_title' => 'Print Disburse Salary',
  3943.                 'export' => 'pdf,print',
  3944.                 'company_name' => $company_data->getName(),
  3945.                 'company_data' => $company_data,
  3946.                 'company_address' => $company_data->getAddress(),
  3947.                 'company_image' => $company_data->getImage(),
  3948.                 'SalaryReports' => $SalaryReports,
  3949.                 'for_month' => $SalaryReports[0]['for_month'],
  3950.                 'from_date' => $SalaryReports[0]['from_date'],
  3951.                 'to_date' => $SalaryReports[0]['to_date'],
  3952.                 'red' => 0
  3953.             )
  3954.         );
  3955.     }
  3956.     public function SalaryReportAction(Request $request)
  3957.     {
  3958.         $em $this->getDoctrine()->getManager();
  3959.         $startDate $request->get('salary_start_date''');
  3960.         $endDate $request->get('salary_till_date''');
  3961.         $segregationType $request->get('segregationType'1);
  3962.         $filterBranchIds $request->get('branchIds', []);
  3963.         $filterBankIds $request->get('bankIds', []);
  3964.         $approvalFilterTypes $request->get('approvalFilterTypes', []);
  3965.         $filterDepartmentIds $request->get('departmentIds', []);
  3966.         $filterEmployeeIds $request->get('employeeIds', []);
  3967.         $Departments $em->getRepository(SysDepartment::class)->findAll();
  3968.         $attendance $em->getRepository(EmployeeAttendanceLog::class)->findAll();
  3969.         $banks $em->getRepository(BankList::class)->findAll();
  3970.         $branches $em->getRepository(Branch::class)->findAll();
  3971.         $SalaryReports HumanResource::GenerateSalaryReport($em$request);
  3972. //        dump($SalaryReports);
  3973.         $Qry "salary_till_date=" $endDate '&' "departmentIds=" implode(','$filterDepartmentIds) . '&' "employeeIds=" implode(','$filterEmployeeIds) .
  3974.             '&' "salary_start_date=" $startDate .
  3975.             '&' "segregationType=" $segregationType .
  3976.             '&' "branchIds=" implode(','$filterBranchIds) .
  3977.             '&' "bankIds=" implode(','$filterBankIds);
  3978. //        if ($request->get('returnJson', 0) == 1) {
  3979.         if ($request->get('returnJson'0) == 1) {
  3980.             return new JsonResponse(array(
  3981.                 'SalaryReports' => $SalaryReports,
  3982.             ));
  3983.         } else {
  3984.             return $this->render('ApplicationBundle:pages/human_resource/report:salary_report.html.twig', array(
  3985.                 'page_title' => 'Salary Report',
  3986.                 'departments' => $Departments,
  3987.                 'branches' => $branches,
  3988.                 'banks' => $banks,
  3989.                 'approvalFilterTypes' => $approvalFilterTypes,
  3990.                 'salaryInfo' => $SalaryReports,
  3991.                 'SalaryReports' => $SalaryReports,
  3992.                 'for_month' => '',
  3993.                 'from_date' => $startDate,
  3994.                 'to_date' => $endDate,
  3995.                 'Qry' => $Qry,
  3996.                 'isMethodGet' => false,
  3997.                 'startDate' => $startDate,
  3998.                 'endDate' => $endDate,
  3999.                 'segregationType' => $segregationType,
  4000.                 'filterBranchIds' => $filterBranchIds,
  4001.                 'filterBankIds' => $filterBankIds,
  4002.                 'filterDepartmentIds' => $filterDepartmentIds,
  4003.                 'filterEmployeeIds' => $filterEmployeeIds,
  4004.             ));
  4005.         }
  4006.     }
  4007.     public function createJobRecruitmentAction(Request $request$id 0)
  4008.     {
  4009.         $data = [];
  4010.         $em_goc $this->getDoctrine()->getManager('company_group');
  4011.         $skillDetails $em_goc->getRepository(EntitySkill::class)->findAll();
  4012.         $em $this->getDoctrine()->getManager();
  4013.         $companyId $this->getLoggedUserCompanyId($request);
  4014.         if ($request->isMethod('POST')) {
  4015.             $em $this->getDoctrine()->getManager();
  4016.             $entity_id array_flip(GeneralConstant::$Entity_list)['JobRecruitment']; //change
  4017.             $dochash $request->request->get('docHash'); //change
  4018.             $loginId $request->getSession()->get(UserConstants::USER_LOGIN_ID);
  4019.             $approveRole $request->request->get('approvalRole');
  4020.             $approveHash $request->request->get('approvalHash');
  4021.             if (!DocValidation::isInsertable($em$entity_id$dochash,
  4022.                 $loginId$approveRole$approveHash$id)
  4023.             ) {
  4024.                 $this->addFlash(
  4025.                     'error',
  4026.                     'Sorry Could not insert Data.'
  4027.                 );
  4028.             } else {
  4029.                 $data $request->request;
  4030.                 $docId HumanResource::createJobRecruitment($em$loginId$id$data$companyId);
  4031.                 //now add Approval info
  4032.                 $approveRole $request->request->get('approvalRole');
  4033.                 $options = array(
  4034.                     'notification_enabled' => $this->container->getParameter('notification_enabled'),
  4035.                     'notification_server' => $this->container->getParameter('notification_server'),
  4036.                     'appId' => $request->getSession()->get(UserConstants::USER_APP_ID),
  4037.                     'url' => $this->generateUrl(
  4038.                         GeneralConstant::$Entity_list_details[array_flip(GeneralConstant::$Entity_list)['JobRecruitment']]
  4039.                         ['entity_view_route_path_name']
  4040.                     )
  4041.                 );
  4042.                 System::setApprovalInfo($this->getDoctrine()->getManager(), $options,
  4043.                     array_flip(GeneralConstant::$Entity_list)['JobRecruitment'],
  4044.                     $docId,
  4045.                     $request->getSession()->get(UserConstants::USER_LOGIN_ID)    //journal voucher
  4046.                 );
  4047.                 System::createEditSignatureHash($this->getDoctrine()->getManager(), array_flip(GeneralConstant::$Entity_list)['JobRecruitment'],
  4048.                     $docId,
  4049.                     $loginId,
  4050.                     $approveRole,
  4051.                     $request->request->get('approvalHash'));
  4052.                 $this->addFlash(
  4053.                     'success',
  4054.                     'New Recruitment Document Added.'
  4055.                 );
  4056.                 $url $this->generateUrl(
  4057.                     'view_job_recruitment'
  4058.                 );
  4059.                 return $this->redirect($url "/" $docId);
  4060.             }
  4061.         }
  4062.         if ($id == 0) {
  4063.         } else {
  4064.             $extDoc $em->getRepository('ApplicationBundle:JobRecruitment')->findOneBy(
  4065.                 array(
  4066.                     'jobRecruitmentId' => $id///material
  4067.                 )
  4068.             );
  4069.             //now if its not editable, redirect to view
  4070.             if ($extDoc) {
  4071.                 if ($extDoc->getEditFlag() != 1) {
  4072.                     $url $this->generateUrl(
  4073.                         'view_job_recruitment'
  4074.                     );
  4075.                     return $this->redirect($url "/" $id);
  4076.                 }
  4077.             }
  4078.         }
  4079.         $jobType HumanResourceConstant::$employeeType;
  4080.         //$skillDetails = $em->getRepository(Skill::class)->findAll();
  4081.         $educationDetails $em->getRepository('ApplicationBundle:EducationQualification')->findAll();
  4082.         $employeeIds $em->getRepository('ApplicationBundle:Employee')->findAll();
  4083.         $location HumanResourceConstant::$location;
  4084.         $salaryPer HumanResourceConstant::$salaryPer;
  4085.         $workExperience HumanResourceConstant::$workExperience;
  4086.         $jobOpeningStatus HumanResourceConstant::$jobOpeningStatus;
  4087.         $compatibility HumanResourceConstant::$compatibility;
  4088.         return $this->render('ApplicationBundle:pages/human_resource/input_forms:create_new_job_post.html.twig', [
  4089.             'page_title' => 'Create New Job Post',
  4090.             'jobType' => $jobType,
  4091.             'skillDetails' => $skillDetails,
  4092.             'educationDetails' => $educationDetails,
  4093.             'employeeIds' => $employeeIds,
  4094.             'location' => $location,
  4095.             'salaryPer' => $salaryPer,
  4096.             'workExperience' => $workExperience,
  4097.             'jobOpeningStatus' => $jobOpeningStatus,
  4098.             'compatibility' => $compatibility
  4099.         ]);
  4100.     }
  4101.     public function viewApplicantInfoAction(Request $request$id)
  4102.     {
  4103.         $em $this->getDoctrine()->getManager('company_group');
  4104.         //$session = $request->getSession();
  4105.         $consultantDetails $em->getRepository(EntityApplicantDetails::class)->find($id);
  4106.         $skillDetails $em->getRepository('CompanyGroupBundle:EntitySkill')->findAll();
  4107.         //$companyId = $this->getLoggedUserCompanyId($request);
  4108.         $gender HumanResourceConstant::$sex;
  4109.         $blood HumanResourceConstant::$BloodGroup;
  4110.         //$userId = $session->get(UserConstants::USER_ID);
  4111.         return $this->render('ApplicationBundle:pages/human_resource/views:view_applicant_info.html.twig', [
  4112.             'page_title' => 'Applicant Information',
  4113.             'gender' => $gender,
  4114.             'blood' => $blood,
  4115.             'consultantDetails' => $consultantDetails,
  4116.             'education' => json_decode($consultantDetails->getEducationData(), true),
  4117.             'workExperience' => json_decode($consultantDetails->getWorkExperienceData(), true),
  4118.             'certificate' => json_decode($consultantDetails->getCertificateData(), true),
  4119.             'courses' => json_decode($consultantDetails->getCoursesData(), true),
  4120.             'languages' => json_decode($consultantDetails->getLanguagesData(), true),
  4121.             'skillDetails' => $skillDetails
  4122.         ]);
  4123.     }
  4124.     public function ListJobRecruitmentAction()
  4125.     {
  4126.         $em $this->getDoctrine()->getManager();
  4127.         $jobRecruitmentList = [];
  4128.         $jobRecruitments $em->getRepository('ApplicationBundle:JobRecruitment')->findAll();
  4129.         foreach ($jobRecruitments as $jobRecruitment) {
  4130.             $jobData = array(
  4131.                 'jobRecruitmentId' => $jobRecruitment->getJobRecruitmentId(),
  4132.                 'title' => $jobRecruitment->getTitle(),
  4133.                 'date' => $jobRecruitment->getDate(),
  4134.                 'jobOpeningStatus' => $jobRecruitment->getJobOpeningStatus(),
  4135.                 'applicationOpeningDate' => $jobRecruitment->getApplicationOpeningDate(),
  4136.                 'applicationClosingDate' => $jobRecruitment->getApplicationClosingDate(),
  4137.             );
  4138.             $jobRecruitmentList[] = $jobData;
  4139.         }
  4140.         return $this->render('ApplicationBundle:pages/human_resource/list:job_recruitment_list.html.twig', [
  4141.             'page_title' => 'Job RecruitmentAction List',
  4142.             'jobRecruitments' => $jobRecruitmentList
  4143.         ]);
  4144.     }
  4145.     public function ViewJobRecruitmentAction(Request $request$id 0)
  4146.     {
  4147.         $em_goc $this->getDoctrine()->getManager('company_group');
  4148.         $skillDetails $em_goc->getRepository('CompanyGroupBundle:EntitySkill')->findAll();
  4149.         $em $this->getDoctrine()->getManager();
  4150.         $companyId $this->getLoggedUserCompanyId($request);
  4151.         $company_data Company::getCompanyData($em$companyId);
  4152. //        return new JsonResponse($encryptedDataArray);
  4153.         $location HumanResourceConstant::$location;
  4154.         $salaryPer HumanResourceConstant::$salaryPer;
  4155.         $workExperience HumanResourceConstant::$workExperience;
  4156.         $jobOpeningStatus HumanResourceConstant::$jobOpeningStatus;
  4157.         $compatibility HumanResourceConstant::$compatibility;
  4158.         $jobType HumanResourceConstant::$employeeType;
  4159.         $educationDetail $em->getRepository(EducationQualification::class)->findAll();
  4160.         $jobRecruitments $em->getRepository('ApplicationBundle:JobRecruitment')->find($id);
  4161.         $em_goc $this->getDoctrine()->getManager('company_group');
  4162.         $applicantApplicationList $em_goc->getRepository("CompanyGroupBundle:EntityApplicantApplicationList")->findBy(
  4163.             array(
  4164.                 'jobPostId' => $id,
  4165.                 'CompanyId' => $companyId,
  4166.                 'appId' => $company_data->getAppId()
  4167.             )
  4168.         );
  4169.         $applicantIdList = [];
  4170.         foreach ($applicantApplicationList as $dt) {
  4171.             $applicantIdList[] = $dt->getApplicantId();
  4172.         }
  4173.         $applicantList ApplicantM::getApplicantList($em_goc$applicantIdList);
  4174.         $Approval_data = [
  4175.             'exists' => 0,
  4176.             'approvalId' => 0,
  4177.             'roleType' => 0,
  4178.             'required' => 0,
  4179.             'acted' => 0,
  4180.             'entity' => array_flip(GeneralConstant::$Entity_list)['JobRecruitment'],
  4181.             'entityId' => $id,
  4182.         ];
  4183.         if (in_array($request->getSession()->get(UserConstants::USER_TYPE), [125]))
  4184.             $Approval_data System::checkIfApprovalExists(
  4185.                 $em,
  4186.                 array_flip(GeneralConstant::$Entity_list)['JobRecruitment'],
  4187.                 $id,
  4188.                 $request->getSession()->get(UserConstants::USER_LOGIN_ID)
  4189.             );
  4190.         return $this->render('ApplicationBundle:pages/human_resource/views:view_job_recruitment.html.twig', [
  4191.             'page_title' => 'View Job RecruitmentAction',
  4192.             'jobRecruitments' => $jobRecruitments,
  4193.             'applicantApplicationList' => $applicantApplicationList,
  4194.             'applicantList' => $applicantList,
  4195. //            'encryptedData' => $encryptedData,
  4196.             'skills' => json_decode($jobRecruitments->getskills()),
  4197.             'skillDetails' => $skillDetails,
  4198.             'education' => json_decode($jobRecruitments->getEducations()),
  4199.             'educationDetails' => $educationDetail,
  4200.             'location' => $location,
  4201.             'salaryPer' => $salaryPer,
  4202.             'workExperience' => $workExperience,
  4203.             'jobType' => $jobType,
  4204.             'compatibility' => $compatibility,
  4205.             'approval_status' => $jobRecruitments->getApproved(),
  4206.             'jobOpeningStatus' => $jobOpeningStatus,
  4207.             'approval_data' => $Approval_data,
  4208.             'auto_created' => $jobRecruitments->getAutocreated(),
  4209.             'document_log' => $jobRecruitments->getAutocreated() == System::getDocumentLog(
  4210.                 $em,
  4211.                 array_flip(GeneralConstant::$Entity_list)['JobRecruitment'],
  4212.                 $id,
  4213.                 $jobRecruitments->getCreatedLoginId(),
  4214.                 $jobRecruitments->getEditedLoginId()
  4215.             ) : []
  4216.         ]);
  4217.     }
  4218.     public function ViewApplicantScheduleAction(Request $request$id 0)
  4219.     {
  4220.         $em $this->getDoctrine()->getManager();
  4221.         $companyId $this->getLoggedUserCompanyId($request);
  4222.         $company_data Company::getCompanyData($em$companyId);
  4223.         $em_goc $this->getDoctrine()->getManager('company_group');
  4224.         $applicantApplicationList $em_goc->getRepository("CompanyGroupBundle:EntityApplicantApplicationList")->findBy(
  4225.             array(
  4226.                 'jobPostId' => $id,
  4227.                 'CompanyId' => $companyId,
  4228.                 'appId' => $company_data->getAppId()
  4229.             )
  4230.         );
  4231.         $applicantIdList = [];
  4232.         foreach ($applicantApplicationList as $dt) {
  4233.             $applicantIdList[] = $dt->getApplicantId();
  4234.         }
  4235.         $applicantList ApplicantM::getApplicantList($em_goc$applicantIdList);
  4236.         return $this->render('ApplicationBundle:pages/human_resource/views:view_applicant_scheduled.html.twig', [
  4237.             'page_title' => 'View Applicant Scheduled',
  4238.             'applicantApplicationList' => $applicantApplicationList,
  4239.             'applicantList' => $applicantList,
  4240.         ]);
  4241.     }
  4242.     public function ViewApplicantReportAction(Request $request$id 0)
  4243.     {
  4244.         $em $this->getDoctrine()->getManager();
  4245.         $companyId $this->getLoggedUserCompanyId($request);
  4246.         $company_data Company::getCompanyData($em$companyId);
  4247.         $em_goc $this->getDoctrine()->getManager('company_group');
  4248.         $applicantApplicationList $em_goc->getRepository("CompanyGroupBundle:EntityApplicantApplicationList")->findBy(
  4249.             array(
  4250.                 'jobPostId' => $id,
  4251.                 'CompanyId' => $companyId,
  4252.                 'appId' => $company_data->getAppId()
  4253.             )
  4254.         );
  4255.         $applicantIdList = [];
  4256.         foreach ($applicantApplicationList as $dt) {
  4257.             $applicantIdList[] = $dt->getApplicantId();
  4258.         }
  4259.         $applicantList ApplicantM::getApplicantList($em_goc$applicantIdList);
  4260.         return $this->render('ApplicationBundle:pages/human_resource/views:view_applicant_report.html.twig', [
  4261.             'page_title' => 'View Applicant Report',
  4262.             'applicantApplicationList' => $applicantApplicationList,
  4263.             'applicantList' => $applicantList,
  4264.         ]);
  4265.     }
  4266.     public function createEmployeePerformanceEvaluationAction(Request $request$id 0)
  4267.     {
  4268.         $data = [];
  4269.         $em $this->getDoctrine()->getManager();
  4270.         $companyId $this->getLoggedUserCompanyId($request);
  4271.         if ($request->isMethod('POST')) {
  4272.             $em $this->getDoctrine()->getManager();
  4273.             $entity_id array_flip(GeneralConstant::$Entity_list)['EmployeePerformanceEvolution']; //change
  4274.             $dochash $request->request->get('docHash'); //change
  4275.             $loginId $request->getSession()->get(UserConstants::USER_LOGIN_ID);
  4276.             $approveRole $request->request->get('approvalRole');
  4277.             $approveHash $request->request->get('approvalHash');
  4278.             if (!DocValidation::isInsertable($em$entity_id$dochash,
  4279.                 $loginId$approveRole$approveHash$id)
  4280.             ) {
  4281.                 $this->addFlash(
  4282.                     'error',
  4283.                     'Sorry Could not insert Data.'
  4284.                 );
  4285.             } else {
  4286.                 $data $request->request;
  4287.                 $docId HumanResource::createEmployeePerformanceEvaluation($em$loginId$id$data$companyId);
  4288.                 //now add Approval info
  4289.                 $approveRole $request->request->get('approvalRole');
  4290.                 $options = array(
  4291.                     'notification_enabled' => $this->container->getParameter('notification_enabled'),
  4292.                     'notification_server' => $this->container->getParameter('notification_server'),
  4293.                     'appId' => $request->getSession()->get(UserConstants::USER_APP_ID),
  4294.                     'url' => $this->generateUrl(
  4295.                         GeneralConstant::$Entity_list_details[array_flip(GeneralConstant::$Entity_list)['EmployeePerformanceEvolution']]
  4296.                         ['entity_view_route_path_name']
  4297.                     )
  4298.                 );
  4299.                 System::setApprovalInfo($this->getDoctrine()->getManager(), $options,
  4300.                     array_flip(GeneralConstant::$Entity_list)['JobRecruitment'],
  4301.                     $docId,
  4302.                     $request->getSession()->get(UserConstants::USER_LOGIN_ID)    //journal voucher
  4303.                 );
  4304.                 System::createEditSignatureHash($this->getDoctrine()->getManager(), array_flip(GeneralConstant::$Entity_list)['EmployeePerformanceEvolution'],
  4305.                     $docId,
  4306.                     $loginId,
  4307.                     $approveRole,
  4308.                     $request->request->get('approvalHash'));
  4309.                 $this->addFlash(
  4310.                     'success',
  4311.                     'New Recruitment Document Added.'
  4312.                 );
  4313.                 $url $this->generateUrl(
  4314.                     'view_employee_performance_evolution'
  4315.                 );
  4316.                 return $this->redirect($url "/" $docId);
  4317.             }
  4318.         }
  4319.         $skill $em->getRepository(Skill::class)->findAll();
  4320.         $educationDetail $em->getRepository(EducationQualification::class)->findAll();
  4321.         $employeeIds $em->getRepository(EmployeeDetails::class)->findAll();
  4322.         $employeeType HumanResourceConstant::$employeeType;
  4323.         $Designation $em->getRepository(SysDepartmentPosition::class)->findAll();
  4324.         $branch $em->getRepository(Branch::class)->findAll();
  4325.         $departments $em->getRepository(SysDepartment::class)->findAll();
  4326.         $department = [];
  4327.         foreach ($departments as $entry) {
  4328.             $department[$entry->getDepartmentId()] = array(
  4329.                 'id' => $entry->getDepartmentId(),
  4330.                 'name' => $entry->getDepartmentName(),
  4331.             );
  4332.         }
  4333.         return $this->render('ApplicationBundle:pages/human_resource/input_forms:employee_performance_evolution.html.twig',
  4334.             array(
  4335.                 'page_title' => 'Create Employee Performance Evaluation',
  4336.                 'employeeIds' => $employeeIds,
  4337.                 'employeeType' => $employeeType,
  4338.                 'Designation' => $Designation,
  4339.                 'branch' => $branch,
  4340.                 'department' => $department,
  4341.                 'skill' => $skill,
  4342.                 'educationDetail' => $educationDetail
  4343.             )
  4344.         );
  4345.     }
  4346.     public function ViewIndividualReviewAction()
  4347.     {
  4348.         return $this->render('ApplicationBundle:pages/human_resource/views:individual_review.html.twig',
  4349.             array(
  4350.                 'page_title' => 'Individual Performance View',
  4351.             )
  4352.         );
  4353.     }
  4354.     public function EmployeeListBySkillPerformanceAction()
  4355.     {
  4356.         $em $this->getDoctrine()->getManager();
  4357.         $employee $em->getRepository('ApplicationBundle:EmployeeDetails')->findAll();
  4358.         $skill $em->getRepository('ApplicationBundle:Skill')->findAll();
  4359.         return $this->render('ApplicationBundle:pages/human_resource/list:employee_performance_evolution_list.html.twig',
  4360.             array(
  4361.                 'page_title' => 'Employee Skill & Performance',
  4362.                 'employee' => $employee,
  4363.                 //'employeeSkill' => json_decode($employee->getSkill(),true),
  4364.                 'skill' => $skill,
  4365.             )
  4366.         );
  4367.     }
  4368.     public function setWorkPlaceAction(Request $req)
  4369.     {
  4370.         $em $this->getDoctrine()->getManager();
  4371.         $companyId $this->getLoggedUserCompanyId($req);
  4372.         $docHash '';
  4373.         if ($req->request->has('XHRreq')) {
  4374.             $docHash HumanResource::HandelXHRreqForEmpWorkplace($em$req);
  4375.             return new JsonResponse([$docHash]);
  4376.         }
  4377.         if ($req->isMethod('GET')) {
  4378.             $TwigData HumanResource::TwigDataForEmployeeWorkplace($em);
  4379.             return $this->render(
  4380.                 'ApplicationBundle:pages/human_resource/input_forms:update_workplace.html.twig',
  4381.                 [
  4382.                     'page_title' => 'Set Workplace',
  4383.                     'employeeIds' => $TwigData['employeeIds']
  4384.                 ]
  4385.             );
  4386.         }
  4387.         if ($req->isMethod('POST')) {
  4388.             $approveHash $req->request->get('approvalHash');
  4389.             $loginId $req->getSession()->get(UserConstants::USER_LOGIN_ID);
  4390.             $isSignatureOk DocValidation::isSignatureOk($em$loginId$approveHash);
  4391.             if ($isSignatureOk) {
  4392.                 $isSuccess HumanResource::CreateOrUpdateForEmpWorkplace($em$req$companyIdfalse$docHash);
  4393.                 if ($isSuccess) {
  4394.                     $this->addFlash(
  4395.                         'success',
  4396.                         'Workplace set!'
  4397.                     );
  4398.                     return $this->redirectToRoute('set_workplace');
  4399.                 }
  4400.             } else {
  4401.                 $this->addFlash(
  4402.                     'error',
  4403.                     'Invalid Approval Hash!'
  4404.                 );
  4405.                 return $this->redirectToRoute('set_workplace');
  4406.             }
  4407.         }
  4408.     }
  4409.     public function setWorkPlaceForAppAction(Request $req)
  4410.     {
  4411.         $em $this->getDoctrine()->getManager();
  4412.         $companyId $this->getLoggedUserCompanyId($req);
  4413.         $docHash HumanResource::HandelXHRreqForEmpWorkplace($em$req);
  4414.         if ($req->isMethod('GET')) {
  4415.             $TwigData HumanResource::TwigDataForEmployeeWorkplace($em);
  4416.             return $this->render(
  4417.                 'ApplicationBundle:pages/human_resource/input_forms:update_workplace.html.twig',
  4418.                 [
  4419.                     'page_title' => 'Set Workplace',
  4420.                     'employeeIds' => $TwigData['employeeIds']
  4421.                 ]
  4422.             );
  4423.         }
  4424.         if ($req->isMethod('POST')) {
  4425.             $approveHash $req->request->get('approvalHash');
  4426.             $loginId $req->getSession()->get(UserConstants::USER_LOGIN_ID);
  4427.             $isSignatureOk DocValidation::isSignatureOk($em$loginId$approveHash);
  4428.             if ($isSignatureOk) {
  4429.                 $isSuccess HumanResource::CreateOrUpdateForEmpWorkplace($em$req$companyIdfalse$docHash);
  4430.                 if ($isSuccess) {
  4431.                     $this->addFlash(
  4432.                         'success',
  4433.                         'Workplace set!'
  4434.                     );
  4435. //                    return $this->redirectToRoute('set_workplace');
  4436.                     return new JsonResponse(array(
  4437.                         "success" => true
  4438.                     ));
  4439.                 }
  4440.             } else {
  4441.                 $this->addFlash(
  4442.                     'error',
  4443.                     'Invalid Approval Hash!'
  4444.                 );
  4445. //                return $this->redirectToRoute('set_workplace');
  4446.             }
  4447.         }
  4448.     }
  4449.     public function ViewMeetingAction(Request $req$action 0$id 0)
  4450.     {
  4451.         $em $this->getDoctrine()->getManager();
  4452.         $companyId $this->getLoggedUserCompanyId($req);
  4453.         if ($req->request->has('XHRreq')) {
  4454.             return new JsonResponse([HumanResource::HandelXHRreqForMeetingScheduling($em$req)]);
  4455.         }
  4456.         if ($action === 'view') {
  4457.             $response HumanResource::TwigDataForScheduledMeetingView($em$req$id);
  4458.             return $this->render(
  4459.                 'ApplicationBundle:pages/human_resource/views:scheduled_meeting_view.html.twig',
  4460.                 [
  4461.                     'page_title' => 'View Scheduled Meeting',
  4462.                     'duration' => $response['duration'],
  4463.                     'appId' => $response['appId'],
  4464.                     'publicView' => 0,
  4465.                     'meeting_data' => $response['meeting_data'],
  4466.                     'agenda_list' => $response['agenda_list'],
  4467.                     'id' => $req->query->get('view_meeting'),
  4468.                     'approval_data' => $response['approval_data'],
  4469.                     'document_log' => $response['document_log'],
  4470.                     'approval_status' => $response['approval_status'],
  4471.                     'created_by' => $response['created_by'],
  4472.                     'updated_at' => $response['updated_at'],
  4473.                     'auto_created' => 0,
  4474.                 ]
  4475.             );
  4476.         }
  4477.         if ($action === 'print') {
  4478.             $response HumanResource::TwigDataForScheduledMeetingView($em$req$id);
  4479. //      $id = $req->query->get('print_meeting');
  4480.             $em $this->getDoctrine()->getManager();
  4481.             $company_data Company::getCompanyData($em1);
  4482.             $Authorizations System::getSignatureListForDocumentPrint($emarray_flip(GeneralConstant::$Entity_list)['ScheduledMeeting'], $id);
  4483.             return $this->render(
  4484.                 'ApplicationBundle:pages/human_resource/print:scheduled_meeting_print.html.twig',
  4485.                 array(
  4486.                     'page_title' => 'View Scheduled Meeting',
  4487.                     'duration' => $response['duration'],
  4488.                     'meeting_data' => $response['meeting_data'],
  4489.                     'agenda_list' => $response['agenda_list'],
  4490.                     'export' => 'pdf,print',
  4491.                     'company_name' => $company_data->getName(),
  4492.                     'company_data' => $company_data,
  4493.                     'company_address' => $company_data->getAddress(),
  4494.                     'company_image' => $company_data->getImage(),
  4495.                     'Authorizations' => $Authorizations,
  4496.                     'red' => 0
  4497.                 )
  4498.             );
  4499.         }
  4500.     }
  4501.     public function UpdateMeetingMinutesAction(Request $req$action 0$id 0)
  4502.     {
  4503.         $em $this->getDoctrine()->getManager();
  4504.         $companyId $this->getLoggedUserCompanyId($req);
  4505.         $scheduleId $req->request->get('scheduleId');
  4506.         $minuteText $req->request->get('minuteText');
  4507.         $agendaKey $req->request->get('key');
  4508.         $scheduledMeeting $em->getRepository(ScheduledMeeting::class)
  4509.             ->find($scheduleId);
  4510.         $agendaList json_decode($scheduledMeeting->getAgendaList(), true);
  4511.         foreach ($agendaList as $key => $item) {
  4512.             if ($key == $agendaKey)
  4513.                 $agendaList[$key]['minutes'] = $minuteText;
  4514.         }
  4515.         $scheduledMeeting->setAgendaList(json_encode($agendaList));
  4516.         $em->flush();
  4517.         return new JsonResponse(array(
  4518.             'success' => true
  4519.         ));
  4520.     }
  4521.     public function deleteLastAttendanceAction(Request $request)
  4522.     {
  4523.         $em $this->getDoctrine()->getManager();
  4524.         $lastAttendance $em->getRepository('ApplicationBundle:EmployeeAttendance')
  4525.             ->createQueryBuilder('ea')
  4526.             ->orderBy('ea.id''DESC')
  4527.             ->setMaxResults(1)
  4528.             ->getQuery()
  4529.             ->getOneOrNullResult();
  4530.         $lastAttendanceLog $em->getRepository('ApplicationBundle:EmployeeAttendanceLog')
  4531.             ->createQueryBuilder('eal')
  4532.             ->orderBy('eal.id''DESC')
  4533.             ->setMaxResults(1)
  4534.             ->getQuery()
  4535.             ->getOneOrNullResult();
  4536.         $deletedCount 0;
  4537.         if ($lastAttendance) {
  4538.             $em->remove($lastAttendance);
  4539.             $deletedCount++;
  4540.         }
  4541.         if ($lastAttendanceLog) {
  4542.             $em->remove($lastAttendanceLog);
  4543.             $deletedCount++;
  4544.         }
  4545.         $em->flush();
  4546.         return new JsonResponse(
  4547.             [
  4548.                 'success' => true,
  4549.                 'message' => "Deleted `$deletedCount` rows from attendance tables."
  4550.             ]
  4551.         );
  4552.     }
  4553.     public function SendMeetingUpdatesAction(Request $req$action 0$id 0)
  4554.     {
  4555.         $em $this->getDoctrine()->getManager();
  4556.         $companyId $this->getLoggedUserCompanyId($req);
  4557.         $session $req->getSession();
  4558.         $companyData Company::getCompanyData($em$companyId);
  4559.         $scheduleId $req->request->get('scheduleId');
  4560.         $minuteText $req->request->get('minuteText');
  4561.         $agendaKey $req->request->get('key');
  4562.         $scheduledMeeting $em->getRepository(ScheduledMeeting::class)
  4563.             ->find($scheduleId);
  4564.         $sendEmailInvitationTo json_decode($scheduledMeeting->getAllParticipantsNameEmail(), true);
  4565.         if ($sendEmailInvitationTo == null)
  4566.             $sendEmailInvitationTo = [];
  4567.         $agendaList json_decode($scheduledMeeting->getAgendaList(), true);
  4568.         if ($agendaList == null)
  4569.             $agendaList = [];
  4570.         $EmployeeList HumanResource::GetEmployeeList($em, []);
  4571.         $meetingType MeetingSchedulingConstant::$meetingType[$scheduledMeeting->getMeetingType()];
  4572.         foreach ($sendEmailInvitationTo as $key => $email) {
  4573.             $name ucWords(str_replace("_"" "$key));
  4574.             $bodyHtml '';
  4575.             $bodyTemplate 'ApplicationBundle:email/meeting_scheduling:scheduled_meeting_update.html.twig';
  4576.             $bodyData = array(
  4577.                 'name' => $name,
  4578.                 'gocId' => $session->get(UserConstants::USER_GOC_ID),
  4579.                 'appId' => $session->get(UserConstants::USER_APP_ID),
  4580.                 'email' => $email,
  4581.                 'meetingData' => $scheduledMeeting,
  4582.                 'meeting_type' => $meetingType,
  4583.                 'agenda_list' => $agendaList,
  4584.                 'companyData' => $companyData,
  4585.                 'employeeList' => $EmployeeList,
  4586.             );
  4587.             $attachments = [];
  4588.             $new_mail $this->get('mail_module');
  4589.             $new_mail->sendMyMail(array(
  4590.                 'senderHash' => '_MEETING_',
  4591.                 'forwardToMailAddress' => $email,
  4592.                 'subject' => "Meeting Updates Arranged By - " $companyData->getName() . " on " $scheduledMeeting->getTitle() . ". ",
  4593.                 'fileName' => '',
  4594.                 'attachments' => $attachments,
  4595.                 'toAddress' => $email,
  4596.                 'mailTemplate' => $bodyTemplate,
  4597.                 'templateData' => $bodyData,
  4598.                 'embedCompanyImage' => 1,
  4599.                 'companyId' => $companyId,
  4600.                 'companyImagePath' => $companyData->getImage()
  4601.             ));
  4602.         }
  4603.         return new JsonResponse(array(
  4604.             'success' => true
  4605.         ));
  4606.     }
  4607.     public function meetingSchedulingAction(Request $req$action 0)
  4608.     {
  4609.         $em $this->getDoctrine()->getManager();
  4610.         $companyId $this->getLoggedUserCompanyId($req);
  4611.         $session $req->getSession();
  4612.         if ($req->request->has('XHRreq')) {
  4613.             return new JsonResponse([HumanResource::HandelXHRreqForMeetingScheduling($em$req)]);
  4614.         }
  4615.         if ($action === 'list') {
  4616.             $response HumanResource::TwigDataForScheduledMeetingList($em, [0null]);
  4617.             return $this->render(
  4618.                 'ApplicationBundle:pages/human_resource/list:scheduled_meeting_list.html.twig',
  4619.                 [
  4620.                     'page_title' => 'Scheduled Meeting List',
  4621.                     'list' => $response
  4622.                 ]
  4623.             );
  4624.         }
  4625.         if ($req->isMethod('GET')) {
  4626.             $response HumanResource::twigDataForMeetingScheduling($em);
  4627.             return $this->render(
  4628.                 'ApplicationBundle:pages/human_resource/input_forms:meeting_scheduling.html.twig',
  4629.                 [
  4630.                     'page_title' => 'Schedule a Meeting',
  4631.                     'employeeIds' => $response['employeeIds'],
  4632.                     'branches' => $response['branches'],
  4633.                     'asset' => $response['asset'],
  4634.                     'rooms' => $response['rooms'],
  4635.                     'sales_orders' => $response['salesOrders'],
  4636.                     'purchase_orders' => $response['purchaseOrders'],
  4637.                     'meeting_types' => $response['meetingType'],
  4638.                 ]
  4639.             );
  4640.         }
  4641.         if ($req->isMethod('POST')) {
  4642.             $approveHash $req->request->get('approvalHash');
  4643.             $approveRole $req->request->get('approvalRole');
  4644.             $loginId $req->getSession()->get(UserConstants::USER_LOGIN_ID);
  4645.             $isSignatureOk DocValidation::isSignatureOk($em$loginId$approveHash);
  4646.             $companyData Company::getCompanyData($em$companyId);
  4647.             if ($isSignatureOk) {
  4648.                 $isSuccess HumanResource::createOrUpdateDataForMeetingScheduling($em$req);
  4649.                 if ($isSuccess) {
  4650.                     $options = array(
  4651.                         'notification_enabled' => $this->container->getParameter('notification_enabled'),
  4652.                         'notification_server' => $this->container->getParameter('notification_server'),
  4653.                         'appId' => $req->getSession()->get(UserConstants::USER_APP_ID),
  4654.                         'url' => $this->generateUrl(
  4655.                             GeneralConstant::$Entity_list_details[array_flip(GeneralConstant::$Entity_list)['ScheduledMeeting']]['entity_view_route_path_name']
  4656.                         )
  4657.                     );
  4658.                     $meetingId $isSuccess[1];
  4659.                     System::setApprovalInfo(
  4660.                         $this->getDoctrine()->getManager(),
  4661.                         $options,
  4662.                         array_flip(GeneralConstant::$Entity_list)['ScheduledMeeting'],
  4663.                         $meetingId,
  4664.                         $req->getSession()->get(UserConstants::USER_LOGIN_ID),
  4665.                         0//normal meeting
  4666.                         0,
  4667.                         $this->get('mail_module')
  4668.                     );
  4669.                     System::createEditSignatureHash(
  4670.                         $this->getDoctrine()->getManager(),
  4671.                         array_flip(GeneralConstant::$Entity_list)['ScheduledMeeting'],
  4672.                         $meetingId,
  4673.                         $loginId,
  4674.                         $approveRole,
  4675.                         $req->request->get('approvalHash')
  4676.                     );
  4677.                     $url $this->generateUrl(
  4678.                         'view_scheduled_meeting'
  4679.                     );
  4680.                     return $this->redirect($url "/" $meetingId);
  4681.                 } else {
  4682.                     return new JsonResponse(array(
  4683.                         'success' => false
  4684.                     ));
  4685.                 }
  4686.             } else {
  4687.                 $this->addFlash(
  4688.                     'error',
  4689.                     'Invalid Approval Hash!'
  4690.                 );
  4691.                 return $this->redirectToRoute('meeting_scheduling');
  4692.             }
  4693.         }
  4694.         return $this->redirectToRoute('meeting_scheduling');
  4695.     }
  4696.     public function MeetingSchedulingForAppAction(Request $request): JsonResponse
  4697.     {
  4698.         $em $this->getDoctrine()->getManager();
  4699.         $session $request->getSession();
  4700.         $mailer $this->get('mail_module');
  4701.         $helper = new HumanResourceHelper($em$mailer);
  4702.         try {
  4703.             $data $request->request->all();
  4704.             $files $request->files->all();
  4705.             $companyId $this->getLoggedUserCompanyId($request);
  4706.             $meeting $helper->prepareMeeting($data$session);
  4707.             $agendaList = [];
  4708.             if (!empty($data['agendaList']) && is_array($data['agendaList'])) {
  4709.                 foreach ($data['agendaList'] as $index => $agendaData) {
  4710.                     $agenda = [
  4711.                         'title' => $agendaData['title'] ?? null,
  4712.                         'desc' => $agendaData['desc'] ?? null,
  4713.                         'notes' => $agendaData['notes'] ?? null,
  4714.                         'taggedDocuments' => $agendaData['taggedDocuments'] ?? [],
  4715.                         'otherDocuments' => [],
  4716.                     ];
  4717.                     if (!empty($files['agendaList'][$index]['otherDocuments'])) {
  4718.                         foreach ($files['agendaList'][$index]['otherDocuments'] as $uploadedFile) {
  4719.                             $uploadedFilePath $this->uploadMeetingFile($uploadedFile$request);
  4720.                             if ($uploadedFilePath) {
  4721.                                 $agenda['otherDocuments'][] = [
  4722.                                     'fileName' => basename($uploadedFilePath),
  4723.                                     'path' => $uploadedFilePath,
  4724.                                     'type' => $uploadedFile->getClientOriginalExtension(),
  4725.                                 ];
  4726.                             }
  4727.                         }
  4728.                     }
  4729.                     $agendaList[] = $agenda;
  4730.                 }
  4731.             }
  4732.             $meeting->setAgendaList(json_encode($agendaList));
  4733.             [$internalInfo$otherInfo$internalIds] = $helper->resolveParticipants(
  4734.                 $data['guests'] ?? [],
  4735.                 $session->get('userEmployeeId')
  4736.             );
  4737.             // Save **full participant objects** to DB
  4738.             $meeting->setInternalParticipantIds(!empty($internalInfo) ? json_encode($internalInfo) : null);
  4739.             $meeting->setOtherParticipantInfo(!empty($otherInfo) ? json_encode($otherInfo) : null);
  4740.             $meeting->setParticipantInfo(json_encode([
  4741.                 'internal' => $internalInfo,
  4742.                 'other' => $otherInfo,
  4743.             ]));
  4744.             // Persist the meeting
  4745.             $em->persist($meeting);
  4746.             $em->flush();
  4747.             // Send invitations
  4748.             $helper->sendInvitations($meeting$internalIds$otherInfo$companyId);
  4749.             return new JsonResponse([
  4750.                 'success' => true,
  4751.                 'message' => 'Meeting scheduled successfully',
  4752.                 'meetingId' => $meeting->getScheduleId(),
  4753.                 'documentHas' => $meeting->getDocumentHash(),
  4754.             ]);
  4755.         } catch (\Exception $e) {
  4756.             return new JsonResponse(['success' => false'error' => $e->getMessage()], 500);
  4757.         }
  4758.     }
  4759.     public function updateMeetingForAppAction(Request $requestint $meetingId): JsonResponse
  4760.     {
  4761.         $em $this->getDoctrine()->getManager();
  4762.         $session $request->getSession();
  4763.         $mailer $this->get('mail_module');
  4764.         $helper = new HumanResourceHelper($em$mailer);
  4765.         try {
  4766.             $data $request->request->all();
  4767.             $files $request->files->all();
  4768.             $meeting $em->getRepository(ScheduledMeeting::class)->find($meetingId);
  4769.             if (!$meeting) {
  4770.                 return new JsonResponse(['success' => false'error' => 'Meeting not found'], 404);
  4771.             }
  4772.             $meeting->setTitle($data['title'] ?? $meeting->getTitle());
  4773.             $meeting->setSpecialType($data['specialType'] ?? $meeting->getSpecialType());
  4774.             $meeting->setStartAt(!empty($data['startAt']) ? new \DateTime($data['startAt']) : $meeting->getStartAt());
  4775.             $meeting->setEndAt(!empty($data['endAt']) ? new \DateTime($data['endAt']) : $meeting->getEndAt());
  4776.             $meeting->setMeetingType($data['meetingType'] ?? $meeting->getMeetingType());
  4777.             $meeting->setLocation($data['location'] ?? $meeting->getLocation());
  4778.             $meeting->setRoomId($data['roomId'] ?? $meeting->getRoomId());
  4779.             $meeting->setDesc($data['desc'] ?? $meeting->getDesc());
  4780.             $meeting->setLastModifiedDate(new \DateTime());
  4781.             if (isset($data['agendaList']) && is_array($data['agendaList'])) {
  4782.                 $agendaList = [];
  4783.                 foreach ($data['agendaList'] as $index => $agendaData) {
  4784.                     $agenda = [
  4785.                         'title' => $agendaData['title'] ?? null,
  4786.                         'desc' => $agendaData['desc'] ?? null,
  4787.                         'notes' => $agendaData['notes'] ?? null,
  4788.                         'taggedDocuments' => $agendaData['taggedDocuments'] ?? [],
  4789.                         'otherDocuments' => [],
  4790.                     ];
  4791.                     if (!empty($files['agendaList'][$index]['otherDocuments'])) {
  4792.                         foreach ($files['agendaList'][$index]['otherDocuments'] as $uploadedFile) {
  4793.                             $uploadedFilePath $this->uploadMeetingFile($uploadedFile$request);
  4794.                             if ($uploadedFilePath) {
  4795.                                 $agenda['otherDocuments'][] = [
  4796.                                     'fileName' => basename($uploadedFilePath),
  4797.                                     'path' => $uploadedFilePath,
  4798.                                     'type' => $uploadedFile->getClientOriginalExtension(),
  4799.                                 ];
  4800.                             }
  4801.                         }
  4802.                     }
  4803.                     if (!empty($agendaData['otherDocumentsExisting'])) {
  4804.                         $agenda['otherDocuments'] = array_merge(
  4805.                             $agenda['otherDocuments'],
  4806.                             $agendaData['otherDocumentsExisting']
  4807.                         );
  4808.                     }
  4809.                     $agendaList[] = $agenda;
  4810.                 }
  4811.                 $meeting->setAgendaList(json_encode($agendaList));
  4812.             }
  4813.             if (isset($data['guests'])) {
  4814.                 [$internalIds$otherInfo] = $helper->resolveParticipants($data['guests'], $session->get('userEmployeeId'));
  4815.                 $meeting->setInternalParticipantIds(!empty($internalIds) ? json_encode($internalIds) : null);
  4816.                 $meeting->setOtherParticipantInfo(!empty($otherInfo) ? json_encode($otherInfo) : null);
  4817.             }
  4818.             $em->persist($meeting);
  4819.             $em->flush();
  4820.             if (isset($internalIds) || isset($otherInfo)) {
  4821.                 $helper->sendInvitations($meeting$internalIds ?? [], $otherInfo ?? [], $meeting->getCompanyId());
  4822.             }
  4823.             return new JsonResponse([
  4824.                 'success' => true,
  4825.                 'message' => 'Meeting updated successfully',
  4826.                 'meetingId' => $meeting->getScheduleId(),
  4827.                 'facilitator' => ['id' => $meeting->getFacilitatorId(), 'name' => $meeting->getFacilitatorName()],
  4828.                 'companyId' => $meeting->getCompanyId(),
  4829.                 'branchId' => $meeting->getBranchId(),
  4830.                 'internalParticipants' => json_decode($meeting->getInternalParticipantIds(), true) ?? [],
  4831.                 'otherParticipants' => json_decode($meeting->getOtherParticipantInfo(), true) ?? [],
  4832.                 'agendas' => json_decode($meeting->getAgendaList(), true) ?? [],
  4833.             ]);
  4834.         } catch (\Exception $e) {
  4835.             return new JsonResponse(['success' => false'error' => $e->getMessage()], 500);
  4836.         }
  4837.     }
  4838.     public function GetDocumentsForMeetingScheduleAppAction(Request $request): JsonResponse
  4839.     {
  4840.         $em $this->getDoctrine()->getManager();
  4841.         $hrHelper = new HumanResourceHelper($em);
  4842.         try {
  4843.             $documents $hrHelper->getAllDocumentsFromApproval($request);
  4844.             return ResponseStructure::success($documents'Documents fetched successfully');
  4845.         } catch (\Exception $e) {
  4846.             return ResponseStructure::error($e->getMessage());
  4847.         }
  4848.     }
  4849.     public function getMeetingsByDateAction(Request $request): JsonResponse
  4850.     {
  4851.         $em $this->getDoctrine()->getManager();
  4852.         $dateParam $request->query->get('date');
  4853.         $monthParam $request->query->get('month');
  4854.         $dayParam $request->query->get('day');
  4855.         $yearParam $request->query->get('year');
  4856.         $start $end null;
  4857.         try {
  4858.             if ($dateParam) {
  4859.                 if (strpos($dateParam',') !== false) {
  4860.                     [$startStr$endStr] = explode(','$dateParam);
  4861.                     $start = new \DateTime($startStr " 00:00:00");
  4862.                     $end = new \DateTime($endStr " 23:59:59");
  4863.                 } else {
  4864.                     $parts explode('-'$dateParam);
  4865.                     if (count($parts) === 3) {
  4866.                         $start = new \DateTime($dateParam " 00:00:00");
  4867.                         $end = new \DateTime($dateParam " 23:59:59");
  4868.                     } elseif (count($parts) === 2) {
  4869.                         $start = new \DateTime($dateParam "-01 00:00:00");
  4870.                         $end = (clone $start)->modify('last day of this month')->setTime(235959);
  4871.                     } else {
  4872.                         throw new \Exception("Invalid date format");
  4873.                     }
  4874.                 }
  4875.             } elseif ($monthParam) {
  4876.                 $year $yearParam ?: date('Y');
  4877.                 $monthDate = new \DateTime("first day of $monthParam $year");
  4878.                 $start = (clone $monthDate)->setTime(000);
  4879.                 $end = (clone $monthDate)->modify('last day of this month')->setTime(235959);
  4880.             } elseif ($dayParam) {
  4881.                 $year $yearParam ?: date('Y');
  4882.                 $startOfYear = new \DateTime("$year-01-01 00:00:00");
  4883.                 $endOfYear = new \DateTime("$year-12-31 23:59:59");
  4884.                 $meetings $em->getRepository(\ApplicationBundle\Entity\ScheduledMeeting::class)
  4885.                     ->createQueryBuilder('m')
  4886.                     ->where('m.startAt BETWEEN :start AND :end')
  4887.                     ->setParameter('start'$startOfYear)
  4888.                     ->setParameter('end'$endOfYear)
  4889.                     ->getQuery()
  4890.                     ->getResult();
  4891.                 $meetingType MeetingSchedulingConstant::$meetingType;
  4892.                 $data = [];
  4893.                 foreach ($meetings as $meeting) {
  4894.                     if (strtolower($meeting->getStartAt()->format('l')) === strtolower($dayParam)) {
  4895.                         $data[] = [
  4896.                             'id' => $meeting->getScheduleId(),
  4897.                             'title' => $meeting->getTitle(),
  4898.                             'desc' => $meeting->getDesc(),
  4899.                             'startAt' => $meeting->getStartAt()->format('Y-m-d H:i:s'),
  4900.                             'endAt' => $meeting->getEndAt() ? $meeting->getEndAt()->format('Y-m-d H:i:s') : null,
  4901.                             'roomId' => $meeting->getRoomId(),
  4902.                             'meetingType' => $meetingType[$meeting->getMeetingType()] ?? null,
  4903.                             'location' => $meeting->getLocation(),
  4904.                             'participant' => json_decode($meeting->getParticipantInfo()),
  4905.                             'status' => $meeting->getStatus(),
  4906.                             'approved' => (bool)$meeting->getApproved(),
  4907.                         ];
  4908.                     }
  4909.                 }
  4910.                 return new JsonResponse([
  4911.                     'success' => true,
  4912.                     'filter' => [
  4913.                         'day' => $dayParam,
  4914.                         'year' => $year
  4915.                     ],
  4916.                     'meetings' => $data
  4917.                 ]);
  4918.             } else {
  4919.                 return new JsonResponse([
  4920.                     'success' => false,
  4921.                     'error' => 'Please provide month, day, or date query parameter.'
  4922.                 ], 400);
  4923.             }
  4924.         } catch (\Exception $e) {
  4925.             return new JsonResponse([
  4926.                 'success' => false,
  4927.                 'error' => 'Invalid date format or input. ' $e->getMessage()
  4928.             ], 400);
  4929.         }
  4930.         $meetings $em->getRepository(\ApplicationBundle\Entity\ScheduledMeeting::class)
  4931.             ->createQueryBuilder('m')
  4932.             ->where('m.startAt BETWEEN :start AND :end')
  4933.             ->setParameter('start'$start)
  4934.             ->setParameter('end'$end)
  4935.             ->getQuery()
  4936.             ->getResult();
  4937.         $meetingType MeetingSchedulingConstant::$meetingType;
  4938.         $data = [];
  4939.         foreach ($meetings as $meeting) {
  4940.             $data[] = [
  4941.                 'id' => $meeting->getScheduleId(),
  4942.                 'title' => $meeting->getTitle(),
  4943.                 'desc' => $meeting->getDesc(),
  4944.                 'startAt' => $meeting->getStartAt() ? $meeting->getStartAt()->format('Y-m-d H:i:s') : null,
  4945.                 'endAt' => $meeting->getEndAt() ? $meeting->getEndAt()->format('Y-m-d H:i:s') : null,
  4946.                 'roomId' => $meeting->getRoomId(),
  4947.                 'meetingType' => $meetingType[$meeting->getMeetingType()] ?? null,
  4948.                 'location' => $meeting->getLocation(),
  4949.                 'participant' => json_decode($meeting->getParticipantInfo()),
  4950.                 'status' => $meeting->getStatus(),
  4951.                 'approved' => (bool)$meeting->getApproved(),
  4952.             ];
  4953.         }
  4954.         return new JsonResponse([
  4955.             'success' => true,
  4956.             'range' => [
  4957.                 'start' => $start->format('Y-m-d H:i:s'),
  4958.                 'end' => $end->format('Y-m-d H:i:s')
  4959.             ],
  4960.             'meetings' => $data
  4961.         ]);
  4962.     }
  4963.     public function getMeetingByYearlyAction(Request $request): JsonResponse
  4964.     {
  4965.         $em $this->getDoctrine()->getManager();
  4966.         $yearParam $request->query->get('year');
  4967.         try {
  4968.             $data HumanResourceHelper::GetMeetingByYearlyAction($em$yearParam);
  4969.             return new JsonResponse($data200);
  4970.         } catch (\Exception $e) {
  4971.             return new JsonResponse([
  4972.                 'success' => false,
  4973.                 'error' => $e->getMessage()
  4974.             ], 400);
  4975.         }
  4976.     }
  4977.     public function getMeetingByIdAction(Request $requestint $id): JsonResponse
  4978.     {
  4979.         $em $this->getDoctrine()->getManager();
  4980.         $meeting $em->getRepository(\ApplicationBundle\Entity\ScheduledMeeting::class)->find($id);
  4981.         if (!$meeting) {
  4982.             return new JsonResponse([
  4983.                 'success' => false,
  4984.                 'error' => 'Meeting not found'
  4985.             ], 404);
  4986.         }
  4987.         return new JsonResponse([
  4988.             'success' => true,
  4989.             'meeting' => [
  4990.                 'id' => $meeting->getScheduleId(),
  4991.                 'docHash' => $meeting->getDocumentHash(),
  4992.                 'title' => $meeting->getTitle(),
  4993.                 'desc' => $meeting->getDesc(),
  4994.                 'specialType' => $meeting->getSpecialType(),
  4995.                 'startAt' => $meeting->getStartAt() ? $meeting->getStartAt()->format('Y-m-d H:i:s') : null,
  4996.                 'endAt' => $meeting->getEndAt() ? $meeting->getEndAt()->format('Y-m-d H:i:s') : null,
  4997.                 'meetingType' => $meeting->getMeetingType(),
  4998.                 'location' => $meeting->getLocation(),
  4999.                 'roomId' => $meeting->getRoomId(),
  5000.                 'facilitator' => [
  5001.                     'id' => $meeting->getFacilitatorId(),
  5002.                     'name' => $meeting->getFacilitatorName()
  5003.                 ],
  5004.                 'companyId' => $meeting->getCompanyId(),
  5005.                 'branchId' => $meeting->getBranchId(),
  5006.                 'agendaList' => $meeting->getAgendaList() ? json_decode($meeting->getAgendaList(), true) : [],
  5007.                 'internalParticipants' => $meeting->getInternalParticipantIds() ? json_decode($meeting->getInternalParticipantIds(), true) : [],
  5008.                 'otherParticipants' => $meeting->getOtherParticipantInfo() ? json_decode($meeting->getOtherParticipantInfo(), true) : [],
  5009.                 'createdAt' => $meeting->getCreatedAt()->format('Y-m-d H:i:s'),
  5010.             ]
  5011.         ]);
  5012.     }
  5013.     public function updateMeetingAction(Request $requestint $id): JsonResponse
  5014.     {
  5015.         $em $this->getDoctrine()->getManager();
  5016.         $meeting $em->getRepository(\ApplicationBundle\Entity\ScheduledMeeting::class)->find($id);
  5017.         if (!$meeting) {
  5018.             return new JsonResponse(['success' => false'error' => 'Meeting not found'], 404);
  5019.         }
  5020.         $data json_decode($request->getContent(), true);
  5021.         if (!$data) {
  5022.             $data $request->request->all();
  5023.         }
  5024.         if (!$data) {
  5025.             return new JsonResponse(['success' => false'error' => 'Invalid data'], 400);
  5026.         }
  5027.         if (isset($data['title'])) $meeting->setTitle($data['title']);
  5028.         if (isset($data['desc'])) $meeting->setDesc($data['desc']);
  5029.         if (isset($data['startAt'])) $meeting->setStartAt(new \DateTime($data['startAt']));
  5030.         if (isset($data['endAt'])) $meeting->setEndAt(new \DateTime($data['endAt']));
  5031.         if (isset($data['location'])) $meeting->setLocation($data['location']);
  5032.         if (isset($data['meetingType'])) $meeting->setMeetingType($data['meetingType']);
  5033.         if (isset($data['roomId'])) $meeting->setRoomId($data['roomId']);
  5034.         if (isset($data['agendaList'])) {
  5035.             $agendaList is_array($data['agendaList']) ? $data['agendaList'] : json_decode($data['agendaList'], true);
  5036.             $meeting->setAgendaList(json_encode($agendaList));
  5037.         }
  5038.         $meeting->setLastModifiedDate(new \DateTime());
  5039.         $em->flush();
  5040.         return new JsonResponse([
  5041.             'success' => true,
  5042.             'message' => 'Meeting updated successfully',
  5043.             'meetingId' => $meeting->getScheduleId()
  5044.         ]);
  5045.     }
  5046.     public function deleteMeetingAction(Request $requestint $id): JsonResponse
  5047.     {
  5048.         $em $this->getDoctrine()->getManager();
  5049.         $meeting $em->getRepository(\ApplicationBundle\Entity\ScheduledMeeting::class)->find($id);
  5050.         if (!$meeting) {
  5051.             return new JsonResponse(['success' => false'error' => 'Meeting not found'], 404);
  5052.         }
  5053.         $em->remove($meeting);
  5054.         $em->flush();
  5055.         return new JsonResponse([
  5056.             'success' => true,
  5057.             'message' => 'Meeting deleted successfully',
  5058.             'deletedId' => $id
  5059.         ]);
  5060.     }
  5061.     public function searchParticipantByEmailAction(Request $request): JsonResponse
  5062.     {
  5063.         $em $this->getDoctrine()->getManager();
  5064.         $email trim($request->query->get('email'));
  5065.         if (empty($email)) {
  5066.             return new JsonResponse([
  5067.                 'success' => false,
  5068.                 'error' => 'Email is required'
  5069.             ], 400);
  5070.         }
  5071.         try {
  5072.             $companyId $this->getLoggedUserCompanyId($request);
  5073.             $client $em->getRepository(\ApplicationBundle\Entity\AccClients::class)
  5074.                 ->findOneBy(['email' => $email]);
  5075.             if ($client) {
  5076.                 return new JsonResponse([
  5077.                     'success' => true,
  5078.                     'type' => 'client',
  5079.                     'data' => [
  5080.                         'client_id' => $client->getClientId(),
  5081.                         'company_id' => $client->getCompanyId(),
  5082.                         'client_name' => $client->getClientName(),
  5083.                         'email' => $client->getEmail(),
  5084.                     ]
  5085.                 ]);
  5086.             }
  5087.             $employee $em->getRepository(\ApplicationBundle\Entity\Employee::class)
  5088.                 ->findOneBy(['email' => $email]);
  5089.             if ($employee) {
  5090.                 return new JsonResponse([
  5091.                     'success' => true,
  5092.                     'type' => 'employee',
  5093.                     'data' => [
  5094.                         'name' => $employee->getName(),
  5095.                         'email' => $employee->getEmail(),
  5096.                         'user_id' => $employee->getUserId(),
  5097.                         'address_contact' => $employee->getAddressContact(),
  5098.                     ]
  5099.                 ]);
  5100.             }
  5101.             return new JsonResponse([
  5102.                 'success' => false,
  5103.                 'error' => 'No client or employee found for this email'
  5104.             ], 404);
  5105.         } catch (\Exception $e) {
  5106.             return new JsonResponse([
  5107.                 'success' => false,
  5108.                 'error' => $e->getMessage()
  5109.             ], 500);
  5110.         }
  5111.     }
  5112.     public function GetRoomInformationForMeetingAction(Request $request): JsonResponse
  5113.     {
  5114.         $em $this->getDoctrine()->getManager();
  5115.         $onlyAvailable $request->query->getBoolean('onlyAvailable'false);
  5116.         $rooms HumanResourceHelper::getRooms($em$onlyAvailable);
  5117.         return new JsonResponse([
  5118.             'status' => 'success',
  5119.             'data' => $rooms
  5120.         ]);
  5121.     }
  5122.     public function MeetingTypeAction(Request $request)
  5123.     {
  5124.         return new JsonResponse([
  5125.             'success' => true,
  5126.             'data' => MeetingSchedulingConstant::$meetingType
  5127.         ]);
  5128.     }
  5129.     public function GetPriorityListAction()
  5130.     {
  5131.         $priority HumanResourceHelper::priorityList();
  5132.         return new JsonResponse([
  5133.             'success' => true,
  5134.             'data' => $priority
  5135.         ]);
  5136.     }
  5137.     public function CreateTrainingScheduleAction(Request $req$action 0)
  5138.     {
  5139.         $em $this->getDoctrine()->getManager();
  5140.         $companyId $this->getLoggedUserCompanyId($req);
  5141.         $session $req->getSession();
  5142.         if ($req->request->has('XHRreq')) {
  5143.             return new JsonResponse([HumanResource::HandelXHRreqForMeetingScheduling($em$req)]);
  5144.         }
  5145.         if ($action === 'list') {
  5146.             $response HumanResource::TwigDataForScheduledMeetingList($em, [1]);
  5147.             return $this->render(
  5148.                 'ApplicationBundle:pages/human_resource/list:scheduled_meeting_list.html.twig',
  5149.                 [
  5150.                     'page_title' => 'Training Schedule List',
  5151.                     'list' => $response
  5152.                 ]
  5153.             );
  5154.         }
  5155.         if ($req->isMethod('GET')) {
  5156.         }
  5157.         if ($req->isMethod('POST')) {
  5158.             $approveHash $req->request->get('approvalHash');
  5159.             $approveRole $req->request->get('approvalRole');
  5160.             $loginId $req->getSession()->get(UserConstants::USER_LOGIN_ID);
  5161.             $isSignatureOk DocValidation::isSignatureOk($em$loginId$approveHash);
  5162.             $companyData Company::getCompanyData($em$companyId);
  5163.             if ($isSignatureOk) {
  5164.                 $isSuccess HumanResource::createOrUpdateDataForMeetingScheduling($em$req);
  5165.                 if ($isSuccess) {
  5166.                     $options = array(
  5167.                         'notification_enabled' => $this->container->getParameter('notification_enabled'),
  5168.                         'notification_server' => $this->container->getParameter('notification_server'),
  5169.                         'appId' => $req->getSession()->get(UserConstants::USER_APP_ID),
  5170.                         'url' => $this->generateUrl(
  5171.                             GeneralConstant::$Entity_list_details[array_flip(GeneralConstant::$Entity_list)['ScheduledMeeting']]['entity_view_route_path_name']
  5172.                         )
  5173.                     );
  5174.                     $meetingId $isSuccess[1];
  5175.                     System::setApprovalInfo(
  5176.                         $this->getDoctrine()->getManager(),
  5177.                         $options,
  5178.                         array_flip(GeneralConstant::$Entity_list)['ScheduledMeeting'],
  5179.                         $meetingId,
  5180.                         $req->getSession()->get(UserConstants::USER_LOGIN_ID),
  5181.                         '',
  5182.                         0,
  5183.                         $this->get('mail_module')
  5184.                     );
  5185.                     System::createEditSignatureHash(
  5186.                         $this->getDoctrine()->getManager(),
  5187.                         array_flip(GeneralConstant::$Entity_list)['ScheduledMeeting'],
  5188.                         $meetingId,
  5189.                         $loginId,
  5190.                         $approveRole,
  5191.                         $req->request->get('approvalHash')
  5192.                     );
  5193.                     $url $this->generateUrl(
  5194.                         'view_scheduled_meeting'
  5195.                     );
  5196.                     return $this->redirect($url "/" $meetingId);
  5197.                 } else {
  5198.                     return new JsonResponse(array(
  5199.                         'success' => false
  5200.                     ));
  5201.                 }
  5202.             } else {
  5203.                 $this->addFlash(
  5204.                     'error',
  5205.                     'Invalid Approval Hash!'
  5206.                 );
  5207.                 return $this->redirectToRoute('create_training_schedule');
  5208.             }
  5209.         }
  5210.         $response HumanResource::twigDataForTrainingScheduling($em);
  5211.         return $this->render(
  5212.             'ApplicationBundle:pages/human_resource/input_forms:create_training_schedule.html.twig',
  5213.             [
  5214.                 'page_title' => 'Schedule a Training',
  5215.                 'employeeIds' => $response['employeeIds'],
  5216.                 'branches' => $response['branches'],
  5217.                 'asset' => $response['asset'],
  5218.                 'rooms' => $response['rooms'],
  5219.                 'courseList' => $response['courseList'],
  5220.                 'sales_orders' => $response['salesOrders'],
  5221.                 'purchase_orders' => $response['purchaseOrders'],
  5222.                 'meeting_types' => $response['meetingType'],
  5223.                 'skillList' => $response['skillList'],
  5224.             ]
  5225.         );
  5226.     }
  5227.     public function ScheduledTrainingListAction(Request $req$action 0)
  5228.     {
  5229.         $em $this->getDoctrine()->getManager();
  5230.         $companyId $this->getLoggedUserCompanyId($req);
  5231.         $session $req->getSession();
  5232.         $response HumanResource::TwigDataForScheduledMeetingList($em, [1]);
  5233.         return $this->render(
  5234.             'ApplicationBundle:pages/human_resource/list:scheduled_training_list.html.twig',
  5235.             [
  5236.                 'page_title' => 'Scheduled Trainings ',
  5237.                 'list' => $response
  5238.             ]
  5239.         );
  5240.     }
  5241.     public function ScheduledInterviewListAction(Request $req$action 0)
  5242.     {
  5243.         $em $this->getDoctrine()->getManager();
  5244.         $companyId $this->getLoggedUserCompanyId($req);
  5245.         $session $req->getSession();
  5246.         $response HumanResource::TwigDataForScheduledMeetingList($em, [2]);
  5247.         return $this->render(
  5248.             'ApplicationBundle:pages/human_resource/list:scheduled_interview_list.html.twig',
  5249.             [
  5250.                 'page_title' => 'Scheduled Interviews ',
  5251.                 'list' => $response
  5252.             ]
  5253.         );
  5254.     }
  5255.     public function GetFilteredQuestionsAction(Request $request$search '')
  5256.     {
  5257.         $em $this->getDoctrine()->getManager();
  5258.         $companyId $this->getLoggedUserCompanyId($request);
  5259.         if ($search == '' || $search == '_EMPTY_')
  5260.             $Query "SELECT  * FROM questionnaire WHERE 1 limit 10;";
  5261.         else
  5262.             $Query "SELECT  * FROM questionnaire WHERE question_text like '%$search%'  limit 10;";
  5263.         $stmt $em->getConnection()->prepare($Query);
  5264.         $stmt->execute();
  5265.         $queryResult $stmt->fetchAll();
  5266.         $parent_head_ids = [];
  5267.         $queryResultIndexed = [];
  5268.         foreach ($queryResult as $dt) {
  5269.             $queryResultIndexed[$dt['question_id']] = $dt;
  5270.         }
  5271.         return new JsonResponse(array(
  5272.             'data' => $queryResult,
  5273.             'queryResultIndexed' => $queryResultIndexed,
  5274.         ));
  5275.     }
  5276.     public function CreateTrainingCourseAction(Request $request$id 0)
  5277.     {
  5278.         $em $this->getDoctrine()->getManager();
  5279.         $companyId $this->getLoggedUserCompanyId($request);
  5280.         $skills $em->getRepository('ApplicationBundle:Skill')->findAll();
  5281.         $courses $em->getRepository('ApplicationBundle:TrainingCourse')->findAll();
  5282.         if ($request->isMethod('POST')) {
  5283.             $loginId $request->getSession()->get(UserConstants::USER_LOGIN_ID);
  5284.             $skill = new TrainingCourse;
  5285.             $skill->setTitle($request->request->get('name'));
  5286.             $skill->setCourseHash($request->request->get('coursehash'));
  5287.             $skill->setTrainingMaterialText($request->request->get('overview'));
  5288.             $skill->setTaggedSkillHashes(json_encode($request->request->get('skill')));
  5289.             $skill->setCompanyId($companyId);
  5290.             //$skill->setEditFlag(1); //editable usually
  5291.             $skill->setCreatedLoginId($request->getSession()->get(UserConstants::USER_LOGIN_ID));
  5292.             //$skill->setApproved(GeneralConstant::APPROVAL_STATUS_PENDING);
  5293.             //$skill->setAutocreated(0);
  5294.             $em->persist($skill);
  5295.             $em->flush();
  5296.         }
  5297.         return $this->render(
  5298.             'ApplicationBundle:pages/human_resource/input_forms:create_training_course.html.twig',
  5299.             [
  5300.                 'page_title' => 'Create Training Course',
  5301.                 'skills' => $skills,
  5302.                 'courses' => $courses
  5303.             ]
  5304.         );
  5305.     }
  5306.     public function CreateEmployeeExpenseAllowanceSettingsAction(Request $request$id 0)
  5307.     {
  5308.         $em $this->getDoctrine()->getManager();
  5309.         $companyId $this->getLoggedUserCompanyId($request);
  5310.         $extDocData = [];
  5311.         $extDetailsData = [];
  5312.         if ($request->isMethod('POST')) {
  5313.             //            Generic::debugMessage($_POST);
  5314.             $em $this->getDoctrine()->getManager();
  5315.             $entity_id array_flip(GeneralConstant::$Entity_list)['EmployeeExpenseAllowanceSettings']; //change
  5316.             $dochash $request->request->get('docHash'); //change
  5317.             $loginId $request->getSession()->get(UserConstants::USER_LOGIN_ID);
  5318.             $approveRole $request->request->get('approvalRole');
  5319.             $approveHash $request->request->get('approvalHash');
  5320.             if (!DocValidation::isInsertable(
  5321.                 $em,
  5322.                 $entity_id,
  5323.                 $dochash,
  5324.                 $loginId,
  5325.                 $approveRole,
  5326.                 $approveHash,
  5327.                 $id
  5328.             )
  5329.             ) {
  5330.                 $this->addFlash(
  5331.                     'error',
  5332.                     'Sorry Could not insert Data.'
  5333.                 );
  5334.             } else {
  5335.                 $funcname 'EmployeeExpenseAllowanceSettings';
  5336.                 DeleteDocument::$funcname($em$id0);
  5337.                 $docId HumanResource::CreateSalarySegregationPolicy($em$request$companyId0);
  5338.                 //now add Approval info
  5339.                 $loginId $request->getSession()->get(UserConstants::USER_LOGIN_ID);
  5340.                 $approveRole $request->request->get('approvalRole');
  5341.                 $options = array(
  5342.                     'notification_enabled' => $this->container->getParameter('notification_enabled'),
  5343.                     'notification_server' => $this->container->getParameter('notification_server'),
  5344.                     'appId' => $request->getSession()->get(UserConstants::USER_APP_ID),
  5345.                     'url' => $this->generateUrl(
  5346.                         GeneralConstant::$Entity_list_details[array_flip(GeneralConstant::$Entity_list)['EmployeeExpenseAllowanceSettings']]['entity_view_route_path_name']
  5347.                     )
  5348.                 );
  5349.                 System::setApprovalInfo(
  5350.                     $this->getDoctrine()->getManager(),
  5351.                     $options,
  5352.                     array_flip(GeneralConstant::$Entity_list)['EmployeeExpenseAllowanceSettings'],
  5353.                     $docId,
  5354.                     $request->getSession()->get(UserConstants::USER_LOGIN_ID)
  5355.                 );
  5356.                 System::createEditSignatureHash(
  5357.                     $this->getDoctrine()->getManager(),
  5358.                     array_flip(GeneralConstant::$Entity_list)['EmployeeExpenseAllowanceSettings'],
  5359.                     $docId,
  5360.                     $loginId,
  5361.                     $approveRole,
  5362.                     $request->request->get('approvalHash')
  5363.                 );
  5364.                 $doc_here $this->getDoctrine()
  5365.                     ->getRepository('ApplicationBundle:EmployeeExpenseAllowanceSettings')
  5366.                     ->findOneBy(
  5367.                         array(
  5368.                             'id' => $docId
  5369.                         )
  5370.                     );
  5371.                 //notify
  5372.                 $this->addFlash(
  5373.                     'success',
  5374.                     'Settings Successfully Updated.'
  5375.                 );
  5376.                 $url $this->generateUrl(
  5377.                     GeneralConstant::$Entity_list_details[array_flip(GeneralConstant::$Entity_list)['EmployeeExpenseAllowanceSettings']]['entity_view_route_path_name']
  5378.                 );
  5379.                 System::AddNewNotification(
  5380.                     $this->container->getParameter('notification_enabled'),
  5381.                     $this->container->getParameter('notification_server'),
  5382.                     $request->getSession()->get(UserConstants::USER_APP_ID),
  5383.                     $request->getSession()->get(UserConstants::USER_COMPANY_ID),
  5384.                     "Salary Segregation Policy : " $doc_here->getDocumentHash() . " Has Been Created And is Under Processing",
  5385.                     'pos',
  5386.                     System::getPositionIdsByDepartment($emGeneralConstant::HRM_DEPARTMENT),
  5387.                     'success',
  5388.                     //                    $url . "/" . $TransID,
  5389.                     $url "/" $docId,
  5390.                     "Journal"
  5391.                 );
  5392.                 return $this->redirect($url "/" $docId);
  5393.             }
  5394.         }
  5395.         //for edits
  5396.         if ($id == 0) {
  5397.         } else {
  5398.             $extDocData $em->getRepository('ApplicationBundle:EmployeeExpenseAllowanceSettings')->findOneBy(
  5399.                 array(
  5400.                     'id' => $id///material
  5401.                 )
  5402.             );
  5403.             //now if its not editable, redirect to view
  5404.             if ($extDocData) {
  5405.                 if ($extDocData->getEditFlag() != 1) {
  5406. //          $url = $this->generateUrl(
  5407. ////              'view_salary_segregation_policy'
  5408. //              'salary_segregation_policy'
  5409. //          );
  5410. //          return $this->redirect($url . "/" . $id);
  5411.                 } else {
  5412. //          $extVoucherDetailsData = Accounts::GetVoucherDataForEdit($em, $voucherId);
  5413. //          $extDetailsData = $em->getRepository('ApplicationBundle:SalarySegregationPolicy')->findOneBy(
  5414. //              array(
  5415. //                  'transactionId' => $id, ///material
  5416. //
  5417. //              )
  5418. //          );
  5419.                 }
  5420.             } else {
  5421.             }
  5422.         }
  5423.         $employeeIds $em->getRepository("ApplicationBundle:Employee")->findAll();
  5424.         $employeeType HumanResourceConstant::$employeeType;
  5425.         $employeeExpenseAllowanceTypes HumanResourceConstant::$employeeExpenseAllowanceTypes;
  5426.         $Designation $em->getRepository("ApplicationBundle:SysDepartmentPosition")->findAll();
  5427.         $branch $em->getRepository("ApplicationBundle:Branch")->findAll();
  5428.         $departments $em->getRepository("ApplicationBundle:SysDepartment")->findAll();
  5429.         $department = [];
  5430.         foreach ($departments as $entry) {
  5431.             $department[$entry->getDepartmentId()] = array(
  5432.                 'id' => $entry->getDepartmentId(),
  5433.                 'name' => $entry->getDepartmentName(),
  5434.             );
  5435.         }
  5436.         return $this->render(
  5437.             'ApplicationBundle:pages/human_resource/input_forms:create_employee_expense_allowance_settings.html.twig',
  5438.             [
  5439.                 'page_title' => 'Employee Expense Allowance Settings',
  5440.                 'employeeIds' => $employeeIds,
  5441.                 'extId' => $id,
  5442.                 'extDocData' => $extDocData,
  5443.                 'employeeType' => $employeeType,
  5444.                 'employeeExpenseAllowanceTypes' => $employeeExpenseAllowanceTypes,
  5445.                 'Designation' => $Designation,
  5446.                 'branch' => $branch,
  5447.                 'department' => $department,
  5448.             ]
  5449.         );
  5450.     }
  5451.     public function EmployeeExpenseAllowanceSettingsListAction(Request $request)
  5452.     {
  5453.         $em $this->getDoctrine()->getManager();
  5454.         $allowed_ids = [];
  5455.         $companyId $this->getLoggedUserCompanyId($request);
  5456.         $listData HumanResource::GetDataForEmployeeExpenseAllowanceSettingsListAction($em$request->isMethod('POST') ? 'POST' 'GET'$request->request$companyId);
  5457.         if ($request->isMethod('POST')) {
  5458.             if ($request->query->has('dataTableQry')) {
  5459.                 return new JsonResponse(
  5460.                     $listData
  5461.                 );
  5462.             }
  5463.         }
  5464.         return $this->render('ApplicationBundle:pages/human_resource/list:employee_expense_allowance_settings_list.html.twig',
  5465. //         return $this->render('ApplicationBundle:pages/dashboard:test_pix_invent.html.twig',
  5466.             array(
  5467.                 'page_title' => 'Expense Allowance Settings List',
  5468. //            'data' => SalesOrderM::GetClientList($em, [], $companyId),
  5469. //            'client_types' => Client::GetClientType($em, $companyId),
  5470. //            'region_list' => Client::RegionList($em, $companyId),
  5471. //            'geographical_region_list' => Client::GeographicalRegionList($em, $companyId)
  5472.             )
  5473.         );
  5474.     }
  5475.     public function salarySegAction(Request $request$id 0)
  5476.     {
  5477.         $em $this->getDoctrine()->getManager();
  5478.         $companyId $this->getLoggedUserCompanyId($request);
  5479.         $extDocData = [];
  5480.         $extDetailsData = [];
  5481.         if ($request->isMethod('POST')) {
  5482.             //            Generic::debugMessage($_POST);
  5483.             $em $this->getDoctrine()->getManager();
  5484.             $entity_id array_flip(GeneralConstant::$Entity_list)['SalarySegregationPolicy']; //change
  5485.             $dochash $request->request->get('docHash'); //change
  5486.             $loginId $request->getSession()->get(UserConstants::USER_LOGIN_ID);
  5487.             $approveRole $request->request->get('approvalRole');
  5488.             $approveHash $request->request->get('approvalHash');
  5489.             if (!DocValidation::isInsertable(
  5490.                 $em,
  5491.                 $entity_id,
  5492.                 $dochash,
  5493.                 $loginId,
  5494.                 $approveRole,
  5495.                 $approveHash,
  5496.                 $id
  5497.             )
  5498.             ) {
  5499.                 $this->addFlash(
  5500.                     'error',
  5501.                     'Sorry Couldnot insert Data.'
  5502.                 );
  5503.             } else {
  5504.                 $funcname 'SalarySegregationPolicy';
  5505.                 DeleteDocument::$funcname($em$id0);
  5506.                 $docId HumanResource::CreateSalarySegregationPolicy($em$request$companyId0);
  5507.                 //now add Approval info
  5508.                 $loginId $request->getSession()->get(UserConstants::USER_LOGIN_ID);
  5509.                 $approveRole $request->request->get('approvalRole');
  5510.                 $options = array(
  5511.                     'notification_enabled' => $this->container->getParameter('notification_enabled'),
  5512.                     'notification_server' => $this->container->getParameter('notification_server'),
  5513.                     'appId' => $request->getSession()->get(UserConstants::USER_APP_ID),
  5514.                     'url' => $this->generateUrl(
  5515.                         GeneralConstant::$Entity_list_details[array_flip(GeneralConstant::$Entity_list)['SalarySegregationPolicy']]['entity_view_route_path_name']
  5516.                     )
  5517.                 );
  5518.                 System::setApprovalInfo(
  5519.                     $this->getDoctrine()->getManager(),
  5520.                     $options,
  5521.                     array_flip(GeneralConstant::$Entity_list)['SalarySegregationPolicy'],
  5522.                     $docId,
  5523.                     $request->getSession()->get(UserConstants::USER_LOGIN_ID),
  5524.                     3    //journal voucher
  5525.                 );
  5526.                 System::createEditSignatureHash(
  5527.                     $this->getDoctrine()->getManager(),
  5528.                     array_flip(GeneralConstant::$Entity_list)['SalarySegregationPolicy'],
  5529.                     $docId,
  5530.                     $loginId,
  5531.                     $approveRole,
  5532.                     $request->request->get('approvalHash')
  5533.                 );
  5534.                 $doc_here $this->getDoctrine()
  5535.                     ->getRepository('ApplicationBundle:SalarySegregationPolicy')
  5536.                     ->findOneBy(
  5537.                         array(
  5538.                             'id' => $docId
  5539.                         )
  5540.                     );
  5541.                 //notify
  5542.                 $this->addFlash(
  5543.                     'success',
  5544.                     'Policy Successfully Updated.'
  5545.                 );
  5546.                 $url $this->generateUrl(
  5547.                     'salary_segregation_policy'
  5548.                 );
  5549.                 System::AddNewNotification(
  5550.                     $this->container->getParameter('notification_enabled'),
  5551.                     $this->container->getParameter('notification_server'),
  5552.                     $request->getSession()->get(UserConstants::USER_APP_ID),
  5553.                     $request->getSession()->get(UserConstants::USER_COMPANY_ID),
  5554.                     "Salary Segregation Policy : " $doc_here->getDocumentHash() . " Has Been Created And is Under Processing",
  5555.                     'pos',
  5556.                     System::getPositionIdsByDepartment($emGeneralConstant::HRM_DEPARTMENT),
  5557.                     'success',
  5558.                     //                    $url . "/" . $TransID,
  5559.                     $url "/" $docId,
  5560.                     "Journal"
  5561.                 );
  5562.                 return $this->redirect($url "/" $docId);
  5563.             }
  5564.         }
  5565.         //for edits
  5566.         if ($id == 0) {
  5567.         } else {
  5568.             $extDocData $em->getRepository('ApplicationBundle:SalarySegregationPolicy')->findOneBy(
  5569.                 array(
  5570.                     'id' => $id///material
  5571.                 )
  5572.             );
  5573.             //now if its not editable, redirect to view
  5574.             if ($extDocData) {
  5575.                 if ($extDocData->getEditFlag() != 1) {
  5576. //          $url = $this->generateUrl(
  5577. ////              'view_salary_segregation_policy'
  5578. //              'salary_segregation_policy'
  5579. //          );
  5580. //          return $this->redirect($url . "/" . $id);
  5581.                 } else {
  5582. //          $extVoucherDetailsData = Accounts::GetVoucherDataForEdit($em, $voucherId);
  5583. //          $extDetailsData = $em->getRepository('ApplicationBundle:SalarySegregationPolicy')->findOneBy(
  5584. //              array(
  5585. //                  'transactionId' => $id, ///material
  5586. //
  5587. //              )
  5588. //          );
  5589.                 }
  5590.             } else {
  5591.             }
  5592.         }
  5593.         $employeeIds $em->getRepository(EmployeeDetails::class)->findAll();
  5594.         $employeeType HumanResourceConstant::$employeeType;
  5595.         $Designation $em->getRepository(SysDepartmentPosition::class)->findAll();
  5596.         $branch $em->getRepository(Branch::class)->findAll();
  5597.         $departments $em->getRepository(SysDepartment::class)->findAll();
  5598.         $department = [];
  5599.         foreach ($departments as $entry) {
  5600.             $department[$entry->getDepartmentId()] = array(
  5601.                 'id' => $entry->getDepartmentId(),
  5602.                 'name' => $entry->getDepartmentName(),
  5603.             );
  5604.         }
  5605.         return $this->render(
  5606.             'ApplicationBundle:pages/human_resource/input_forms:salary_segregation_policy.html.twig',
  5607.             [
  5608.                 'page_title' => 'Salary Segregation Policy',
  5609.                 'employeeIds' => $employeeIds,
  5610.                 'extId' => $id,
  5611.                 'extDocData' => $extDocData,
  5612.                 'employeeType' => $employeeType,
  5613.                 'Designation' => $Designation,
  5614.                 'branch' => $branch,
  5615.                 'department' => $department,
  5616.             ]
  5617.         );
  5618.     }
  5619.     public function GetSalarySegregationDataForEmployeeEntryAction(Request $request)
  5620.     {
  5621.         $em $this->getDoctrine()->getManager();
  5622.         $companyId $this->getLoggedUserCompanyId($request);
  5623.         if ($request->request->has('salSagDataReq')) {
  5624.             $ajaxData HumanResource::handelXhrForSalSeg($em$request);
  5625.             return new JsonResponse($ajaxData);
  5626.         }
  5627.         return new JsonResponse(array('success' => false));
  5628.     }
  5629.     public function WorkHourPolicyAction(Request $req$id 0)
  5630.     {
  5631.         $em $this->getDoctrine()->getManager();
  5632.         $companyId $this->getLoggedUserCompanyId($req);
  5633.         $extData = [];
  5634.         if ($id != 0) {
  5635.             $extData $em->getRepository('ApplicationBundle:WorkHourPolicy')
  5636.                 ->findOneBy(
  5637.                     array(
  5638.                         'id' => $id
  5639.                     )
  5640.                 );
  5641.         }
  5642.         if ($req->isMethod('POST')) {
  5643.             $storeDataRes HumanResource::checkSignature($em$req);
  5644.             if ($storeDataRes['hasErr']) {
  5645.                 $msg $storeDataRes['msg'];
  5646.                 $this->addFlash(
  5647.                     'error',
  5648.                     $msg
  5649.                 );
  5650.                 return $this->redirectToRoute('work_hour_policy');
  5651.             } else {
  5652.                 HumanResource::storeDataForWhPolicy($em$req$companyId);
  5653.                 $this->addFlash(
  5654.                     'success',
  5655.                     'Policy Successfully Created!'
  5656.                 );
  5657.                 return $this->redirectToRoute('work_hour_policy');
  5658.             }
  5659.         }
  5660.         $twigData HumanResource::twigDataForWorkHourPolicy($em);
  5661.         $timeZonesArray = array();
  5662.         return $this->render(
  5663.             'ApplicationBundle:pages/human_resource/input_forms:work_hour_policy.html.twig',
  5664.             [
  5665.                 'page_title' => 'Work Hour Policy',
  5666.                 'extId' => $id,
  5667.                 'extData' => $extData,
  5668.                 'employeeIds' => $twigData['employeeIds'],
  5669.                 'employeeType' => $twigData['employeeType'],
  5670.                 'Designation' => $twigData['Designation'],
  5671.                 'branch' => $twigData['branch'],
  5672.                 'department' => $twigData['department'],
  5673.             ]
  5674.         );
  5675.     }
  5676.     public function WorkHourPolicyListAction(Request $request)
  5677.     {
  5678.         $em $this->getDoctrine()->getManager();
  5679.         $allowed_ids = [];
  5680.         $companyId $this->getLoggedUserCompanyId($request);
  5681.         $listData HumanResource::GetDataForWorkHourPolicyListAction($em$request->isMethod('POST') ? 'POST' 'GET'$request->request$companyId);
  5682.         if ($request->isMethod('POST')) {
  5683.             if ($request->query->has('dataTableQry')) {
  5684.                 return new JsonResponse(
  5685.                     $listData
  5686.                 );
  5687.             }
  5688.         }
  5689.         return $this->render('ApplicationBundle:pages/human_resource/list:work_hour_policy_list.html.twig',
  5690. //         return $this->render('ApplicationBundle:pages/dashboard:test_pix_invent.html.twig',
  5691.             array(
  5692.                 'page_title' => 'Work Hour Policy List',
  5693. //            'data' => SalesOrderM::GetClientList($em, [], $companyId),
  5694. //            'client_types' => Client::GetClientType($em, $companyId),
  5695. //            'region_list' => Client::RegionList($em, $companyId),
  5696. //            'geographical_region_list' => Client::GeographicalRegionList($em, $companyId)
  5697.             )
  5698.         );
  5699.     }
  5700.     public function WorkPlacePolicyListAction(Request $request)
  5701.     {
  5702.         $em $this->getDoctrine()->getManager();
  5703.         $workplacePolicyDetails $em->getRepository('ApplicationBundle:EmployeeWorkplace')->findAll();
  5704. //        $employee = $em->getRepository('ApplicationBundle:Employee')->findAll();
  5705.         return $this->render('ApplicationBundle:pages/human_resource/list:work_place_policy_list.html.twig', array(
  5706.             'page_title' => 'Work Place Policy List',
  5707.             'workplacePolicyDetails' => $workplacePolicyDetails,
  5708. //            'employee'=>$employee
  5709.         ));
  5710.     }
  5711.     public function workPlacePolicyAction(Request $data$id)
  5712.     {
  5713.         $em $this->getDoctrine()->getManager();
  5714.         $workPlacePolicy $em->getRepository('ApplicationBundle:EmployeeWorkplace')->find($id);
  5715.         $employee $em->getRepository(Employee::class)->findAll();
  5716.         $Approval_data System::checkIfApprovalExists(
  5717.             $em,
  5718.             array_flip(GeneralConstant::$Entity_list)['EmployeeWorkplace'],
  5719.             $id,
  5720.             $data->getSession()->get(UserConstants::USER_LOGIN_ID)
  5721.         );
  5722.         $ApprovalStatus GeneralConstant::$approvalStatus;
  5723.         return $this->render('ApplicationBundle:pages/human_resource/views:viewWorkPlacePolicy.html.twig', array(
  5724.             'page_title' => 'Work Place Policy  View',
  5725.             'workPlacePolicy' => $workPlacePolicy,
  5726.             'employee' => $employee,
  5727.             'approval_data' => $Approval_data,
  5728.             'approval_status' => $workPlacePolicy->getApproved(),
  5729.             'id' => $id,
  5730.         ));
  5731.     }
  5732.     public function SalarySegregationPolicyListAction(Request $request)
  5733.     {
  5734.         $em $this->getDoctrine()->getManager();
  5735.         $allowed_ids = [];
  5736.         $companyId $this->getLoggedUserCompanyId($request);
  5737.         $listData HumanResource::GetDataForSalarySegregationPolicyListAction($em$request->isMethod('POST') ? 'POST' 'GET'$request->request$companyId);
  5738.         if ($request->isMethod('POST')) {
  5739.             if ($request->query->has('dataTableQry')) {
  5740.                 return new JsonResponse(
  5741.                     $listData
  5742.                 );
  5743.             }
  5744.         }
  5745.         return $this->render('ApplicationBundle:pages/human_resource/list:salary_segregation_policy_list.html.twig',
  5746. //         return $this->render('ApplicationBundle:pages/dashboard:test_pix_invent.html.twig',
  5747.             array(
  5748.                 'page_title' => 'Salary Segregation Policy List',
  5749. //            'data' => SalesOrderM::GetClientList($em, [], $companyId),
  5750. //            'client_types' => Client::GetClientType($em, $companyId),
  5751. //            'region_list' => Client::RegionList($em, $companyId),
  5752. //            'geographical_region_list' => Client::GeographicalRegionList($em, $companyId)
  5753.             )
  5754.         );
  5755.     }
  5756.     public function HolidayCalendarListAction(Request $request)
  5757.     {
  5758.         $q $this->getDoctrine()
  5759.             ->getRepository('ApplicationBundle:HolidayCalendar')
  5760.             ->findBy(
  5761.                 array(
  5762. //                'status' => GeneralConstant::ACTIVE,
  5763.                     'CompanyId' => $this->getLoggedUserCompanyId($request)
  5764. //                    'approved' =>  GeneralConstant::APPROVED,
  5765.                 )
  5766.             );
  5767.         $stage_list = array(
  5768.             => 'Pending',
  5769.             => 'Pending',
  5770.             => 'Complete',
  5771.             => 'Partial',
  5772.         );
  5773.         $data = [];
  5774.         foreach ($q as $entry) {
  5775.             $data[] = array(
  5776. //          'doc_date' => $entry->getSalesReplacementDate(),
  5777.                 'id' => $entry->getHolidayCalendarId(),
  5778.                 'title' => $entry->getHoliDayTitle(),
  5779.                 'approval_status' => GeneralConstant::$approvalStatus[$entry->getApproved()],
  5780. //          'stage' => $stage_list[$entry->getStage()]
  5781.             );
  5782.         }
  5783.         return $this->render('ApplicationBundle:pages/human_resource/list:holiday_calendar_list.html.twig',
  5784.             array(
  5785.                 'page_title' => 'Holiday Calendar List',
  5786.                 'data' => $data
  5787.             )
  5788.         );
  5789.     }
  5790.     public function PayrollPolicyListAction(Request $request)
  5791.     {
  5792.         $em $this->getDoctrine()->getManager();
  5793.         $allowed_ids = [];
  5794.         $companyId $this->getLoggedUserCompanyId($request);
  5795.         $listData HumanResource::GetDataForPayrollPolicyListAction($em$request->isMethod('POST') ? 'POST' 'GET'$request->request$companyId);
  5796.         if ($request->isMethod('POST')) {
  5797.             if ($request->query->has('dataTableQry')) {
  5798.                 return new JsonResponse(
  5799.                     $listData
  5800.                 );
  5801.             }
  5802.         }
  5803.         return $this->render('ApplicationBundle:pages/human_resource/list:payroll_policy_list.html.twig',
  5804. //         return $this->render('ApplicationBundle:pages/dashboard:test_pix_invent.html.twig',
  5805.             array(
  5806.                 'page_title' => 'Payroll Policy List',
  5807. //            'data' => SalesOrderM::GetClientList($em, [], $companyId),
  5808. //            'client_types' => Client::GetClientType($em, $companyId),
  5809. //            'region_list' => Client::RegionList($em, $companyId),
  5810. //            'geographical_region_list' => Client::GeographicalRegionList($em, $companyId)
  5811.             )
  5812.         );
  5813.     }
  5814.     public function payslipAction(Request $req$action 0$id 0)
  5815.     {
  5816.         $em $this->getDoctrine()->getManager();
  5817.         $attendanceSource HumanResourceConstant::$attendanceSources;
  5818.         if ($action === 'list') {
  5819.             $response HumanResource::twigDataForPayslipList($em);
  5820.             $approval_status GeneralConstant::$approvalAction;
  5821.             return $this->render(
  5822.                 'ApplicationBundle:pages/human_resource/list:payslip_list.html.twig',
  5823.                 [
  5824.                     'page_title' => 'Payslip List',
  5825.                     'reports' => $response,
  5826.                     'approval_status' => $approval_status
  5827.                 ]
  5828.             );
  5829.         }
  5830.         if ($action === 'view') {
  5831.             $response HumanResource::twigDataForPayslipViewAndPrint($em$req$id);
  5832.             return $this->render(
  5833.                 'ApplicationBundle:pages/human_resource/views:payslip_view.html.twig',
  5834.                 [
  5835.                     'page_title' => 'View Payslip',
  5836.                     'approval_data' => $response['approval_data'],
  5837.                     'payslip' => $response['payslip'],
  5838.                     'bankAccount' => $response['bankAccount'],
  5839.                     'tin' => $response['tin'],
  5840.                     'employeeCode' => $response['employeeCode'],
  5841.                     'earningValues' => $response['earningValues'],
  5842.                     'facilityValues' => $response['facilityValues'],
  5843.                     'deductionValues' => $response['deductionValues'],
  5844.                     'document_log' => $response['document_log'],
  5845.                     'approval_status' => $response['approval_status'],
  5846.                     'created_by' => $response['created_by'],
  5847.                     'updated_at' => $response['updated_at'],
  5848.                     'employeeId' => $response['employeeId'],
  5849.                     'totalAttendance' => $response['totalPresent'],
  5850.                     'leaveList' => HumanResourceConstant::$LeaveType,
  5851.                     'AttReportData' => $response['AttReportData'],
  5852. //                    'attendanceLog' => $response['attendanceLog'],
  5853.                     'attendanceSource' => $attendanceSource,
  5854.                     'auto_created' => 0,
  5855.                 ]
  5856.             );
  5857.         }
  5858.         if ($action === 'print') {
  5859.             $em $this->getDoctrine()->getManager();
  5860.             $company_data Company::getCompanyData($em1);
  5861.             $Authorizations System::getSignatureListForDocumentPrint($emarray_flip(GeneralConstant::$Entity_list)['Payslip'], $id);
  5862.             $response HumanResource::twigDataForPayslipViewAndPrint($em$req$id);
  5863.             return $this->render(
  5864.                 'ApplicationBundle:pages/human_resource/print:payslip_print.html.twig',
  5865.                 array(
  5866.                     'page_title' => 'Print Payslip',
  5867.                     'export' => 'pdf,print',
  5868.                     'payslip' => $response['payslip'],
  5869.                     'bankAccount' => $response['bankAccount'],
  5870.                     'tin' => $response['tin'],
  5871.                     'employeeCode' => $response['employeeCode'],
  5872.                     'earningValues' => $response['earningValues'],
  5873.                     'facilityValues' => $response['facilityValues'],
  5874.                     'deductionValues' => $response['deductionValues'],
  5875.                     'company_name' => $company_data->getName(),
  5876.                     'company_data' => $company_data,
  5877.                     'company_address' => $company_data->getAddress(),
  5878.                     'company_image' => $company_data->getImage(),
  5879.                     'Authorizations' => $Authorizations,
  5880.                     'totalAttendance' => $response['totalPresent'],
  5881.                     'leaveList' => HumanResourceConstant::$LeaveType,
  5882.                     'AttReportData' => $response['AttReportData'],
  5883.                     'attendanceSource' => $attendanceSource,
  5884.                     'red' => 0
  5885.                 )
  5886.             );
  5887.         }
  5888.         if ($req->isMethod('POST')) {
  5889.             $sigRes HumanResource::checkSignature($em$req);
  5890.             if ($sigRes['hasErr']) {
  5891.                 $msg $sigRes['msg'];
  5892.                 return new JsonResponse(['success' => false'msg' => $msg]);
  5893.             }
  5894.             HumanResource::storeDataForPayslip($em$req);
  5895.             return new JsonResponse(['success' => true]);
  5896.         }
  5897.     }
  5898.     public function applicantInfoAction(Request $request$id)
  5899.     {
  5900.         $em $this->getDoctrine()->getManager('company_group');
  5901.         $session $request->getSession();
  5902.         $consultantDetails $em->getRepository(EntityApplicantDetails::class)->find($session->get(UserConstants::USER_ID));
  5903.         $skillDetails $em->getRepository(EntitySkill::class)->findAll();
  5904.         $companyId $this->getLoggedUserCompanyId($request);
  5905.         $gender HumanResourceConstant::$sex;
  5906.         $blood HumanResourceConstant::$BloodGroup;
  5907.         $userId $session->get(UserConstants::USER_ID);
  5908.         $encData $request->query->has('ref') ? $request->query->get('ref') : '';
  5909.         $education = array(
  5910.             'instituteName' => $request->get('instituteName'),
  5911.             'courseOfStudy' => $request->get('courseOfStudy'),
  5912.             'courseStartDate' => $request->get('courseStartDate'),
  5913.             'courseEndDate' => $request->get('courseEndDate'),
  5914.             'result' => $request->get('result'),
  5915.             'grade' => $request->get('grade'),
  5916.             'degree' => $request->get('degree'),
  5917.         );
  5918.         $workExperience = array(
  5919.             'title' => $request->get('title'),
  5920.             'companyName' => $request->get('companyName'),
  5921.             'jobStartDate' => $request->get('jobStartDate'),
  5922.             'jobEndDate' => $request->get('jobEndDate'),
  5923.             'description' => $request->get('description'),
  5924.         );
  5925.         $certificate = array(
  5926.             'certificatename' => $request->get('certificatename'),
  5927.             'issuedDate' => $request->get('issuedDate'),
  5928.         );
  5929.         $courses = array(
  5930.             'courseName' => $request->get('courseName'),
  5931.             'date' => $request->get('date'),
  5932.             'duration' => $request->get('duration')
  5933.         );
  5934.         $languages = array(
  5935.             'languageName' => $request->get('languageName'),
  5936.             'writtenSkill' => $request->get('writtenSkill'),
  5937.             'verbalSkill' => $request->get('verbalSkill'),
  5938.         );
  5939.         if ($request->isMethod('POST')) {
  5940.             if ($consultantDetails)
  5941.                 $consultant $consultantDetails;
  5942.             else
  5943.                 $consultant = new EntityApplicantDetails();
  5944.             $consultant->setApplicationText($request->request->get('applicationText'));
  5945.             $consultant->setFirstname($request->request->get('firstname'));
  5946.             $consultant->setLastname($request->request->get('lastname'));
  5947.             $consultant->setIsImgLegal($request->request->get('is_img_legal'));
  5948.             $consultant->setNid($request->request->get('nid'));
  5949.             $consultant->setDob(new \DateTime($request->get('dob')));
  5950.             $consultant->setSex($request->request->get('sex'));
  5951.             $consultant->setFather($request->request->get('father'));
  5952.             $consultant->setMother($request->request->get('mother'));
  5953.             $consultant->setBlood($request->request->get('blood'));
  5954.             $consultant->setPhone($request->request->get('phone'));
  5955.             $consultant->setCountry($request->request->get('country'));
  5956.             $consultant->setPostalCode($request->request->get('postalCode'));
  5957.             $consultant->setCurrAddr($request->request->get('curr_addr'));
  5958.             $consultant->setSkill(json_encode($request->request->get('skill')));
  5959.             $consultant->setEmergencyContactNumber($request->request->get('emm_contact'));
  5960.             $consultant->setCurrentEmployment($request->request->get('currentEmployment'));
  5961.             $consultant->setTin($request->request->get('tin'));
  5962.             $consultant->setEducationData(json_encode($education));
  5963.             $consultant->setWorkExperienceData(json_encode($workExperience));
  5964.             $consultant->setCertificateData(json_encode($certificate));
  5965.             $consultant->setCoursesData(json_encode($courses));
  5966.             $consultant->setLanguagesData(json_encode($languages));
  5967.             $consultant->setWorkExperienceYear($request->request->get('workExperienceYear'));
  5968.             //$consultant->setApplyForConsultant(1);
  5969.             $em->persist($consultant);
  5970.             $em->flush();
  5971.             $path "";
  5972.             $defaultProductImage '';
  5973.             $uploadedFile null;
  5974.             $upl_dir $this->container->getParameter('kernel.root_dir') . '/../web/uploads/applicantCv/';
  5975.             $uploadedFile $request->files->get('docUpload');
  5976.             if ($uploadedFile != null) {
  5977.                 $fileName 'cv' $consultantDetails->getApplicantId() . '.' $uploadedFile->guessExtension();
  5978.                 $path $fileName;
  5979. //            $upl_dir = $this->container->getParameter('kernel.root_dir') . '/../web/uploads/Products/';
  5980.                 if (!file_exists($upl_dir)) {
  5981.                     mkdir($upl_dir0777true);
  5982.                 }
  5983.                 $uploadedFile->move($upl_dir$path);
  5984.                 $defaultProductImage 'uploads/applicantCv/' $path;
  5985.                 $consultant->setDocImage($defaultProductImage);
  5986.                 $em->flush();
  5987.             }
  5988.             $this->addFlash(
  5989.                 'success',
  5990.                 'Data Updated.'
  5991.             );
  5992.             if ($encData != '') {
  5993.                 $url $this->generateUrl(
  5994.                     'applicant_job_recruitment_view'
  5995.                 );
  5996.                 return $this->redirect($url '?auto_apply=1&encData=' $encData);
  5997.             }
  5998.             $url $this->generateUrl(
  5999.                 'job_recruitment_list_applicant'
  6000.             );
  6001.             return $this->redirect($url);
  6002.         }
  6003.         return $this->render('ApplicationBundle:pages/human_resource/input_forms:applicant_info.html.twig', array(
  6004.             'page_title' => 'My Information ',
  6005.             'gender' => $gender,
  6006.             'blood' => $blood,
  6007.             'consultantDetails' => $consultantDetails,
  6008.             'education' => json_decode($consultantDetails->getEducationData(), true),
  6009.             'workExperience' => json_decode($consultantDetails->getWorkExperienceData(), true),
  6010.             'certificate' => json_decode($consultantDetails->getCertificateData(), true),
  6011.             'courses' => json_decode($consultantDetails->getCoursesData(), true),
  6012.             'languages' => json_decode($consultantDetails->getLanguagesData(), true),
  6013.             'skill' => json_decode($consultantDetails->getSkill(), true),
  6014.             'skillDetails' => $skillDetails
  6015.         ));
  6016. //        $em = $this->getDoctrine()->getManager('company_group');
  6017. //        $applicantRepo = $em->getRepository(EntityApplicantDetails::class);
  6018. //        $skillDetails = $em->getRepository(EntitySkill::class)->findAll();
  6019. //
  6020. //
  6021. //        if ($req->isMethod('POST')) {
  6022. //            $applicant = $applicantRepo->find($id);
  6023. //
  6024. //            if ($req->files->get('img')) {
  6025. //                $ImgName = HumanResource::StoreFiles($req->files->get('img'), 'Applicant');
  6026. //                $applicant->setImage($ImgName);
  6027. //            }
  6028. //
  6029. //            $applicant->setFirstname($req->request->get('firstname'));
  6030. //            $applicant->setLastname($req->request->get('lastname'));
  6031. //            $applicant->setIsImgLegal($req->request->get('is_img_legal'));
  6032. //            $applicant->setNid($req->request->get('nid'));
  6033. //            $applicant->setDob(HumanResource::StringToDate($req->request->get('dob')));
  6034. //            $applicant->setSex($req->request->get('sex'));
  6035. //            $applicant->setFather($req->request->get('father'));
  6036. //            $applicant->setMother($req->request->get('mother'));
  6037. //            $applicant->setSpouse($req->request->get('spouse'));
  6038. //            $applicant->setChild1($req->request->get('child_1'));
  6039. //            $applicant->setChild2($req->request->get('child_2'));
  6040. //            $applicant->setBlood($req->request->get('blood'));
  6041. //            $applicant->setPhone($req->request->get('phone'));
  6042. //            $applicant->setOAuthEmail($req->request->get('oauth_email'));
  6043. //            $applicant->setCurrAddr($req->request->get('curr_addr'));
  6044. //            $applicant->setPermAddr($req->request->get('perm_addr'));
  6045. //            $applicant->setEmmContact($req->request->get('emm_contact'));
  6046. //
  6047. //            $applicant->setInst1($req->request->get('inst1'));
  6048. //            $applicant->setYr1($req->request->get('yr1'));
  6049. //            $applicant->setDur1($req->request->get('dur1'));
  6050. //            $applicant->setInst2($req->request->get('inst2'));
  6051. //            $applicant->setYr2($req->request->get('yr2'));
  6052. //            $applicant->setDur2($req->request->get('dur2'));
  6053. //            $applicant->setInst3($req->request->get('inst3'));
  6054. //            $applicant->setYr3($req->request->get('yr3'));
  6055. //            $applicant->setDur3($req->request->get('dur3'));
  6056. //            $applicant->setEinst1($req->request->get('einst1'));
  6057. //            $applicant->setEyr1($req->request->get('eyr1'));
  6058. //            $applicant->setEdeg1($req->request->get('edeg1'));
  6059. //            $applicant->setEinst2($req->request->get('einst2'));
  6060. //            $applicant->setEyr2($req->request->get('eyr2'));
  6061. //            $applicant->setEdeg2($req->request->get('edeg2'));
  6062. //            $applicant->setEinst3($req->request->get('einst3'));
  6063. //            $applicant->setEyr3($req->request->get('eyr3'));
  6064. //            $applicant->setEdeg3($req->request->get('edeg3'));
  6065. //
  6066. //            $em->persist($applicant);
  6067. //            $em->flush();
  6068. //
  6069. //            return $this->render(
  6070. //                'ApplicationBundle:pages/human_resource/input_forms:applicant_info.html.twig',
  6071. //                [
  6072. //                    'page_title' => 'Applicant Info',
  6073. //                    'applicant_info' => $applicant,
  6074. //                    'blood' => HumanResourceConstant::$BloodGroup,
  6075. //                    'gender' => HumanResourceConstant::$sex,
  6076. //                    'skillDetails' => $skillDetails,
  6077. //                    'HasUpdateMode' => true,
  6078. //                ]
  6079. //            );
  6080. //        }
  6081. //
  6082. //        if ($id) {
  6083. //            $applicant = $applicantRepo->find($id);
  6084. //
  6085. //            return $this->render(
  6086. //                'ApplicationBundle:pages/human_resource/input_forms:applicant_info.html.twig',
  6087. //                [
  6088. //                    'page_title' => 'Applicant Info',
  6089. //                    'applicant_info' => $applicant,
  6090. //                    'blood' => HumanResourceConstant::$BloodGroup,
  6091. //                    'gender' => HumanResourceConstant::$sex,
  6092. //                    'skillDetails' => $skillDetails,
  6093. //                    'HasUpdateMode' => false,
  6094. //                ]
  6095. //            );
  6096. //        }
  6097. //
  6098. //        $google_client = new Google_Client();
  6099. //        $google_client->setClientId('916737688016-l2qfmb9p37cumudkaqpu8s7ndngq9una.apps.googleusercontent.com');
  6100. //        $google_client->setClientSecret('BEWpEBRvv3-hSoB4cGBrVB3z');
  6101. //        $google_client->setRedirectUri('http://localhost/applicant_info');
  6102. //        $google_client->addScope('email');
  6103. //        $google_client->addScope('profile');
  6104.     }
  6105.     public function applicantDashboardAction()
  6106.     {
  6107.         return new JsonResponse(['this is applicant dashboard']);
  6108.     }
  6109.     public function resignApplicationAction(Request $req$id)
  6110.     {
  6111.         $em $this->getDoctrine()->getManager();
  6112.         if ($req->request->has('xhrReq')) {
  6113.             $response HumanResource::HandelXhrForResignApplication($em$req);
  6114.             return new JsonResponse($response);
  6115.         }
  6116.         if ($req->isMethod('GET')) {
  6117.             $applicant $em->getRepository(EmployeeDetails::class)->findBy(['emp_status' => 1]);
  6118.             $resignReason HumanResourceConstant::$resignReason;
  6119.             return $this->render(
  6120.                 'ApplicationBundle:pages/human_resource/input_forms:resign_application.html.twig',
  6121.                 [
  6122.                     'page_title' => 'Resign Application',
  6123.                     'employeeIds' => $applicant,
  6124.                     'resignReasons' => $resignReason,
  6125.                     'HasUpdateMode' => false,
  6126.                 ]
  6127.             );
  6128.         }
  6129.         if ($req->isMethod('POST')) {
  6130.             $approveHash $req->request->get('approvalHash');
  6131.             $loginId $req->getSession()->get(UserConstants::USER_LOGIN_ID);
  6132.             $isSignatureOk DocValidation::isSignatureOk($em$loginId$approveHash);
  6133.             if ($isSignatureOk) {
  6134.                 $response HumanResource::storeResignApplicationData($em$req);
  6135.                 if ($response) {
  6136.                     return $this->redirectToRoute(
  6137.                         'view_resign_application',
  6138.                         array('id' => $response->getResignApplicationId()),
  6139.                         Response::HTTP_MOVED_PERMANENTLY
  6140.                     );
  6141.                 }
  6142.             } else {
  6143.                 $this->addFlash(
  6144.                     'error',
  6145.                     'Invalid Approval Hash!'
  6146.                 );
  6147.                 return $this->redirectToRoute('resign_application');
  6148.             }
  6149.         }
  6150.     }
  6151.     public function viewResignApplicationAction(Request $req$id 0)
  6152.     {
  6153.         $em $this->getDoctrine()->getManager();
  6154.         $response HumanResource::twigDataForResignApplicationView($em$req$id);
  6155.         return $this->render(
  6156.             'ApplicationBundle:pages/human_resource/views:resign_application_view.html.twig',
  6157.             [
  6158.                 'page_title' => 'View Resign Application',
  6159.                 'approval_data' => $response['approval_data'],
  6160.                 'application' => $response['application'],
  6161.                 'applicant' => $response['applicant'],
  6162.                 'document_log' => $response['document_log'],
  6163.                 'approval_status' => $response['approval_status'],
  6164.                 'created_by' => $response['created_by'],
  6165.                 'updated_at' => $response['updated_at'],
  6166.                 'auto_created' => 0,
  6167.             ]
  6168.         );
  6169.     }
  6170.     public function printResignApplicationAction(Request $req$id)
  6171.     {
  6172.         if ($id) {
  6173.             $em $this->getDoctrine()->getManager();
  6174.             $company_data Company::getCompanyData($em1);
  6175.             $authorizations System::getSignatureListForDocumentPrint($emarray_flip(GeneralConstant::$Entity_list)['ResignApplication'], $id);
  6176.             $response HumanResource::twigDataForResignApplicationView($em$req$id);
  6177.             return $this->render(
  6178.                 'ApplicationBundle:pages/human_resource/print:resign_application_print.html.twig',
  6179.                 array(
  6180.                     'page_title' => 'Print Resign Application',
  6181.                     'export' => 'pdf,print',
  6182.                     'company_name' => $company_data->getName(),
  6183.                     'company_data' => $company_data,
  6184.                     'company_address' => $company_data->getAddress(),
  6185.                     'company_image' => $company_data->getImage(),
  6186.                     'application' => $response['application'],
  6187.                     'applicant' => $response['applicant'],
  6188.                     'Authorizations' => $authorizations,
  6189.                     'red' => 0
  6190.                 )
  6191.             );
  6192.         }
  6193.         return new JsonResponse(array(
  6194.             'success' => false,
  6195.             'msg' => 'Wrong URL format! Please try with application ID'
  6196.         ));
  6197.     }
  6198.     public function listResignApplicationAction(Request $req)
  6199.     {
  6200.         $em $this->getDoctrine()->getManager();
  6201.         $response HumanResource::getResignApplicationList($em$req);
  6202.         return $this->render("ApplicationBundle:pages/human_resource/list:resign_application_list.html.twig", array(
  6203.             'page_title' => 'Resign Application List',
  6204.             'applications' => $response,
  6205.         ));
  6206.     }
  6207.     public function viewNocApprovalAction(Request $req$id)
  6208.     {
  6209.         $em $this->getDoctrine()->getManager();
  6210.         $response HumanResource::twigDataForNocView($em$req$id);
  6211.         return $this->render(
  6212.             'ApplicationBundle:pages/human_resource/views:noc_view.html.twig',
  6213.             [
  6214.                 'page_title' => 'View NOC',
  6215.                 'approval_data' => $response['approval_data'],
  6216.                 'noc_application' => $response['noc_application'],
  6217.                 'resign_application' => $response['resign_application'],
  6218.                 'applicant' => $response['applicant'],
  6219.                 'document_log' => $response['document_log'],
  6220.                 'approval_status' => $response['approval_status'],
  6221.                 'created_by' => $response['created_by'],
  6222.                 'updated_at' => $response['updated_at'],
  6223.                 'auto_created' => 0,
  6224.             ]
  6225.         );
  6226.     }
  6227.     public function printNocApprovalAction(Request $req$id)
  6228.     {
  6229.         $em $this->getDoctrine()->getManager();
  6230.         $company_data Company::getCompanyData($em1);
  6231.         $Authorizations System::getSignatureListForDocumentPrint($emarray_flip(GeneralConstant::$Entity_list)['NocApproval'], $id);
  6232.         $response HumanResource::twigDataForNocView($em$req$id);
  6233.         return $this->render(
  6234.             'ApplicationBundle:pages/human_resource/print:noc_print.html.twig',
  6235.             [
  6236.                 'page_title' => 'Print NOC',
  6237.                 'noc_application' => $response['noc_application'],
  6238.                 'resign_application' => $response['resign_application'],
  6239.                 'applicant' => $response['applicant'],
  6240.                 'export' => 'pdf,print',
  6241.                 'company_name' => $company_data->getName(),
  6242.                 'company_data' => $company_data,
  6243.                 'company_address' => $company_data->getAddress(),
  6244.                 'company_image' => $company_data->getImage(),
  6245.                 'Authorizations' => $Authorizations,
  6246.                 'red' => 0
  6247.             ]
  6248.         );
  6249.     }
  6250.     public function createHolidayAction(Request $request$id)
  6251.     {
  6252.         $em $this->getDoctrine()->getManager();
  6253.         $companyId $this->getLoggedUserCompanyId($request);
  6254.         if ($request->isMethod('POST')) {
  6255.             $entity_id array_flip(GeneralConstant::$Entity_list)['HolidayCalendar']; //change
  6256.             $dochash $request->request->get('doc_hash'); //change
  6257.             $loginId $request->getSession()->get(UserConstants::USER_LOGIN_ID);
  6258.             $approveRole $request->request->get('approvalRole');
  6259.             $approveHash $request->request->get('approvalHash');
  6260.             if (!DocValidation::isInsertable(
  6261.                 $em,
  6262.                 $entity_id,
  6263.                 $dochash,
  6264.                 $loginId,
  6265.                 $approveRole,
  6266.                 $approveHash,
  6267.                 $id
  6268.             )
  6269.             ) {
  6270.                 $this->addFlash(
  6271.                     'error',
  6272.                     'Sorry Couldnot insert Data.'
  6273.                 );
  6274.             } else {
  6275.                 $funcname 'HolidayCalendar';
  6276.                 $doc_id $id;
  6277.                 DeleteDocument::$funcname($em$doc_id0);
  6278.                 if ($id != 0)
  6279.                     $HolidayCalender $em->getRepository(HolidayCalendar::class)->find($id);
  6280.                 else
  6281.                     $HolidayCalender = new HolidayCalendar;
  6282.                 $HolidayCalender->setDocumentHash($request->request->get('doc_hash'));
  6283.                 $HolidayCalender->setHoliDayTitle($request->request->get('holidayCalendarTitle'));
  6284.                 $HolidayCalender->setEmployeeIds(json_encode($request->request->get('employee')));
  6285.                 $HolidayCalender->setEmployeeTypeIds(json_encode($request->request->get('emp_status')));
  6286.                 $HolidayCalender->setDesignationIds(json_encode($request->request->get('desg', [])));
  6287.                 $HolidayCalender->setDepartmentIds(json_encode($request->request->get('dept', [])));
  6288.                 $HolidayCalender->setBranchIds(json_encode($request->request->get('branch', [])));
  6289.                 $HolidayCalender->setLevelSelectionStr($request->get('levelSelectionStr'''));
  6290.                 $HolidayCalender->setLevels(json_encode(HumanResource::getLevelsFromLevelSelectionStr($request->get('levelSelectionStr'''))));
  6291.                 $HolidayCalender->setCompanyId($companyId);
  6292.                 $HolidayCalender->setTypeHash('HD');
  6293.                 $HolidayCalender->setEditFlag(1); //editable usually
  6294.                 $HolidayCalender->setPrefixHash($request->request->get('prefix'));
  6295.                 $HolidayCalender->setAssocHash($request->request->get('assoc'));
  6296.                 $HolidayCalender->setNumberHash($request->request->get('number_hash'));
  6297.                 $HolidayCalender->setCreatedLoginId($request->getSession()->get(UserConstants::USER_LOGIN_ID));
  6298.                 $HolidayCalender->setApproved(GeneralConstant::APPROVAL_STATUS_PENDING);
  6299.                 $HolidayCalender->setAutocreated(0);
  6300. //
  6301. //        $arr = [
  6302. //            'date' =>$request->request->get('start_date'),
  6303. //            'title' => $request->request->get('title'),
  6304. //        ];
  6305. //
  6306. //        $HolidayCalender->setData(json_encode($arr));
  6307.                 $em->persist($HolidayCalender);
  6308.                 $em->flush();
  6309.                 $indHolidays = [];
  6310.                 if ($request->request->has('start_date'))
  6311.                     $indHolidays $request->request->get('start_date');
  6312.                 foreach ($indHolidays as $ind => $dateRangeStr) {
  6313.                     $currRow $request->request->get('row')[$ind];//string
  6314.                     $holidayTitle $request->request->get('title')[$ind];//string
  6315.                     $currStartDate $request->request->get('start_date')[$ind];//string
  6316.                     $currEndDate $request->request->get('end_date')[$ind];//string
  6317.                     $HolidayDate = new HolidayCalendarDates();
  6318.                     $HolidayDate->setHolidayCalendarId($HolidayCalender->getHolidayCalendarId());
  6319.                     $HolidayDate->setDateRange($currStartDate '-' $currEndDate);//string
  6320.                     $HolidayDate->setStartDate(new \DateTime($currStartDate));//date
  6321.                     $HolidayDate->setEndDate(new \DateTime($currEndDate ' 23:59:59'));//date
  6322.                     $HolidayDate->setHolidayTitle($holidayTitle);
  6323. //          $HolidayDate->setIsVariableEachYearFlag($request->request->get('is_variable_each_year',null));
  6324.                     $HolidayDate->setIsVariableEachYearFlag($request->request->get('is_variable_each_year_' $currRownull));
  6325.                     $HolidayDate->setAllDayFlag($request->request->get('all_day_flag_' $currRow1));
  6326.                     $em->persist($HolidayDate);
  6327.                     $em->flush();
  6328.                 }
  6329.                 $options = [];
  6330.                 $entity array_flip(GeneralConstant::$Entity_list)['HolidayCalendar'];
  6331.                 $loginId $request->getSession()->get(UserConstants::USER_LOGIN_ID);
  6332.                 $approveRole $request->request->get('approvalRole');
  6333.                 System::setApprovalInfo(
  6334.                     $em,
  6335.                     $options,
  6336.                     $entity,
  6337.                     $HolidayCalender->getHolidayCalendarId(),
  6338.                     $request->getSession()->get(UserConstants::USER_LOGIN_ID)
  6339.                 );
  6340.                 System::createEditSignatureHash(
  6341.                     $em,
  6342.                     $entity,
  6343.                     $HolidayCalender->getHolidayCalendarId(),
  6344.                     $loginId,
  6345.                     $approveRole,
  6346.                     $request->request->get('approvalHash')
  6347.                 );
  6348.                 $url $this->generateUrl(
  6349.                     'view_holiday_calendar'
  6350.                 );
  6351.                 return $this->redirect($url "/" $HolidayCalender->getHolidayCalendarId());
  6352.             }
  6353.         }
  6354.         $em $this->getDoctrine()->getManager();
  6355.         $branches $em->getRepository(Branch::class)->findAll();
  6356.         $employee $em->getRepository(Employee::class)->findAll();
  6357.         $departments $em->getRepository(SysDepartment::class)->findAll();
  6358.         $departmentPositions $em->getRepository(SysDepartmentPosition::class)->findAll();
  6359.         $EmploymentStatus HumanResourceConstant::$employeeType;
  6360.         $em $this->getDoctrine()->getManager();
  6361.         $extDocData = [];
  6362.         if ($id != 0)
  6363.             $extDocData $em->getRepository(HolidayCalendar::class)->find($id);
  6364.         return $this->render(
  6365.             'ApplicationBundle:pages/human_resource/input_forms:create_holiday.html.twig',
  6366.             [
  6367.                 'page_title' => 'Create Holiday',
  6368.                 'branches' => $branches,
  6369.                 'id' => $id,
  6370.                 'extDocData' => $extDocData,
  6371.                 'departments' => $departments,
  6372.                 'departmentPositions' => $departmentPositions,
  6373.                 'employeeStatus' => $EmploymentStatus,
  6374.                 'employeeIds' => $employee,
  6375.                 'holidayCalendarList' => $em->getRepository('ApplicationBundle:HolidayCalendar')
  6376.                     ->findBy(array())
  6377.             ]
  6378.         );
  6379.     }
  6380.     public function HolidayViewAction(Request $request$id)
  6381.     {
  6382.         $em $this->getDoctrine()->getManager();
  6383.         $HolidaysCalendar $em->getRepository(HolidayCalendar::class)->find($id);
  6384.         $holidayCalendarDetails $em->getRepository('ApplicationBundle:HolidayCalendarDates')
  6385.             ->findBy(array(
  6386.                 'holidayCalendarId' => $id
  6387.             ));
  6388.         $Approval_data System::checkIfApprovalExists(
  6389.             $em,
  6390.             array_flip(GeneralConstant::$Entity_list)['HolidayCalendar'],
  6391.             $id,
  6392.             $request->getSession()->get(UserConstants::USER_LOGIN_ID)
  6393.         );
  6394.         return $this->render('ApplicationBundle:pages/human_resource/views:holidays_view.html.twig', array(
  6395.             'page_title' => 'View Holiday',
  6396.             'holidays' => $HolidaysCalendar,
  6397.             'holidayCalendarDetails' => $holidayCalendarDetails,
  6398.             'approval_status' => $HolidaysCalendar->getApproved(),
  6399.             'approval_data' => $Approval_data,
  6400.             'auto_created' => $HolidaysCalendar->getAutocreated(),
  6401.             'document_log' => $HolidaysCalendar->getAutocreated() == System::getDocumentLog(
  6402.                 $this->getDoctrine()->getManager(),
  6403.                 array_flip(GeneralConstant::$Entity_list)['HolidayCalendar'],
  6404.                 $id,
  6405.                 $HolidaysCalendar->getCreatedLoginId(),
  6406.                 $HolidaysCalendar->getEditedLoginId()
  6407.             ) : []
  6408.         ));
  6409.     }
  6410.     public function GetHolidayDetailsAction(Request $request$id)
  6411.     {
  6412.         $em $this->getDoctrine()->getManager();
  6413.         $holidayCalendar $em->getRepository('ApplicationBundle:HolidayCalendar')
  6414.             ->findOneBy(array(
  6415.                 'holidayCalendarId' => $id
  6416.             ));
  6417.         $holidayCalendarDetails $em->getRepository('ApplicationBundle:HolidayCalendarDates')
  6418.             ->findBy(array(
  6419.                 'holidayCalendarId' => $id
  6420.             ));
  6421.         $holidayList = [];
  6422.         foreach ($holidayCalendarDetails as $det) {
  6423.             $dateDet = array(
  6424.                 'title' => $det->getHolidayTitle(),
  6425.                 'startDate' => $det->getStartDate()->format('Y-m-d'),
  6426.                 'endDate' => $det->getEndDate()->format('Y-m-d'),
  6427.             );
  6428.             $holidayList[] = $dateDet;
  6429.         }
  6430.         return new JsonResponse(
  6431.             array(
  6432.                 'success' => true,
  6433.                 'holidayList' => $holidayList
  6434.             )
  6435.         );
  6436.     }
  6437.     public function GetHolidayListByEmployeeIdAction(Request $request$id)
  6438.     {
  6439.         $em $this->getDoctrine()->getManager();
  6440.         $options = [];
  6441.         $options['employeeId'] = $id;
  6442.         HumanResource::getFilteredHolidaysSingle($em$options);
  6443.         $holidayCalendar $em->getRepository('ApplicationBundle:HolidayCalendar')
  6444.             ->findOneBy(array(
  6445.                 'holidayCalendarId' => $id
  6446.             ));
  6447.         $holidayCalendarDetails $em->getRepository('ApplicationBundle:HolidayCalendarDates')
  6448.             ->findBy(array(
  6449.                 'holidayCalendarId' => $id
  6450.             ));
  6451.         $holidayList = [];
  6452.         foreach ($holidayCalendarDetails as $det) {
  6453.             $dateDet = array(
  6454.                 'title' => $det->getHolidayTitle(),
  6455.                 'startDate' => $det->getStartDate()->format('Y-m-d'),
  6456.                 'endDate' => $det->getEndDate()->format('Y-m-d'),
  6457.             );
  6458.             $holidayList[] = $dateDet;
  6459.         }
  6460.         return new JsonResponse(
  6461.             array(
  6462.                 'success' => true,
  6463.                 'holidayList' => $holidayList
  6464.             )
  6465.         );
  6466.     }
  6467.     public function createQuestionAction(Request $request)
  6468.     {
  6469.         $em $this->getDoctrine()->getManager();
  6470.         $em_goc $this->getDoctrine()->getManager('company_group');
  6471.         $companyId $this->getLoggedUserCompanyId($request);
  6472.         if ($request->isMethod('POST')) {
  6473.             $loginId $request->getSession()->get(UserConstants::USER_LOGIN_ID);
  6474.             $question = new Questionnaire();
  6475.             $question->setQuestionTitle($request->request->get('questionTitle'''));
  6476.             $question->setQuestionText($request->request->get('questionText'''));
  6477.             $question->setIsForPlanningItem($request->request->has('forPlanningItem') ? 0);
  6478.             $question->setIsForInterview($request->request->has('forInterview') ? 0);
  6479.             $question->setIsForMock($request->request->has('forMock') ? 0);
  6480.             $question->setIsForTraining($request->request->has('forTraining') ? 0);
  6481.             $question->setTaggedSkillHashes($request->request->get('skillHash'));
  6482.             $question->setCorrectAnswers(json_encode($request->request->get('correctAns')));
  6483.             $question->setCompanyId($companyId);
  6484.             $optionData = [];
  6485.             foreach ($request->request->get('optionText') as $key => $val) {
  6486.                 $option = array(
  6487.                     'index' => $request->request->get('optionIndex')[$key],
  6488.                     'text' => $val,
  6489.                 );
  6490.                 $optionData[] = $option;
  6491.             }
  6492.             $question->setOptions(json_encode($optionData));
  6493.             $question->setQuestionValueWeight(1);
  6494.             $question->setQuestionText($request->request->get('questionText'));
  6495.             $question->setUniqueHash('_NONE_');
  6496.             $question->setType($request->request->get('type'0));
  6497.             //$skill->setEditFlag(1); //editable usually
  6498.             $question->setCreatedLoginId($request->getSession()->get(UserConstants::USER_LOGIN_ID));
  6499.             //$skill->setApproved(GeneralConstant::APPROVAL_STATUS_PENDING);
  6500.             //$skill->setAutocreated(0);
  6501.             $em->persist($question);
  6502.             $em->flush();
  6503.             $questionId $question->getQuestionId();
  6504.             $file_path_list = [];
  6505.             if ($questionId != 0)
  6506.                 if (!empty($request->files)) {
  6507.                     MiscActions::RemoveFilesForEntityDoc($em_goc'Question'$questionId);
  6508.                     $storePath 'uploads/Questionnaire/';
  6509.                     $path "";
  6510.                     $file_path "";
  6511.                     $session $request->getSession();
  6512. //                    MiscActions::RemoveExpiredFiles($em_goc);
  6513.                     foreach ($request->files as $uploadedFileGG) {
  6514.                         //            if($uploadedFile->getImage())
  6515.                         //                var_dump($uploadedFile->getFile());
  6516.                         //                var_dump($uploadedFile);
  6517.                         $tempD $uploadedFileGG;
  6518.                         if (!is_array($uploadedFileGG)) {
  6519.                             $uploadedFileGG = array();
  6520.                             $uploadedFileGG[] = $tempD;
  6521.                         }
  6522.                         foreach ($uploadedFileGG as $uploadedFile) {
  6523.                             if ($uploadedFile != null) {
  6524.                                 $extension $uploadedFile->guessExtension();
  6525.                                 $size $uploadedFile->getSize();
  6526.                                 $fileName 'QUES_' $questionId '_' . (md5(uniqid())) . '.' $uploadedFile->guessExtension();
  6527.                                 $path $fileName;
  6528.                                 $upl_dir $this->container->getParameter('kernel.root_dir') . '/../web/' $storePath;
  6529.                                 if (!file_exists($upl_dir)) {
  6530.                                     mkdir($upl_dir0777true);
  6531.                                 }
  6532.                                 if (file_exists($upl_dir '' $path)) {
  6533.                                     chmod($upl_dir '' $path0755);
  6534.                                     unlink($upl_dir '' $path);
  6535.                                 }
  6536.                                 $file $uploadedFile->move($upl_dir$path);
  6537.                                 $expireNever 1;
  6538.                                 $expireTs 0;
  6539.                                 $EntityFile = new EntityFile();
  6540.                                 $EntityFile->setPath($this->container->getParameter('kernel.root_dir') . '/../web/' $storePath $path);
  6541.                                 $EntityFile->setMarker('_GEN_');
  6542.                                 $EntityFile->setExtension($extension);
  6543.                                 $EntityFile->setExpireTs($expireTs);
  6544.                                 $EntityFile->setSize($size);
  6545.                                 $EntityFile->setRelativePath($storePath $path);
  6546.                                 $EntityFile->setEntityName('Questionnaire');
  6547.                                 $EntityFile->setEntityBundle('ApplicationBundle');
  6548.                                 $EntityFile->setEntityId($questionId);
  6549.                                 $EntityFile->setEntityIdField('questionId');
  6550.                                 $EntityFile->setModifyFieldSetter('setFiles');
  6551.                                 $EntityFile->setDocIdForApplicant(0);
  6552.                                 $EntityFile->setUserId($session->get(UserConstants::USER_ID0));
  6553.                                 $EntityFile->setAppId($session->get(UserConstants::USER_APP_ID0));
  6554.                                 $EntityFile->setEmployeeId($session->get(UserConstants::USER_EMPLOYEE_ID0));
  6555.                                 $EntityFile->setUserType($session->get(UserConstants::USER_TYPE0));
  6556.                                 $em_goc->persist($EntityFile);
  6557.                                 $em_goc->flush();
  6558.                                 $EntityFileId $EntityFile->getId();
  6559.                             }
  6560.                             if ($path != "")
  6561.                                 $file_path_list[] = ($storePath $path);
  6562.                         }
  6563.                     }
  6564.                     $g_path $this->container->getParameter('kernel.root_dir') . '/../web/' $storePath $path;
  6565.                     $question->setFiles(implode(','$file_path_list));
  6566.                     $em->flush();
  6567.                 }
  6568.             if ($request->request->has('returnJson') || $request->query->has('returnJson')) {
  6569.                 if ($question)
  6570.                     return new JsonResponse(
  6571.                         array(
  6572.                             'id' => $questionId,
  6573.                             'value' => $questionId,
  6574.                             'question_id' => $questionId,
  6575.                             'text' => $question->getQuestionText(),
  6576.                             'question_text' => $question->getQuestionText(),
  6577.                             'question_title' => $question->getQuestionTitle(),
  6578.                             'files' => explode(','$question->getFiles()),
  6579.                             'options' => json_decode($question->getFiles(), true),
  6580.                             'answer_text' => '',
  6581.                             'success' => true
  6582.                         )
  6583.                     );
  6584.                 else
  6585.                     return new JsonResponse(
  6586.                         array(
  6587.                             'success' => false
  6588.                         )
  6589.                     );
  6590.             }
  6591.         }
  6592.         $skillDetails $em->getRepository(Skill::class)->findAll();
  6593.         $skillListObj = [];
  6594.         $skillListArray = [];
  6595.         foreach ($skillDetails as $skillDetail) {
  6596.             $dt = array(
  6597.                 'id' => $skillDetail->getSkillId(),
  6598.                 'name' => $skillDetail->getName(),
  6599.                 'hash' => $skillDetail->getUniqueHash(),
  6600.             );
  6601.             $skillListArray[] = $dt;
  6602.         }
  6603.         return $this->render('ApplicationBundle:pages/human_resource/input_forms:createQuestion.html.twig', array(
  6604.             'page_title' => 'Create Question',
  6605.             'skiillDetails' => $skillDetails,
  6606.             'skillListArray' => $skillListArray,
  6607.         ));
  6608.     }
  6609.     public function createSkillAction(Request $request)
  6610.     {
  6611.         $em $this->getDoctrine()->getManager();
  6612.         $companyId $this->getLoggedUserCompanyId($request);
  6613.         if ($request->isMethod('POST')) {
  6614.             $loginId $request->getSession()->get(UserConstants::USER_LOGIN_ID);
  6615.             $skill = new Skill;
  6616.             $skill->setName($request->request->get('skillName'));
  6617.             $skill->setParentId($request->request->get('parentName'));
  6618.             $skill->setUniqueHash($request->request->get('uniqueHash'));
  6619.             $skill->setCompanyId($companyId);
  6620.             //$skill->setEditFlag(1); //editable usually
  6621.             $skill->setCreatedLoginId($request->getSession()->get(UserConstants::USER_LOGIN_ID));
  6622.             //$skill->setApproved(GeneralConstant::APPROVAL_STATUS_PENDING);
  6623.             //$skill->setAutocreated(0);
  6624.             $em->persist($skill);
  6625.             $em->flush();
  6626.         }
  6627.         $skillDetails $em->getRepository(Skill::class)->findAll();
  6628.         return $this->render('ApplicationBundle:pages/human_resource/input_forms:createSkill.html.twig', array(
  6629.             'page_title' => 'Create Skill',
  6630.             'skiillDetails' => $skillDetails,
  6631.         ));
  6632.     }
  6633.     public function createEducationQualificationAction(Request $request)
  6634.     {
  6635.         $em $this->getDoctrine()->getManager();
  6636.         $companyId $this->getLoggedUserCompanyId($request);
  6637.         if ($request->isMethod('POST')) {
  6638.             $loginId $request->getSession()->get(UserConstants::USER_LOGIN_ID);
  6639.             $new = new EducationQualification;
  6640.             $new->setName($request->request->get('educationName'));
  6641.             $new->setParentId($request->request->get('parentName'));
  6642.             $new->setUniqueHash($request->request->get('uniqueHash'));
  6643.             $new->setCompanyId($companyId);
  6644.             //$skill->setEditFlag(1); //editable usually
  6645.             $new->setCreatedLoginId($request->getSession()->get(UserConstants::USER_LOGIN_ID));
  6646.             //$skill->setApproved(GeneralConstant::APPROVAL_STATUS_PENDING);
  6647.             //$skill->setAutocreated(0);
  6648.             $em->persist($new);
  6649.             $em->flush();
  6650.         }
  6651.         $educationDetails $em->getRepository(EducationQualification::class)->findAll();
  6652.         return $this->render('ApplicationBundle:pages/human_resource/input_forms:create_education.html.twig', array(
  6653.             'page_title' => 'Create Education',
  6654.             'educationDetails' => $educationDetails,
  6655.         ));
  6656.     }
  6657.     public function createEvaluationCategoryAction(Request $request$id 0)
  6658.     {
  6659.         $em $this->getDoctrine()->getManager();
  6660.         $companyId $this->getLoggedUserCompanyId($request);
  6661.         if ($request->isMethod('POST')) {
  6662.             $loginId $request->getSession()->get(UserConstants::USER_LOGIN_ID);
  6663.             $new = new EvaluationCategory;
  6664.             $new->setName($request->request->get('name'));
  6665.             $new->setBranch($request->request->get('branch'));
  6666.             $new->setSelectionType($request->request->get('selection_type'));
  6667.             $new->setEmployeeIds($request->request->get('selected_employeeIds'));
  6668.             $new->setEmployeeTypeIds($request->request->get('employee_types'));
  6669.             $new->setDesignationIds($request->request->get('designation'));
  6670.             $new->setDesignationIds($request->request->get('designation'));
  6671.             $new->setmark($request->request->get('mark'));
  6672.             $new->setSkills(json_encode($request->request->get('skill')));
  6673.             $new->setLevelSelectionStr($request->request->get('levelSelectionStr'));
  6674.             $new->setCompanyId($companyId);
  6675.             $new->setCreatedLoginId($request->getSession()->get(UserConstants::USER_LOGIN_ID));
  6676.             $em->persist($new);
  6677.             $em->flush();
  6678.         }
  6679.         $skill $em->getRepository(Skill::class)->findAll();
  6680.         $employeeIds $em->getRepository(EmployeeDetails::class)->findAll();
  6681.         $employeeType HumanResourceConstant::$employeeType;
  6682.         $Designation $em->getRepository(SysDepartmentPosition::class)->findAll();
  6683.         $branch $em->getRepository(Branch::class)->findAll();
  6684.         $departments $em->getRepository(SysDepartment::class)->findAll();
  6685.         $department = [];
  6686.         foreach ($departments as $entry) {
  6687.             $department[$entry->getDepartmentId()] = array(
  6688.                 'id' => $entry->getDepartmentId(),
  6689.                 'name' => $entry->getDepartmentName(),
  6690.             );
  6691.             return $this->render('ApplicationBundle:pages/human_resource/input_forms:create_evaluation_category.html.twig', array(
  6692.                 'page_title' => 'Create Evaluation Category',
  6693.                 'employeeIds' => $employeeIds,
  6694.                 'employeeType' => $employeeType,
  6695.                 'Designation' => $Designation,
  6696.                 'branch' => $branch,
  6697.                 'department' => $department,
  6698.                 'skill' => $skill,
  6699.             ));
  6700.         }
  6701.     }
  6702.     public function createWorkplaceHarassmentAction(Request $request$id 0)
  6703.     {
  6704.         $em $this->getDoctrine()->getManager();
  6705.         $employeeIds $em->getRepository(EmployeeDetails::class)->findAll();
  6706.         //$employeeType = HumanResourceConstant::$employeeType;
  6707.         $Designation $em->getRepository(SysDepartmentPosition::class)->findAll();
  6708.         $branches $em->getRepository(Branch::class)->findAll();
  6709.         $departments $em->getRepository(SysDepartment::class)->findAll();
  6710.         $harassmentType HumanResourceConstant::$harrasmentType;
  6711.         $department = [];
  6712.         foreach ($departments as $entry) {
  6713.             $department[$entry->getDepartmentId()] = array(
  6714.                 'id' => $entry->getDepartmentId(),
  6715.                 'name' => $entry->getDepartmentName(),
  6716.             );
  6717.         }
  6718.         return $this->render('ApplicationBundle:pages/human_resource/input_forms:create_workplace_harrasment.html.twig', array(
  6719.             'page_title' => 'Create Workplace Harrasment',
  6720.             'employeeIds' => $employeeIds,
  6721.             'branches' => $branches,
  6722.             'harassmentType' => $harassmentType,
  6723.             'departments' => $department,
  6724.             'designationIds' => $Designation
  6725.         ));
  6726.     }
  6727.     public function ViewHarasssmentComplainAction()
  6728.     {
  6729.         return $this->render('ApplicationBundle:pages/human_resource/views:view_harassment_compalin.html.twig', array(
  6730.             'page_title' => 'View Harassment Complain',
  6731.         ));
  6732.     }
  6733.     public function createWorkplaceViolenceAction(Request $request$id 0)
  6734.     {
  6735.         $em $this->getDoctrine()->getManager();
  6736.         $employeeIds $em->getRepository(EmployeeDetails::class)->findAll();
  6737.         //$employeeType = HumanResourceConstant::$employeeType;
  6738.         $Designation $em->getRepository(SysDepartmentPosition::class)->findAll();
  6739.         $branches $em->getRepository(Branch::class)->findAll();
  6740.         $departments $em->getRepository(SysDepartment::class)->findAll();
  6741.         $harassmentType HumanResourceConstant::$harrasmentType;
  6742.         $department = [];
  6743.         foreach ($departments as $entry) {
  6744.             $department[$entry->getDepartmentId()] = array(
  6745.                 'id' => $entry->getDepartmentId(),
  6746.                 'name' => $entry->getDepartmentName(),
  6747.             );
  6748.         }
  6749.         return $this->render('ApplicationBundle:pages/human_resource/input_forms:register_workplace_complaint.html.twig', array(
  6750.             'page_title' => 'Register Complaint',
  6751.             'employeeIds' => $employeeIds,
  6752.             'branches' => $branches,
  6753.             'harassmentType' => $harassmentType,
  6754.             'departments' => $department,
  6755.             'designationIds' => $Designation
  6756.         ));
  6757.     }
  6758.     public function createBonusPolicyAction(Request $request$id 0)
  6759.     {
  6760.         $em $this->getDoctrine()->getManager();
  6761.         $companyId $this->getLoggedUserCompanyId($request);
  6762.         $extDocData = [];
  6763.         $extDetailsData = [];
  6764.         if ($request->isMethod('POST')) {
  6765.             //            Generic::debugMessage($_POST);
  6766.             $em $this->getDoctrine()->getManager();
  6767.             $entity_id array_flip(GeneralConstant::$Entity_list)['BonusPolicy']; //change
  6768.             $dochash $request->request->get('docHash'); //change
  6769.             $loginId $request->getSession()->get(UserConstants::USER_LOGIN_ID);
  6770.             $approveRole $request->request->get('approvalRole');
  6771.             $approveHash $request->request->get('approvalHash');
  6772.             if (!DocValidation::isInsertable(
  6773.                 $em,
  6774.                 $entity_id,
  6775.                 $dochash,
  6776.                 $loginId,
  6777.                 $approveRole,
  6778.                 $approveHash,
  6779.                 $id
  6780.             )
  6781.             ) {
  6782.                 $this->addFlash(
  6783.                     'error',
  6784.                     'Sorry Couldnot insert Data.'
  6785.                 );
  6786.             } else {
  6787.                 $funcname 'BonusPolicy';
  6788.                 DeleteDocument::$funcname($em$id0);
  6789.                 $loginId $request->getSession()->get(UserConstants::USER_LOGIN_ID);
  6790.                 $docId HumanResource::createBonusPolicy($em$request$companyId$loginId0);
  6791.                 //now add Approval info
  6792.                 $approveRole $request->request->get('approvalRole');
  6793.                 $options = array(
  6794.                     'notification_enabled' => $this->container->getParameter('notification_enabled'),
  6795.                     'notification_server' => $this->container->getParameter('notification_server'),
  6796.                     'appId' => $request->getSession()->get(UserConstants::USER_APP_ID),
  6797.                     'url' => $this->generateUrl(
  6798.                         GeneralConstant::$Entity_list_details[array_flip(GeneralConstant::$Entity_list)['BonusPolicy']]['entity_view_route_path_name']
  6799.                     )
  6800.                 );
  6801.                 System::setApprovalInfo(
  6802.                     $this->getDoctrine()->getManager(),
  6803.                     $options,
  6804.                     array_flip(GeneralConstant::$Entity_list)['BonusPolicy'],
  6805.                     $docId,
  6806.                     $request->getSession()->get(UserConstants::USER_LOGIN_ID)
  6807.                 );
  6808.                 System::createEditSignatureHash(
  6809.                     $this->getDoctrine()->getManager(),
  6810.                     array_flip(GeneralConstant::$Entity_list)['BonusPolicy'],
  6811.                     $docId,
  6812.                     $loginId,
  6813.                     $approveRole,
  6814.                     $request->request->get('approvalHash')
  6815.                 );
  6816.                 $doc_here $this->getDoctrine()
  6817.                     ->getRepository('ApplicationBundle:BonusPolicy')
  6818.                     ->findOneBy(
  6819.                         array(
  6820.                             'id' => $docId
  6821.                         )
  6822.                     );
  6823.                 //notify
  6824.                 $this->addFlash(
  6825.                     'success',
  6826.                     'Policy Successfully Updated.'
  6827.                 );
  6828.                 $url $this->generateUrl(
  6829.                     'view_bonus_policy'
  6830.                 );
  6831. //                System::AddNewNotification(
  6832. //                    $this->container->getParameter('notification_enabled'),
  6833. //                    $this->container->getParameter('notification_server'),
  6834. //                    $request->getSession()->get(UserConstants::USER_APP_ID),
  6835. //                    $request->getSession()->get(UserConstants::USER_COMPANY_ID),
  6836. //                    "Salary Segregation Policy : " . $doc_here->getDocumentHash() . " Has Been Created And is Under Processing",
  6837. //                    'pos',
  6838. //                    System::getPositionIdsByDepartment($em, GeneralConstant::HRM_DEPARTMENT),
  6839. //                    'success',
  6840. //                    //                    $url . "/" . $TransID,
  6841. //                    $url . "/" . $docId,
  6842. //                    "Journal"
  6843. //
  6844. //                );
  6845.                 return $this->redirect($url "/" $docId);
  6846.             }
  6847.         }
  6848.         //for edits
  6849.         if ($id == 0) {
  6850.         } else {
  6851.             $extDocData $em->getRepository('ApplicationBundle:BonusPolicy')->findOneBy(
  6852.                 array(
  6853.                     'id' => $id///material
  6854.                 )
  6855.             );
  6856.             //now if its not editable, redirect to view
  6857.             if ($extDocData) {
  6858.                 if ($extDocData->getEditFlag() != 1) {
  6859. //          $url = $this->generateUrl(
  6860. ////              'view_salary_segregation_policy'
  6861. //              'salary_segregation_policy'
  6862. //          );
  6863. //          return $this->redirect($url . "/" . $id);
  6864.                 } else {
  6865. //          $extVoucherDetailsData = Accounts::GetVoucherDataForEdit($em, $voucherId);
  6866. //          $extDetailsData = $em->getRepository('ApplicationBundle:SalarySegregationPolicy')->findOneBy(
  6867. //              array(
  6868. //                  'transactionId' => $id, ///material
  6869. //
  6870. //              )
  6871. //          );
  6872.                 }
  6873.             } else {
  6874.             }
  6875.         }
  6876.         $employeeIds $em->getRepository(EmployeeDetails::class)->findAll();
  6877.         $employeeType HumanResourceConstant::$employeeType;
  6878.         $Designation $em->getRepository(SysDepartmentPosition::class)->findAll();
  6879.         $branch $em->getRepository(Branch::class)->findAll();
  6880.         $departments $em->getRepository(SysDepartment::class)->findAll();
  6881.         $department = [];
  6882.         foreach ($departments as $entry) {
  6883.             $department[$entry->getDepartmentId()] = array(
  6884.                 'id' => $entry->getDepartmentId(),
  6885.                 'name' => $entry->getDepartmentName(),
  6886.             );
  6887.         }
  6888.         return $this->render('ApplicationBundle:pages/human_resource/input_forms:create_bonus_policy.html.twig', array(
  6889.             'page_title' => 'Create Bonus Policy',
  6890.             'employeeIds' => $employeeIds,
  6891.             'employeeType' => $employeeType,
  6892.             'Designation' => $Designation,
  6893.             'branch' => $branch,
  6894.             'department' => $department,
  6895.         ));
  6896.     }
  6897.     public function BonusPolicyListAction()
  6898.     {
  6899.         $em $this->getDoctrine()->getManager();
  6900.         $bonusPolicy $em->getRepository(BonusPolicy::class)->findAll();
  6901.         return $this->render('ApplicationBundle:pages/human_resource/list:bonus_policy_list.html.twig', array(
  6902.             'page_title' => 'Increment Policy List',
  6903.             'bonusPolicy' => $bonusPolicy
  6904.         ));
  6905.     }
  6906.     public function createIncrementPolicyAction(Request $request$id 0)
  6907.     {
  6908.         $em $this->getDoctrine()->getManager();
  6909.         $companyId $this->getLoggedUserCompanyId($request);
  6910.         $extDocData = [];
  6911.         $extDetailsData = [];
  6912.         if ($request->isMethod('POST')) {
  6913.             //            Generic::debugMessage($_POST);
  6914.             $em $this->getDoctrine()->getManager();
  6915.             $entity_id array_flip(GeneralConstant::$Entity_list)['IncrementPolicy']; //change
  6916.             $dochash $request->request->get('docHash'); //change
  6917.             $loginId $request->getSession()->get(UserConstants::USER_LOGIN_ID);
  6918.             $approveRole $request->request->get('approvalRole');
  6919.             $approveHash $request->request->get('approvalHash');
  6920.             if (!DocValidation::isInsertable(
  6921.                 $em,
  6922.                 $entity_id,
  6923.                 $dochash,
  6924.                 $loginId,
  6925.                 $approveRole,
  6926.                 $approveHash,
  6927.                 $id
  6928.             )
  6929.             ) {
  6930.                 $this->addFlash(
  6931.                     'error',
  6932.                     'Sorry Couldnot insert Data.'
  6933.                 );
  6934.             } else {
  6935.                 $funcname 'IncrementPolicy';
  6936.                 DeleteDocument::$funcname($em$id0);
  6937.                 $docId HumanResource::createIncrementPolicy($em$request$companyId0);
  6938.                 //now add Approval info
  6939.                 $loginId $request->getSession()->get(UserConstants::USER_LOGIN_ID);
  6940.                 $approveRole $request->request->get('approvalRole');
  6941.                 $options = array(
  6942.                     'notification_enabled' => $this->container->getParameter('notification_enabled'),
  6943.                     'notification_server' => $this->container->getParameter('notification_server'),
  6944.                     'appId' => $request->getSession()->get(UserConstants::USER_APP_ID),
  6945.                     'url' => $this->generateUrl(
  6946.                         GeneralConstant::$Entity_list_details[array_flip(GeneralConstant::$Entity_list)['IncrementPolicy']]
  6947.                         ['entity_view_route_path_name']
  6948.                     )
  6949.                 );
  6950.                 System::setApprovalInfo(
  6951.                     $this->getDoctrine()->getManager(),
  6952.                     $options,
  6953.                     array_flip(GeneralConstant::$Entity_list)['IncrementPolicy'],
  6954.                     $docId,
  6955.                     $request->getSession()->get(UserConstants::USER_LOGIN_ID),
  6956.                     3    //journal voucher
  6957.                 );
  6958.                 System::createEditSignatureHash(
  6959.                     $this->getDoctrine()->getManager(),
  6960.                     array_flip(GeneralConstant::$Entity_list)['IncrementPolicy'],
  6961.                     $docId,
  6962.                     $loginId,
  6963.                     $approveRole,
  6964.                     $request->request->get('approvalHash')
  6965.                 );
  6966.                 $doc_here $this->getDoctrine()
  6967.                     ->getRepository('ApplicationBundle:IncrementPolicy')
  6968.                     ->findOneBy(
  6969.                         array(
  6970.                             'id' => $docId
  6971.                         )
  6972.                     );
  6973.                 //notify
  6974.                 $this->addFlash(
  6975.                     'success',
  6976.                     'Policy Successfully Updated.'
  6977.                 );
  6978.                 $url $this->generateUrl(
  6979.                     'view_increment_policy'
  6980.                 );
  6981.                 return $this->redirect($url "/" $docId);
  6982.             }
  6983.         }
  6984.         //for edits
  6985.         if ($id == 0) {
  6986.         } else {
  6987.             $extDocData $em->getRepository('ApplicationBundle:IncrementPolicy')->findOneBy(
  6988.                 array(
  6989.                     'id' => $id///material
  6990.                 )
  6991.             );
  6992.             //now if its not editable, redirect to view
  6993.             if ($extDocData) {
  6994.                 if ($extDocData->getEditFlag() != 1) {
  6995. //          $url = $this->generateUrl(
  6996. ////              'view_salary_segregation_policy'
  6997. //              'salary_segregation_policy'
  6998. //          );
  6999. //          return $this->redirect($url . "/" . $id);
  7000.                 } else {
  7001. //          $extVoucherDetailsData = Accounts::GetVoucherDataForEdit($em, $voucherId);
  7002. //          $extDetailsData = $em->getRepository('ApplicationBundle:SalarySegregationPolicy')->findOneBy(
  7003. //              array(
  7004. //                  'transactionId' => $id, ///material
  7005. //
  7006. //              )
  7007. //          );
  7008.                 }
  7009.             } else {
  7010.             }
  7011.         }
  7012.         //$em = $this->getDoctrine()->getManager();
  7013.         $employeeIds $em->getRepository(EmployeeDetails::class)->findAll();
  7014.         $employeeType HumanResourceConstant::$employeeType;
  7015.         $Designation $em->getRepository(SysDepartmentPosition::class)->findAll();
  7016.         $branch $em->getRepository(Branch::class)->findAll();
  7017.         $departments $em->getRepository(SysDepartment::class)->findAll();
  7018.         $department = [];
  7019.         foreach ($departments as $entry) {
  7020.             $department[$entry->getDepartmentId()] = array(
  7021.                 'id' => $entry->getDepartmentId(),
  7022.                 'name' => $entry->getDepartmentName(),
  7023.             );
  7024.         }
  7025.         return $this->render('ApplicationBundle:pages/human_resource/input_forms:create_increment_policy.html.twig', array(
  7026.             'page_title' => 'Create Increment Policy',
  7027.             'employeeIds' => $employeeIds,
  7028.             'employeeType' => $employeeType,
  7029.             'Designation' => $Designation,
  7030.             'branch' => $branch,
  7031.             'department' => $department,
  7032.         ));
  7033.     }
  7034.     public function IncrementPolicyListAction()
  7035.     {
  7036.         $em $this->getDoctrine()->getManager();
  7037.         $incrementPolicy $em->getRepository(IncrementPolicy::class)->findAll();
  7038.         return $this->render('ApplicationBundle:pages/human_resource/list:increment_policy_list.html.twig', array(
  7039.             'page_title' => 'Increment Policy List',
  7040.             'incrementPolicy' => $incrementPolicy
  7041.         ));
  7042.     }
  7043.     public function ViewIncrementPolicyAction(Request $request$id)
  7044.     {
  7045.         $em $this->getDoctrine()->getManager();
  7046.         $incrementPolicy $em->getRepository(IncrementPolicy::class)->find($id);
  7047.         $Approval_data System::checkIfApprovalExists(
  7048.             $em,
  7049.             array_flip(GeneralConstant::$Entity_list)['IncrementPolicy'],
  7050.             $id,
  7051.             $request->getSession()->get(UserConstants::USER_LOGIN_ID)
  7052.         );
  7053.         return $this->render('ApplicationBundle:pages/human_resource/views:view_increment_policy.html.twig', array(
  7054.             'page_title' => 'Increment Policy List',
  7055.             'incrementPolicy' => $incrementPolicy,
  7056.             'approval_status' => $incrementPolicy->getApproved(),
  7057.             'approval_data' => $Approval_data,
  7058.             'auto_created' => $incrementPolicy->getAutocreated(),
  7059.             'id' => $id,
  7060.             'document_log' => $incrementPolicy->getAutocreated() == System::getDocumentLog(
  7061.                 $this->getDoctrine()->getManager(),
  7062.                 array_flip(GeneralConstant::$Entity_list)['FundRequisition'],
  7063.                 $id,
  7064.                 $incrementPolicy->getCreatedLoginId(),
  7065.                 $incrementPolicy->getEditedLoginId()
  7066.             ) : []
  7067.         ));
  7068.     }
  7069.     public function createConsultancyTopicAction(Request $request$id 0)
  7070.     {
  7071.         $em $this->getDoctrine()->getManager();
  7072.         $companyId $this->getLoggedUserCompanyId($request);
  7073.         if ($request->isMethod('POST')) {
  7074.             $loginId $request->getSession()->get(UserConstants::USER_LOGIN_ID);
  7075.             $new = new ConsultancyTopic();
  7076.             $new->setTopicName($request->request->get('topicName'));
  7077.             $new->setParentTopicName($request->request->get('parentTopicName'));
  7078.             $new->setUniqueHash($request->request->get('uniqueHash'));
  7079.             $new->setCompanyId($companyId);
  7080.             $new->setTopicSlug($request->request->get('topicSlug'));
  7081.             $new->setTitle($request->request->get('title'));
  7082.             $new->setSubTitle($request->request->get('subTitle'));
  7083.             $new->setSummary($request->request->get('content'));
  7084.             $new->setVideo($request->request->get('video'));
  7085.             $new->setAuthor($request->request->get('author'));
  7086.             $new->setAuthorSummary($request->request->get('authorSummary'));
  7087.             $new->setCreatedLoginId($request->getSession()->get(UserConstants::USER_LOGIN_ID));
  7088. //            $arr = [
  7089. //                'requirement' => $request->request->get('requirement'),
  7090. //
  7091. //            ];
  7092. //            $new->setRequirementData(json_encode($arr));
  7093.             $em->persist($new);
  7094.             $em->flush();
  7095.         }
  7096. //            $data = [];
  7097. //            $em = $this->getDoctrine()->getManager();
  7098. //            $companyId = $this->getLoggedUserCompanyId($request);
  7099. //            if ($request->isMethod('POST')) {
  7100. //                $em = $this->getDoctrine()->getManager();
  7101. //                $entity_id = array_flip(GeneralConstant::$Entity_list)['ConsultancyTopic'];
  7102. //                //$dochash = $request->request->get('docHash');//change
  7103. //                $approveRole = $request->request->get('approvalRole');
  7104. //                $approveHash = $request->request->get('approvalHash');
  7105. //                $loginId = $request->getSession()->get(UserConstants::USER_LOGIN_ID);
  7106. //                if (!DocValidation::isInsertable($em, $entity_id,
  7107. //                    $loginId, $approveRole, $approveHash, $id)
  7108. //                ) {
  7109. //                    $this->addFlash(
  7110. //                        'error',
  7111. //                        'Sorry Could not insert Data.'
  7112. //                    );
  7113. //                }  else {
  7114. //                    $data = $request->request;
  7115. //                    $docId = HumanResource::createConsultancyTopic($em, $loginId, $id, $data, $companyId);
  7116. ////                    now add Approval info
  7117. //
  7118. //                    $approveRole = $request->request->get('approvalRole');
  7119. //                    $options = array(
  7120. //                        'notification_enabled' => $this->container->getParameter('notification_enabled'),
  7121. //                        'notification_server' => $this->container->getParameter('notification_server'),
  7122. //                        'appId' => $request->getSession()->get(UserConstants::USER_APP_ID),
  7123. ////                        'url' => $this->generateUrl(
  7124. ////                            GeneralConstant::$Entity_list_details[array_flip(GeneralConstant::$Entity_list)['EmployeePerformanceEvolution']]
  7125. ////                            ['entity_view_route_path_name']
  7126. ////                        )
  7127. //                    );
  7128. //                    System::setApprovalInfo($this->getDoctrine()->getManager(), $options,
  7129. //                        array_flip(GeneralConstant::$Entity_list)['ConsultancyTopic'],
  7130. //                        $docId,
  7131. //                        $request->getSession()->get(UserConstants::USER_LOGIN_ID)    //journal voucher
  7132. //                    );
  7133. //                    System::createEditSignatureHash($this->getDoctrine()->getManager(), array_flip(GeneralConstant::$Entity_list)['ConsultancyTopic'],
  7134. //                        $docId,
  7135. //                        $loginId,
  7136. //                        $request->request->get('approvalHash'));
  7137. //                    $this->addFlash(
  7138. //                        'success',
  7139. //                        'New Consultancy Topic Added.'
  7140. //                    );
  7141. ////                    $url = $this->generateUrl(
  7142. ////                        'create_consultancy_topic'
  7143. ////                    );
  7144. //                    //return $this->redirect($url);
  7145. //
  7146. //                }
  7147. //            }
  7148.         $consultancyDetails $em->getRepository('ApplicationBundle:ConsultancyTopic')->findAll();
  7149.         return $this->render('ApplicationBundle:pages/human_resource/input_forms:create_consultancy.html.twig', array(
  7150.             'page_title' => 'Consultancy Topic',
  7151.             'consultancyDetails' => $consultancyDetails,
  7152. //                'requirement' => json_decode($consultancyDetails->getRequirementData())
  7153.         ));
  7154.     }
  7155.     public function createTopicAction(Request $request$id 0)
  7156.     {
  7157.         $em $this->getDoctrine()->getManager('company_group');
  7158.         $companyId $this->getLoggedUserCompanyId($request);
  7159.         $documentQRY $em->getRepository('CompanyGroupBundle:EntityCreateDocument')->findAll();
  7160.         $topicList $em->getRepository('CompanyGroupBundle:EntityCreateTopic')->findAll();
  7161.         $topic = [];
  7162.         $sessionName BuddybeeConstant::$sessionName;
  7163.         $document = [];
  7164.         foreach ($documentQRY as $d) {
  7165.             $document[$d->getId()] = array(
  7166.                 'id' => $d->getId(),
  7167.                 'documentName' => $d->getDocumentName(),
  7168.                 'text' => $d->getDocumentName(),
  7169.             );
  7170.         }
  7171.         $topicId $id;
  7172.         if ($topicId != 0)
  7173.             $topic $em->getRepository('CompanyGroupBundle:EntityCreateTopic')->findOneBy(
  7174.                 array(
  7175.                     'id' => $topicId
  7176.                 )
  7177.             );
  7178.         if ($request->isMethod('POST')) {
  7179.             if ($request->request->has('topicId'))
  7180.                 $topicId $request->request->get('topicId');
  7181. //            $loginId = $request->getSession()->get(UserConstants::USER_LOGIN_ID);
  7182.             if ($topicId != 0)
  7183.                 $new $em->getRepository('CompanyGroupBundle:EntityCreateTopic')->findOneBy(
  7184.                     array(
  7185.                         'id' => $topicId
  7186.                     )
  7187.                 );
  7188.             else
  7189.                 $new = new EntityCreateTopic();
  7190.             $new->setTopicName($request->request->get('topicName'));
  7191.             $new->setParentTopicId($request->request->get('parentTopic'));
  7192.             if ($request->request->get('countryId') != '')
  7193.                 $new->setCountryId($request->request->get('countryId'));
  7194.             else if ($request->request->get('parentTopic') != '') {
  7195.                 $parentTopic $em->getRepository('CompanyGroupBundle:EntityCreateTopic')->findOneBy(
  7196.                     array(
  7197.                         'id' => $request->request->get('parentTopic')
  7198.                     )
  7199.                 );
  7200.                 if ($parentTopic)
  7201.                     $new->setCountryId($parentTopic->getCountryId());
  7202.             }
  7203.             $new->setTimeSlotMultipliers($request->request->get('timeSlotMultipliers'));
  7204.             $new->setOnlyBookableByAdmin($request->request->get('onlyBookableByAdmin'0));
  7205.             $new->setMeetingType($request->request->get('meetingType'0));
  7206.             $new->setConsultantCanUpload($request->request->get('consultantCanUpload'0));
  7207.             $new->setTopicMarker($request->request->get('topicMarker'));
  7208.             $new->setCoinMultiplierValue($request->request->get('coinMultiplierValue'1));
  7209.             $new->setMinLifetimeCoinsBalance($request->request->get('minLifetimeCoinsBalance'0));
  7210.             $new->setMapEmbedIframe($request->request->get('mapEmbedIframe'''));
  7211.             $new->setTopicSummary($request->request->get('topicSummary'));
  7212.             $new->setAddress($request->request->get('address'));
  7213.             $new->setLocationString($request->request->get('locationString'));
  7214.             $new->setLocationLat($request->request->get('locationLat'));
  7215.             $new->setLocationLong($request->request->get('locationLong'));
  7216.             $new->setUniversityRanking($request->request->get('universityRanking'));
  7217.             $new->setIsParent($request->request->get('isParent'));
  7218.             $new->setIsEvent($request->request->get('isEvent'));
  7219.             $new->setConsultancyEnabled($request->request->get('consultancyEnabled'0));
  7220.             $new->setEventExpired($request->request->get('eventExpired'0));
  7221.             $new->setEventDesc($request->request->get('eventDesc'0));
  7222.             $eventStartDate = new \DateTime($request->request->get('eventStartDate'));
  7223.             $eventEndDate = new \DateTime($request->request->get('eventStartDate'));
  7224.             $new->setEventStartDate($eventStartDate);
  7225.             $new->setEventStartDateTs($eventStartDate->format('U'));
  7226.             $new->setEventEndDate($eventEndDate);
  7227.             $new->setEventStartDateTs($eventEndDate->format('U'));
  7228.             $new->setCreatedLoginId($request->getSession()->get(UserConstants::USER_LOGIN_ID));
  7229.             $checkListStringArray = [];
  7230.             if ($request->request->has('checkList'))
  7231.                 foreach ($request->request->get('checkList') as $value) {
  7232.                     $checkListStringArray [] = explode(","$value);
  7233.                 }
  7234.             $docData = [];
  7235.             foreach ($request->request->get('document', []) as $key => $value)
  7236.                 $docData[] = [
  7237.                     'document' => $request->request->get('document')[$key],
  7238.                     'expDays' => $request->request->get('expDays')[$key],
  7239.                     'stage' => $request->request->get('stage')[$key],
  7240.                     'generalProcessingDays' => $request->request->get('generalProcessingDays')[$key],
  7241.                     'emergencyProcessingDays' => $request->request->get('emergencyProcessingDays')[$key],
  7242.                     'thresholdDaysOffset' => $request->request->get('thresholdDaysOffset')[$key],
  7243.                     'checklist' => explode(","$request->request->get('checkList')[$key])
  7244.                 ];
  7245.             $coursePlanData = [];
  7246.             foreach ($request->request->get('coursePlanSessionNo', []) as $key => $value)
  7247.                 if ($request->request->get('coursePlanSessionNo')[$key] != '' and $request->request->get('coursePlanSessionNo')[$key] != null) {
  7248.                     if (!isset($coursePlanData[$request->request->get('coursePlanSessionNo')[$key]]))
  7249.                         $coursePlanData[$request->request->get('coursePlanSessionNo')[$key]] = [];
  7250.                     $coursePlanData[$request->request->get('coursePlanSessionNo')[$key]][] = [
  7251.                         'sessionNo' => $request->request->get('coursePlanSessionNo')[$key],
  7252.                         'subject' => $request->request->get('coursePlanSubject')[$key],
  7253.                         'details' => $request->request->get('coursePlanDetails')[$key],
  7254.                         'optimumMin' => $request->request->get('coursePlanOptimumMin')[$key],
  7255.                     ];
  7256.                 }
  7257.             $routineData = [];
  7258.             foreach ($request->request->get('routine_sequence', []) as $key => $value) {
  7259.                 $routineData[] = [
  7260.                     'sequence' => $request->request->get('routine_sequence')[$key],
  7261.                     'topicId' => $request->request->get('routine_topic_id')[$key],
  7262.                     'topicName' => $request->request->get('routine_topic_name')[$key],
  7263.                     'meetingType' => $request->request->get('routine_topic_meeting_type')[$key],
  7264.                     'duration' => $request->request->get('routine_duration')[$key],
  7265.                     'offset' => $request->request->get('routine_offset')[$key],
  7266.                     'coins' => $request->request->get('routine_coins')[$key],
  7267.                     'nextSequenceStart' => $request->request->has('routine_next_sequence_start_' $value) ? 0,
  7268.                     'modifiable' => $request->request->has('routine_modifiable_' $value) ? 0,
  7269.                 ];
  7270.             }
  7271.             $sessionData = [];
  7272.             foreach ($request->request->get('sessionId', []) as $key => $value)
  7273.                 $sessionData[] = [
  7274.                     'sessionId' => $request->request->get('sessionId')[$key],
  7275.                     'sessionYear' => $request->request->get('year')[$key],
  7276.                     'threshold' => $request->request->get('threshold')[$key],
  7277.                     'sessionStart' => $request->request->get('sessionStart')[$key],
  7278.                     'applicationStartDate' => $request->request->get('applicationStartDate')[$key],
  7279.                 ];
  7280.             $coursesData = [];
  7281.             foreach ($request->request->get('courseName', []) as $key => $value)
  7282.                 $coursesData[] = [
  7283.                     'courseName' => $request->request->get('courseName')[$key],
  7284.                 ];
  7285.             $departmentData = [];
  7286.             foreach ($request->request->get('departmentName', []) as $key => $value)
  7287.                 $departmentData[] = [
  7288.                     'departmentName' => $request->request->get('departmentName')[$key],
  7289.                 ];
  7290.             $benefitsData = [];
  7291.             foreach ($request->request->get('benefit', []) as $key => $value)
  7292.                 $benefitsData[] = [
  7293.                     'benefit' => $request->request->get('benefit')[$key],
  7294.                 ];
  7295.             $new->setRoutineData(json_encode($routineData));
  7296.             $new->setDocumentData(json_encode($docData));
  7297.             $new->setCoursePlanData(json_encode($coursePlanData));
  7298.             $new->setSessionData(json_encode($sessionData));
  7299.             $new->setCourses(json_encode($coursesData));
  7300.             $new->setDepartments(json_encode($departmentData));
  7301.             $new->setBenefits(json_encode($benefitsData));
  7302.             $otherDataObj = [];
  7303.             foreach (BuddybeeConstant::$otherDataByHash as $ohash => $otherDataGroup)
  7304.                 foreach ($otherDataGroup as $otherData) {
  7305.                     $fieldExists $request->request->has($ohash '_' $otherData['field']);
  7306.                     if ($fieldExists) {
  7307.                         $fieldValue $request->request->get($ohash '_' $otherData['field'], '');
  7308.                         $otherDataObj[$ohash '_' $otherData['field']] = $fieldValue;
  7309.                     }
  7310.                 }
  7311.             $new->setOtherData(json_encode($otherDataObj));
  7312.             $new->setBenefits(json_encode($benefitsData));
  7313.             $em->persist($new);
  7314.             $em->flush();
  7315.             $path "";
  7316.             $defaultProductImage '';
  7317.             $uploadedFile null;
  7318.             $upl_dir $this->container->getParameter('kernel.root_dir') . '/../web/uploads/topicImage/';
  7319.             $uploadedFile $request->files->get('topicSummaryImage');
  7320.             if ($uploadedFile != null) {
  7321.                 $fileName 'TSI' $new->getId() . '.' $uploadedFile->guessExtension();
  7322.                 $path $fileName;
  7323. //            $upl_dir = $this->container->getParameter('kernel.root_dir') . '/../web/uploads/Products/';
  7324.                 if (!file_exists($upl_dir)) {
  7325.                     mkdir($upl_dir0777true);
  7326.                 }
  7327.                 $uploadedFile->move($upl_dir$path);
  7328.                 $defaultProductImage 'uploads/topicImage/' $path;
  7329.                 $new->setTopicSummaryImage($defaultProductImage);
  7330.                 $em->flush();
  7331.             }
  7332.             $path "";
  7333.             $defaultProductImage '';
  7334.             $uploadedFile null;
  7335.             $upl_dir $this->container->getParameter('kernel.root_dir') . '/../web/uploads/topicImage/';
  7336.             $uploadedFile $request->files->get('topicImage');
  7337.             if ($uploadedFile != null) {
  7338.                 $fileName 'TI' $new->getId() . '.' $uploadedFile->guessExtension();
  7339.                 $path $fileName;
  7340. //            $upl_dir = $this->container->getParameter('kernel.root_dir') . '/../web/uploads/Products/';
  7341.                 if (!file_exists($upl_dir)) {
  7342.                     mkdir($upl_dir0777true);
  7343.                 }
  7344.                 $uploadedFile->move($upl_dir$path);
  7345.                 $defaultProductImage 'uploads/topicImage/' $path;
  7346.                 $new->setTopicImage($defaultProductImage);
  7347.                 $em->flush();
  7348.             }
  7349.             $this->addFlash(
  7350.                 'success',
  7351.                 'Topic Added.'
  7352.             );
  7353.         }
  7354.         return $this->render('ApplicationBundle:pages/human_resource/input_forms:create_topic.html.twig', array(
  7355.             'page_title' => 'Create Topic',
  7356.             'defaultCoursePlan' => BuddybeeConstant::$defaultCoursePlan,
  7357.             'coursePlanSessionTitle' => BuddybeeConstant::$coursePlanSessionTitle,
  7358.             'coursePlanSessionTitleShort' => BuddybeeConstant::$coursePlanSessionTitleShort,
  7359.             'document' => $document,
  7360.             'topic' => $topic,
  7361.             'otherDataByHash' => BuddybeeConstant::$otherDataByHash,
  7362.             'topicId' => $topicId,
  7363.             'topicList' => $topicList,
  7364.             'topicMarker' => BuddybeeConstant::$topicMarkup,
  7365.             'sessionName' => $sessionName,
  7366.         ));
  7367.     }
  7368.     public function ConsultancyRequirementSettingsAction(Request $request$id 0)
  7369.     {
  7370.         $em $this->getDoctrine()->getManager('company_group');
  7371.         $entityList $em->getRepository('CompanyGroupBundle:EntityCountryConsultantRequirements')->findAll();
  7372.         $documentQRY $em->getRepository('CompanyGroupBundle:EntityCreateDocument')->findAll();
  7373.         $entity = [];
  7374.         $sessionName BuddybeeConstant::$sessionName;
  7375.         $document = [];
  7376.         foreach ($documentQRY as $d) {
  7377.             $document[$d->getId()] = array(
  7378.                 'id' => $d->getId(),
  7379.                 'documentName' => $d->getDocumentName(),
  7380.                 'text' => $d->getDocumentName(),
  7381.             );
  7382.         }
  7383.         $countryId $id;
  7384.         if ($countryId != 0)
  7385.             $entity $em->getRepository('CompanyGroupBundle:EntityCountryConsultantRequirements')->findOneBy(
  7386.                 array(
  7387.                     'countryId' => $countryId
  7388.                 )
  7389.             );
  7390.         if ($request->isMethod('POST')) {
  7391.             if ($request->request->has('countryId'))
  7392.                 $countryId $request->request->get('countryId');
  7393. //            $loginId = $request->getSession()->get(UserConstants::USER_LOGIN_ID);
  7394.             if ($countryId != 0) {
  7395.                 $new $em->getRepository('CompanyGroupBundle:EntityCountryConsultantRequirements')->findOneBy(
  7396.                     array(
  7397.                         'countryId' => $countryId
  7398.                     )
  7399.                 );
  7400.                 if (!$new)
  7401.                     $new = new EntityCountryConsultantRequirements();
  7402.             } else
  7403.                 $new = new EntityCountryConsultantRequirements();
  7404.             $new->setCountryId($request->request->get('countryId'));
  7405.             $new->setContractLetterHtml($request->request->get('contractLetterHtml'));
  7406.             $new->setRequiredFields($request->request->get('requiredFields'));
  7407.             $new->setAllowedWorkingHoursPerDay($request->request->get('allowedWorkingHoursPerDay'));
  7408.             $new->setAllowedWorkingHoursPerMonth($request->request->get('allowedWorkingHoursPerMonth'));
  7409.             $new->setAllowedWorkingHoursPerWeek($request->request->get('allowedWorkingHoursPerWeek'));
  7410.             $new->setAllowedWorkingHoursPerYear($request->request->get('allowedWorkingHoursPerYear'));
  7411.             $new->setAllowedEarningPerDay($request->request->get('allowedEarningPerDay'));
  7412.             $new->setAllowedEarningPerMonth($request->request->get('allowedEarningPerMonth'));
  7413.             $new->setAllowedEarningPerWeek($request->request->get('allowedEarningPerWeek'));
  7414.             $new->setAllowedEarningPerYear($request->request->get('allowedEarningPerYear'));
  7415.             $new->setRevenuePercentagePerSession($request->request->get('revenuePercentagePerSession'));
  7416.             $docData = [];
  7417.             foreach ($request->request->get('document', []) as $key => $value)
  7418.                 $docData[] = [
  7419.                     'document' => $request->request->get('document')[$key],
  7420.                     'expDays' => $request->request->get('expDays')[$key],
  7421.                     'stage' => $request->request->get('stage')[$key],
  7422.                     'generalProcessingDays' => $request->request->get('generalProcessingDays')[$key],
  7423.                     'emergencyProcessingDays' => $request->request->get('emergencyProcessingDays')[$key],
  7424.                     'thresholdDaysOffset' => $request->request->get('thresholdDaysOffset')[$key],
  7425.                     'checklist' => explode(","$request->request->get('checkList')[$key])
  7426.                 ];
  7427.             $new->setDocumentList(json_encode($docData));
  7428.             $em->persist($new);
  7429.             $em->flush();
  7430.             $this->addFlash(
  7431.                 'success',
  7432.                 'Restriction Updated.'
  7433.             );
  7434.         }
  7435.         return $this->render('@Buddybee/pages/create_consultancy_requirements.html.twig', array(
  7436.             'page_title' => 'Create Requirements',
  7437.             'defaultCoursePlan' => BuddybeeConstant::$defaultCoursePlan,
  7438.             'coursePlanSessionTitle' => BuddybeeConstant::$coursePlanSessionTitle,
  7439.             'coursePlanSessionTitleShort' => BuddybeeConstant::$coursePlanSessionTitleShort,
  7440.             'document' => $document,
  7441.             'entity' => $entity,
  7442.             'otherDataByHash' => BuddybeeConstant::$otherDataByHash,
  7443.             'countryId' => $countryId,
  7444.             'entityList' => $entityList,
  7445.             'topicMarker' => BuddybeeConstant::$topicMarkup,
  7446.             'sessionName' => $sessionName,
  7447.         ));
  7448.     }
  7449.     public function PromoCodeSettingsAction(Request $request$id 0)
  7450.     {
  7451.         $em $this->getDoctrine()->getManager('company_group');
  7452.         $entityList $em->getRepository('CompanyGroupBundle:PromoCode')->findAll();
  7453.         $applicantList $em->getRepository('CompanyGroupBundle:EntityApplicantDetails')->findAll();
  7454.         $promoCodeId $id;
  7455.         $entity = [];
  7456.         if ($promoCodeId != 0)
  7457.             $entity $em->getRepository('CompanyGroupBundle:PromoCode')->findOneBy(
  7458.                 array(
  7459.                     'id' => $promoCodeId
  7460.                 )
  7461.             );
  7462.         if ($request->isMethod('POST')) {
  7463.             if ($request->request->has('promoCodeId'))
  7464.                 $promoCodeId $request->request->get('promoCodeId');
  7465. //            $loginId = $request->getSession()->get(UserConstants::USER_LOGIN_ID);
  7466.             if ($promoCodeId != 0) {
  7467.                 $new $em->getRepository('CompanyGroupBundle:PromoCode')->findOneBy(
  7468.                     array(
  7469.                         'id' => $promoCodeId
  7470.                     )
  7471.                 );
  7472.                 if (!$new)
  7473.                     $new = new PromoCode();
  7474.             } else
  7475.                 $new = new PromoCode();
  7476. //            $new->setCountryId($request->request->get('countryId'));
  7477.             $new->setCode($request->request->get('code'''));
  7478.             $new->setPromoType($request->request->get('promoType'1));
  7479.             $new->setPromoCodeType($request->request->get('promoCodeType'1));
  7480.             $new->setPromoValue($request->request->get('promoValue'0));
  7481.             $new->setPerpetual($request->request->get('perpetual'0));
  7482.             $new->setMaxDiscountAmount($request->request->get('maxDiscountAmount', -1));
  7483.             $new->setMaxCoinAddition($request->request->get('maxCoinAddition', -1));
  7484.             $new->setMinAmountForApplication($request->request->get('minAmountForApplication'0));
  7485.             $new->setMinCoinForApplication($request->request->get('minCoinForApplication'0));
  7486.             $new->setNextApplicationEachCoinCount($request->request->get('nextApplicationEachCoinCount', -1));
  7487.             $new->setMaxUseCount($request->request->get('maxUseCount', -1));
  7488.             $new->setMaxUseCountPerUser($request->request->get('maxUseCountPerUser', -1));
  7489.             $new->setUseCountBalance($request->request->get('useCountBalance', -1));
  7490.             $new->setReferralApplicantId($request->request->get('referralApplicantId'0));
  7491.             $new->setMaxReferralCommissionCount($request->request->get('maxReferralCommissionCount'0));
  7492.             $new->setReferralCommissionCountBalance($request->request->get('referralCommissionCountBalance'0));
  7493.             $new->setReferralCommissionType($request->request->get('referralCommissionType'1));
  7494.             $new->setReferralAmount($request->request->get('referralAmount'0));
  7495.             $startsAt = new \DateTime($request->request->get('startsAt'''));
  7496.             $expiresAt = new \DateTime($request->request->get('expiresAt'''));
  7497.             $new->setStartsAtTs($startsAt->format('U'));
  7498.             $new->setExpiresAtTs($expiresAt->format('U'));
  7499. //
  7500. //        startsAtTs:
  7501. //            type: integer
  7502. //            nullable: true
  7503. //        expiresAtTs:
  7504. //            type: integer
  7505. //            nullable: true
  7506.             $em->persist($new);
  7507.             $em->flush();
  7508.             $this->addFlash(
  7509.                 'success',
  7510.                 'Promo Code Updated.'
  7511.             );
  7512.         }
  7513.         return $this->render('@Buddybee/pages/buddybee_promo_code_settings.html.twig', array(
  7514.             'page_title' => 'Promo Codes',
  7515.             'entity' => $entity,
  7516.             'promoCodeId' => $promoCodeId,
  7517.             'entityList' => $entityList,
  7518.             'applicantList' => $applicantList,
  7519.         ));
  7520.     }
  7521.     public function createDocumentAction(Request $request$id 0)
  7522.     {
  7523.         $em $this->getDoctrine()->getManager('company_group');
  7524.         $companyId $this->getLoggedUserCompanyId($request);
  7525.         $document $em->getRepository('CompanyGroupBundle:EntityCreateDocument')->findAll();
  7526.         $thisDoc = [];
  7527.         if ($id != 0)
  7528.             $thisDoc $em->getRepository('CompanyGroupBundle:EntityCreateDocument')->findOneBy(
  7529.                 array(
  7530.                     'Id' => $id
  7531.                 )
  7532.             );
  7533.         if ($request->isMethod('POST')) {
  7534.             if ($id != 0)
  7535.                 $new $thisDoc;
  7536.             else
  7537.                 $new = new EntityCreateDocument();
  7538.             $new->setDocumentName($request->request->get('docName'));
  7539.             $new->setExpiryDays($request->request->get('expDays'));
  7540.             $new->setProcessingDays($request->request->get('processingDays'));
  7541.             $new->setEmergencyProcessingDays($request->request->get('emergencyProcessingDays'));
  7542.             $new->setDocVideo($request->request->get('docVideoLink'));
  7543.             $new->setRequiredDocument(json_encode($request->request->get('requiredDoc')));
  7544.             $new->setCreatedLoginId($request->getSession()->get(UserConstants::USER_LOGIN_ID));
  7545.             $arr = [
  7546.                 'checkListName' => $request->request->get('checkListName'),
  7547.             ];
  7548.             $new->setCheckList(json_encode($arr));
  7549.             $em->persist($new);
  7550.             $em->flush();
  7551.         }
  7552.         $this->addFlash(
  7553.             'Document Added',
  7554.             'Topic Added.'
  7555.         );
  7556.         return $this->render('ApplicationBundle:pages/human_resource/input_forms:create_document.html.twig', array(
  7557.             'page_title' => 'Create Document',
  7558.             'document' => $document,
  7559.             'thisDoc' => $thisDoc
  7560.         ));
  7561.     }
  7562.     public function getIndividualDocumentAction(Request $request$id)
  7563.     {
  7564.         $em $this->getDoctrine()->getManager('company_group');
  7565.         if ($id == 0) {
  7566.             if ($request->request->has('documentId'))
  7567.                 $id $request->request->get('documentId');
  7568.         }
  7569.         $document $em->getRepository('CompanyGroupBundle:EntityCreateDocument')->find($id);
  7570.         return new JsonResponse(
  7571.             array(
  7572.                 'success' => true,
  7573.                 'rowId' => $request->request->get('rowId'),
  7574.                 'expiryDays' => $document->getExpiryDays(),
  7575.                 'processingDays' => $document->getProcessingDays(),
  7576.                 'emergencyProcessing' => $document->getEmergencyProcessingDays(),
  7577.                 'checklist' => json_decode($document->getCheckList()),
  7578.             )
  7579.         );
  7580.     }
  7581.     public function createBlogAction(Request $request$id)
  7582.     {
  7583.         if (!$id) {
  7584.             if ($request->isMethod('POST')) {
  7585.                 $em $this->getDoctrine()->getManager('company_group');
  7586.                 $loginId $request->getSession()->get(UserConstants::USER_LOGIN_ID);
  7587.                 $new = new EntityCreateBlog();
  7588.                 $new->setTopicId($request->request->get('topicId'));
  7589.                 $new->setTitle($request->request->get('title'));
  7590.                 $new->setSubtitle($request->request->get('subTitle'));
  7591.                 $new->setContent($request->request->get('content'));
  7592.                 $new->setVideoLink($request->request->get('videoLink'));
  7593.                 $new->setAuthorName($request->request->get('authorName'));
  7594.                 $new->setAuthorSummary($request->request->get('authorSummary'));
  7595.                 $new->setIsPrimaryBlog($request->request->get('checkPrimaryBlog'));
  7596.                 $em->persist($new);
  7597.                 $em->flush();
  7598.                 //$fileName = 'cv' . $consultantDetails->getApplicantId() . '.' . $uploadedFile->guessExtension();
  7599.                 $path "";
  7600.                 $defaultProductImage '';
  7601.                 $uploadedFile null;
  7602.                 $upl_dir $this->container->getParameter('kernel.root_dir') . '/../web/uploads/authorImage/';
  7603.                 $uploadedFile $request->files->get('authorImage');
  7604.                 if ($uploadedFile != null) {
  7605.                     $fileName 'authorImage' $new->getId() . '.' $uploadedFile->guessExtension();
  7606.                     $path $fileName;
  7607. //            $upl_dir = $this->container->getParameter('kernel.root_dir') . '/../web/uploads/Products/';
  7608.                     if (!file_exists($upl_dir)) {
  7609.                         mkdir($upl_dir0777true);
  7610.                     }
  7611.                     $uploadedFile->move($upl_dir$path);
  7612.                     $defaultProductImage 'uploads/authorImage/' $path;
  7613.                     $new->setAuthorImage($defaultProductImage);
  7614.                     $em->flush();
  7615.                 }
  7616.                 $path "";
  7617.                 $defaultProductImage '';
  7618.                 $uploadedFile null;
  7619.                 $upl_dir $this->container->getParameter('kernel.root_dir') . '/../web/uploads/mainImage/';
  7620.                 $uploadedFile $request->files->get('main_img');
  7621.                 if ($uploadedFile != null) {
  7622.                     $fileName 'mainImage' $new->getId() . '.' $uploadedFile->guessExtension();
  7623.                     $path $fileName;
  7624. //            $upl_dir = $this->container->getParameter('kernel.root_dir') . '/../web/uploads/Products/';
  7625.                     if (!file_exists($upl_dir)) {
  7626.                         mkdir($upl_dir0777true);
  7627.                     }
  7628.                     $uploadedFile->move($upl_dir$path);
  7629.                     $defaultProductImage 'uploads/mainImage/' $path;
  7630.                     $new->setMainImage($defaultProductImage);
  7631.                     $em->flush();
  7632.                 }
  7633.                 $topicDetails $em->getRepository('CompanyGroupBundle:EntityCreateTopic')->findOneBy(
  7634.                     array(
  7635.                         'id' => $request->request->get('topicId')
  7636.                     )
  7637.                 );
  7638.                 if ($new->getIsPrimaryBlog() == 1) {
  7639.                     if ($topicDetails)
  7640.                         $topic $topicDetails;
  7641.                     else
  7642.                         $topic = new EntityCreateTopic();
  7643.                     $topic->setPrimaryBlogId($new->getId());
  7644.                     $em->flush();
  7645.                 }
  7646.                 $this->addFlash(
  7647.                     'success',
  7648.                     'Blog Added.'
  7649.                 );
  7650.             } else {
  7651.                 $em $this->getDoctrine()->getManager('company_group');
  7652.                 $topic $em->getRepository('CompanyGroupBundle:EntityCreateTopic')->findAll();
  7653.                 $applicant $em->getRepository('CompanyGroupBundle:EntityApplicantDetails')->findAll();
  7654.                 $blogs $em->getRepository('CompanyGroupBundle:EntityCreateBlog')->findAll();
  7655.                 $topicIds = [];
  7656.                 foreach ($blogs as $blog) {
  7657.                     $topicIds [] = $blog->getTopicId();
  7658.                 }
  7659. //                $topic = $em->getRepository('CompanyGroupBundle:EntityCreateTopic')->findBy(
  7660. //                    array(
  7661. //                        'id' => $topicIds
  7662. //                    )
  7663. //                );
  7664.                 return $this->render('ApplicationBundle:pages/human_resource/input_forms:create_blog.html.twig', array(
  7665.                     'page_title' => 'Create Blog',
  7666.                     'topic' => $topic,
  7667.                     'applicant' => $applicant,
  7668.                     'blog' => $blogs,
  7669.                     'id' => $id,
  7670.                 ));
  7671.             }
  7672.         } else {
  7673.             if ($request->isMethod('GET')) {
  7674.                 $em $this->getDoctrine()->getManager('company_group');
  7675.                 $topic $em->getRepository('CompanyGroupBundle:EntityCreateTopic')->findAll();
  7676.                 $applicant $em->getRepository('CompanyGroupBundle:EntityApplicantDetails')->findAll();
  7677.                 $blogs $em->getRepository('CompanyGroupBundle:EntityCreateBlog')->find($id);
  7678.                 return $this->render('ApplicationBundle:pages/human_resource/input_forms:create_blog.html.twig', array(
  7679.                     'page_title' => 'Create Blog',
  7680.                     'topic' => $topic,
  7681.                     'applicant' => $applicant,
  7682.                     'blog' => $blogs,
  7683.                     'id' => $id,
  7684.                 ));
  7685.             } else {
  7686.                 $em $this->getDoctrine()->getManager('company_group');
  7687.                 $new = new EntityCreateBlog();
  7688.                 $new->setTopicId($request->request->get('topicId'));
  7689.                 $new->setTitle($request->request->get('title'));
  7690.                 $new->setSubtitle($request->request->get('subTitle'));
  7691.                 $new->setContent($request->request->get('content'));
  7692.                 $new->setVideoLink($request->request->get('videoLink'));
  7693.                 $new->setAuthorName($request->request->get('authorName'));
  7694.                 $new->setAuthorSummary($request->request->get('authorSummary'));
  7695.                 //$em->persist($new);
  7696.                 $em->flush();
  7697.                 $path "";
  7698.                 $defaultProductImage '';
  7699.                 $uploadedFile null;
  7700.                 $upl_dir $this->container->getParameter('kernel.root_dir') . '/../web/uploads/authorImage/';
  7701.                 $uploadedFile $request->files->get('authorImage');
  7702.                 if ($uploadedFile != null) {
  7703.                     $fileName 'authorImage' '.' $uploadedFile->guessExtension();
  7704.                     $path $fileName;
  7705. //            $upl_dir = $this->container->getParameter('kernel.root_dir') . '/../web/uploads/Products/';
  7706.                     if (!file_exists($upl_dir)) {
  7707.                         mkdir($upl_dir0777true);
  7708.                     }
  7709.                     $uploadedFile->move($upl_dir$path);
  7710.                     $defaultProductImage 'uploads/authorImage/' $path;
  7711.                     $new->setAuthorImage($defaultProductImage);
  7712.                     $em->flush();
  7713.                 }
  7714.                 $this->addFlash(
  7715.                     'success',
  7716.                     'Blog Updated.'
  7717.                 );
  7718.             }
  7719.         }
  7720.         return new JsonResponse(
  7721.             array(
  7722.                 'success' => true,
  7723.             )
  7724.         );
  7725. //        if ($request->isMethod('POST')) {
  7726. //            $loginId = $request->getSession()->get(UserConstants::USER_LOGIN_ID);
  7727. //
  7728. //            $new = new EntityCreateBlog();
  7729. //
  7730. //            $new->setTopicId($request->request->get('topicId'));
  7731. //            $new->setTitle($request->request->get('title'));
  7732. //            $new->setSubtitle($request->request->get('subTitle'));
  7733. //            $new->setContent($request->request->get('content'));
  7734. //            $new->setVideoLink($request->request->get('videoLink'));
  7735. //            $new->setAuthorName($request->request->get('authorName'));
  7736. //            $new->setAuthorSummary($request->request->get('authorSummary'));
  7737. //
  7738. //            $em->persist($new);
  7739. //            $em->flush();
  7740. //
  7741. //
  7742. //            $path = "";
  7743. //            $defaultProductImage = '';
  7744. //            $uploadedFile = null;
  7745. //            $upl_dir = $this->container->getParameter('kernel.root_dir') . '/../web/uploads/authorImage/';
  7746. //            $uploadedFile=  $request->files->get('authorImage');
  7747. //
  7748. //            if ($uploadedFile != null) {
  7749. //
  7750. //                $fileName = 'authorImage' .'.' . $uploadedFile->guessExtension();
  7751. //                $path = $fileName;
  7752. ////            $upl_dir = $this->container->getParameter('kernel.root_dir') . '/../web/uploads/Products/';
  7753. //                if (!file_exists($upl_dir)) {
  7754. //                    mkdir($upl_dir, 0777, true);
  7755. //                }
  7756. //                $uploadedFile->move($upl_dir, $path);
  7757. //                $defaultProductImage = 'uploads/authorImage/' . $path;
  7758. //                $new->setAuthorImage($defaultProductImage);
  7759. //                $em->flush();
  7760. //
  7761. //            }
  7762. //            $this->addFlash(
  7763. //                'success',
  7764. //                'Blog Added.'
  7765. //            );
  7766. //        }
  7767. //        return $this->render('ApplicationBundle:pages/human_resource/input_forms:create_blog.html.twig', array(
  7768. //            'page_title' => 'Create Blog',
  7769. //            'topic'=> $topic,
  7770. //            'applicant' => $applicant,
  7771. //            'blog' => $blogs
  7772. //        ));
  7773.     }
  7774.     public function applicantConsultancyAction()
  7775.     {
  7776.         return $this->render('ApplicationBundle:pages/human_resource/input_forms:consultancy.html.twig', array(
  7777.             'page_title' => 'Consultancy',
  7778.         ));
  7779.     }
  7780.     public function viewConsultantDetailsAction(Request $request$id 0)
  7781.     {
  7782.         $gocEnabled 1;
  7783.         $currAppId 4;
  7784.         $honeybeeAppId 1;
  7785.         $buddybeeAppId 4;
  7786.         $em_goc $this->getDoctrine()->getManager('company_group');
  7787.         $em $this->getDoctrine()->getManager();
  7788.         $option = [];
  7789.         $option['appId'] = $currAppId//honeybee
  7790.         $option['departmentId'] = 18//consultancy
  7791.         $option['designationId'] = 50;
  7792. //        $dataToConnect = System::changeDoctrineManagerByAppId(
  7793. //            $this->getDoctrine()->getManager('company_group'),
  7794. //            $gocEnabled,
  7795. //            $currAppId
  7796. //        );
  7797. //        if (!empty($dataToConnect)) {
  7798. //            $connector = $this->container->get('application_connector');
  7799. //            $connector->resetConnection(
  7800. //                'default',
  7801. //                $dataToConnect['dbName'],
  7802. //                $dataToConnect['dbUser'],
  7803. //                $dataToConnect['dbPass'],
  7804. //                $dataToConnect['dbHost'],
  7805. //                $reset = true
  7806. //            );
  7807. //            $em = $this->getDoctrine()->getManager();
  7808. //        } else {
  7809. //            $currAppId = $honeybeeAppId;
  7810. //            $dataToConnectAgain = System::changeDoctrineManagerByAppId(
  7811. //                $this->getDoctrine()->getManager('company_group'),
  7812. //                $gocEnabled,
  7813. //                $currAppId
  7814. //            );
  7815. //            if (!empty($dataToConnectAgain)) {
  7816. //                $connector = $this->container->get('application_connector');
  7817. //                $connector->resetConnection(
  7818. //                    'default',
  7819. //                    $dataToConnect['dbName'],
  7820. //                    $dataToConnect['dbUser'],
  7821. //                    $dataToConnect['dbPass'],
  7822. //                    $dataToConnect['dbHost'],
  7823. //                    $reset = true
  7824. //                );
  7825. //                $em = $this->getDoctrine()->getManager();
  7826. //            }
  7827. //
  7828. //        }
  7829.         $consultantDetails $em_goc->getRepository(EntityApplicantDetails::class)->find($id);
  7830.         $skill $em_goc->getRepository(EntitySkill::class)->findAll();
  7831.         $gender HumanResourceConstant::$sex;
  7832.         $blood HumanResourceConstant::$BloodGroup;
  7833.         $consultantLevel HumanResourceConstant::$consultantLevel;
  7834.         $companyId $this->getLoggedUserCompanyId($request);
  7835.         $designation $em->getRepository("ApplicationBundle:SysDepartmentPosition")->findAll();
  7836.         $departments $em->getRepository("ApplicationBundle:SysDepartment")->findAll();
  7837.         $companyData Company::getCompanyData($em$companyId);
  7838.         $currDate = new \DateTime();
  7839.         if ($request->isMethod('POST')) {
  7840.             //for consultant only
  7841.             $convertToConsultant HumanResource::convertToConsultant($em_goc$em$id$option$request->request);
  7842.             if ($request->request->get('confirmStatus'0) == 1) {
  7843.                 $bodyTemplate 'ApplicationBundle:email/templates:consultantApprovalEmail.html.twig';
  7844.                 $contractLetterHtml '';
  7845.                 $bodyData = array(
  7846.                     'name' => $consultantDetails->getFirstname() . ' ' $consultantDetails->getLastname(),
  7847.                     'companyData' => $companyData,
  7848.                     'contractLetterHtml' => $contractLetterHtml,
  7849.                     'commentText' => $request->request->get('commentText'),
  7850.                 );
  7851.                 $new_mail $this->get('mail_module');
  7852.                 $new_mail->sendMyMail(array(
  7853.                     'senderHash' => '_CUSTOM_',
  7854.                     'encryptionMethod' => 'ssl',
  7855.                     'userName' => 'management@buddybee.eu',
  7856.                     'fromAddress' => 'management@buddybee.eu',
  7857.                     'password' => 'Eco@0112',
  7858.                     'smtpServer' => 'smtp.hostinger.com',
  7859.                     'smtpPort' => '465',
  7860.                     'forwardToMailAddress' => $consultantDetails->getEmail(),
  7861.                     'subject' => 'Consultant Contract Letter Of ' $consultantDetails->getFirstName(),
  7862.                     'fileName' => '',
  7863.                     //'attachments' => $attachments,
  7864.                     'toAddress' => $consultantDetails->getEmail(),
  7865.                     'mailTemplate' => $bodyTemplate,
  7866.                     'templateData' => $bodyData,
  7867.                     'embedCompanyImage' => 1,
  7868.                     'companyId' => $companyId,
  7869.                     'companyImagePath' => ""
  7870.                 ));
  7871.             }
  7872.             if ($request->request->get('confirmStatus'0) == 0) {
  7873.                 $bodyTemplate 'ApplicationBundle:email/templates:consultantRejectionEmail.html.twig';
  7874.                 $contractLetterHtml '';
  7875.                 $bodyData = array(
  7876.                     'name' => $consultantDetails->getFirstname() . ' ' $consultantDetails->getLastname(),
  7877.                     'companyData' => $companyData,
  7878.                     'contractLetterHtml' => $contractLetterHtml,
  7879.                     'commentText' => $request->request->get('commentText'),
  7880.                 );
  7881.                 $new_mail $this->get('mail_module');
  7882.                 $new_mail->sendMyMail(array(
  7883.                     'senderHash' => '_CUSTOM_',
  7884.                     'encryptionMethod' => 'ssl',
  7885.                     'userName' => 'management@buddybee.eu',
  7886.                     'fromAddress' => 'management@buddybee.eu',
  7887.                     'password' => 'Eco@0112',
  7888.                     'smtpServer' => 'smtp.hostinger.com',
  7889.                     'smtpPort' => '465',
  7890.                     'forwardToMailAddress' => $consultantDetails->getEmail(),
  7891.                     'subject' => 'Rejection Letter Of ' $consultantDetails->getFirstName(),
  7892.                     'fileName' => '',
  7893.                     //'attachments' => $attachments,
  7894.                     'toAddress' => $consultantDetails->getEmail(),
  7895.                     'mailTemplate' => $bodyTemplate,
  7896.                     'templateData' => $bodyData,
  7897.                     'embedCompanyImage' => 1,
  7898.                     'companyId' => $companyId,
  7899.                     'companyImagePath' => ""
  7900.                 ));
  7901.             }
  7902.         }
  7903.         $docList MiscActions::GetDocumentDataForBuddybeeConsultantApply($em_goc,
  7904.             $id,
  7905.             $consultantDetails->getCurrentCountryId()
  7906.         );
  7907.         return $this->render('ApplicationBundle:pages/human_resource/views:viewConsultantDetails.html.twig', array(
  7908.             'page_title' => 'Consultant Details',
  7909.             'applicantId' => $id,
  7910.             'consultantDetails' => $consultantDetails,
  7911.             'education' => json_decode($consultantDetails->getEducationData(), true),
  7912.             'workExperience' => json_decode($consultantDetails->getWorkExperienceData(), true),
  7913.             'certificate' => json_decode($consultantDetails->getCertificateData(), true),
  7914.             'gender' => $gender,
  7915.             'blood' => $blood,
  7916.             'skill' => $skill,
  7917.             'docList' => $docList,
  7918.             'countryId' => $consultantDetails->getCurrentCountryId(),
  7919.             'consultantLevel' => $consultantLevel,
  7920.             'designation' => $designation,
  7921.             'department' => $departments
  7922.         ));
  7923.     }
  7924.     public function ApplicableEmployeSettingsAction()
  7925.     {
  7926.         $em $this->getDoctrine()->getManager();
  7927.         $employeeIds $em->getRepository(Employee::class)->findAll();
  7928.         return $this->render('ApplicationBundle:pages/human_resource/input_forms:applicable_employee_settings.html.twig', array(
  7929.             'page_title' => 'Applicable Employee Settings',
  7930.             'employeeIds' => $employeeIds
  7931.         ));
  7932.     }
  7933.     public function GetApplicableSettingsForSingleEmployeeAction($id)
  7934.     {
  7935.         $em $this->getDoctrine()->getManager();
  7936.         $bankLists $em->getRepository(WorkHourPolicy::class)->findAll();
  7937.         if (json_decode($bankLists->getEmployeeIds()) == $id) {
  7938.             return new JsonResponse(
  7939.                 array(
  7940.                     'success' => true,
  7941.                     'msg' => 'employee found'
  7942.                 )
  7943.             );
  7944.         } else {
  7945.             return new JsonResponse(
  7946.                 array(
  7947.                     'success' => true,
  7948.                     'msg' => 'employee not found'
  7949.                 )
  7950.             );
  7951.         }
  7952.     }
  7953. //    public function  getEmployeeDataAction(){
  7954. //        $em = $this->getDoctrine()->getManager();
  7955. //        $emplyeeDetails =  $em->getRepository('ApplicationBundle:EmployeeDeatils')->findAll();
  7956. //        $days = HumanResourceConstant::$days;
  7957. //        $holidays = ;
  7958. //        $workHourPolicies = ;
  7959. //
  7960. //    }
  7961.     public function meetingSchedulingForTabAction()
  7962.     {
  7963.         $em $this->getDoctrine()->getManager();
  7964.         $date date('Y-m-d');
  7965.         $month date('m');
  7966.         $year date('Y');
  7967.         $monthName date("F"mktime(000$month));
  7968.         $totalDayOfMonth cal_days_in_month(CAL_GREGORIAN$month$year);
  7969.         $fromdt date('Y-m-01 'strtotime("First Day Of  $monthName $year"));
  7970. //        echo "Start Date : $fromdt" . "<br>";
  7971.         $todt date('Y-m-d 'strtotime("Last Day of $monthName $year"));
  7972. //        echo "End Date : $todt" . "<br>";
  7973.         $num_friday '';
  7974.         for ($i 0$i < ((strtotime($todt) - strtotime($fromdt)) / 86400); $i++) {
  7975.             if (date('l'strtotime($fromdt) + ($i 86400)) == 'Friday') {
  7976.                 $num_friday++;
  7977.             }
  7978.         }
  7979.         $num_saturday '';
  7980.         for ($i 0$i < ((strtotime($todt) - strtotime($fromdt)) / 86400); $i++) {
  7981.             if (date('l'strtotime($fromdt) + ($i 86400)) == 'Saturday') {
  7982.                 $num_saturday++;
  7983.             }
  7984.         }
  7985.         $totalWeekends $num_saturday $num_friday;
  7986.         $totalCompanyWorkingDay $totalDayOfMonth $totalWeekends;
  7987. //        $attendanceData=$em->getRepository('ApplicationBundle:EmployeeAttendanceLog')->findOneBy(
  7988. //            array(
  7989. //                'employeeId' => 3
  7990. //            )
  7991. //        );
  7992.         $DateRange = [];
  7993.         $holidayDates $em->getRepository('ApplicationBundle:HolidayCalendarDates')->findAll();
  7994.         foreach ($holidayDates as $holiday) {
  7995.             $holidaayData = array(
  7996.                 'startDate' => $holiday->getStartDate(),
  7997.                 'endDate' => $holiday->getEndDate(),
  7998.             );
  7999.             $DateRange $holidaayData;
  8000.         }
  8001.         $employeeDataDetail = [];
  8002.         $employeeDetail $em->getRepository('ApplicationBundle:EmployeeDetails')->findOneBy(
  8003.             array(
  8004.                 'id' => 3
  8005.             )
  8006.         );
  8007. //        foreach($employeeDetail as $employee){
  8008.         $employeeData = array(
  8009.             'firstName' => $employeeDetail->getFirstname(),
  8010.             'basic' => $employeeDetail->getEar1(),
  8011.             'dearness' => $employeeDetail->getEar2(),
  8012.             'houseRent' => $employeeDetail->getEar3(),
  8013.             'medical' => $employeeDetail->getEar4(),
  8014.             'leaveTravel' => $employeeDetail->getEar5(),
  8015.             'childEducation' => $employeeDetail->getEar6(),
  8016.             'totalEarning' => $employeeDetail->getEart(),
  8017.         );
  8018.         $employeeDataDetail $employeeData;
  8019. //        }
  8020.         $attendanceData $em->getRepository(EmployeeAttendanceLog::class);
  8021. //        $employeeId = $attendanceData->getEmployeeId();
  8022. //        $countId = count($employeeId);
  8023.         $totalPresent $attendanceData->createQueryBuilder('a')
  8024.             // Filter by some parameter if you want
  8025.             ->where('a.employeeId = 3')
  8026.             ->andWhere('a.isPresent = 1')
  8027.             ->select('a.isPresent')
  8028.             ->getQuery()
  8029.             ->getResult();
  8030. //        $countAt = 0;
  8031.         $count count($totalPresent);
  8032. //        $count = $countAt+$count;
  8033.         //get holiday
  8034.         $holidayStartDate $DateRange['startDate']->format('Y-m-d');
  8035.         $holidayEndDate $DateRange['endDate']->format('Y-m-d');
  8036.         $dates HumanResource::getBetweenDates($holidayStartDate$holidayEndDate);
  8037.         $dateCount count($dates);
  8038.         $totalOffDay $totalWeekends $dateCount;
  8039.         $totalCompanyWorkingDay $totalDayOfMonth $totalOffDay;
  8040.         $totalAbsent $totalCompanyWorkingDay $count;
  8041. //        foreach($dates as $compDate ){
  8042. //
  8043. //
  8044. //
  8045. //            if($date == $compDate){
  8046. //                echo $date;
  8047. //                echo $compDate;
  8048. //                echo "holiday" ;
  8049. //
  8050. //            }
  8051. //            else{
  8052. //                echo "no holiday" ;
  8053. //            }
  8054. //        }
  8055.         $twigData HumanResource::twigDataForWorkHourPolicy($em);
  8056.         return $this->render('ApplicationBundle:pages/human_resource/list:meeting_schedule_list_for_tab.html.twig', array(
  8057.             'page_title' => 'Meeting Schedule List',
  8058.             'date' => $date,
  8059.             'totalWeekends' => $totalWeekends,
  8060.             'totalCompanyWorkingDay' => $totalCompanyWorkingDay,
  8061. //            'attendanceData' => $attendanceData,
  8062. //            'employeeId' => $employeeId,
  8063.             'count' => $count,
  8064.             'totalAbsent' => $totalAbsent,
  8065.             'employeeDataDetail' => $employeeDataDetail,
  8066.             'holiday' => $DateRange,
  8067.             'holidayStartDate' => $holidayStartDate,
  8068.             'holidayEndDate' => $holidayEndDate,
  8069.             'holidayCount' => $dateCount,
  8070.             'totalOffDay' => $totalOffDay,
  8071.             'employeeIds' => $twigData['employeeIds'],
  8072.         ));
  8073.     }
  8074.     public function getEmployeeDataForDisburseAction($id)
  8075.     {
  8076.         $em $this->getDoctrine()->getManager();
  8077.         $employeeDetail $em->getRepository('ApplicationBundle:EmployeeDetails')->find($id);
  8078.         return new JsonResponse(
  8079.             array(
  8080.                 'success' => true,
  8081.                 'firstName' => $employeeDetail->getFirstName(),
  8082.             )
  8083.         );
  8084.     }
  8085.     public function BulkAttendanceAction(Request $request)
  8086.     {
  8087.         $em $this->getDoctrine()->getManager();
  8088.         $companyId $this->getLoggedUserCompanyId($request);
  8089.         if ($request->isMethod('POST')) {
  8090.             $attendance = [];
  8091.             foreach ($request->request->get('date') as $key => $val) {
  8092.                 $loginId $request->getSession()->get(UserConstants::USER_LOGIN_ID);
  8093.                 $bulkAttendance null;
  8094.                 if ($request->request->get('attId')[$key] != 0)
  8095.                     $bulkAttendance $em->getRepository('ApplicationBundle:EmployeeAttendance')->findOneBy(array(
  8096.                         'id' => $request->request->get('attId')[$key],
  8097.                     ));
  8098.                 if (!$bulkAttendance)
  8099.                     $bulkAttendance = new EmployeeAttendance;
  8100.                 $theDate = new \DateTime($request->request->get('date')[$key]);
  8101.                 $bulkAttendance->setEmployeeId($request->request->get('employeeId'));
  8102.                 $bulkAttendance->setDate($theDate);
  8103.                 $bulkAttendance->setEntry(
  8104.                     ($request->request->get('startTimeTs')[$key] == '' ||
  8105.                         $request->request->get('startTimeTs')[$key] == 'NaN' ||
  8106.                         $request->request->get('startTimeTs')[$key] == 0) ? null :
  8107.                         new \DateTime('@' $request->request->get('startTimeTs')[$key])
  8108.                 );
  8109.                 $bulkAttendance->setLastOut(($request->request->get('endTimeTs')[$key] == '' ||
  8110.                     $request->request->get('endTimeTs')[$key] == 'NaN' ||
  8111.                     $request->request->get('endTimeTs')[$key] == 0) ? null :
  8112.                     new \DateTime('@' $request->request->get('endTimeTs')[$key]));
  8113.                 $bulkAttendance->setData(json_encode(
  8114.                     array(
  8115.                         "in" => json_decode($request->request->get('entryDataIn')[$key], true),
  8116.                         "out" => json_decode($request->request->get('entryDataOut')[$key], true)
  8117.                     )
  8118.                 ));
  8119. //                $bulkAttendance->setLastStartTime(new \DateTime($request->request->get('startDate')));
  8120. //                $bulkAttendance->setIsPresent(1);
  8121.                 $bulkAttendance->setLastStartTimeTs($request->request->get('startTimeTs')[$key]);
  8122.                 $bulkAttendance->setLastEndTimeTs($request->request->get('endTimeTs')[$key]);
  8123. //                $bulkAttendance->setTotalWorkHour($request->request->get('totalWorkHour')[$key]);
  8124.                 $em->persist($bulkAttendance);
  8125.                 $em->flush();
  8126.                 $bulkAttendanceLog $em->getRepository('ApplicationBundle:EmployeeAttendanceLog')->findOneBy(array(
  8127.                     'attendance_id' => $bulkAttendance->getId(),
  8128.                 ));
  8129.                 if (!$bulkAttendanceLog)
  8130.                     $bulkAttendanceLog = new EmployeeAttendanceLog;
  8131.                 $bulkAttendanceLog->setAttendanceId($bulkAttendance->getId());
  8132.                 $bulkAttendanceLog->setEmployeeId($request->request->get('employeeId'));
  8133.                 $bulkAttendanceLog->setLastStartTime(
  8134.                     ($request->request->get('startTimeTs')[$key] == '' ||
  8135.                         $request->request->get('startTimeTs')[$key] == 'NaN' ||
  8136.                         $request->request->get('startTimeTs')[$key] == 0) ? null :
  8137.                         new \DateTime('@' $request->request->get('startTimeTs')[$key])
  8138.                 );
  8139.                 $bulkAttendanceLog->setLastEndTime(($request->request->get('endTimeTs')[$key] == '' ||
  8140.                     $request->request->get('endTimeTs')[$key] == 'NaN' ||
  8141.                     $request->request->get('endTimeTs')[$key] == 0) ? null :
  8142.                     new \DateTime('@' $request->request->get('endTimeTs')[$key]));
  8143. //                $bulkAttendance->setLastStartTime(new \DateTime($request->request->get('startDate')));
  8144.                 $bulkAttendanceLog->setIsPresent(1);
  8145.                 $bulkAttendanceLog->setLastStartTimeTs($request->request->get('startTimeTs')[$key]);
  8146.                 $bulkAttendanceLog->setLastEndTimeTs($request->request->get('endTimeTs')[$key]);
  8147.                 $bulkAttendanceLog->setTotalWorkHour($request->request->get('totalWorkHour')[$key]);
  8148. //                $bulkAttendanceLog->setPositionArray(json_encode($request->request->get('locations')[$key]));
  8149.                 $em->persist($bulkAttendanceLog);
  8150.                 $em->flush();
  8151.             }
  8152.         }
  8153.         $startDate $request->query->get('start_date''');
  8154.         $endDate $request->query->get('end_date''');
  8155.         $employeeId $request->query->get('employee_id'0);
  8156.         $existingData = [];
  8157.         $startDateTs 0;
  8158.         $endDateTs 0;
  8159.         $returnData = array(
  8160.             'page_title' => 'Bulk Attendance',
  8161.             'existingData' => $existingData,
  8162.             'startDateTs' => $startDateTs,
  8163.             'endDateTs' => $endDateTs,
  8164.         );
  8165.         if ($request->query->has('returnJson')) {
  8166.             if ($startDate != '' && $endDate != '' && $employeeId != 0) {
  8167.                 $startDateDt = new \DateTime($startDate);
  8168.                 $endDateDt = new \DateTime($endDate);
  8169.                 $startDateTs $startDateDt->format('U');
  8170.                 $endDateTs $endDateDt->format('U');
  8171.                 $attendanceQuery $em->getRepository('ApplicationBundle:EmployeeAttendance')
  8172.                     ->createQueryBuilder('p')
  8173.                     ->where("p.employeeId = " $employeeId)
  8174. //                ->andWhere("p.date => '" . ($startDateDt->format('Y-m-d'))."'")
  8175.                     ->andWhere("p.date <= :last")
  8176.                     ->andWhere("p.date >= :start")
  8177.                     ->setParameter('start'$startDateDt)
  8178.                     ->setParameter('last'$endDateDt);
  8179.                 $attendanceResults $attendanceQuery->getQuery()->getResult();
  8180.                 foreach ($attendanceResults as $att) {
  8181.                     $entryDateTime null;
  8182.                     $outDateTime null;
  8183.                     if ($att->getEntry()) $entryDateTime = new \DateTime($att->getDate()->format('Y-m-d') . ' ' $att->getEntry()->format('H:i:00 +0000'));
  8184.                     if ($att->getLastOut()) $outDateTime = new \DateTime($att->getDate()->format('Y-m-d') . ' ' $att->getLastOut()->format('H:i:00 +0000'));
  8185.                     $attData = array(
  8186.                         'id' => $att->getId(),
  8187.                         'date_str' => $att->getDate()->format('Y-m-d'),
  8188.                         'date_str_full' => $att->getDate()->format('Y-m-d H:i:s'),
  8189.                         'in_time_full' => $entryDateTime $entryDateTime->format(DATE_RFC2822) : '',
  8190.                         'date_ts' => $att->getDate()->format('U'),
  8191.                         'in_time' => $entryDateTime $entryDateTime->format('H:i:s') : '',
  8192.                         'in_time_ts' => $entryDateTime $entryDateTime->format('U') : 0,
  8193.                         'last_out_time' => $outDateTime $outDateTime->format('H:i:s') : '',
  8194.                         'last_out_time_ts' => $outDateTime $outDateTime->format('U') : '',
  8195.                     );
  8196.                     $locations = [];
  8197.                     $locList = [];
  8198.                     $logHere $em->getRepository('ApplicationBundle:EmployeeAttendanceLog')->findOneBy(array(
  8199.                         'attendance_id' => $att->getId(),
  8200.                     ));
  8201.                     if ($logHere)
  8202.                         $locList json_decode($logHere->getPositionArray(), true);
  8203.                     if ($locList == null)
  8204.                         $locList = [];
  8205.                     $entry_data json_decode($att->getData(), true);
  8206.                     if ($entry_data == null$entry_data = [];
  8207.                     $lastLat 0;
  8208.                     $lastLng 0;
  8209.                     foreach ($locList as $lg) {
  8210.                         $dist 0;
  8211.                         if (isset($lg['lat'])) {
  8212.                             if ($lastLat == 0) {
  8213.                                 $lastLat $lg['lat'];
  8214.                                 $lastLng $lg['lng'];
  8215.                             }
  8216.                             $theta $lastLng $lg['lng'];
  8217.                             $dist sin(deg2rad($lastLat)) * sin(deg2rad($lg['lat'])) + cos(deg2rad($lastLat)) * cos(deg2rad($lg['lat'])) * cos(deg2rad($theta));
  8218.                             $dist acos($dist);
  8219.                             $dist rad2deg($dist);
  8220.                             $miles $dist 60 1.1515;
  8221.                             $dist $miles 1609.344;
  8222.                             if (abs($dist) > 1000) {
  8223.                                 $locations[] = array(
  8224.                                     'ts' => $lg['ts'],
  8225.                                     'lat' => $lg['lat'],
  8226.                                     'lng' => $lg['lng'],
  8227.                                 );
  8228.                                 $lastLat $lg['lat'];
  8229.                                 $lastLng $lg['lng'];
  8230.                             }
  8231.                         }
  8232.                     }
  8233.                     $attData['locations'] = $locations;
  8234.                     $attData['entryData'] = $entry_data;
  8235.                     $existingData[$att->getDate()->format('U')] = $attData;
  8236.                 }
  8237.             }
  8238.             $returnData = array(
  8239.                 'page_title' => 'Bulk Attendance',
  8240.                 'existingData' => $existingData,
  8241.                 'startDateTs' => $startDateTs,
  8242.                 'endDateTs' => $endDateTs,
  8243.             );
  8244.             return new JsonResponse($returnData);
  8245.         } else
  8246.             return $this->render('ApplicationBundle:pages/human_resource/attendance:bulk_attendance.html.twig'$returnData);
  8247.     }
  8248.     public function CreateAttendanceAmendmentAction(Request $request$id 0)
  8249.     {
  8250.         $em $this->getDoctrine()->getManager();
  8251.         $companyId $this->getLoggedUserCompanyId($request);
  8252.         $extDocData = [];
  8253.         if ($request->isMethod('POST')) {
  8254.             $em $this->getDoctrine()->getManager();
  8255.             $entity_id array_flip(GeneralConstant::$Entity_list)['AttendanceAmendment']; //change
  8256.             $dochash $request->request->get('docHash'); //change
  8257.             $loginId $request->getSession()->get(UserConstants::USER_LOGIN_ID);
  8258.             $approveRole $request->request->get('approvalRole');
  8259.             $approveHash $request->request->get('approvalHash');
  8260.             if ($dochash == '') {
  8261.                 $numberHash MiscActions::GetNumberHash($em'ATAM'$request->request->get('prefix_hash'$request->request->get('employeeId'0)), $request->request->get('assoc_hash'0), ''1);
  8262.                 $dochash 'ATAM' '/' $request->request->get('prefix_hash'$request->request->get('employeeId'0)) . '/' $request->request->get('assoc_hash'0) . '/' $numberHash;
  8263.             } else
  8264.                 $numberHash $request->request->get('number_hash');
  8265.             if (!DocValidation::isInsertable($em$entity_id$dochash,
  8266.                 $loginId$approveRole$approveHash$id)
  8267.             ) {
  8268.                 if ($request->request->has('returnJson')) {
  8269.                     return new JsonResponse(array(
  8270.                         'success' => false,
  8271.                         'documentHash' => 0,
  8272.                         'documentId' => 0,
  8273.                     ));
  8274.                 } else
  8275.                     $this->addFlash(
  8276.                         'error',
  8277.                         'Sorry Could not insert Data.'
  8278.                     );
  8279.             } else {
  8280.                 $funcname 'AttendanceAmendment';
  8281.                 $doc_id $id;
  8282.                 DeleteDocument::$funcname($em$doc_id0);
  8283.                 $attendanceAmendment = new AttendanceAmendment();
  8284.                 $attendanceAmendment->setDocumentHash($dochash);
  8285.                 $attendanceAmendment->setAttendanceAmendmentDate(new \DateTime($request->request->get('docDate''')));
  8286.                 $attendanceAmendment->setStartDate(new \DateTime($request->request->get('startDate''')));
  8287.                 $attendanceAmendment->setEndDate(new \DateTime($request->request->get('endDate''')));
  8288.                 $attendanceAmendment->setTypeHash('ATAM');
  8289.                 $attendanceAmendment->setPrefixHash($request->request->get('prefix_hash'0));
  8290.                 $attendanceAmendment->setAssocHash($request->request->get('assoc_hash'0));
  8291.                 $attendanceAmendment->setNumberHash($numberHash);
  8292.                 $attendanceAmendment->setCreatedLoginId($request->getSession()->get(UserConstants::USER_LOGIN_ID));
  8293.                 $attendanceAmendment->setApproved(array_flip(GeneralConstant::$approvalStatus)['pending']);
  8294.                 $attendanceAmendment->setAutoCreated($request->request->get('fullApprove'0));
  8295.                 $attendanceAmendment->setEmployeeId($request->request->get('forcedEmployeeId'$request->request->get('employeeId'0)));
  8296. //                $attendanceAmendment->setAutocreated(0);
  8297.                 if ($request->request->has('dataArrayJson')) {
  8298.                     $attendanceAmendment->setData($request->request->get('dataArrayJson''[]'));
  8299.                 } else {
  8300.                     $arr = [
  8301.                     ];
  8302.                     //dump($arr);
  8303.                     foreach ($request->request->get('date', []) as $key => $val) {
  8304.                         if ($request->request->get('isChanged')[$key] == 1) {
  8305.                             $dt = array(
  8306.                                 'enabled' => 1,
  8307.                                 'attId' => $request->request->get('attId')[$key],
  8308.                                 'note' => $request->request->get('note')[$key],
  8309.                                 'startTimeTs' => $request->request->get('startTimeTs')[$key],
  8310.                                 'endTimeTs' => $request->request->get('endTimeTs')[$key],
  8311.                                 'totalWorkHour' => $request->request->get('totalWorkHour')[$key],
  8312.                                 'entryDataIn' => json_decode($request->request->get('entryDataIn')[$key], true),
  8313.                                 'entryDataOut' => json_decode($request->request->get('entryDataOut')[$key], true),
  8314.                             );
  8315.                             $arr[$val] = $dt;
  8316.                         }
  8317.                     }
  8318.                     $attendanceAmendment->setData(json_encode($arr));
  8319.                 }
  8320.                 $em->persist($attendanceAmendment);
  8321.                 $em->flush();
  8322.                 $ID $attendanceAmendment->getAttendanceAmendmentId();
  8323.                 //now add Approval info
  8324.                 $loginId $request->getSession()->get(UserConstants::USER_LOGIN_ID);
  8325.                 $approveRole 1;  //created
  8326.                 $options = array(
  8327.                     'notification_enabled' => $this->container->getParameter('notification_enabled'),
  8328.                     'notification_server' => $this->container->getParameter('notification_server'),
  8329.                     'appId' => $request->getSession()->get(UserConstants::USER_APP_ID),
  8330.                     'url' => $this->generateUrl(
  8331.                         GeneralConstant::$Entity_list_details[array_flip(GeneralConstant::$Entity_list)['AttendanceAmendment']]
  8332.                         ['entity_view_route_path_name']
  8333.                     )
  8334.                 );
  8335.                 System::setApprovalInfo($this->getDoctrine()->getManager(), $options,
  8336.                     array_flip(GeneralConstant::$Entity_list)['AttendanceAmendment'],
  8337.                     $ID,
  8338.                     $request->getSession()->get(UserConstants::USER_LOGIN_ID)    //journal voucher
  8339.                 );
  8340.                 if ($request->request->get('fullApprove'0) == 1) {
  8341.                     DeleteDocument::AttendanceAmendment($em$ID);
  8342.                 } else {
  8343.                     System::createEditSignatureHash($this->getDoctrine()->getManager(), array_flip(GeneralConstant::$Entity_list)['AttendanceAmendment'], $ID,
  8344.                         $loginId,
  8345.                         $approveRole,
  8346.                         $request->request->get('approvalHash'));
  8347.                     $url $this->generateUrl(
  8348.                         'view_attendance_amendment'
  8349.                     );
  8350.                     if ($request->request->has('returnJson')) {
  8351.                         return new JsonResponse(array(
  8352.                             'success' => true,
  8353.                             'documentHash' => $dochash,
  8354.                             'documentId' => $ID,
  8355.                             'viewUrl' => $url "/" $ID,
  8356.                         ));
  8357.                     } else {
  8358.                         $this->addFlash(
  8359.                             'success',
  8360.                             'Attendance Amendment Note Added.'
  8361.                         );
  8362.                         return $this->redirect($url "/" $ID);
  8363.                     }
  8364.                 }
  8365.             }
  8366.         }
  8367.         if ($id == 0) {
  8368.         } else {
  8369.             $extDoc $em->getRepository('ApplicationBundle:AttendanceAmendment')->findOneBy(
  8370.                 array(
  8371.                     'salesOrderId' => $id///material
  8372.                 )
  8373.             );
  8374.             //now if its not editable, redirect to view
  8375.             if ($extDoc) {
  8376.                 if ($extDoc->getEditFlag() != 1) {
  8377.                     $url $this->generateUrl(
  8378.                         'view_attendance_amendment'
  8379.                     );
  8380.                     return $this->redirect($url "/" $id);
  8381.                 } else {
  8382.                     $extDocData $extDoc;
  8383.                 }
  8384.             } else {
  8385.             }
  8386.         }
  8387.         $startDate $request->query->get('start_date''');
  8388.         $endDate $request->query->get('end_date''');
  8389.         $employeeId $request->query->get('employee_id'0);
  8390.         $existingData = [];
  8391.         $startDateTs 0;
  8392.         $endDateTs 0;
  8393.         $returnData = array(
  8394.             'page_title' => 'Attendance Amendment',
  8395.             'existingData' => $existingData,
  8396.             'startDateTs' => $startDateTs,
  8397.             'extDocData' => $extDocData,
  8398.             'endDateTs' => $endDateTs,
  8399.         );
  8400.         if ($request->query->has('returnJson')) {
  8401.             if ($startDate != '' && $endDate != '' && $employeeId != 0) {
  8402.                 $startDateDt = new \DateTime($startDate);
  8403.                 $endDateDt = new \DateTime($endDate);
  8404.                 $startDateTs $startDateDt->format('U');
  8405.                 $endDateTs $endDateDt->format('U');
  8406.                 $attendanceQuery $em->getRepository('ApplicationBundle:EmployeeAttendance')
  8407.                     ->createQueryBuilder('p')
  8408.                     ->where("p.employeeId = " $employeeId)
  8409. //                ->andWhere("p.date => '" . ($startDateDt->format('Y-m-d'))."'")
  8410.                     ->andWhere("p.date <= :last")
  8411.                     ->andWhere("p.date >= :start")
  8412.                     ->setParameter('start'$startDateDt)
  8413.                     ->setParameter('last'$endDateDt);
  8414.                 $attendanceResults $attendanceQuery->getQuery()->getResult();
  8415.                 foreach ($attendanceResults as $att) {
  8416.                     $entryDateTime null;
  8417.                     $outDateTime null;
  8418.                     if ($att->getEntry()) $entryDateTime = new \DateTime($att->getDate()->format('Y-m-d') . ' ' $att->getEntry()->format('H:i:00 +0000'));
  8419.                     if ($att->getLastOut()) $outDateTime = new \DateTime($att->getDate()->format('Y-m-d') . ' ' $att->getLastOut()->format('H:i:00 +0000'));
  8420.                     $attData = array(
  8421.                         'id' => $att->getId(),
  8422.                         'date_str' => $att->getDate()->format('Y-m-d'),
  8423.                         'date_str_full' => $att->getDate()->format('Y-m-d H:i:s'),
  8424.                         'in_time_full' => $entryDateTime $entryDateTime->format(DATE_RFC2822) : '',
  8425.                         'date_ts' => $att->getDate()->format('U'),
  8426.                         'in_time' => $entryDateTime $entryDateTime->format('H:i:s') : '',
  8427.                         'in_time_ts' => $entryDateTime $entryDateTime->format('U') : 0,
  8428.                         'last_out_time' => $outDateTime $outDateTime->format('H:i:s') : '',
  8429.                         'last_out_time_ts' => $outDateTime $outDateTime->format('U') : '',
  8430.                     );
  8431.                     $locations = [];
  8432.                     $locList = [];
  8433.                     $logHere $em->getRepository('ApplicationBundle:EmployeeAttendanceLog')->findOneBy(array(
  8434.                         'attendance_id' => $att->getId(),
  8435.                     ));
  8436.                     if ($logHere)
  8437.                         $locList json_decode($logHere->getPositionArray(), true);
  8438.                     if ($locList == null)
  8439.                         $locList = [];
  8440.                     $entry_data json_decode($att->getData(), true);
  8441.                     if ($entry_data == null$entry_data = [];
  8442.                     $lastLat 0;
  8443.                     $lastLng 0;
  8444.                     foreach ($locList as $lg) {
  8445.                         $dist 0;
  8446.                         if (isset($lg['lat'])) {
  8447.                             if ($lastLat == 0) {
  8448.                                 $lastLat $lg['lat'];
  8449.                                 $lastLng $lg['lng'];
  8450.                             }
  8451.                             $theta $lastLng $lg['lng'];
  8452.                             $dist sin(deg2rad($lastLat)) * sin(deg2rad($lg['lat'])) + cos(deg2rad($lastLat)) * cos(deg2rad($lg['lat'])) * cos(deg2rad($theta));
  8453.                             $dist acos($dist);
  8454.                             $dist rad2deg($dist);
  8455.                             $miles $dist 60 1.1515;
  8456.                             $dist $miles 1609.344;
  8457.                             if (abs($dist) > 1000) {
  8458.                                 $locations[] = array(
  8459.                                     'ts' => $lg['ts'],
  8460.                                     'lat' => $lg['lat'],
  8461.                                     'lng' => $lg['lng'],
  8462.                                 );
  8463.                                 $lastLat $lg['lat'];
  8464.                                 $lastLng $lg['lng'];
  8465.                             }
  8466.                         }
  8467.                     }
  8468.                     $attData['locations'] = $locations;
  8469.                     $attData['entryData'] = $entry_data;
  8470.                     $existingData[$att->getDate()->format('U')] = $attData;
  8471.                 }
  8472.             }
  8473.             $returnData = array(
  8474.                 'page_title' => 'Attendance Amendment',
  8475.                 'existingData' => $existingData,
  8476.                 'startDateTs' => $startDateTs,
  8477.                 'extDocData' => $extDocData,
  8478.                 'endDateTs' => $endDateTs,
  8479.             );
  8480.             return new JsonResponse($returnData);
  8481.         } else
  8482.             return $this->render('ApplicationBundle:pages/human_resource/attendance:create_attendance_amendment.html.twig'$returnData);
  8483.     }
  8484.     public function AttendanceAmendmentListAction(Request $request)
  8485.     {
  8486.         $data = [];
  8487.         return $this->render('ApplicationBundle:pages/human_resource/list:attendance_amendment_list.html.twig',
  8488.             array(
  8489.                 'page_title' => 'Attendance Amendment List',
  8490.                 'data' => $data
  8491.             )
  8492.         );
  8493.     }
  8494.     public function ViewAttendanceAmendmentAction(Request $request$id)
  8495.     {
  8496.         $em $this->getDoctrine()->getManager();
  8497.         $dt HumanResource::GetAttendanceAmendmentDetails($em$id);
  8498.         return $this->render('ApplicationBundle:pages/human_resource/views:view_attendance_amendment.html.twig',
  8499.             array(
  8500.                 'page_title' => 'Attendance Amendment',
  8501.                 'data' => $dt,
  8502.                 'approval_data' => System::checkIfApprovalExists($emarray_flip(GeneralConstant::$Entity_list)['AttendanceAmendment'],
  8503.                     $id$request->getSession()->get(UserConstants::USER_LOGIN_ID)),
  8504.                 'document_log' => System::getDocumentLog($this->getDoctrine()->getManager(),
  8505.                     array_flip(GeneralConstant::$Entity_list)['AttendanceAmendment'],
  8506.                     $id,
  8507.                     $dt['created_by'],
  8508.                     $dt['edited_by'])
  8509.             )
  8510.         );
  8511.     }
  8512.     public function PrintAttendanceAmendmentAction(Request $request$id)
  8513.     {
  8514.         $em $this->getDoctrine()->getManager();
  8515.         $dt HumanResource::GetAttendanceAmendmentDetails($em$id);
  8516.         $company_data Company::getCompanyData($em1);
  8517.         $document_mark = array(
  8518.             'original' => '/images/Original-Stamp-PNG-Picture.png',
  8519.             'copy' => ''
  8520.         );
  8521.         if ($request->query->has('pdf') && $this->get('knp_snappy.pdf')) {
  8522.             $html $this->renderView('@Inventory/pages/print/print_stock_received_note.html.twig',
  8523.                 array(
  8524.                     //full array here
  8525.                     'pdf' => true,
  8526.                     'page_title' => 'Stock Received Note',
  8527.                     'export' => 'pdf,print',
  8528.                     'data' => $dt,
  8529.                     'approval_data' => System::checkIfApprovalExists($emarray_flip(GeneralConstant::$Entity_list)['AttendanceAmendment'],
  8530.                         $id$request->getSession()->get(UserConstants::USER_LOGIN_ID)),
  8531.                     'document_log' => System::getDocumentLog($this->getDoctrine()->getManager(),
  8532.                         array_flip(GeneralConstant::$Entity_list)['AttendanceAmendment'],
  8533.                         $id,
  8534.                         $dt['created_by'],
  8535.                         $dt['edited_by']),
  8536.                     'document_mark_image' => $document_mark['original'],
  8537.                     'company_name' => $company_data->getName(),
  8538.                     'company_data' => $company_data,
  8539.                     'company_address' => $company_data->getAddress(),
  8540.                     'company_image' => $company_data->getImage(),
  8541.                     'invoice_footer' => $company_data->getInvoiceFooter(),
  8542.                     'red' => 0
  8543.                 )
  8544.             );
  8545.             $pdf_response $this->get('knp_snappy.pdf')->getOutputFromHtml($html, array(
  8546. //                'orientation' => 'landscape',
  8547. //                'enable-javascript' => true,
  8548. //                'javascript-delay' => 1000,0
  8549.                 'no-stop-slow-scripts' => false,
  8550.                 'no-background' => false,
  8551.                 'lowquality' => false,
  8552.                 'encoding' => 'utf-8',
  8553. //            'images' => true,
  8554. //            'cookie' => array(),
  8555.                 'dpi' => 300,
  8556.                 'image-dpi' => 300,
  8557. //                'enable-external-links' => true,
  8558. //                'enable-internal-links' => true
  8559.             ));
  8560.             return new Response(
  8561.                 $pdf_response,
  8562.                 200,
  8563.                 array(
  8564.                     'Content-Type' => 'application/pdf',
  8565.                     'Content-Disposition' => 'attachment; filename="stock_received_note_' $id '.pdf"'
  8566.                 )
  8567.             );
  8568.         }
  8569.         return $this->render('ApplicationBundle:pages/human_resource/views:view_attendance_amendment.html.twig',
  8570.             array(
  8571.                 'page_title' => 'Attendance Amendment',
  8572.                 'data' => $dt,
  8573.                 'approval_data' => System::checkIfApprovalExists($emarray_flip(GeneralConstant::$Entity_list)['AttendanceAmendment'],
  8574.                     $id$request->getSession()->get(UserConstants::USER_LOGIN_ID)),
  8575.                 'document_log' => System::getDocumentLog($this->getDoctrine()->getManager(),
  8576.                     array_flip(GeneralConstant::$Entity_list)['AttendanceAmendment'],
  8577.                     $id,
  8578.                     $dt['created_by'],
  8579.                     $dt['edited_by'])
  8580.             )
  8581.         );
  8582.     }
  8583.     public function createRoomAction(Request $request)
  8584.     {
  8585.         $em $this->getDoctrine()->getManager();
  8586.         $companyId $this->getLoggedUserCompanyId($request);
  8587.         if ($request->isMethod('POST')) {
  8588.             $loginId $request->getSession()->get(UserConstants::USER_LOGIN_ID);
  8589.             $room = new Room;
  8590.             $room->setRoomNo($request->request->get('RoomNo'));
  8591.             //$room->setRoomName($request->request->get('RoomName'));
  8592.             $room->setBuilding($request->request->get('buildingName'));
  8593.             $room->setFloor($request->request->get('floor'));
  8594.             $room->setCapacity($request->request->get('capacity'));
  8595.             $room->setCreatedLoginId($request->getSession()->get(UserConstants::USER_LOGIN_ID));
  8596.             $em->persist($room);
  8597.             $em->flush();
  8598.         }
  8599.         return $this->render('ApplicationBundle:pages/human_resource/input_forms:create_room.html.twig', array(
  8600.             'page_title' => 'Add Room',
  8601.         ));
  8602.     }
  8603.     public function ExpenseTypeAction()
  8604.     {
  8605.         $expenseType HumanResourceConstant::$employeeExpenseAllowanceTypes;
  8606.         $expenseTypeArray = [];
  8607.         foreach ($expenseType as $k => $dt) {
  8608.             $dt['id'] = $k;
  8609.             $newSegs = [];
  8610.             foreach ($dt['segregations'] as $l => $s) {
  8611.                 $newOptions = [];
  8612.                 foreach ($s['options'] as $l2 => $s2) {
  8613.                     $s3 = array(
  8614.                         'value' => $l2,
  8615.                         'text' => $s2,
  8616.                     );
  8617.                     $newOptions[] = $s3;
  8618.                 }
  8619.                 $s['options'] = $newOptions;
  8620.                 if (is_string($s['defaultVal'])) $s['defaultVal'] = [$s['defaultVal']];
  8621.                 $newSegs[] = $s;
  8622.             }
  8623.             $dt['segregations'] = $newSegs;
  8624.             $expenseTypeArray[] = $dt;
  8625.         }
  8626.         return new JsonResponse(
  8627.             array(
  8628.                 'success' => true,
  8629.                 'expenseType' => $expenseType,
  8630.                 'expenseTypeArray' => $expenseTypeArray,
  8631.             )
  8632.         );
  8633.     }
  8634.     public function DemoDataTableAction()
  8635.     {
  8636.         return $this->render('ApplicationBundle:pages/human_resource/list:demo_data_table.html.twig', array(
  8637.             'page_title' => 'Add Room',
  8638.         ));
  8639.     }
  8640.     public function workEnrtyAction(Request $request)
  8641.     {
  8642. //        $em = $this->getDoctrine()->getManager();
  8643. //        $companyId = $this->getLoggedUserCompanyId($request);
  8644. //        if ($request->isMethod('POST')) {
  8645. //            $loginId = $request->getSession()->get(UserConstants::USER_LOGIN_ID);
  8646. //            $labour = new Labour();
  8647. //            $labour->setLabourName($request->request->get('labourName'));
  8648. //            $labour->setNidNumber($request->request->get('nidNumber'));
  8649. //            $em->persist($labour);
  8650. //            $em->flush();
  8651. //            $this->addFlash(
  8652. //                'success',
  8653. //                'Labour Added'
  8654. //            );
  8655. //        }
  8656.         return $this->render('ApplicationBundle:pages/human_resource/input_forms:work_entry.html.twig', array(
  8657.             'page_title' => 'Work Entry',
  8658.         ));
  8659.     }
  8660.     public function ViewContractLetterAction(Request $request$id)
  8661.     {
  8662.         $em $this->getDoctrine()->getManager();
  8663.         $employeeDetail $em->getRepository('ApplicationBundle:EmployeeDetails')->find($id);
  8664. //        $employeeData = [];
  8665. //        foreach ($employeeDetails as $employeeDetail) {
  8666. //            $data = array(
  8667. //                'firstName' => $employeeDetail->getNid(),
  8668. //
  8669. //
  8670. //
  8671. //            );
  8672. //
  8673. //
  8674. //            $employeeData[] = $data;
  8675. //        }
  8676.         return $this->render('ApplicationBundle:pages/human_resource/views:viewContractLetter.html.twig', array(
  8677.             'page_title' => 'Contract Letter',
  8678.             'employeeDetail' => $employeeDetail
  8679.         ));
  8680.     }
  8681.     public function getAttendanceReportForEmployeeAction(Request $request)
  8682.     {
  8683.         $em $this->getDoctrine()->getManager();
  8684.         $session $request->getSession();
  8685.         $fromDateRow = (new \DateTime($request->get('start_date''')));
  8686. //        $fromDate = $fromDateRow->format("M d, Y");
  8687.         $toDateRow = (new \DateTime($request->get('end_date'$fromDateRow) . ' 23:59:59'));
  8688. //        $toDate = $toDateRow->format("M d, Y");
  8689. //        $startDate = "2025-02-13";
  8690. //        $endDate = "2025-02-16";
  8691.         $userId $session->get(UserConstants::USER_ID);
  8692.         $attendanceDetails $em->getRepository('ApplicationBundle:EmployeeAttendance')->createQueryBuilder('A')
  8693. //            ->select('A.createdAt','A.data')
  8694.             ->where('A.sysId = :userId')
  8695.             ->andWhere('A.createdAt >=  :startDate')
  8696.             ->andWhere('A.createdAt <=  :endDate')
  8697.             ->setParameter('userId'$userId)
  8698.             ->setParameter('startDate'$fromDateRow)
  8699.             ->setParameter('endDate'$toDateRow)
  8700.             ->getQuery()
  8701.             ->getResult();
  8702.         $attendance = [];
  8703.         $dt = [];
  8704.         foreach ($attendanceDetails as $data) {
  8705.             $in_out_data json_decode($data->getData(), true);
  8706.             $new_in_data = [];
  8707.             $elapsed_data = [];
  8708.             $new_out_data = [];
  8709.             if ($in_out_data == null$in_out_data = [];
  8710.             if (isset($in_out_data['in'])) {
  8711.                 foreach ($in_out_data['in'] as $ind => $g) {
  8712.                     if (!isset($elapsed_data[$ind])) {
  8713.                         $elapsed_data[$ind] = 0;
  8714.                     }
  8715.                     $the_time = new \DateTime($data->getDate()->format('Y-m-d ') . $g ' +0000');
  8716.                     $new_in_data[] = $the_time->format('U');
  8717.                 }
  8718.             }
  8719.             if (isset($in_out_data['out'])) {
  8720.                 foreach ($in_out_data['out'] as $ind => $g) {
  8721.                     if (!isset($elapsed_data[$ind])) {
  8722.                         $elapsed_data[$ind] = 0;
  8723.                     }
  8724.                     $the_time = new \DateTime($data->getDate()->format('Y-m-d ') . $g ' +0000');
  8725.                     $new_out_data[] = $the_time->format('U');
  8726.                     if (isset($new_in_data[$ind])) {
  8727.                         $elapsed_data[$ind] = $new_out_data[$ind] - $new_in_data[$ind];
  8728.                     }
  8729.                 }
  8730.             }
  8731.             $list = array(
  8732.                 'date' => $data->getDate()->format('F d Y'),
  8733.                 'attendanceData' => [
  8734.                     'in' => $new_in_data,
  8735.                     'out' => $new_out_data,
  8736.                     'elapsedSec' => $elapsed_data,
  8737.                 ]
  8738.             );
  8739.             $dt[] = $list;
  8740.         }
  8741.         $count count($attendance);
  8742. //        for ($i=0;$i < $count; $i++){
  8743. //            $dt[] = $attendance[$i]['date'];
  8744. //            $dt[] = ($attendance[$i]['attendanceData']);
  8745. //        }
  8746. ////        $decodeData = json_decode($dt, true);
  8747. //
  8748. //        $work_hours = [];
  8749. //
  8750. //        foreach ($dt as $index => $entry) {
  8751. //            $in_times = $entry['in'];
  8752. //            $out_times = $entry['out'];
  8753. //
  8754. //
  8755. //            $count = min(count($in_times), count($out_times));
  8756. //
  8757. //            for ($i = 0; $i < $count; $i++) {
  8758. //                $time_in = new DateTime($in_times[$i]);
  8759. //                $time_out = new DateTime($out_times[$i]);
  8760. //
  8761. //
  8762. //                $interval = $time_in->diff($time_out);
  8763. //                $total_hours = $interval->format('%h');
  8764. //                $total_minutes = $interval->format('%i');
  8765. //
  8766. //
  8767. //                $work_hours[] = [
  8768. ////                    "set" => $index + 1,
  8769. //                    "in" => $in_times[$i],
  8770. //                    "out" => $out_times[$i],
  8771. //                    "worked" => "$total_hours hours, $total_minutes minutes"
  8772. //                ];
  8773. //            }
  8774. //        }
  8775. //
  8776. ////        foreach ($work_hours as $work) {
  8777. ////           return new  JsonResponse(
  8778. ////               array(
  8779. ////                   'in'=>$work['in'],
  8780. ////                   'out' => $work['out'],
  8781. ////                   'hour' => $work['worked']
  8782. ////               )
  8783. ////           ) ;
  8784. //////            echo "Set {$work['set']} - IN: {$work['in']} - OUT: {$work['out']} => Worked: {$work['worked']}\n";
  8785. ////        }
  8786.         return new JsonResponse($dt);
  8787.     }
  8788.     public function getTotalWorkHourAction(Request $request)
  8789.     {
  8790.         $em $this->getDoctrine()->getManager();
  8791.         $currentDate = new \DateTime(date('y-m-d'));
  8792.         $session $request->getSession();
  8793.         $token $session->get(UserConstants::USER_TOKEN);
  8794.         $employeeId $session->get(UserConstants::USER_EMPLOYEE_ID);
  8795.         $planningItemId $session->get(UserConstants::USER_CURRENT_PLANNING_ITEM_ID);
  8796.         $attendanceData $em->getRepository('ApplicationBundle:EmployeeAttendance');
  8797.         $currentStatus HumanResource::getCurrentStatusFromDb($attendanceData$employeeId$currentDate);
  8798.         $providedToken $request->headers->get('auth-token');
  8799.         if (empty($providedToken) || $providedToken !== $token) {
  8800.             return new JsonResponse([
  8801.                 'status' => 'error',
  8802.                 'message' => 'Token not match or missing',
  8803.             ], 401);
  8804.         }
  8805.         $planningItemDetails $em->getRepository(PlanningItem::class)->createQueryBuilder('p')
  8806.             ->select('p.itemAlias')
  8807.             ->where('p.id = :planningItemId')
  8808.             ->setParameter('planningItemId'$planningItemId)
  8809.             ->getQuery()
  8810.             ->getResult();
  8811.         // Check if "data" key exists and contains "in" times
  8812.         if (empty($currentStatus["data"]["in"])) {
  8813.             return new JsonResponse([
  8814. //                'message' => 'No attendance data available',
  8815.                 'currentStatus' => $currentStatus,
  8816.                 'totalWorkingTime' => '00:00:00'
  8817.             ]);
  8818.         }
  8819.         $totalSeconds 0;
  8820.         for ($i 0$i count($currentStatus["data"]["in"]); $i++) {
  8821.             $inTime $currentStatus["data"]["in"][$i];
  8822.             // Check if "out" time exists for this "in" time
  8823.             if (!isset($currentStatus["data"]["out"][$i])) {
  8824.                 continue; // Skip this entry if there is no out time
  8825.             }
  8826.             $outTime $currentStatus["data"]["out"][$i];
  8827.             // Calculate the difference
  8828.             $totalSeconds += ($outTime $inTime);
  8829.         }
  8830.         // If no valid time pairs were found, return 00:00:00
  8831. //        if ($totalSeconds == 0) {
  8832. //            return new JsonResponse([
  8833. //                'message' => 'No complete in-out records found',
  8834. //                'totalWorkingTime' => '00:00:00'
  8835. //            ]);
  8836. //        }
  8837.         // Convert total seconds to hours, minutes, and seconds
  8838.         $hours floor($totalSeconds 3600);
  8839.         $minutes floor(($totalSeconds 3600) / 60);
  8840.         $seconds $totalSeconds 60;
  8841.         $totalWorkingTime sprintf("%02d:%02d:%02d"$hours$minutes$seconds);
  8842.         return new JsonResponse([
  8843.             'taskName' => isset($planningItemDetails[0]) ? $planningItemDetails[0]['itemAlias'] : '',
  8844.             'currentStatus' => $currentStatus,
  8845.             'totalWorkingTime' => $totalWorkingTime,
  8846.         ]);
  8847.     }
  8848. //    public function getEmployeeDataAction(Request $request)
  8849. //    {
  8850. //        $em = $this->getDoctrine()->getManager();
  8851. //        $session = $request->getSession();
  8852. //        $employeeId = $session->get(UserConstants::USER_EMPLOYEE_ID);
  8853. //
  8854. //
  8855. //        $employeeDetails = $em->getRepository('ApplicationBundle:EmployeeDetails')->createQueryBuilder('E')
  8856. //            ->select('E.firstname', 'E.lastname', 'E.nid', 'E.tin','E.image', 'P.positionName')
  8857. //            ->addSelect('A.current_balance')
  8858. //            ->leftJoin('ApplicationBundle:SysDepartmentPosition', 'P', 'WITH', 'E.desg = P.positionId')
  8859. //            ->leftJoin('ApplicationBundle:Employee', 'EMP', 'WITH', 'EMP.employeeId = E.id')
  8860. //            ->leftJoin('ApplicationBundle:AccAccountsHead', 'A', 'WITH', 'EMP.accountsHeadId = A.accountsHeadId')
  8861. //            ->where('E.id = :employeeId')
  8862. //            ->setParameter('employeeId', $employeeId)
  8863. //            ->getQuery()
  8864. //            ->getResult();
  8865. //
  8866. //        return new JsonResponse($employeeDetails[0]);
  8867. //    }
  8868. //    public function getEmployeeDataAction(Request $request)
  8869. //    {
  8870. //        $em = $this->getDoctrine()->getManager();
  8871. //        $session = $request->getSession();
  8872. //        $employeeId = $session->get(UserConstants::USER_EMPLOYEE_ID);
  8873. //        $image = $session->get(UserConstants::USER_IMAGE);
  8874. //        $absoluteUrl = $this->generateUrl('dashboard', [], UrlGenerator::ABSOLUTE_URL);
  8875. //
  8876. //        $employeeDetails = $em->getRepository('ApplicationBundle:EmployeeDetails')->createQueryBuilder('E')
  8877. //            ->select('E.firstname', 'E.lastname', 'E.nid', 'E.tin', 'E.image', 'P.positionName')
  8878. //            ->addSelect('A.current_balance')
  8879. //            ->leftJoin('ApplicationBundle:SysDepartmentPosition', 'P', 'WITH', 'E.desg = P.positionId')
  8880. //            ->leftJoin('ApplicationBundle:Employee', 'EMP', 'WITH', 'EMP.employeeId = E.id')
  8881. //            ->leftJoin('ApplicationBundle:AccAccountsHead', 'A', 'WITH', 'EMP.accountsHeadId = A.accountsHeadId')
  8882. //            ->where('E.id = :employeeId')
  8883. //            ->setParameter('employeeId', $employeeId)
  8884. //            ->getQuery()
  8885. //            ->getResult();
  8886. //
  8887. //        // If image is null or empty, assign empty string
  8888. //        if (empty($employeeDetails['image'])) {
  8889. //            $employeeDetails['image'] =  $image;
  8890. //        }
  8891. //
  8892. //        return new JsonResponse($employeeDetails);
  8893. //    }
  8894.     public function getEmployeeDataAction(Request $request)
  8895.     {
  8896.         $em $this->getDoctrine()->getManager();
  8897.         $session $request->getSession();
  8898.         $employeeId $session->get(UserConstants::USER_EMPLOYEE_ID);
  8899.         $image $session->get(UserConstants::USER_IMAGE);
  8900.         $absoluteUrl $this->generateUrl('dashboard', [], UrlGenerator::ABSOLUTE_URL);
  8901.         $userImage $session->get(UserConstants::USER_IMAGE);
  8902.         $employeeDetails $em->getRepository('ApplicationBundle:EmployeeDetails')->createQueryBuilder('E')
  8903.             ->select('E.firstname''E.lastname''E.nid''E.tin''E.image''P.positionName')
  8904.             ->addSelect('A.current_balance')
  8905.             ->leftJoin('ApplicationBundle:SysDepartmentPosition''P''WITH''E.desg = P.positionId')
  8906.             ->leftJoin('ApplicationBundle:Employee''EMP''WITH''EMP.employeeId = E.id')
  8907.             ->leftJoin('ApplicationBundle:AccAccountsHead''A''WITH''EMP.accountsHeadId = A.accountsHeadId')
  8908.             ->where('E.id = :employeeId')
  8909.             ->setParameter('employeeId'$employeeId)
  8910.             ->getQuery()
  8911.             ->getOneOrNullResult(\Doctrine\ORM\Query::HYDRATE_ARRAY); // Only one employee expected
  8912.         if (!$employeeDetails) {
  8913.             return new JsonResponse(['error' => 'Employee not found'], 404);
  8914.         }
  8915.         // If image is missing, fallback to session image
  8916.         if (empty($employeeDetails['image'])) {
  8917.             $employeeDetails['image'] = $image;
  8918.         }
  8919.         // If image is still available, prefix it with absolute URL
  8920.         if (!empty($employeeDetails['image'])) {
  8921.             $employeeDetails['image_url'] = $absoluteUrl '' $userImage;
  8922.         } else {
  8923.             $employeeDetails['image_url'] = ''// no image
  8924.         }
  8925.         return new JsonResponse($employeeDetails);
  8926.     }
  8927.     public function updateEmployeeDataForAppAction(Request $request)
  8928.     {
  8929.         $em $this->getDoctrine()->getManager();
  8930.         $session $request->getSession();
  8931.         $employeeId $session->get(UserConstants::USER_EMPLOYEE_ID);
  8932.         $employeeDetails $em->getRepository('ApplicationBundle:EmployeeDetails')->find($employeeId);
  8933.         if ($request->isMethod('POST')) {
  8934.             $firstname $request->request->get('firstname');
  8935.             $lastname $request->request->get('lastname');
  8936.             $nid $request->request->get('nid');
  8937.             $tin $request->request->get('tin');
  8938.             if ($firstname !== null) {
  8939.                 $employeeDetails->setFirstName($firstname);
  8940.             }
  8941.             if ($lastname !== null) {
  8942.                 $employeeDetails->setLastName($lastname);
  8943.             }
  8944.             if ($nid !== null) {
  8945.                 $employeeDetails->setNid($nid);
  8946.             }
  8947.             if ($tin !== null) {
  8948.                 $employeeDetails->setTin($tin);
  8949.             }
  8950.             $em->flush();
  8951.             return new JsonResponse(['success' => true]);
  8952.         }
  8953.         return new JsonResponse(['success' => false'message' => 'Invalid request method']);
  8954.     }
  8955. //    public function updateEmployeeDataForAppAction(Request $request){
  8956. //        $em = $this->getDoctrine()->getManager();
  8957. //        $session = $request->getSession();
  8958. //        $employeeId = $session->get(UserConstants::USER_EMPLOYEE_ID);
  8959. //        $employeeDetails = $em->getRepository('ApplicationBundle:EmployeeDetails')->find($employeeId);
  8960. //
  8961. //        if ($request->isMethod('POST')) {
  8962. //            $employeeDetails->setFirstName(($request->request->get('firstname',$employeeDetails->getFirstName())));
  8963. //            $employeeDetails->setLastName($request->request->get('lastname',$employeeDetails->getLastName()));
  8964. //            $employeeDetails->setNid($request->request->get('nid'),$employeeDetails->getNid());
  8965. //            $employeeDetails->setTin($request->request->get('tin'),$employeeDetails->getTin());
  8966. //
  8967. //            $em->flush(); //
  8968. //
  8969. //            return new JsonResponse(['success' => true]);
  8970. //        }
  8971. //
  8972. //
  8973. //    }
  8974.     public function leaveApplicationListForAppAction(Request $request)
  8975.     {
  8976.         $em $this->getDoctrine()->getManager();
  8977.         $session $request->getSession();
  8978.         $employeeId $session->get(UserConstants::USER_EMPLOYEE_ID);
  8979.         $leaveType HumanResourceConstant::$LeaveType;
  8980.         $approvalStatus GeneralConstant::$approvalAction;
  8981.         $leaveCategory HumanResourceConstant::$leavCategory;
  8982.         // Get page and limit from request (default: page=1, limit=10)
  8983.         $page max((int)$request->query->get('page'1), 1);
  8984.         $limit max((int)$request->query->get('limit'10), 1);
  8985.         $offset = ($page 1) * $limit;
  8986.         // Get total count
  8987.         $total $em->getRepository('ApplicationBundle:EmployeeLeaveApplication')
  8988.             ->createQueryBuilder('L')
  8989.             ->select('COUNT(L.employeeLeaveApplicationId)')
  8990.             ->where('L.employeeId = :employeeId')
  8991.             ->setParameter('employeeId'$employeeId)
  8992.             ->getQuery()
  8993.             ->getSingleScalarResult();
  8994.         // Get paginated results
  8995.         $leaveRecords $em->getRepository('ApplicationBundle:EmployeeLeaveApplication')
  8996.             ->createQueryBuilder('L')
  8997.             ->select(
  8998.                 'L.documentHash',
  8999.                 'L.employeeLeaveApplicationId',
  9000.                 'L.leaveStartDate',
  9001.                 'L.leaveEndDate',
  9002.                 'L.leaveTypeId',
  9003.                 'L.leaveCategory',
  9004.                 'L.approved',
  9005.                 'L.createdAt',
  9006.                 'L.alternateDate',
  9007.                 'L.leaveComment',
  9008.                 'L.createdAt',
  9009.                 'L.approved_by'
  9010.             )
  9011.             ->where('L.employeeId = :employeeId')
  9012.             ->setParameter('employeeId'$employeeId)
  9013.             ->setFirstResult($offset)
  9014.             ->setMaxResults($limit)
  9015.             ->orderBy('L.employeeLeaveApplicationId''DESC')   //
  9016.             ->getQuery()
  9017.             ->getResult();
  9018.         // Count total approved (approved = 1)
  9019.         $totalApproved $em->getRepository('ApplicationBundle:EmployeeLeaveApplication')
  9020.             ->createQueryBuilder('L')
  9021.             ->select('COUNT(L.employeeLeaveApplicationId)')
  9022.             ->where('L.employeeId = :employeeId')
  9023.             ->andWhere('L.approved = 1')
  9024.             ->setParameter('employeeId'$employeeId)
  9025.             ->getQuery()
  9026.             ->getSingleScalarResult();
  9027. // Count total pending (approved = 3)
  9028.         $totalPending $em->getRepository('ApplicationBundle:EmployeeLeaveApplication')
  9029.             ->createQueryBuilder('L')
  9030.             ->select('COUNT(L.employeeLeaveApplicationId)')
  9031.             ->where('L.employeeId = :employeeId')
  9032.             ->andWhere('L.approved = 3')
  9033.             ->setParameter('employeeId'$employeeId)
  9034.             ->getQuery()
  9035.             ->getSingleScalarResult();
  9036. // Count total cancelled (approved = 0)
  9037.         $totalCancelled $em->getRepository('ApplicationBundle:EmployeeLeaveApplication')
  9038.             ->createQueryBuilder('L')
  9039.             ->select('COUNT(L.employeeLeaveApplicationId)')
  9040.             ->where('L.employeeId = :employeeId')
  9041.             ->andWhere('L.approved = 0')
  9042.             ->setParameter('employeeId'$employeeId)
  9043.             ->getQuery()
  9044.             ->getSingleScalarResult();
  9045.         // Format the results
  9046.         $formattedData = [];
  9047.         foreach ($leaveRecords as $leave) {
  9048.             $formattedData[] = [
  9049.                 'documentHash' => $leave['documentHash'],
  9050.                 'employeeLeaveApplicationId' => $leave['employeeLeaveApplicationId'],
  9051.                 'leaveStartDate' => $leave['leaveStartDate'] ? $leave['leaveStartDate']->getTimestamp() : 0,
  9052.                 'leaveEndDate' => $leave['leaveEndDate'] ? $leave['leaveEndDate']->getTimestamp() : 0,
  9053.                 'leaveType' => $leaveType[$leave['leaveTypeId']] ?? 'Unknown',
  9054.                 'leaveCategory' => $leaveCategory[$leave['leaveCategory']] ?? 'Unknown',
  9055.                 'approved' => $approvalStatus[$leave['approved']] ?? 'Unknown',
  9056.                 'createdAt' => $leave['createdAt'] ? $leave['createdAt']->getTimestamp() : 0,
  9057.                 'alternateDate' => $leave['alternateDate'] ? $leave['alternateDate']->getTimestamp() : 0,
  9058.                 'note' => $leave['leaveComment'] ? $leave['leaveComment'] : '',
  9059.                 'appliedOn' => $leave['createdAt'] ? $leave['createdAt']->getTimestamp() : 0,
  9060.                 'approvedBy' => $leave['approved_by'] ? $leave['approved_by'] : 'automatically approved',
  9061.             ];
  9062.         }
  9063.         $employee $em->getRepository('ApplicationBundle:EmployeeDetails')
  9064.             ->find($employeeId);
  9065.         $totalLeaveBalance 0;
  9066.         for ($i 1$i <= 10$i++) {
  9067.             $getter "getLeave{$i}Tkn";
  9068.             $totalLeaveBalance +=$employee->$getter();
  9069.         }
  9070.         // Final response with pagination meta
  9071.         return new JsonResponse([
  9072.             'success' => true,
  9073.             'message' => 'Leave application list fetched successfully',
  9074.             'totalLeaveBalance' => (int) ($totalLeaveBalance ?? 0),
  9075.             'totalApproved' => (int) ($totalApproved ?? 0),
  9076.             'totalPending' => (int) ($totalPending ?? 0),
  9077.             'totalCancelled' => (int) ($totalCancelled ?? 0),
  9078.             'data' => $formattedData,
  9079.             'CurrentPage' => $page,
  9080.             'limit' => $limit,
  9081.             'total' =>$total,
  9082.         ]);
  9083.     }
  9084.     public function PublicProfilePageAction(Request $request)
  9085.     {
  9086.         return new JsonResponse(['success' => true]);
  9087.     }
  9088.     public function leaveSettingsAction(Request $request)
  9089.     {
  9090.         $em $this->getDoctrine()->getManager();
  9091.         if ($request->isMethod('POST')) {
  9092.             $ids $request->request->get('id', []);
  9093.             $leaveTitles $request->request->get('leaveTitle', []);
  9094.             $carryForwardTypes $request->request->get('carryForwardType', []);
  9095.             $carryForwardQtys $request->request->get('number', []);
  9096.             $totalLeaves $request->request->get('totalLeave', []);
  9097.             $resetFreqTypes $request->request->get('resetFrequencyType', []);
  9098.             $resetFreqQtys $request->request->get('resetFrequencyQty', []);
  9099.             $additionConditions $request->request->get('additionCondition', []);
  9100.             $additionDurations $request->request->get('additionConditionDuration', []);
  9101.             for ($i 0$i count($leaveTitles); $i++) {
  9102.                 if (
  9103.                     isset(
  9104.                         $carryForwardTypes[$i],
  9105.                         $carryForwardQtys[$i],
  9106.                         $totalLeaves[$i],
  9107.                         $resetFreqTypes[$i],
  9108.                         $resetFreqQtys[$i],
  9109.                         $additionConditions[$i],
  9110.                         $additionDurations[$i]
  9111.                     )
  9112.                 ) {
  9113.                     $id $ids[$i] ?? null;
  9114.                     $leaveSetting null;
  9115.                     if ($id) {
  9116.                         $leaveSetting $em->getRepository('ApplicationBundle:LeaveSettings')->find($id);
  9117.                     }
  9118.                     if (!$leaveSetting) {
  9119.                         $leaveSetting = new LeaveSettings();
  9120.                     }
  9121.                     $leaveSetting->setId($id);
  9122.                     $leaveSetting->setLeaveTitle($leaveTitles[$i]);
  9123.                     $leaveSetting->setCarryForwardType((int)$carryForwardTypes[$i]);
  9124.                     $leaveSetting->setCarryForwardQty((int)$carryForwardQtys[$i]);
  9125.                     $leaveSetting->setTotalLeave((int)$totalLeaves[$i]);
  9126.                     $leaveSetting->setResetFrequencyType((int)$resetFreqTypes[$i]);
  9127.                     $leaveSetting->setResetFrequencyQty((int)$resetFreqQtys[$i]);
  9128.                     $leaveSetting->setAdditionCondition((int)$additionConditions[$i]);
  9129.                     $leaveSetting->setAdditionConditionDuration((int)$additionDurations[$i]);
  9130.                     $em->persist($leaveSetting);
  9131.                 }
  9132.             }
  9133.             $em->flush();
  9134.             $this->addFlash('success''Leave settings saved successfully!');
  9135.             return $this->redirectToRoute('leave_settings_list');
  9136.         }
  9137.         $defaultLeaveType HumanResourceConstant::$defaultLeaveType;
  9138.         $savedLeaveSettings $em->getRepository('ApplicationBundle:LeaveSettings')->findAll();
  9139.         $useDefaultLeave count($savedLeaveSettings) === 0;
  9140.         $leaveSettings array_map(function ($setting) {
  9141.             return [
  9142.                 'id' => $setting->getId(),
  9143.                 'leaveTitle' => $setting->getLeaveTitle(),
  9144.                 'carryForwardType' => $setting->getCarryForwardType(),
  9145.                 'carryForwardQty' => $setting->getCarryForwardQty(),
  9146.                 'totalLeave' => $setting->getTotalLeave(),
  9147.                 'resetFrequencyType' => $setting->getResetFrequencyType(),
  9148.                 'resetFrequencyQty' => $setting->getResetFrequencyQty(),
  9149.                 'additionCondition' => $setting->getAdditionCondition(),
  9150.                 'additionConditionDuration' => $setting->getAdditionConditionDuration(),
  9151.             ];
  9152.         }, $savedLeaveSettings);
  9153.         return $this->render('ApplicationBundle:pages/human_resource/input_forms:leave_settings.html.twig', [
  9154.             'page_title' => 'Leave Settings',
  9155.             'defaultLeaveType' => $defaultLeaveType,
  9156.             'leaveSettings' => $leaveSettings,
  9157.             'useDefaultLeave' => $useDefaultLeave,
  9158.         ]);
  9159.     }
  9160.     public function leavePolicyListAction()
  9161.     {
  9162.         return $this->render("ApplicationBundle:pages/human_resource/list:leaveApplicationSettingsList.html.twig", array(
  9163.             'page_title' => 'Leave PolicyList',
  9164.         ));
  9165.     }
  9166. //    public function getEmployeeDataAction(Request $request)
  9167. //    {
  9168. //        $em = $this->getDoctrine()->getManager();
  9169. //        $session = $request->getSession();
  9170. //        $userId = $session->get(UserConstants::USER_ID);
  9171. //        $absoluteUrl = $this->generateUrl('dashboard', [], UrlGenerator::ABSOLUTE_URL);
  9172. //
  9173. //        $employeeData = $em->getRepository('ApplicationBundle:Employee')
  9174. //            ->findOneBy(
  9175. //                array(
  9176. //
  9177. //                    'userId' => $userId
  9178. //                )
  9179. //            );
  9180. //        $data = [
  9181. //            'firstname' => $employeeData->getFirstname(),
  9182. //            'lastname' => $employeeData->getLastname(),
  9183. //            'userImage' => $absoluteUrl . '' . $employeeData->getImage()
  9184. //
  9185. //        ];
  9186. //
  9187. //        return new JsonResponse([
  9188. //            'success' => true,
  9189. //            'data' => $data
  9190. //        ]);
  9191. //    }
  9192. }