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.         $em_goc $this->getDoctrine()->getManager('company_group');
  1170.         $connection $em->getConnection();
  1171.         $connection->beginTransaction();
  1172.         $skills $em->getRepository(Skill::class)->findAll();
  1173.         $session $data->getSession();
  1174.         $ownOnly 0;
  1175.         $consultancyLevel HumanResourceConstant::$consultantLevel;
  1176.         $systemType $this->container->hasParameter('system_type') ? $this->container->getParameter('system_type') : '_ERP_';
  1177.         $banks $em->getRepository(BankList::class)->findAll();
  1178.         $bankListObj = [];
  1179.         $deviceList $em_goc->getRepository('CompanyGroupBundle:Device')->findBy([
  1180.             'appId' => $session->get(UserConstants::USER_APP_ID)
  1181.         ]);
  1182.         $id $data->request->get('employeeId'$id);
  1183.         foreach ($banks as $bank) {
  1184.             $bankListObj[$bank->getBankId()] = $bank->getName();
  1185.         }
  1186.         if ($id === "my") {
  1187.             $id $session->get(UserConstants::USER_EMPLOYEE_ID);
  1188.             $ownOnly 1;
  1189.             if ($id == || $id == null) {
  1190.                 return $this->redirectToRoute('permission_denied_page');
  1191.             }
  1192.         }
  1193.         if ($id) {
  1194.             if ($data->isMethod('GET')) {
  1195.                 $Employee $this->getDoctrine()->getRepository(EmployeeDetails::class)->find($id);
  1196.                 if (!$Employee) {
  1197.                     $this->addFlash(
  1198.                         'error',
  1199.                         'Invalid User ID!'
  1200.                     );
  1201.                     return $this->redirectToRoute('add_employee');
  1202.                 } else {
  1203.                     $EmployeeRes HumanResource::TwigDataForAddEmployee($em$id);
  1204.                     $Employee $EmployeeRes['employee'];
  1205.                     $EmployeeMain $EmployeeRes['employeeMain'];
  1206.                     $sysUserId $EmployeeRes['sysId'];
  1207.                     $existingSysUser $sysUserId $em->getRepository('ApplicationBundle:SysUser')->find($sysUserId) : [];
  1208.                     $regionIdsArray json_decode($EmployeeMain->getRegionIds(), true) ?: [];
  1209.                     $regionLeaderFlagsArray json_decode($EmployeeMain->getRegionLeaderFlags(), true) ?: [];
  1210.                     $existingRegionAssociations = [];
  1211.                     if (!empty($regionIdsArray)) {
  1212.                         $regionRepo $this->getDoctrine()->getRepository('ApplicationBundle:Region');
  1213.                         $regions $regionRepo->findBy(['id' => $regionIdsArray]);
  1214.                         $regionMap = [];
  1215.                         foreach ($regions as $region) {
  1216.                             $regionMap[$region->getId()] = $region;
  1217.                         }
  1218.                         foreach ($regionIdsArray as $index => $regionId) {
  1219.                             if (!isset($regionMap[$regionId])) continue;
  1220.                             $region $regionMap[$regionId];
  1221.                             $existingRegionAssociations[] = [
  1222.                                 'regionLevelId' => $region->getRegionLevelId(),
  1223.                                 'regionId' => $region->getId(),
  1224.                                 'isLeader' => isset($regionLeaderFlagsArray[$index]) ? (int)$regionLeaderFlagsArray[$index] : 0
  1225.                             ];
  1226.                         }
  1227.                     }
  1228.                     $TwigData HumanResource::TwigDataForAddEmployee($em0);
  1229.                     return $this->render(
  1230.                         'ApplicationBundle:pages/human_resource/input_forms:add_employee.html.twig',
  1231.                         array(
  1232.                             'page_title' => 'Update Employee',
  1233.                             'ownOnly' => $ownOnly,
  1234.                             'deviceList' => $deviceList,
  1235.                             'branches' => $TwigData['branches'],
  1236.                             'bankListObj' => $bankListObj,
  1237.                             'heads' => Accounts::getLedgerHeadsWithParents($em),
  1238.                             'departments' => $TwigData['departments'],
  1239.                             'departmentPositions' => $TwigData['departmentPositions'],
  1240.                             'regions' => $TwigData['regions'],
  1241.                             'supervisors' => $TwigData['supervisors'],
  1242.                             'sysUsers' => $TwigData['sysUser'],
  1243.                             'EmploymentStatus' => $TwigData['EmploymentStatus'],
  1244.                             'sex' => $TwigData['sex'],
  1245.                             'BloodGroup' => $TwigData['BloodGroup'],
  1246.                             'days' => $TwigData['days'],
  1247.                             'employeeMain' => $EmployeeMain,
  1248.                             'employee' => $Employee,
  1249.                             'skills' => $skills,
  1250.                             'existingSysUser' => $existingSysUser,
  1251.                             'id' => $id,
  1252.                             'default_route' => $EmployeeRes['defaultRoute'],
  1253.                             'user_type' => $EmployeeRes['userType'],
  1254.                             'user_type_data' => HumanResourceConstant::$userType,
  1255.                             'AccountTypes' => $TwigData['AccountType'],
  1256.                             'weekends' => explode(','$Employee->getWeeklyHoliday()),
  1257.                             'consultancyLevel' => $consultancyLevel,
  1258.                             'module_data_array' => $TwigData['module_data_array'],
  1259.                             'HasUpdateMode' => true,
  1260.                             'brand_list' => Inventory::GetBrandList($em$this->getLoggedUserCompanyId($data)),
  1261.                             'branch_list' => Client::BranchList($this->getDoctrine()->getManager(), $this->getLoggedUserCompanyId($data)),
  1262.                             'region_data' => Client::RegionList($this->getDoctrine()->getManager(), $this->getLoggedUserCompanyId($data)),
  1263.                             'leaveSettings' => $TwigData['leaveSettings'],
  1264.                             'leaveData' => $EmployeeRes['leaveData'],
  1265.                             'positions' => $EmployeeRes['positions'],
  1266.                             'existing_region_associations' => $existingRegionAssociations
  1267.                         )
  1268.                     );
  1269.                 }
  1270.             } else {
  1271.                 $approveHash $data->request->get('approvalHash');
  1272.                 $loginId $data->getSession()->get(UserConstants::USER_LOGIN_ID);
  1273.                 $isSignatureOk DocValidation::isSignatureOk($em$loginId$approveHash);
  1274.                 $upl_dir $this->container->getParameter('kernel.root_dir') . '/../web/uploads/Users/';
  1275.                 $image $data->files->get('img');
  1276.                 $profileImage $this->uploadImage($image$data);
  1277.                 $path '';
  1278.                 if ($isSignatureOk) {
  1279.                     $CompanyId $this->getLoggedUserCompanyId($data);
  1280.                     $user $em->getRepository('ApplicationBundle:SysUser')->findOneBy(['email' => $data->get('email')]);
  1281.                     if ($user) {
  1282.                         $sysUserId $user->getUserId();
  1283.                         $message $this->get('user_module')->updateUser(
  1284.                             $sysUserId,
  1285.                             $data->request->get('firstname') . " " $data->request->get('lastname'),
  1286.                             $data->request->has('email') ? $data->request->get('email') : '_UNCHANGED_',
  1287.                             $data->request->has('username') ? $data->request->get('username') : '_UNCHANGED_',
  1288.                             $data->request->get('password'),
  1289.                             1,
  1290.                             $data->request->get('user_type''_UNCHANGED_'),
  1291.                             $data->request->get('supervisor'),
  1292.                             $data->request->get('default_route'),
  1293.                             $data->request->get('branch'),
  1294.                             $data->request->has('access_module') ? 0,
  1295.                             $data->getSession()->get(UserConstants::USER_LOGIN_ID),
  1296.                             $data->request->get('global_user_id'null),
  1297.                             $profileImage,
  1298.                             $upl_dir
  1299.                         );
  1300.                         if (isset($message[0]) && $message[0] === 'success') {
  1301.                             HumanResource::StoreDataForAddEmployee($em$data$id$CompanyId$profileImage);
  1302.                             $connection->commit();
  1303.                             if ($systemType == '_CENTRAL_') {
  1304.                             } else {
  1305.                                 $Employee $em->getRepository(Employee::class)->find($id);
  1306.                                 $EmployeeDetails $em->getRepository(EmployeeDetails::class)->findOneBy(
  1307.                                     array(
  1308.                                         'id' => $id
  1309.                                     )
  1310.                                 );
  1311.                                 $em_goc $this->getDoctrine()->getManager('company_group');
  1312.                                 $em_goc->getConnection()->connect();
  1313.                                 $connected $em_goc->getConnection()->isConnected();
  1314.                                 $gocDataList = [];
  1315.                                 $gocDataListByAppId = [];
  1316.                                 $retDataDebug = array();
  1317.                                 $appIds $message[3]->getUserAppId();
  1318.                                 $userIds $message[3]->getUserId();
  1319.                                 if ($connected) {
  1320.                                     $findByQuery = array(
  1321.                                         'active' => 1
  1322.                                     );
  1323.                                     if ($appIds !== '_UNSET_')
  1324.                                         $findByQuery['appId'] = $appIds;
  1325.                                     $gocList $this->getDoctrine()->getManager('company_group')
  1326.                                         ->getRepository("CompanyGroupBundle:CompanyGroup")
  1327.                                         ->findBy($findByQuery);
  1328.                                     foreach ($gocList as $entry) {
  1329.                                         $d = array(
  1330.                                             'name' => $entry->getName(),
  1331.                                             'id' => $entry->getId(),
  1332.                                             'image' => $entry->getImage(),
  1333.                                             'companyGroupHash' => $entry->getCompanyGroupHash(),
  1334.                                             'dbName' => $entry->getDbName(),
  1335.                                             'dbUser' => $entry->getDbUser(),
  1336.                                             'dbPass' => $entry->getDbPass(),
  1337.                                             'dbHost' => $entry->getDbHost(),
  1338.                                             'appId' => $entry->getAppId(),
  1339.                                             'companyRemaining' => $entry->getCompanyRemaining(),
  1340.                                             'companyAllowed' => $entry->getCompanyAllowed(),
  1341.                                         );
  1342.                                         $gocDataList[$entry->getId()] = $d;
  1343.                                         $gocDataListByAppId[$entry->getAppId()] = $d;
  1344.                                     }
  1345.                                     $debugCount 0;
  1346.                                     foreach ($gocDataList as $gocId => $entry) {
  1347.                                         $skipSend 1;
  1348.                                         $connector $this->container->get('application_connector');
  1349.                                         $connector->resetConnection(
  1350.                                             'default',
  1351.                                             $gocDataList[$gocId]['dbName'],
  1352.                                             $gocDataList[$gocId]['dbUser'],
  1353.                                             $gocDataList[$gocId]['dbPass'],
  1354.                                             $gocDataList[$gocId]['dbHost'],
  1355.                                             $reset true);
  1356.                                         $em $this->getDoctrine()->getManager();
  1357.                                         if ($userIds !== '_UNSET_')
  1358.                                             $users $this->getDoctrine()
  1359.                                                 ->getRepository('ApplicationBundle:SysUser')
  1360.                                                 ->findBy(
  1361.                                                     array(
  1362.                                                         'userId' => $userIds
  1363.                                                     )
  1364.                                                 );
  1365.                                         else
  1366.                                             $users $this->getDoctrine()
  1367.                                                 ->getRepository('ApplicationBundle:SysUser')
  1368.                                                 ->findBy(
  1369.                                                     array()
  1370.                                                 );
  1371.                                         $output '';
  1372.                                         $userData = array();
  1373.                                         $userFiles = array();
  1374.                                         foreach ($users as $user) {
  1375.                                             $file $this->container->getParameter('kernel.root_dir') . '/../web/' $user->getImage();
  1376.                                             if ($user->getImage() != '' && $user->getImage() != null && file_exists($file)) {
  1377.                                                 $mime mime_content_type($file);
  1378.                                                 $info pathinfo($file);
  1379.                                                 $name $info['basename'];
  1380.                                                 if (strpos($mime'image') !== false) {
  1381.                                                     $output = new \CURLFile($file$mime$name);
  1382.                                                 }
  1383.                                                 $skipSend 0;
  1384.                                                 $userFiles['file_' $user->getUserAppId() . '_' $user->getUserId()] = $output;
  1385.                                             } else {
  1386.                                                 $user->setImage(null);
  1387.                                                 $userFiles['file_' $user->getUserAppId() . '_' $user->getUserId()] = 'pika';
  1388.                                                 $em->flush();
  1389.                                             }
  1390.                                             $getters array_filter(get_class_methods($user), function ($method) {
  1391.                                                 return 'get' === substr($method03);
  1392.                                             });
  1393.                                             $userDataSingle = array();
  1394.                                             foreach ($getters as $getter) {
  1395.                                                 if ($getter == 'getCreatedAt' || $getter == 'getUpdatedAt' || $getter == 'getImage')
  1396.                                                     continue;
  1397.                                                 if ($user->{$getter}() instanceof \DateTime) {
  1398.                                                     $ggtd $user->{$getter}();
  1399.                                                     $userDataSingle[$getter] = $ggtd->format('Y-m-d');
  1400.                                                 } else
  1401.                                                     $userDataSingle[$getter] = $user->{$getter}();
  1402.                                             }
  1403.                                             $employeeGetters = array(
  1404.                                                 'getFirstname''getLastname''getImage''getIsImgLegal''getNid''getDob''getSex''getReligion''getFather',
  1405.                                                 'getMother''getSpouse''getChild1''getChild2''getBlood''getPhone''getOfficailPhone''getCurrAddr',
  1406.                                                 'getCurrAddrLat''getCurrAddrLng''getPermAddr''getEmmContact''getUsername''getEmail''getPassword',
  1407.                                                 'getUserId''getJoiningDate''getEmpValidTill''getEmpStatus''getEmpType''getEmpCode''getEmpLabel''getTin',
  1408.                                                 'getTinValidTill''getMedIns''getMedInsValidTill''getDocs''getNocApproval''getInst1''getYr1''getDur1',
  1409.                                                 'getInst2''getYr2''getDur2''getInst3''getYr3''getDur3''getEinst1''getEyr1''getEdeg1''getEinst2',
  1410.                                                 'getEyr2''getEdeg2''getEinst3''getEyr3''getEdeg3''getBankAcc''getBankAccType''getBankAccValidFrom',
  1411.                                                 'getBankAccValidTo''getRoutingCode''getSwiftCode''getEar1''getEar2''getEar3''getEar4''getEar5''getEar6',
  1412.                                                 'getEart''getDed1''getDed2''getDed3''getDed4''getDedt''getPayable''getHandCash''getBankTransfer',
  1413.                                                 'getSecDep''getSecDepSpan''getSecDepRemMon''getSecDepRemAmount''getSlQty''getSlTkn''getSlFreq''getMlQty',
  1414.                                                 'getMlTkn''getMlFreq''getElQty''getElTkn''getElFreq''getClQty''getClTkn''getClFreq''getLevt',
  1415.                                                 'getWeeklyHoliday''getFiles''getSupervisor''getDept''getDesg''getBranch''getDivision''getCreatedAt',
  1416.                                                 'getUpdatedAt''getEmployeeLevel''getSkill''getProbationaryPeriod''getDocBookedFlag''getTimeStampOfForm',
  1417.                                                 'getIsConsultant''getConsultantLevel''getApplicationText''getCurrentEmployment''getEmergencyContactNumber',
  1418.                                                 'getPostalCode''getCountry''getEducationData''getWorkExperienceData''getCertificateData''getLanguagesData',
  1419.                                                 'getBeneficiaryName''getBankName''getBranchName''getClockedIn'
  1420.                                             );
  1421.                                             foreach ($employeeGetters as $getter) {
  1422.                                                 if (!method_exists($EmployeeDetails$getter)) continue;
  1423.                                                 try {
  1424.                                                     $value $EmployeeDetails->{$getter}();
  1425.                                                     if ($value instanceof \DateTime) {
  1426.                                                         $userDataSingle[$getter] = $value->format('Y-m-d');
  1427.                                                     } elseif (is_object($value)) {
  1428.                                                         continue;
  1429.                                                     } else {
  1430.                                                         $userDataSingle[$getter] = $value;
  1431.                                                     }
  1432.                                                 } catch (\Exception $e) {
  1433.                                                     continue;
  1434.                                                 }
  1435.                                             }
  1436.                                             $userData[] = $userDataSingle;
  1437.                                         }
  1438.                                         $retDataDebug[$debugCount] = array(
  1439.                                             'skipSend' => $skipSend
  1440.                                         );
  1441.                                         {
  1442.                                             $urlToCall GeneralConstant::HONEYBEE_CENTRAL_SERVER '/SyncUserToCentralUser';
  1443.                                             $userFiles['userData'] = json_encode($userData);
  1444.                                             $curl curl_init();
  1445.                                             curl_setopt_array($curl, array(
  1446.                                                 CURLOPT_RETURNTRANSFER => 1,
  1447.                                                 CURLOPT_POST => 1,
  1448.                                                 CURLOPT_URL => $urlToCall,
  1449.                                                 CURLOPT_CONNECTTIMEOUT => 10,
  1450.                                                 CURLOPT_SSL_VERIFYPEER => false,
  1451.                                                 CURLOPT_SSL_VERIFYHOST => false,
  1452.                                                 CURLOPT_HTTPHEADER => array(),
  1453.                                                 CURLOPT_POSTFIELDS => $userFiles
  1454.                                             ));
  1455.                                             $retData curl_exec($curl);
  1456.                                             $errData curl_error($curl);
  1457.                                             curl_close($curl);
  1458.                                             $retDataObj json_decode($retDatatrue);
  1459.                                             $retDataDebug[$debugCount] = $retDataObj;
  1460.                                             if (isset($retDataObj['globalIdsData']))
  1461.                                                 foreach ($retDataObj['globalIdsData'] as $app_id => $usrList) {
  1462.                                                     $connector $this->container->get('application_connector');
  1463.                                                     $connector->resetConnection(
  1464.                                                         'default',
  1465.                                                         $gocDataListByAppId[$app_id]['dbName'],
  1466.                                                         $gocDataListByAppId[$app_id]['dbUser'],
  1467.                                                         $gocDataListByAppId[$app_id]['dbPass'],
  1468.                                                         $gocDataListByAppId[$app_id]['dbHost'],
  1469.                                                         $reset true);
  1470.                                                     $em $this->getDoctrine()->getManager();
  1471.                                                     foreach ($usrList as $sys_id => $globaldata) {
  1472.                                                         $user $this->getDoctrine()
  1473.                                                             ->getRepository('ApplicationBundle:SysUser')
  1474.                                                             ->findOneBy(
  1475.                                                                 array(
  1476.                                                                     'userId' => $sys_id
  1477.                                                                 )
  1478.                                                             );
  1479.                                                         if ($user) {
  1480.                                                             $user->setGlobalId($globaldata['gid']);
  1481.                                                             $em->flush();
  1482.                                                         }
  1483.                                                     }
  1484.                                                 }
  1485.                                         }
  1486.                                         $debugCount++;
  1487.                                     }
  1488.                                 }
  1489.                             }
  1490.                         } else {
  1491.                             $errorMsg $message['message'] ?? 'Unknown error occurred.';
  1492.                             $this->addFlash('error'$errorMsg);
  1493.                             return $this->redirectToRoute('add_employee');
  1494.                         }
  1495.                         $userType $data->getSession()->get(UserConstants::USER_TYPE);
  1496.                         $redirctUrl $this->generateUrl('employee_list', [], UrlGenerator::ABSOLUTE_URL);
  1497.                         if ($userType == 1) {
  1498.                             $redirctUrl $this->generateUrl('employee_list', [], UrlGenerator::ABSOLUTE_URL);
  1499.                         } else {
  1500.                             $redirctUrl $this->generateUrl('edit_employee', [], UrlGenerator::ABSOLUTE_URL) . '/my';
  1501.                         }
  1502.                         return new JsonResponse(array(
  1503.                             'employeeId' => $Employee->getEmployeeId(),
  1504.                             'redirectToNew' => 0,
  1505.                             'success' => true,
  1506.                             'redirectUrl' => $redirctUrl,
  1507.                         ));
  1508.                     }
  1509.                 } else {
  1510.                     $this->addFlash(
  1511.                         'error',
  1512.                         'Invalid Approval Hash!'
  1513.                     );
  1514.                     return $this->redirectToRoute('add_employee');
  1515.                 }
  1516.             }
  1517.         } else {
  1518.             if ($data->isMethod('GET')) {
  1519.                 $TwigData HumanResource::TwigDataForAddEmployee($em0);
  1520.                 $existingRegionAssociations = [];
  1521.                 return $this->render(
  1522.                     'ApplicationBundle:pages/human_resource/input_forms:add_employee.html.twig',
  1523.                     array(
  1524.                         'page_title' => 'Add Employee',
  1525.                         'ownOnly' => $ownOnly,
  1526.                         'deviceList' => $deviceList,
  1527.                         'heads' => Accounts::getLedgerHeadsWithParents($em),
  1528.                         'bankListObj' => $bankListObj,
  1529.                         'branches' => $TwigData['branches'],
  1530.                         'departments' => $TwigData['departments'],
  1531.                         'departmentPositions' => $TwigData['departmentPositions'],
  1532.                         'regions' => $TwigData['regions'],
  1533.                         'supervisors' => $TwigData['supervisors'],
  1534.                         'sysUsers' => $TwigData['sysUser'],
  1535.                         'EmploymentStatus' => $TwigData['EmploymentStatus'],
  1536.                         'sex' => $TwigData['sex'],
  1537.                         'skills' => $skills,
  1538.                         'id' => $id,
  1539.                         'consultancyLevel' => $consultancyLevel,
  1540.                         'existingSysUser' => null,
  1541.                         'BloodGroup' => $TwigData['BloodGroup'],
  1542.                         'days' => $TwigData['days'],
  1543.                         'AccountTypes' => $TwigData['AccountType'],
  1544.                         'module_data_array' => $TwigData['module_data_array'],
  1545.                         'user_type_data' => HumanResourceConstant::$userType,
  1546.                         'HasUpdateMode' => false,
  1547.                         'brand_list' => Inventory::GetBrandList($em$this->getLoggedUserCompanyId($data)),
  1548.                         'leaveSettings' => $TwigData['leaveSettings'],
  1549.                         'employee' => [],
  1550.                         'positions' => $TwigData['positions'],
  1551.                         'existing_region_associations' => $existingRegionAssociations ?? [],
  1552.                         'branch_list' => Client::BranchList($this->getDoctrine()->getManager(), $this->getLoggedUserCompanyId($data)),
  1553.                         'region_data' => Client::RegionList($this->getDoctrine()->getManager(), $this->getLoggedUserCompanyId($data)),
  1554.                     )
  1555.                 );
  1556.             } else {
  1557.                 try {
  1558.                     $approveHash $data->request->get('approvalHash');
  1559.                     $loginId $data->getSession()->get(UserConstants::USER_LOGIN_ID);
  1560.                     $CompanyId $this->getLoggedUserCompanyId($data);
  1561.                     $isSignatureOk DocValidation::isSignatureOk($em$loginId$approveHash);
  1562.                     if (!$isSignatureOk) {
  1563.                         $this->addFlash('error''Invalid Approval Hash!');
  1564.                         return $this->redirectToRoute('add_employee');
  1565.                     }
  1566.                     $message $this->get('user_module')->addNewUser(
  1567.                         $data->request->get('firstname') . " " $data->request->get('lastname'),
  1568.                         $data->request->get('email'),
  1569.                         $data->request->get('username'),
  1570.                         $data->request->get('password'),
  1571.                         $data->request->get('desg'),
  1572.                         $this->getLoggedUserLoginId($data),
  1573.                         $data->request->get('company'),
  1574.                         $data->request->get('user_type'),
  1575.                         $data->request->get('companyIdList'),
  1576.                         $data->request->get('branch'),
  1577.                         $data->request->get('supervisor'),
  1578.                         $data->request->get('default_route'),
  1579.                         $data->request->has('access_module') ? 0,
  1580.                         "",
  1581.                         $data->files->get('img'),
  1582.                         '',
  1583.                         00,
  1584.                         ''''''0''0,
  1585.                         $data->request->get('global_user_id'null)
  1586.                     );
  1587.                     if ($message[0] === 'error') {
  1588.                         $this->addFlash('error''Invalid Approval Hash!');
  1589.                         return $this->redirectToRoute('add_employee');
  1590.                     }
  1591.                     $isSuccess HumanResource::StoreDataForAddEmployee($em$datafalse$CompanyId);
  1592.                     $Employee $isSuccess;
  1593.                     $EmployeeDetails $em->getRepository(EmployeeDetails::class)->findOneBy(['id' => $id]);
  1594.                     $Employee->setUserId($message[3]->getUserId());
  1595.                     $em->persist($Employee);
  1596.                     if ($EmployeeDetails) {
  1597.                         $EmployeeDetails->setUserId($message[3]->getUserId());
  1598.                         $em->persist($EmployeeDetails);
  1599.                     }
  1600.                     $em->flush();
  1601.                     $connection->commit();
  1602.                 } catch (Throwable $e) {
  1603.                     $connection->rollBack();
  1604.                     $em->close();
  1605.                     $this->addFlash('error''Failed to save employee: ' $e->getMessage());
  1606.                     return $this->redirectToRoute('add_employee');
  1607.                 }
  1608.                 if ($systemType !== '_CENTRAL_') {
  1609.                     $em_goc $this->getDoctrine()->getManager('company_group');
  1610.                     $em_goc->getConnection()->connect();
  1611.                     $connected $em_goc->getConnection()->isConnected();
  1612.                     if ($connected) {
  1613.                         $appIds $message[2]->getAppId();
  1614.                         $userIds $message[3]->getUserId();
  1615.                         $findByQuery = ['active' => 1];
  1616.                         if ($appIds !== '_UNSET_'$findByQuery['appId'] = $appIds;
  1617.                         $gocList $em_goc->getRepository("CompanyGroupBundle:CompanyGroup")->findBy($findByQuery);
  1618.                         $gocDataList $gocDataListByAppId = [];
  1619.                         foreach ($gocList as $entry) {
  1620.                             $d = [
  1621.                                 'name' => $entry->getName(),
  1622.                                 'id' => $entry->getId(),
  1623.                                 'image' => $entry->getImage(),
  1624.                                 'companyGroupHash' => $entry->getCompanyGroupHash(),
  1625.                                 'dbName' => $entry->getDbName(),
  1626.                                 'dbUser' => $entry->getDbUser(),
  1627.                                 'dbPass' => $entry->getDbPass(),
  1628.                                 'dbHost' => $entry->getDbHost(),
  1629.                                 'appId' => $entry->getAppId(),
  1630.                                 'companyRemaining' => $entry->getCompanyRemaining(),
  1631.                                 'companyAllowed' => $entry->getCompanyAllowed(),
  1632.                             ];
  1633.                             $gocDataList[$entry->getId()] = $d;
  1634.                             $gocDataListByAppId[$entry->getAppId()] = $d;
  1635.                         }
  1636.                         $debugCount 0;
  1637.                         foreach ($gocDataList as $gocId => $entry) {
  1638.                             $skipSend 1;
  1639.                             $connector $this->container->get('application_connector');
  1640.                             $connector->resetConnection(
  1641.                                 'default',
  1642.                                 $entry['dbName'],
  1643.                                 $entry['dbUser'],
  1644.                                 $entry['dbPass'],
  1645.                                 $entry['dbHost'],
  1646.                                 $reset true
  1647.                             );
  1648.                             $em $this->getDoctrine()->getManager();
  1649.                             $users = ($userIds !== '_UNSET_')
  1650.                                 ? $this->getDoctrine()->getRepository('ApplicationBundle:SysUser')->findBy(['userId' => $userIds])
  1651.                                 : $this->getDoctrine()->getRepository('ApplicationBundle:SysUser')->findBy([]);
  1652.                             $userData $userFiles = [];
  1653.                             foreach ($users as $user) {
  1654.                                 $filePath $this->container->getParameter('kernel.root_dir') . '/../web/' $user->getImage();
  1655.                                 if ($user->getImage() && file_exists($filePath)) {
  1656.                                     $mime mime_content_type($filePath);
  1657.                                     $info pathinfo($filePath);
  1658.                                     $name $info['basename'];
  1659.                                     if (strpos($mime'image') !== false) {
  1660.                                         $userFiles['file_' $user->getUserAppId() . '_' $user->getUserId()] = new \CURLFile($filePath$mime$name);
  1661.                                         $skipSend 0;
  1662.                                     }
  1663.                                 } else {
  1664.                                     $user->setImage(null);
  1665.                                     $userFiles['file_' $user->getUserAppId() . '_' $user->getUserId()] = 'pika';
  1666.                                     $em->flush();
  1667.                                 }
  1668.                                 $getters array_filter(get_class_methods($user), function ($m) {
  1669.                                     return substr($m03) === 'get';
  1670.                                 });
  1671.                                 $userDataSingle = [];
  1672.                                 foreach ($getters as $getter) {
  1673.                                     if (in_array($getter, ['getCreatedAt''getUpdatedAt''getImage'])) continue;
  1674.                                     $val $user->{$getter}();
  1675.                                     $userDataSingle[$getter] = $val instanceof \DateTime $val->format('Y-m-d') : $val;
  1676.                                 }
  1677.                                 $employeeGetters = [
  1678.                                     'getFirstname''getLastname''getImage''getIsImgLegal''getNid''getDob''getSex''getReligion',
  1679.                                     'getFather''getMother''getSpouse''getChild1''getChild2''getBlood''getPhone''getOfficailPhone',
  1680.                                     'getCurrAddr''getCurrAddrLat''getCurrAddrLng''getPermAddr''getEmmContact''getUsername''getEmail',
  1681.                                     'getPassword''getUserId''getJoiningDate''getEmpValidTill''getEmpStatus''getEmpType''getEmpCode',
  1682.                                     'getEmpLabel''getTin''getTinValidTill''getMedIns''getMedInsValidTill''getDocs''getNocApproval',
  1683.                                     'getInst1''getYr1''getDur1''getInst2''getYr2''getDur2''getInst3''getYr3''getDur3''getEinst1',
  1684.                                     'getEyr1''getEdeg1''getEinst2''getEyr2''getEdeg2''getEinst3''getEyr3''getEdeg3''getBankAcc',
  1685.                                     'getBankAccType''getBankAccValidFrom''getBankAccValidTo''getRoutingCode''getSwiftCode''getEar1',
  1686.                                     'getEar2''getEar3''getEar4''getEar5''getEar6''getEart''getDed1''getDed2''getDed3''getDed4',
  1687.                                     'getDedt''getPayable''getHandCash''getBankTransfer''getSecDep''getSecDepSpan''getSecDepRemMon',
  1688.                                     'getSecDepRemAmount''getSlQty''getSlTkn''getSlFreq''getMlQty''getMlTkn''getMlFreq''getElQty',
  1689.                                     'getElTkn''getElFreq''getClQty''getClTkn''getClFreq''getLevt''getWeeklyHoliday''getFiles',
  1690.                                     'getSupervisor''getDept''getDesg''getBranch''getDivision''getCreatedAt''getUpdatedAt',
  1691.                                     'getEmployeeLevel''getSkill''getProbationaryPeriod''getDocBookedFlag''getTimeStampOfForm',
  1692.                                     'getIsConsultant''getConsultantLevel''getApplicationText''getCurrentEmployment''getEmergencyContactNumber',
  1693.                                     'getPostalCode''getCountry''getEducationData''getWorkExperienceData''getCertificateData''getLanguagesData',
  1694.                                     'getBeneficiaryName''getBankName''getBranchName''getClockedIn'
  1695.                                 ];
  1696.                                 foreach ($employeeGetters as $getter) {
  1697.                                     if (!method_exists($EmployeeDetails$getter)) continue;
  1698.                                     $value $EmployeeDetails->{$getter}();
  1699.                                     if ($value instanceof \DateTime$userDataSingle[$getter] = $value->format('Y-m-d');
  1700.                                     elseif (!is_object($value)) $userDataSingle[$getter] = $value;
  1701.                                 }
  1702.                                 $userData[] = $userDataSingle;
  1703.                             }
  1704.                             $retDataDebug[$debugCount] = ['skipSend' => $skipSend];
  1705.                             $urlToCall GeneralConstant::HONEYBEE_CENTRAL_SERVER '/SyncUserToCentralUser';
  1706.                             $userFiles['userData'] = json_encode($userData);
  1707.                             $curl curl_init();
  1708.                             curl_setopt_array($curl, [
  1709.                                 CURLOPT_RETURNTRANSFER => 1,
  1710.                                 CURLOPT_POST => 1,
  1711.                                 CURLOPT_URL => $urlToCall,
  1712.                                 CURLOPT_CONNECTTIMEOUT => 10,
  1713.                                 CURLOPT_SSL_VERIFYPEER => false,
  1714.                                 CURLOPT_SSL_VERIFYHOST => false,
  1715.                                 CURLOPT_POSTFIELDS => $userFiles
  1716.                             ]);
  1717.                             $retData curl_exec($curl);
  1718.                             $errData curl_error($curl);
  1719.                             curl_close($curl);
  1720.                             $retDataObj $errData ? ['status' => 'error''message' => 'cURL Error: ' $errData] : json_decode($retDatatrue);
  1721.                             $retDataDebug[$debugCount] = $retDataObj;
  1722.                             if (isset($retDataObj['globalIdsData'])) {
  1723.                                 foreach ($retDataObj['globalIdsData'] as $app_id => $usrList) {
  1724.                                     $connector->resetConnection(
  1725.                                         'default',
  1726.                                         $gocDataListByAppId[$app_id]['dbName'],
  1727.                                         $gocDataListByAppId[$app_id]['dbUser'],
  1728.                                         $gocDataListByAppId[$app_id]['dbPass'],
  1729.                                         $gocDataListByAppId[$app_id]['dbHost'],
  1730.                                         $reset true
  1731.                                     );
  1732.                                     $em $this->getDoctrine()->getManager();
  1733.                                     foreach ($usrList as $sys_id => $globaldata) {
  1734.                                         $user $this->getDoctrine()->getRepository('ApplicationBundle:SysUser')->findOneBy(['userId' => $sys_id]);
  1735.                                         if ($user) {
  1736.                                             $user->setGlobalId($globaldata['gid']);
  1737.                                             $em->persist($user);
  1738.                                             $em->flush();
  1739.                                         }
  1740.                                     }
  1741.                                 }
  1742.                             }
  1743.                             $debugCount++;
  1744.                         }
  1745.                     }
  1746.                 }
  1747.                 $companyData $message[2];
  1748.                 if ($message[0] === 'success' && GeneralConstant::EMAIL_ENABLED == 1) {
  1749.                     $bodyTemplate 'ApplicationBundle:email/user:registration.html.twig';
  1750.                     $bodyData = [
  1751.                         'name' => $data->request->get('name'),
  1752.                         'companyData' => $companyData,
  1753.                         'userName' => $data->request->get('username'),
  1754.                         'password' => $data->request->get('password'),
  1755.                     ];
  1756.                     $new_mail $this->get('mail_module');
  1757.                     $new_mail->sendMyMail([
  1758.                         'senderHash' => '_CUSTOM_',
  1759.                         'forwardToMailAddress' => $data->request->get('email'),
  1760.                         'subject' => 'User Registration on HoneyBee Ecosystem under Entity ' $companyData->getName(),
  1761.                         'fileName' => '',
  1762.                         'attachments' => [],
  1763.                         'toAddress' => $data->request->get('email'),
  1764.                         'fromAddress' => 'no-reply@ourhoneybee.eu',
  1765.                         'userName' => 'no-reply@ourhoneybee.eu',
  1766.                         'password' => 'Honeybee@0112',
  1767.                         'smtpServer' => 'smtp.hostinger.com',
  1768.                         'smtpPort' => 465,
  1769.                         'mailTemplate' => $bodyTemplate,
  1770.                         'templateData' => $bodyData,
  1771.                         'embedCompanyImage' => 1,
  1772.                         'companyId' => $data->request->get('company'),
  1773.                         'companyImagePath' => $companyData->getImage()
  1774.                     ]);
  1775.                 }
  1776.                 $this->addFlash('success''New Employee Successfully Added!');
  1777.                 $userType $data->getSession()->get(UserConstants::USER_TYPE);
  1778.                 $redirectUrl $userType == 1
  1779.                     $this->generateUrl('employee_list', [], UrlGenerator::ABSOLUTE_URL)
  1780.                     : $this->generateUrl('add_employee', [], UrlGenerator::ABSOLUTE_URL);
  1781.                 return new JsonResponse([
  1782.                     'employeeId' => $Employee->getEmployeeId(),
  1783.                     'redirectToNew' => 1,
  1784.                     'success' => true,
  1785.                     'redirectUrl' => $redirectUrl,
  1786.                 ]);
  1787.             }
  1788.         }
  1789.     }
  1790.     public function AddNewEmployeeAction(Request $request$id)
  1791.     {
  1792.         $em $this->getDoctrine()->getManager();
  1793.         $systemType $this->container->hasParameter('system_type') ? $this->container->getParameter('system_type') : '_ERP_';
  1794.         $approveHash $request->request->get('approvalHash');
  1795.         $loginId $request->getSession()->get(UserConstants::USER_LOGIN_ID);
  1796.         $CompanyId $this->getLoggedUserCompanyId($request);
  1797.         $isSignatureOk DocValidation::isSignatureOk($em$loginId$approveHash);
  1798.         $employee HumanResource::StoreDataForAddEmployee($em$requestfalse$CompanyId);
  1799.         $isUserExist $em->getRepository(EmployeeDetails::class);
  1800.         if ($isSignatureOk) {
  1801.             if ($isUserExist) {
  1802.                 if ($employee) {
  1803.                     $message $this->get('user_module')->addNewUser(
  1804.                         $request->request->get('firstname') . " " $request->request->get('lastname'),
  1805.                         $request->request->get('email'),
  1806.                         $request->request->get('username'),
  1807.                         $request->request->get('password'),
  1808.                         $request->request->get('desg'),
  1809.                         $request->getLoggedUserLoginId($request),
  1810.                         $request->request->get('company'),
  1811.                         $request->request->get('user_type'),
  1812.                         $request->request->get('companyIdList'),
  1813.                         $request->request->get('branch'),
  1814.                         $request->request->get('supervisor'),
  1815.                         $request->request->get('default_route'),
  1816.                         $request->request->has('access_module') ? 0
  1817.                     );
  1818.                     if ($message[0] == 'success') {
  1819.                         $employee->setUserId($message[3]->getUserId());
  1820.                         $em->flush();
  1821.                         if ($systemType == '_CENTRAL_') {
  1822.                         } else {
  1823.                             $em_goc $this->getDoctrine()->getManager('company_group');
  1824.                             $em_goc->getConnection()->connect();
  1825.                             $connected $em_goc->getConnection()->isConnected();
  1826.                             $gocDataList = [];
  1827.                             $gocDataListByAppId = [];
  1828.                             $retDataDebug = array();
  1829.                             $appIds $message[2]->getAppId();
  1830.                             $userIds $message[3]->getUserId();
  1831.                             if ($connected) {
  1832.                                 $findByQuery = array(
  1833.                                     'active' => 1
  1834.                                 );
  1835.                                 if ($appIds !== '_UNSET_')
  1836.                                     $findByQuery['appId'] = $appIds;
  1837.                                 $gocList $this->getDoctrine()->getManager('company_group')
  1838.                                     ->getRepository("CompanyGroupBundle:CompanyGroup")
  1839.                                     ->findBy($findByQuery);
  1840.                                 foreach ($gocList as $entry) {
  1841.                                     $d = array(
  1842.                                         'name' => $entry->getName(),
  1843.                                         'id' => $entry->getId(),
  1844.                                         'image' => $entry->getImage(),
  1845.                                         'companyGroupHash' => $entry->getCompanyGroupHash(),
  1846.                                         'dbName' => $entry->getDbName(),
  1847.                                         'dbUser' => $entry->getDbUser(),
  1848.                                         'dbPass' => $entry->getDbPass(),
  1849.                                         'dbHost' => $entry->getDbHost(),
  1850.                                         'appId' => $entry->getAppId(),
  1851.                                         'companyRemaining' => $entry->getCompanyRemaining(),
  1852.                                         'companyAllowed' => $entry->getCompanyAllowed(),
  1853.                                     );
  1854.                                     $gocDataList[$entry->getId()] = $d;
  1855.                                     $gocDataListByAppId[$entry->getAppId()] = $d;
  1856.                                 }
  1857.                                 $debugCount 0;
  1858.                                 foreach ($gocDataList as $gocId => $entry) {
  1859.                                     $skipSend 1;
  1860.                                     $connector $this->container->get('application_connector');
  1861.                                     $connector->resetConnection(
  1862.                                         'default',
  1863.                                         $gocDataList[$gocId]['dbName'],
  1864.                                         $gocDataList[$gocId]['dbUser'],
  1865.                                         $gocDataList[$gocId]['dbPass'],
  1866.                                         $gocDataList[$gocId]['dbHost'],
  1867.                                         $reset true);
  1868.                                     $em $this->getDoctrine()->getManager();
  1869.                                     if ($userIds !== '_UNSET_')
  1870.                                         $users $this->getDoctrine()
  1871.                                             ->getRepository('ApplicationBundle:SysUser')
  1872.                                             ->findBy(
  1873.                                                 array(
  1874.                                                     'userId' => $userIds
  1875.                                                 )
  1876.                                             );
  1877.                                     else
  1878.                                         $users $this->getDoctrine()
  1879.                                             ->getRepository('ApplicationBundle:SysUser')
  1880.                                             ->findBy(
  1881.                                                 array()
  1882.                                             );
  1883.                                     $output '';
  1884.                                     $userData = array();
  1885.                                     $userFiles = array();
  1886.                                     foreach ($users as $user) {
  1887.                                         $file $this->container->getParameter('kernel.root_dir') . '/../web/' $user->getImage();
  1888.                                         if ($user->getImage() != '' && $user->getImage() != null && file_exists($file)) {
  1889.                                             $mime mime_content_type($file);
  1890.                                             $info pathinfo($file);
  1891.                                             $name $info['basename'];
  1892.                                             if (strpos($mime'image') !== false) {
  1893.                                                 $output = new \CURLFile($file$mime$name);
  1894.                                             }
  1895.                                             $skipSend 0;
  1896.                                             $userFiles['file_' $user->getUserAppId() . '_' $user->getUserId()] = $output;
  1897.                                         } else {
  1898.                                             $user->setImage(null);
  1899.                                             $userFiles['file_' $user->getUserAppId() . '_' $user->getUserId()] = 'pika';
  1900.                                             $em->flush();
  1901.                                         }
  1902.                                         $getters array_filter(get_class_methods($user), function ($method) {
  1903.                                             return 'get' === substr($method03);
  1904.                                         });
  1905.                                         $userDataSingle = array();
  1906.                                         foreach ($getters as $getter) {
  1907.                                             if ($getter == 'getCreatedAt' || $getter == 'getUpdatedAt' || $getter == 'getImage')
  1908.                                                 continue;
  1909. //                                if(is_string($user->{$getter}())|| is_numeric($user->{$getter}()))
  1910. //                                {
  1911. //                                    $userDataSingle[$getter]= $user->{$getter}();
  1912. //                                }
  1913.                                             if ($user->{$getter}() instanceof \DateTime) {
  1914.                                                 $ggtd $user->{$getter}();
  1915.                                                 $userDataSingle[$getter] = $ggtd->format('Y-m-d');
  1916.                                             } else
  1917.                                                 $userDataSingle[$getter] = $user->{$getter}();
  1918.                                         }
  1919. //                                                    $userDataSingle['getNid']=$Employee->getNid();
  1920. //                                                    $userDataSingle['getCurrAddr'] = $Employee->getCurrAddr();
  1921.                                         $userData[] = $userDataSingle;
  1922.                                     }
  1923.                                     $retDataDebug[$debugCount] = array(
  1924.                                         'skipSend' => $skipSend
  1925.                                     );
  1926.                                     {
  1927.                                         $urlToCall GeneralConstant::HONEYBEE_CENTRAL_SERVER '/SyncUserToCentralUser';
  1928.                                         $userFiles['userData'] = json_encode($userData);
  1929.                                         $curl curl_init();
  1930.                                         curl_setopt_array($curl, array(
  1931.                                             CURLOPT_RETURNTRANSFER => 1,
  1932.                                             CURLOPT_POST => 1,
  1933.                                             CURLOPT_URL => $urlToCall,
  1934.                                             CURLOPT_CONNECTTIMEOUT => 10,
  1935.                                             CURLOPT_SSL_VERIFYPEER => false,
  1936.                                             CURLOPT_SSL_VERIFYHOST => false,
  1937. //                            CURLOPT_SAFE_UPLOAD => false,
  1938.                                             CURLOPT_HTTPHEADER => array(//                                "Accept: multipart/form-data",
  1939.                                             ),
  1940.                                             //                        CURLOPT_USERAGENT => 'InnoPM',
  1941. //                            CURLOPT_POSTFIELDS => array(
  1942. //                                'userData'=>json_encode($userData),
  1943. //                                'userFiles'=>$userFiles
  1944. //                            ),
  1945.                                             CURLOPT_POSTFIELDS => $userFiles
  1946.                                         ));
  1947.                                         $retData curl_exec($curl);
  1948.                                         $errData curl_error($curl);
  1949.                                         curl_close($curl);
  1950.                                         $response = [];
  1951.                                         if ($errData) {
  1952.                                             $response['status'] = 'error';
  1953.                                             $response['message'] = 'cURL Error: ' $errData;
  1954.                                         } else {
  1955.                                             $retDataObj json_decode($retDatatrue);
  1956.                                             if (!$retDataObj) {
  1957.                                                 $response['status'] = 'error';
  1958.                                                 $response['message'] = 'Invalid response from central server';
  1959.                                                 $response['raw_response'] = $retData;
  1960.                                             } else {
  1961.                                                 $response['status'] = 'success';
  1962.                                                 $response['data'] = $retDataObj;
  1963.                                             }
  1964.                                         }
  1965. // Return JSON response
  1966. //                                                    return new JsonResponse($response);
  1967.                                         $retDataDebug[$debugCount] = $retDataObj;
  1968.                                         if (isset($retDataObj['globalIdsData']))
  1969.                                             foreach ($retDataObj['globalIdsData'] as $app_id => $usrList) {
  1970.                                                 $connector $this->container->get('application_connector');
  1971.                                                 $connector->resetConnection(
  1972.                                                     'default',
  1973.                                                     $gocDataListByAppId[$app_id]['dbName'],
  1974.                                                     $gocDataListByAppId[$app_id]['dbUser'],
  1975.                                                     $gocDataListByAppId[$app_id]['dbPass'],
  1976.                                                     $gocDataListByAppId[$app_id]['dbHost'],
  1977.                                                     $reset true);
  1978.                                                 $em $this->getDoctrine()->getManager();
  1979.                                                 foreach ($usrList as $sys_id => $globaldata) {
  1980.                                                     $user $this->getDoctrine()
  1981.                                                         ->getRepository('ApplicationBundle:SysUser')
  1982.                                                         ->findOneBy(
  1983.                                                             array(
  1984.                                                                 'userId' => $sys_id
  1985.                                                             )
  1986.                                                         );
  1987.                                                     if ($user) {
  1988.                                                         $user->setGlobalId($globaldata['gid']);
  1989.                                                         $em->persist($user);
  1990.                                                         $em->flush();
  1991.                                                     }
  1992.                                                 }
  1993.                                             }
  1994.                                     }
  1995.                                     $debugCount++;
  1996.                                 }
  1997.                             }
  1998. //                    return new JsonResponse($retDataDebug);
  1999.                         }
  2000.                     }
  2001. //                                    if($message[0]=='success'){
  2002. //                                        $SysUserRepo = $em->getRepository('ApplicationBundle:SysUser');
  2003. //                                        $SysUser = $SysUserRepo->findOneBy([
  2004. //                                            'email' => $data->request->get('email')
  2005. //                                        ]);
  2006. //
  2007. //                                        if ($SysUser === null) {
  2008. //                                            throw new \Exception("User with email " . $data->request->get('email') . " not found.");
  2009. //                                        }
  2010. //
  2011. //                                        $isSuccess->setUserId($SysUser->getUserId());
  2012. //                                        $em->persist($isSuccess);
  2013. //                                        $em->flush();
  2014. //                                    }
  2015.                     $companyData $message[2];
  2016.                     if ($message[0] == 'success' && GeneralConstant::EMAIL_ENABLED == 1) {
  2017.                         $bodyHtml '';
  2018.                         $bodyTemplate 'ApplicationBundle:email/user:registration.html.twig';
  2019.                         $bodyData = array(
  2020.                             'name' => $request->request->get('name'),
  2021.                             'companyData' => $companyData,
  2022.                             'userName' => $request->request->get('username'),
  2023.                             'password' => $request->request->get('password'),
  2024.                         );
  2025.                         $attachments = [];
  2026.                         $new_mail $this->get('mail_module');
  2027.                         $new_mail->sendMyMail(array(
  2028.                             'senderHash' => '_CUSTOM_',
  2029.                             //                        'senderHash'=>'_CUSTOM_',
  2030.                             'forwardToMailAddress' => $request->request->get('email'),
  2031.                             'fromAddress' => 'no-reply@ourhoneybee.eu',
  2032.                             'userName' => 'no-reply@ourhoneybee.eu',
  2033.                             'password' => 'Honeybee@0112',
  2034.                             'smtpServer' => 'smtp.hostinger.com',
  2035.                             'smtpPort' => 465,
  2036.                             'subject' => 'User Registration on HoneyBee Ecosystem under Entity ' $companyData->getName(),
  2037.                             'fileName' => '',
  2038.                             'attachments' => $attachments,
  2039.                             'toAddress' => $request->request->get('email'),
  2040.                             'mailTemplate' => $bodyTemplate,
  2041.                             'templateData' => $bodyData,
  2042.                             'embedCompanyImage' => 1,
  2043.                             'companyId' => $request->request->get('company'),
  2044.                             'companyImagePath' => $companyData->getImage()
  2045.                         ));
  2046.                     }
  2047.                 }
  2048.                 $this->addFlash(
  2049.                     'success',
  2050.                     'New Employee Successfully Added!'
  2051.                 );
  2052.                 return $this->redirectToRoute('add_employee');
  2053.             } else {
  2054. //                        $requiredFields = [
  2055. //                            'email', 'username', 'password', 'firstname', 'lastname', 'nid', 'dob',
  2056. //                            'sex', 'blood', 'phone', 'perm_addr', 'dept', 'desg', 'branch',
  2057. //                            'emp_type', 'tin'
  2058. //                        ];
  2059. //
  2060. //                        $missingFields = [];
  2061. //
  2062. //                        foreach ($requiredFields as $field) {
  2063. //                            if (!$data->request->get($field)) {
  2064. //                                $missingFields[] = $field;
  2065. //                            }
  2066. //                        }
  2067. //                        if (!empty($missingFields)) {
  2068. //                            $this->addFlash('error', 'Missing fields: ' . implode(', ', $missingFields));
  2069. //                            return $this->redirectToRoute('add_employee');
  2070. //                        }
  2071. //                        $password = $data->request->get('password');
  2072. //                        $passwordPattern = '/^(?=.*[A-Z])(?=.*[a-z])(?=.*\d)(?=.*[\W_]).{8,}$/';
  2073. //                        if (!preg_match($passwordPattern, $password)) {
  2074. //                            $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));
  2075. //                            return $this->redirectToRoute('add_employee');
  2076. //                        }
  2077.                 $CompanyId $this->getLoggedUserCompanyId($request);
  2078.                 $isSuccess HumanResource::StoreDataForAddEmployee($em$requestfalse$CompanyId);
  2079.                 if ($isSuccess) {
  2080.                     if ($request->request->has('send_appointment')) {
  2081.                         $email $request->request->get('email');
  2082.                         $bodyHtml '';
  2083.                         $bodyTemplate 'ApplicationBundle:email/general:appointment_letter_test.html.twig';
  2084.                         $bodyData = [];
  2085.                         $attachments = [];
  2086.                         $forwardToMailAddress $email;
  2087.                         $new_mail $this->get('mail_module');
  2088.                         $new_mail->sendMyMail(array(
  2089.                             'senderHash' => '_CUSTOM_',
  2090.                             'forwardToMailAddress' => $forwardToMailAddress,
  2091.                             'subject' => 'Appointment Letter',
  2092.                             'attachments' => $attachments,
  2093.                             'toAddress' => $forwardToMailAddress,
  2094.                             'fromAddress' => 'no-reply@ourhoneybee.eu',
  2095.                             'userName' => 'no-reply@ourhoneybee.eu',
  2096.                             'password' => 'Honeybee@0112',
  2097.                             'smtpServer' => 'smtp.hostinger.com',
  2098.                             'smtpPort' => 465,
  2099.                             'emailBody' => $bodyHtml,
  2100.                             'mailTemplate' => $bodyTemplate,
  2101.                             'templateData' => $bodyData,
  2102.                         ));
  2103.                     }
  2104.                     // Mailer function
  2105.                     if ($request->get("send_mail") && empty($request->get('sys_user'))) {
  2106.                         $message $this->get('user_module')->addNewUser(
  2107.                             $request->request->get('firstname') . " " $request->request->get('lastname'),
  2108.                             $request->request->get('email'),
  2109.                             $request->request->get('username'),
  2110.                             $request->request->get('password'),
  2111.                             $request->request->get('desg'),
  2112.                             $request->getLoggedUserLoginId($request),
  2113.                             $request->request->get('company'),
  2114.                             $request->request->get('user_type'),
  2115.                             $request->request->get('companyIdList'),
  2116.                             $request->request->get('branch'),
  2117.                             $request->request->get('supervisor'),
  2118.                             $request->request->get('default_route'),
  2119.                             $request->request->has('access_module') ? 0
  2120.                         );
  2121.                         if ($message[0] == 'success') {
  2122.                             if ($systemType == '_CENTRAL_') {
  2123.                             } else {
  2124.                                 $em_goc $this->getDoctrine()->getManager('company_group');
  2125.                                 $em_goc->getConnection()->connect();
  2126.                                 $connected $em_goc->getConnection()->isConnected();
  2127.                                 $gocDataList = [];
  2128.                                 $gocDataListByAppId = [];
  2129.                                 $retDataDebug = array();
  2130.                                 $appIds $message[2]->getAppId();
  2131.                                 $userIds $message[3]->getUserId();
  2132.                                 if ($connected) {
  2133.                                     $findByQuery = array(
  2134.                                         'active' => 1
  2135.                                     );
  2136.                                     if ($appIds !== '_UNSET_')
  2137.                                         $findByQuery['appId'] = $appIds;
  2138.                                     $gocList $this->getDoctrine()->getManager('company_group')
  2139.                                         ->getRepository("CompanyGroupBundle:CompanyGroup")
  2140.                                         ->findBy($findByQuery);
  2141.                                     foreach ($gocList as $entry) {
  2142.                                         $d = array(
  2143.                                             'name' => $entry->getName(),
  2144.                                             'id' => $entry->getId(),
  2145.                                             'image' => $entry->getImage(),
  2146.                                             'companyGroupHash' => $entry->getCompanyGroupHash(),
  2147.                                             'dbName' => $entry->getDbName(),
  2148.                                             'dbUser' => $entry->getDbUser(),
  2149.                                             'dbPass' => $entry->getDbPass(),
  2150.                                             'dbHost' => $entry->getDbHost(),
  2151.                                             'appId' => $entry->getAppId(),
  2152.                                             'companyRemaining' => $entry->getCompanyRemaining(),
  2153.                                             'companyAllowed' => $entry->getCompanyAllowed(),
  2154.                                         );
  2155.                                         $gocDataList[$entry->getId()] = $d;
  2156.                                         $gocDataListByAppId[$entry->getAppId()] = $d;
  2157.                                     }
  2158.                                     $debugCount 0;
  2159.                                     foreach ($gocDataList as $gocId => $entry) {
  2160.                                         $skipSend 1;
  2161.                                         $connector $this->container->get('application_connector');
  2162.                                         $connector->resetConnection(
  2163.                                             'default',
  2164.                                             $gocDataList[$gocId]['dbName'],
  2165.                                             $gocDataList[$gocId]['dbUser'],
  2166.                                             $gocDataList[$gocId]['dbPass'],
  2167.                                             $gocDataList[$gocId]['dbHost'],
  2168.                                             $reset true);
  2169.                                         $em $this->getDoctrine()->getManager();
  2170.                                         if ($userIds !== '_UNSET_')
  2171.                                             $users $this->getDoctrine()
  2172.                                                 ->getRepository('ApplicationBundle:SysUser')
  2173.                                                 ->findBy(
  2174.                                                     array(
  2175.                                                         'userId' => $userIds
  2176.                                                     )
  2177.                                                 );
  2178.                                         else
  2179.                                             $users $this->getDoctrine()
  2180.                                                 ->getRepository('ApplicationBundle:SysUser')
  2181.                                                 ->findBy(
  2182.                                                     array()
  2183.                                                 );
  2184.                                         $output '';
  2185.                                         $userData = array();
  2186.                                         $userFiles = array();
  2187.                                         foreach ($users as $user) {
  2188.                                             $file $this->container->getParameter('kernel.root_dir') . '/../web/' $user->getImage();
  2189.                                             if ($user->getImage() != '' && $user->getImage() != null && file_exists($file)) {
  2190.                                                 $mime mime_content_type($file);
  2191.                                                 $info pathinfo($file);
  2192.                                                 $name $info['basename'];
  2193.                                                 if (strpos($mime'image') !== false) {
  2194.                                                     $output = new \CURLFile($file$mime$name);
  2195.                                                 }
  2196.                                                 $skipSend 0;
  2197.                                                 $userFiles['file_' $user->getUserAppId() . '_' $user->getUserId()] = $output;
  2198.                                             } else {
  2199.                                                 $user->setImage(null);
  2200.                                                 $userFiles['file_' $user->getUserAppId() . '_' $user->getUserId()] = 'pika';
  2201.                                                 $em->flush();
  2202.                                             }
  2203.                                             $getters array_filter(get_class_methods($user), function ($method) {
  2204.                                                 return 'get' === substr($method03);
  2205.                                             });
  2206.                                             $userDataSingle = array();
  2207.                                             foreach ($getters as $getter) {
  2208.                                                 if ($getter == 'getCreatedAt' || $getter == 'getUpdatedAt' || $getter == 'getImage')
  2209.                                                     continue;
  2210. //                                if(is_string($user->{$getter}())|| is_numeric($user->{$getter}()))
  2211. //                                {
  2212. //                                    $userDataSingle[$getter]= $user->{$getter}();
  2213. //                                }
  2214.                                                 if ($user->{$getter}() instanceof \DateTime) {
  2215.                                                     $ggtd $user->{$getter}();
  2216.                                                     $userDataSingle[$getter] = $ggtd->format('Y-m-d');
  2217.                                                 } else
  2218.                                                     $userDataSingle[$getter] = $user->{$getter}();
  2219.                                             }
  2220. //                                                    $userDataSingle['getNid']=$Employee->getNid();
  2221. //                                                    $userDataSingle['getCurrAddr'] = $Employee->getCurrAddr();
  2222.                                             $userData[] = $userDataSingle;
  2223.                                         }
  2224.                                         $retDataDebug[$debugCount] = array(
  2225.                                             'skipSend' => $skipSend
  2226.                                         );
  2227.                                         {
  2228.                                             $urlToCall GeneralConstant::HONEYBEE_CENTRAL_SERVER '/SyncUserToCentralUser';
  2229.                                             $userFiles['userData'] = json_encode($userData);
  2230.                                             $curl curl_init();
  2231.                                             curl_setopt_array($curl, array(
  2232.                                                 CURLOPT_RETURNTRANSFER => 1,
  2233.                                                 CURLOPT_POST => 1,
  2234.                                                 CURLOPT_URL => $urlToCall,
  2235.                                                 CURLOPT_CONNECTTIMEOUT => 10,
  2236.                                                 CURLOPT_SSL_VERIFYPEER => false,
  2237.                                                 CURLOPT_SSL_VERIFYHOST => false,
  2238. //                            CURLOPT_SAFE_UPLOAD => false,
  2239.                                                 CURLOPT_HTTPHEADER => array(//                                "Accept: multipart/form-data",
  2240.                                                 ),
  2241.                                                 //                        CURLOPT_USERAGENT => 'InnoPM',
  2242. //                            CURLOPT_POSTFIELDS => array(
  2243. //                                'userData'=>json_encode($userData),
  2244. //                                'userFiles'=>$userFiles
  2245. //                            ),
  2246.                                                 CURLOPT_POSTFIELDS => $userFiles
  2247.                                             ));
  2248.                                             $retData curl_exec($curl);
  2249.                                             $errData curl_error($curl);
  2250.                                             curl_close($curl);
  2251.                                             $response = [];
  2252.                                             if ($errData) {
  2253.                                                 $response['status'] = 'error';
  2254.                                                 $response['message'] = 'cURL Error: ' $errData;
  2255.                                             } else {
  2256.                                                 $retDataObj json_decode($retDatatrue);
  2257.                                                 if (!$retDataObj) {
  2258.                                                     $response['status'] = 'error';
  2259.                                                     $response['message'] = 'Invalid response from central server';
  2260.                                                     $response['raw_response'] = $retData;
  2261.                                                 } else {
  2262.                                                     $response['status'] = 'success';
  2263.                                                     $response['data'] = $retDataObj;
  2264.                                                 }
  2265.                                             }
  2266. // Return JSON response
  2267. //                                                    return new JsonResponse($response);
  2268.                                             $retDataDebug[$debugCount] = $retDataObj;
  2269.                                             if (isset($retDataObj['globalIdsData']))
  2270.                                                 foreach ($retDataObj['globalIdsData'] as $app_id => $usrList) {
  2271.                                                     $connector $this->container->get('application_connector');
  2272.                                                     $connector->resetConnection(
  2273.                                                         'default',
  2274.                                                         $gocDataListByAppId[$app_id]['dbName'],
  2275.                                                         $gocDataListByAppId[$app_id]['dbUser'],
  2276.                                                         $gocDataListByAppId[$app_id]['dbPass'],
  2277.                                                         $gocDataListByAppId[$app_id]['dbHost'],
  2278.                                                         $reset true);
  2279.                                                     $em $this->getDoctrine()->getManager();
  2280.                                                     foreach ($usrList as $sys_id => $globaldata) {
  2281.                                                         $user $this->getDoctrine()
  2282.                                                             ->getRepository('ApplicationBundle:SysUser')
  2283.                                                             ->findOneBy(
  2284.                                                                 array(
  2285.                                                                     'userId' => $sys_id
  2286.                                                                 )
  2287.                                                             );
  2288.                                                         if ($user) {
  2289.                                                             $user->setGlobalId($globaldata['gid']);
  2290.                                                             $em->persist($user);
  2291.                                                             $em->flush();
  2292.                                                         }
  2293.                                                     }
  2294.                                                 }
  2295.                                         }
  2296.                                         $debugCount++;
  2297.                                     }
  2298.                                 }
  2299. //                    return new JsonResponse($retDataDebug);
  2300.                             }
  2301.                         }
  2302.                         $SysUserRepo $em->getRepository(SysUser::class);
  2303.                         $SysUser $SysUserRepo->findOneBy(array(
  2304.                             'email' => $request->request->get('email')
  2305.                         ));
  2306.                         $isSuccess->setUserId($SysUser->getUserId());
  2307.                         $em->persist($isSuccess);
  2308.                         $em->flush();
  2309.                         $companyData $message[2];
  2310.                         if ($message[0] == 'success' && GeneralConstant::EMAIL_ENABLED == 1) {
  2311.                             $bodyHtml '';
  2312.                             $bodyTemplate 'ApplicationBundle:email/user:registration.html.twig';
  2313.                             $bodyData = array(
  2314.                                 'name' => $request->request->get('name'),
  2315.                                 'companyData' => $companyData,
  2316.                                 'userName' => $request->request->get('username'),
  2317.                                 'password' => $request->request->get('password'),
  2318.                             );
  2319.                             $attachments = [];
  2320. //                    $upl_dir = $this->container->getParameter('kernel.root_dir') . '/../web/uploads/temp/' . 'ledger' . '.pdf'
  2321.                             $new_mail $this->get('mail_module');
  2322.                             $new_mail->sendMyMail(array(
  2323.                                 'senderHash' => '_CUSTOM_',
  2324.                                 //                        'senderHash'=>'_CUSTOM_',
  2325.                                 'forwardToMailAddress' => $request->request->get('email'),
  2326.                                 'subject' => 'User Registration on HoneyBee Ecosystem under Entity ' $companyData->getName(),
  2327.                                 'fileName' => '',
  2328.                                 'attachments' => $attachments,
  2329.                                 'toAddress' => $request->request->get('email'),
  2330.                                 'fromAddress' => 'no-reply@ourhoneybee.eu',
  2331.                                 'userName' => 'no-reply@ourhoneybee.eu',
  2332.                                 'password' => 'Honeybee@0112',
  2333.                                 'smtpServer' => 'smtp.hostinger.com',
  2334.                                 'smtpPort' => 465,
  2335. //                        'fromAddress'=>'sales@entity.innobd.com',
  2336. //                        'userName'=>'sales@entity.innobd.com',
  2337. //                        'password'=>'Y41dh8g0112',
  2338. //                        'smtpServer'=>'smtp.hostinger.com',
  2339. //                        'smtpPort'=>587,
  2340. //                        'emailBody'=>$bodyHtml,
  2341.                                 'mailTemplate' => $bodyTemplate,
  2342.                                 'templateData' => $bodyData,
  2343.                                 'embedCompanyImage' => 1,
  2344.                                 'companyId' => $request->request->get('company'),
  2345.                                 'companyImagePath' => $companyData->getImage()
  2346.                             ));
  2347. //                  $emailmessage = (new \Swift_Message('Registration to Entity'))
  2348. //                    ->setFrom('registration@entity.innobd.com')
  2349. //                    ->setTo($data->request->get('email'))
  2350. //                    ->setBody(
  2351. //                      $this->renderView(
  2352. //                        'ApplicationBundle:email/user:registration.html.twig',
  2353. //                        array(
  2354. //                          'name' => $data->request->get('name'),
  2355. //                          'companyData' => $companyData,
  2356. //                          'userName' => $data->request->get('email'),
  2357. //                          'password' => $data->request->get('password'),
  2358. //                        )
  2359. //                      ),
  2360. //                      'text/html'
  2361. //                    );
  2362. //                  $this->get('mailer')->send($emailmessage);
  2363.                         }
  2364.                     }
  2365.                     // End Mailer function
  2366.                     $this->addFlash(
  2367.                         'success',
  2368.                         'New Employee Successfully Added!'
  2369.                     );
  2370.                     return $this->redirectToRoute('employee_list');
  2371.                 } else {
  2372.                     $this->addFlash(
  2373.                         'error',
  2374.                         'Something Went Wrong!'
  2375.                     );
  2376.                     return $this->redirectToRoute('add_employee');
  2377.                 }
  2378.             }
  2379.         } else {
  2380.             $this->addFlash(
  2381.                 'error',
  2382.                 'Invalid Approval Hash!'
  2383.             );
  2384.             return $this->redirectToRoute('add_employee');
  2385.         }
  2386.     }
  2387.     public function UpdateEmployeeAction(Request $request$id)
  2388.     {
  2389.     }
  2390.     private function uploadImage($image$request)
  2391.     {
  2392.         $upl_dir $this->container->getParameter('kernel.root_dir') . '/../web/uploads/Users/';
  2393.         $profileImage '';
  2394.         if ($image != null) {
  2395.             $fileName $request->request->get('firstname') . '.' $request->request->get('global_user_id') . '.' $image->guessExtension();
  2396.             $path $fileName;
  2397.             if (!file_exists($upl_dir)) {
  2398.                 mkdir($upl_dir0777true);
  2399.             }
  2400.             $image->move($upl_dir$path);
  2401.             $profileImage 'uploads/Users/' $path;
  2402.         }
  2403.         return $profileImage;
  2404.     }
  2405.     private function uploadMeetingFile($file$request)
  2406.     {
  2407.         $upl_dir $this->container->getParameter('kernel.root_dir') . '/../web/uploads/meeting/';
  2408.         $uploadedFilePath '';
  2409.         if ($file != null) {
  2410.             $fileName uniqid() . '.' $file->guessExtension();
  2411.             if (!file_exists($upl_dir)) {
  2412.                 mkdir($upl_dir0777true);
  2413.             }
  2414.             $file->move($upl_dir$fileName);
  2415.             $uploadedFilePath 'uploads/meeting/' $fileName;
  2416.         }
  2417.         return $uploadedFilePath;
  2418.     }
  2419.     public function OnboardEmployeeAction(Request $request)
  2420.     {
  2421.         $systemType $this->container->hasParameter('system_type') ? $this->container->getParameter('system_type') : '_ERP_';
  2422.         $email $request->request->get('email');
  2423.         $applicantId $request->request->get('applicant_id');
  2424.         $em_goc $this->getDoctrine()->getManager('company_group');
  2425.         $em $this->getDoctrine()->getManager();
  2426.         $session $request->getSession();
  2427.         $companyId $session->get('userCompanyId');
  2428.         $appId $session->get('userAppId');
  2429.         $urlToCall GeneralConstant::HONEYBEE_CENTRAL_SERVER '/get_applicant_data_central';
  2430.         $applicantFiles = [
  2431.             'email' => $email,
  2432.             'applicantId' => $applicantId
  2433.         ];
  2434.         $entityToken $em_goc->getRepository('CompanyGroupBundle:EntityTokenStorage')
  2435.             ->findOneBy(['userId' => $applicantId]);
  2436.         $curl curl_init();
  2437.         curl_setopt_array($curl, array(
  2438.             CURLOPT_RETURNTRANSFER => 1,
  2439.             CURLOPT_POST => 1,
  2440.             CURLOPT_URL => $urlToCall,
  2441.             CURLOPT_CONNECTTIMEOUT => 10,
  2442.             CURLOPT_SSL_VERIFYPEER => false,
  2443.             CURLOPT_SSL_VERIFYHOST => false,
  2444.             CURLOPT_HTTPHEADER => array(),
  2445.             CURLOPT_POSTFIELDS => $applicantFiles
  2446.         ));
  2447.         $retData curl_exec($curl);
  2448.         $errData curl_error($curl);
  2449.         curl_close($curl);
  2450.         $retDataObj json_decode($retDatatrue);
  2451.         if (!isset($retDataObj['status']) || $retDataObj['status'] !== 'success') {
  2452.             return new JsonResponse([
  2453.                 'status' => 'error',
  2454.                 'message' => 'Failed to get applicant data from central server',
  2455.                 'response' => $retDataObj
  2456.             ]);
  2457.         }
  2458.         $centralData $retDataObj['centralData'];
  2459.         $em $this->getDoctrine()->getManager();
  2460.         $existingUser $em->getRepository('ApplicationBundle:SysUser')->findOneBy([
  2461.             'globalId' => $centralData['globalId']
  2462.         ]);
  2463.         if ($existingUser) {
  2464.             return new JsonResponse([
  2465.                 'status' => 'info',
  2466.                 'message' => 'User is already onboarded',
  2467.                 'userId' => $existingUser->getUserId(),
  2468.                 'redirectUrl' => 'dashboard'
  2469.             ]);
  2470.         }
  2471.         $sysUser = new SysUser();
  2472.         $sysUser->setGlobalId($centralData['globalId'] ?? '');
  2473.         $sysUser->setUsername($centralData['username'] ?? '');
  2474.         $sysUser->setEmail($centralData['email'] ?? '');
  2475.         $sysUser->setName($centralData['firstname'] ?? '');
  2476.         $sysUser->setUserType(1);
  2477.         $sysUser->setUserAppId($appId);
  2478.         $sysUser->setUserCompanyId($companyId);
  2479.         $sysUser->setStatus(1);
  2480.         $sysUser->setDefaultRoute('sales_dashboard');
  2481.         $em->persist($sysUser);
  2482.         $em->flush();
  2483.         $employee $em->getRepository('ApplicationBundle:Employee')
  2484.             ->findOneBy(
  2485.                 array(
  2486.                     'userId' => $sysUser->getUserId(),
  2487.                 )
  2488.             );
  2489.         if (!$employee) {
  2490.             $employee = new Employee();
  2491.             if ($sysUser->getUserId()) {
  2492.                 $employee->setEmail($sysUser->getEmail());
  2493.                 $employee->setFirstName($sysUser->getUsername());
  2494.                 $employee->setLastName($sysUser->getName());
  2495.                 $employee->setCompanyId($sysUser->getUserCompanyId());
  2496.                 $employee->setStatus(1);
  2497.                 $employee->setUserId($sysUser->getUserId());
  2498.                 $em->persist($employee);
  2499.                 $em->flush();
  2500.             } else {
  2501.                 return new JsonResponse([
  2502.                     'status' => 'error',
  2503.                     'message' => 'Missing employee data',
  2504.                 ]);
  2505.             }
  2506.         }
  2507.         $employeeDetails $em->getRepository('ApplicationBundle:EmployeeDetails')
  2508.             ->findOneBy([
  2509.                 'userId' => $sysUser->getUserId(),
  2510.             ]);
  2511.         if (!$employeeDetails) {
  2512.             $employeeDetails = new EmployeeDetails();
  2513.             if ($sysUser->getUserId() && $employee->getEmployeeId()) {
  2514.                 $employeeDetails->setId($employee->getEmployeeId());
  2515.                 $employeeDetails->setEmail($sysUser->getEmail());
  2516.                 $employeeDetails->setFirstName($sysUser->getUsername());
  2517.                 $employeeDetails->setLastName($sysUser->getName());
  2518.                 $employeeDetails->setUsername($sysUser->getUsername());
  2519.                 $employeeDetails->setUserId($sysUser->getUserId());
  2520.                 $employeeDetails->setEmpStatus(1);
  2521.                 $em->persist($employeeDetails);
  2522.                 $em->flush();
  2523.             } else {
  2524.                 return new JsonResponse([
  2525.                     'status' => 'error',
  2526.                     'message' => 'Missing employee details data',
  2527.                 ]);
  2528.             }
  2529.         }
  2530.         $company $em->getRepository('ApplicationBundle:Company')->find($companyId);
  2531.         $companyName $company $company->getName() : '';
  2532.         $newAccess = [
  2533.             'userType' => 2,
  2534.             'userTypeName' => UserConstants::$userTypeName[2],
  2535.             'globalId' => $applicantId,
  2536.             'serverId' => 1,
  2537.             'serverUrl' => $request->getSchemeAndHttpHost(),
  2538.             'serverPort' => 80,
  2539.             'systemType' => '_ERP_',
  2540.             'companyId' => 1,
  2541.             'appId' => $appId,
  2542.             'companyLogoUrl' => '/uploads/CompanyImage/company_image' $request->request->get('appId') . '.png',
  2543.             'companyName' => $companyName,
  2544.             'authenticationStr' => $this->get('url_encryptor')->encrypt(json_encode(
  2545.                     array(
  2546.                         'globalId' => $applicantId,
  2547.                         'appId' => $appId,
  2548.                         'authenticate' => 1,
  2549.                         'userType' => 2,
  2550.                         'userTypeName' => UserConstants::$userTypeName[2]
  2551.                     )
  2552.                 )
  2553.             ),
  2554.             'userCompanyList' => [],
  2555.         ];
  2556.         $urlToCall GeneralConstant::HONEYBEE_CENTRAL_SERVER '/update_token_storage';
  2557.         $curl curl_init();
  2558.         curl_setopt_array($curl, array(
  2559.             CURLOPT_RETURNTRANSFER => 1,
  2560.             CURLOPT_POST => 1,
  2561.             CURLOPT_URL => $urlToCall,
  2562.             CURLOPT_CONNECTTIMEOUT => 10,
  2563.             CURLOPT_SSL_VERIFYPEER => false,
  2564.             CURLOPT_SSL_VERIFYHOST => false,
  2565.             CURLOPT_HTTPHEADER => array(),
  2566.             CURLOPT_POSTFIELDS => json_encode($newAccess)
  2567.         ));
  2568.         $retData curl_exec($curl);
  2569.         $errData curl_error($curl);
  2570.         return new JsonResponse([
  2571.             'status' => 'success',
  2572.             'message' => 'User onboarded successfully',
  2573.             'redirectUlr' => 'dashboard',
  2574.             'returnData' => $retData,
  2575.             'errorData' => $errData
  2576.         ]);
  2577.     }
  2578.     public function DecodeQrAction(Request $request)
  2579.     {
  2580.         $applicantId $request->request->get('applicant_id');
  2581.         $urlToCall GeneralConstant::HONEYBEE_CENTRAL_SERVER '/get_applicant_data_central';
  2582.         $applicantFiles = [
  2583.             'applicantId' => $applicantId
  2584.         ];
  2585.         $curl curl_init();
  2586.         curl_setopt_array($curl, array(
  2587.             CURLOPT_RETURNTRANSFER => 1,
  2588.             CURLOPT_POST => 1,
  2589.             CURLOPT_URL => $urlToCall,
  2590.             CURLOPT_CONNECTTIMEOUT => 10,
  2591.             CURLOPT_SSL_VERIFYPEER => false,
  2592.             CURLOPT_SSL_VERIFYHOST => false,
  2593.             CURLOPT_HTTPHEADER => array(),
  2594.             CURLOPT_POSTFIELDS => $applicantFiles
  2595.         ));
  2596.         $retData curl_exec($curl);
  2597.         $errData curl_error($curl);
  2598.         curl_close($curl);
  2599.         $retDataObj json_decode($retDatatrue);
  2600.         return new JsonResponse($retDataObj['centralData']);
  2601.     }
  2602.     public function GetApplicantDataForErpAction(Request $request)
  2603.     {
  2604.         $applicantId $request->request->get('applicantId');
  2605.         if (!$applicantId) {
  2606.             return new JsonResponse([
  2607.                 'status' => 'error',
  2608.                 'message' => 'Missing applicantId in request.'
  2609.             ]);
  2610.         }
  2611.         $em_goc $this->getDoctrine()->getManager('company_group');
  2612.         $entityApplicant $em_goc->getRepository("CompanyGroupBundle:EntityApplicantDetails")
  2613.             ->findOneBy(['applicantId' => $applicantId]);
  2614.         if (!$entityApplicant) {
  2615.             return new JsonResponse([
  2616.                 'status' => 'error',
  2617.                 'message' => 'Applicant not found.'
  2618.             ]);
  2619.         }
  2620.         return new JsonResponse([
  2621.             'status' => 'success',
  2622.             'centralData' => [
  2623.                 'globalId' => $entityApplicant->getApplicantId(),
  2624.                 'username' => $entityApplicant->getUsername(),
  2625.                 'email' => $entityApplicant->getEmail(),
  2626.                 'firstname' => $entityApplicant->getFirstname(),
  2627.                 'lastname' => $entityApplicant->getLastname(),
  2628.                 'image' => $entityApplicant->getImage(),
  2629.                 'phone' => $entityApplicant->getPhone(),
  2630.                 'address' => $entityApplicant->getPermAddr()
  2631.             ]
  2632.         ]);
  2633.     }
  2634.     public function UpdateTokenStorageAction(Request $request)
  2635.     {
  2636.         $em_goc $this->getDoctrine()->getManager('company_group');
  2637.         $newAccess $request->request->all();
  2638.         $appId = isset($newAccess['appId']) ? $newAccess['appId'] : null;
  2639.         $globalId = isset($newAccess['globalId']) ? $newAccess['globalId'] : null;
  2640.         $sesssionData MiscActions::UpdateCompanyListInSession(
  2641.             $em_goc,
  2642.             $globalId,
  2643.             1,
  2644.             1,
  2645.             1,
  2646.             $newAccess
  2647.         );
  2648.         return new JsonResponse([
  2649.             'status' => 'success',
  2650.             'message' => 'Token storage updated',
  2651.             'newaccess' => $newAccess
  2652.         ]);
  2653.     }
  2654.     public function EmployeeListAction(Request $data)
  2655.     {
  2656.         $em $this->getDoctrine()->getManager();
  2657.         if ($data->isMethod('GET')) {
  2658.             return $this->render("ApplicationBundle:pages/human_resource/list:list_employee.html.twig", array(
  2659.                 'page_title' => 'Employee List',
  2660.             ));
  2661.         }
  2662.     }
  2663.     public function OrganizationChartAction()
  2664.     {
  2665.         $em $this->getDoctrine()->getManager();
  2666.         $Reponse HumanResource::TwigDataForOrgChart($em);
  2667.         return $this->render('ApplicationBundle:pages/human_resource/views:org_chart.html.twig', array(
  2668.             'page_title' => 'Organization Chart',
  2669.             'supervisors' => $Reponse['TreantJsData'],
  2670.             'alluser' => $Reponse['TreantJsInitUser']
  2671.         ));
  2672.     }
  2673.     public function EmployeeListSelectizeAjaxAction(Request $request$str '_EMPTY_')
  2674.     {
  2675.         $em $this->getDoctrine()->getManager();
  2676.         $companyId $this->getLoggedUserCompanyId($request);
  2677.         $company_data Company::getCompanyData($em$companyId);
  2678.         $data = [];
  2679.         $html '';
  2680.         $qryStrs explode(' '$str);
  2681.         $qryStrAddedForSpacedName "";
  2682.         if ($str == '_EMPTY_') {
  2683.             $query "SELECT *
  2684. from  employee  order by employee_id asc limit 10";
  2685.         } else {
  2686.             foreach ($qryStrs as $qryStr) {
  2687.                 $qryStrAddedForSpacedName .= "or first_name like '%$qryStr%' or last_name like '%$qryStr%' ";
  2688.             }
  2689.             $query "SELECT  *
  2690. 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";
  2691.         }
  2692.         $stmt $em->getConnection()->prepare($query);
  2693.         $stmt->execute();
  2694.         $res $stmt->fetchAll();
  2695. //    if(!empty($res)) {
  2696.         foreach ($res as $i => $r) {
  2697.             $res[$i]['id_padded'] = str_pad($r['employee_id'], 8'0'STR_PAD_LEFT);
  2698.         }
  2699. //    }
  2700.         return new JsonResponse(
  2701.             array(
  2702.                 'success' => true,
  2703.                 'data' => $res,
  2704.             )
  2705.         );
  2706.     }
  2707.     public function AttendanceAction(Request $data$remoteVerify 0)
  2708.     {
  2709.         $em $this->getDoctrine()->getManager();
  2710.         $em_goc $this->getDoctrine()->getManager('company_group');
  2711.         $session $data->getSession();
  2712. //        $token = $session->get(UserConstants::USER_TOKEN);
  2713. //        $providedToken = $data->headers->get('auth-token');
  2714. //
  2715. //        if (empty($providedToken) || $providedToken !== $token) {
  2716. //            return new JsonResponse([
  2717. //                'status' => 'error',
  2718. //                'message' => 'Token not match or missing',
  2719. //            ], 401);
  2720. //        }
  2721.         $workHourPolicy $em->getRepository('ApplicationBundle:WorkHourPolicy')->findAll();
  2722.         $options = array(
  2723.             'notification_enabled' => $this->container->getParameter('notification_enabled'),
  2724.             'notification_server' => $this->container->getParameter('notification_server'),
  2725.         );
  2726.         if ($data->get('DataTable')) {
  2727.             $response HumanResource::HandelAjaxRequestForManualAttendance($em$data);
  2728.             return new JsonResponse($response);
  2729.         }
  2730.         if ($data->request->get('getAttendanceStatus')) {
  2731.             $response HumanResource::getAttendanceStatus($em$data);
  2732.             return new JsonResponse($response);
  2733.         }
  2734. //        if ($session->get('devAdminMode', 0) != 1 && $data->get('returnJson', 0) == 0)
  2735. //            return $this->redirectToRoute('permission_denied_page');
  2736.         // Auto attendance
  2737.         if ($data->get('autoAttendance') && $data->request->has('position_array')) {
  2738. //            $empId = $data->query->get('id');
  2739.             $empId $data->request->get('id'$session->get(UserConstants::USER_EMPLOYEE_ID));
  2740.             $positionsArray $data->request->get('position_array', []);
  2741.             if (is_string($positionsArray)) $positionsArray json_decode($positionsArraytrue);
  2742.             if ($positionsArray == null$positionsArray = [];
  2743.             $dataByAttId = [];
  2744.             $workPlaceType '_UNSET_';
  2745.             foreach ($positionsArray as $d) {
  2746.                 $sysUserId 0;
  2747.                 $userId 0;
  2748.                 $empId 0;
  2749.                 $dtTs 0;
  2750.                 $timeZoneStr '+0000';
  2751. //                $timeZoneStr = '+0600';
  2752.                 $token '_unset_';
  2753.                 if (isset($d['token'])) $token $d['token'];
  2754.                 if (isset($d['employeeId'])) $empId $d['employeeId'];
  2755.                 if (isset($d['userId'])) $userId $d['userId'];
  2756.                 if (isset($d['sysUserId'])) $sysUserId $d['sysUserId'];
  2757.                 if (isset($d['tsMilSec'])) {
  2758.                     $dtTs ceil(($d['tsMilSec']) / 1000);
  2759.                 }
  2760.                 if ($token != '_unset_') {
  2761.                     $sessionData MiscActions::GetSessionDataFromToken($em_goc$token)['sessionData'];
  2762.                     if (isset($sessionData[UserConstants::USER_EMPLOYEE_ID]))
  2763.                         $empId $sessionData[UserConstants::USER_EMPLOYEE_ID];
  2764.                 }
  2765.                 if ($sysUserId == 0)
  2766.                     $sysUserId $userId;
  2767.                 if ($sysUserId == 0)
  2768.                     $sysUserId $em->getRepository(Employee::class)
  2769.                         ->findOneBy(['employeeId' => $empId])->getUserId();
  2770.                 if ($dtTs == 0) {
  2771.                     $currTsTime = new \DateTime();
  2772.                     $dtTs $currTsTime->format('U');
  2773.                 } else {
  2774.                     $currTsTime = new \DateTime('@' $dtTs);
  2775.                 }
  2776.                 $currTsTime->setTimezone(new \DateTimeZone('UTC'));
  2777.                 $attDate = new \DateTime($currTsTime->format('Y-m-d') . ' 00:00:00' $timeZoneStr);
  2778.                 $EmployeeAttendance $this->getDoctrine()
  2779.                     ->getRepository(EmployeeAttendance::class)
  2780.                     ->findOneBy(array('employeeId' => $empId'date' => $attDate));
  2781.                 if (!$EmployeeAttendance)
  2782.                     $EmployeeAttendance = new EmployeeAttendance;
  2783.                 $attendanceInfo HumanResource::StoreAttendance($em$empId$sysUserId$data$EmployeeAttendance$attDate$dtTs$timeZoneStr$d['markerId']);
  2784.                 if ($d['markerId'] == HumanResourceConstant::ATTENDANCE_MARKER_CLOCK_IN) {
  2785.                     if ($empId == 24)
  2786.                         $workPlaceType '_HYBRID_';
  2787.                     else
  2788.                         $workPlaceType '_STATIC_';
  2789.                 }
  2790.                 if (!isset($dataByAttId[$attendanceInfo->getId()]))
  2791.                     $dataByAttId[$attendanceInfo->getId()] = array(
  2792.                         'attendanceInfo' => $attendanceInfo,
  2793.                         'empId' => $empId,
  2794.                         'lat' => 0,
  2795.                         'lng' => 0,
  2796.                         'address' => 0,
  2797.                         'sysUserId' => $sysUserId,
  2798.                         'companyId' => $data->getSession()->get(UserConstants::USER_COMPANY_ID),
  2799.                         'appId' => $data->getSession()->get(UserConstants::USER_APP_ID),
  2800.                         'positionArray' => []
  2801.                     );
  2802.                 $posData = array(
  2803.                     'ts' => $dtTs,
  2804.                     'lat' => $d['lat'],
  2805.                     'lng' => $d['lng'],
  2806.                     'marker' => $d['markerId'],
  2807.                     'src' => 2,
  2808.                 );
  2809.                 $posDataArray = array(
  2810.                     $dtTs,
  2811.                     $d['lat'],
  2812.                     $d['lng'],
  2813.                     $d['markerId'],
  2814.                     2
  2815.                 );
  2816.                 $dataByAttId[$attendanceInfo->getId()]['markerId'] = $d['markerId'];
  2817.                 //this markerId will be calclulted and modified to check if user is in our out of office/workplace later
  2818.                 $dataByAttId[$attendanceInfo->getId()]['attendanceInfo'] = $attendanceInfo;
  2819.                 $dataByAttId[$attendanceInfo->getId()]['positionArray'][] = $posData;
  2820.                 $dataByAttId[$attendanceInfo->getId()]['lat'] = $d['lat'];  //for last lat lng etc
  2821.                 $dataByAttId[$attendanceInfo->getId()]['lng'] = $d['lng'];  //for last lat lng etc
  2822.                 if (isset($d['address']))
  2823.                     $dataByAttId[$attendanceInfo->getId()]['address'] = $d['address'];  //for last lat lng etc
  2824. //                $dataByAttId[$attendanceInfo->getId()]['positionArray'][]=$posDataArray;
  2825.             }
  2826.             $response = array(
  2827.                 'success' => true,
  2828.             );
  2829.             foreach ($dataByAttId as $attInfoId => $d) {
  2830.                 $response HumanResource::setAttendanceLogFlutterApp($em,
  2831.                     $d['empId'],
  2832.                     $d['sysUserId'],
  2833.                     $d['companyId'],
  2834.                     $d['appId'],
  2835.                     $data,
  2836.                     $d['attendanceInfo'],
  2837.                     $options,
  2838.                     $d['positionArray'],
  2839.                     $d['lat'],
  2840.                     $d['lng'],
  2841.                     $d['address'],
  2842.                     $d['markerId']
  2843.                 );
  2844.             }
  2845.             if ($data->request->get('requestFromMobile')) {
  2846.                 $today = new \DateTime(date('y-m-d'));
  2847.                 $repository $this->getDoctrine()->getRepository(EmployeeAttendance::class);
  2848.                 $ActivitiesTemplate HumanResource::getCurrentStatusFromDb($repository$empId$today);
  2849.                 return new JsonResponse(array(
  2850.                     'success' => $response['success'] == true true false,
  2851.                     'msg' => $response['success'] == true 'Employee activities successfully updated.' 'Action Failed',
  2852.                     'workPlaceType' => $workPlaceType,
  2853.                     'data' => $ActivitiesTemplate
  2854.                 ));
  2855.             }
  2856.             return new JsonResponse(
  2857.                 array(
  2858.                     'success' => true,
  2859.                     'msg' => 'Employee activities successfully updated.',
  2860.                     'workPlaceType' => $workPlaceType,
  2861.                 )
  2862.             );
  2863.         } else if ($data->get('autoAttendance')) {
  2864.             if ($data->request->get('requestFromMobile')) {
  2865.                 $empId $data->request->get('employeeId');
  2866.                 $userId $data->request->get('userId'0);
  2867.             } else {
  2868.                 $empId $data->request->get('employeeId'0);
  2869.                 $userId $data->request->get('userId'$data->request->get('id'0));
  2870.             }
  2871.             $dtTs $data->request->get('timeTs'0);
  2872.             $timeZoneStr '+0000';
  2873.             if ($dtTs == 0) {
  2874.                 $currTsTime = new \DateTime();
  2875.                 $dtTs $currTsTime->format('U');
  2876.             } else {
  2877.                 $currTsTime = new \DateTime('@' $dtTs);
  2878.             }
  2879.             $today = new \DateTime(date('y-m-d'));
  2880.             $currTsTime->setTimezone(new \DateTimeZone('UTC'));
  2881.             $attDate = new \DateTime($currTsTime->format('Y-m-d') . ' 00:00:00' $timeZoneStr);
  2882.             $appId=$data->getSession()->get(UserConstants::USER_APP_ID);
  2883.             $response=MiscActions::autoAttendanceGeneral($this->getDoctrine()->getManager(),$empId$userId,$appId$dtTs,$options,$data->request->get('requestFromMobile'));
  2884.             if ($data->request->get('requestFromMobile')) {
  2885.                 return new JsonResponse(array(
  2886.                     'success' => $response['success'] == true true false,
  2887.                     'msg' => $response['success'] == true 'Employee activities successfully updated.' 'Action Failed',
  2888.                 ));
  2889.             }
  2890.             return new JsonResponse(
  2891.                 array(
  2892.                     'success' => true,
  2893.                     'dtTs' => $dtTs,
  2894.                     'attDate' => $attDate->format(DATE_RFC822),
  2895.                     'currTsTime' => $currTsTime->format(DATE_RFC822),
  2896.                     'msg' => 'Employee activities successfully updated.',
  2897.                 )
  2898.             );
  2899.         } else {
  2900.             if ($data->get('manualAttendance')) {
  2901.                 return $this->render(
  2902.                     'ApplicationBundle:pages/human_resource/input_forms:manual_attendance.html.twig',
  2903.                     array(
  2904.                         'page_title' => 'Manual Attendance',
  2905.                         'workPolicy' => $workHourPolicy,
  2906. //                        'workTime' => json_decode($workHourPolicy->getRepeatationData()),
  2907. //                        'workTime' => json_decode($workHourPolicy->getRepeatationData()),
  2908. //                        'workTime' => json_decode($workHourPolicy->getEmployeeTypeIds(),true),
  2909.                     )
  2910.                 );
  2911.             }
  2912.             // Show all matching employee list during ajax request
  2913.             // Show current location according to id
  2914.             if ($data->get('getCurrLocById')) {
  2915.                 $Id $data->get("id");
  2916.                 $options = array(
  2917.                     'employeeId' => $Id,
  2918.                     'entityDbaseName' => 'work_hour_policy',
  2919.                     'entityDbaseIdField' => 'id',
  2920.                     'entityDbaseEmployeeIdsField' => 'employeeIds',
  2921.                     'entityDesignationIdsField' => 'designationIds',
  2922.                     'entityDepartmentIdsField' => 'departmentIds',
  2923.                     'entityEmployeeTypeIdsField' => 'employee_types',
  2924.                     'limit' => 1,
  2925.                     'single' => 1,
  2926.                 );
  2927.                 $workHourPolicyData HumanResource::getApplicableSettingsDataForEmployee($em$options);
  2928.                 $today = new \DateTime(date('y-m-d'));
  2929.                 $repository $this->getDoctrine()->getRepository(EmployeeAttendance::class);
  2930.                 $ActivitiesTemplate HumanResource::getActivitiesTemplate($repository$Id$today);
  2931.                 return new JsonResponse(["success" => true"workHourPolicyData" => $workHourPolicyData"template" => $ActivitiesTemplate]);
  2932.             }
  2933.         }
  2934.     }
  2935.     public function AttendanceForAppAction(Request $data$remoteVerify 0)
  2936.     {
  2937.         $em $this->getDoctrine()->getManager();
  2938.         $em_goc $this->getDoctrine()->getManager('company_group');
  2939.         $session $data->getSession();
  2940.         $token $session->get(UserConstants::USER_TOKEN);
  2941.         $providedToken $data->headers->get('auth-token');
  2942.         if (empty($providedToken) || $providedToken !== $token) {
  2943.             return new JsonResponse([
  2944.                 'status' => 'error',
  2945.                 'message' => 'Token not match or missing',
  2946.             ], 401);
  2947.         }
  2948.         $workHourPolicy $em->getRepository('ApplicationBundle:WorkHourPolicy')->findAll();
  2949.         $options = array(
  2950.             'notification_enabled' => $this->container->getParameter('notification_enabled'),
  2951.             'notification_server' => $this->container->getParameter('notification_server'),
  2952.         );
  2953.         if ($data->get('DataTable')) {
  2954.             $response HumanResource::HandelAjaxRequestForManualAttendance($em$data);
  2955.             return new JsonResponse($response);
  2956.         }
  2957.         if ($data->request->get('getAttendanceStatus')) {
  2958.             $response HumanResource::getAttendanceStatus($em$data);
  2959.             return new JsonResponse($response);
  2960.         }
  2961. //        if ($session->get('devAdminMode', 0) != 1 && $data->get('returnJson', 0) == 0)
  2962. //            return $this->redirectToRoute('permission_denied_page');
  2963.         // Auto attendance
  2964.         if ($data->get('autoAttendance') && $data->request->has('position_array')) {
  2965. //            $empId = $data->query->get('id');
  2966.             $empId $data->request->get('id'$session->get(UserConstants::USER_EMPLOYEE_ID));
  2967.             $positionsArray $data->request->get('position_array', []);
  2968.             if (is_string($positionsArray)) $positionsArray json_decode($positionsArraytrue);
  2969.             if ($positionsArray == null$positionsArray = [];
  2970.             $dataByAttId = [];
  2971.             $workPlaceType '_UNSET_';
  2972.             foreach ($positionsArray as $d) {
  2973.                 $sysUserId 0;
  2974.                 $userId 0;
  2975.                 $empId 0;
  2976.                 $dtTs 0;
  2977.                 $timeZoneStr '+0000';
  2978. //                $timeZoneStr = '+0600';
  2979.                 $token '_unset_';
  2980.                 if (isset($d['token'])) $token $d['token'];
  2981.                 if (isset($d['employeeId'])) $empId $d['employeeId'];
  2982.                 if (isset($d['userId'])) $userId $d['userId'];
  2983.                 if (isset($d['sysUserId'])) $sysUserId $d['sysUserId'];
  2984.                 if (isset($d['tsMilSec'])) {
  2985.                     $dtTs ceil(($d['tsMilSec']) / 1000);
  2986.                 }
  2987.                 if ($token != '_unset_') {
  2988.                     $sessionData MiscActions::GetSessionDataFromToken($em_goc$token)['sessionData'];
  2989.                     if (isset($sessionData[UserConstants::USER_EMPLOYEE_ID]))
  2990.                         $empId $sessionData[UserConstants::USER_EMPLOYEE_ID];
  2991.                 }
  2992.                 if ($sysUserId == 0)
  2993.                     $sysUserId $userId;
  2994.                 if ($sysUserId == 0)
  2995.                     $sysUserId $em->getRepository(Employee::class)
  2996.                         ->findOneBy(['employeeId' => $empId])->getUserId();
  2997.                 if ($dtTs == 0) {
  2998.                     $currTsTime = new \DateTime();
  2999.                     $dtTs $currTsTime->format('U');
  3000.                 } else {
  3001.                     $currTsTime = new \DateTime('@' $dtTs);
  3002.                 }
  3003.                 $currTsTime->setTimezone(new \DateTimeZone('UTC'));
  3004.                 $attDate = new \DateTime($currTsTime->format('Y-m-d') . ' 00:00:00' $timeZoneStr);
  3005.                 $EmployeeAttendance $this->getDoctrine()
  3006.                     ->getRepository(EmployeeAttendance::class)
  3007.                     ->findOneBy(array('employeeId' => $empId'date' => $attDate));
  3008.                 if (!$EmployeeAttendance)
  3009.                     $EmployeeAttendance = new EmployeeAttendance;
  3010.                 $attendanceInfo HumanResource::StoreAttendance($em$empId$sysUserId$data$EmployeeAttendance$attDate$dtTs$timeZoneStr$d['markerId']);
  3011.                 if ($d['markerId'] == HumanResourceConstant::ATTENDANCE_MARKER_CLOCK_IN) {
  3012.                     if ($empId == 24)
  3013.                         $workPlaceType '_HYBRID_';
  3014.                     else
  3015.                         $workPlaceType '_STATIC_';
  3016.                 }
  3017.                 if (!isset($dataByAttId[$attendanceInfo->getId()]))
  3018.                     $dataByAttId[$attendanceInfo->getId()] = array(
  3019.                         'attendanceInfo' => $attendanceInfo,
  3020.                         'empId' => $empId,
  3021.                         'lat' => 0,
  3022.                         'lng' => 0,
  3023.                         'address' => 0,
  3024.                         'sysUserId' => $sysUserId,
  3025.                         'companyId' => $data->getSession()->get(UserConstants::USER_COMPANY_ID),
  3026.                         'appId' => $data->getSession()->get(UserConstants::USER_APP_ID),
  3027.                         'positionArray' => []
  3028.                     );
  3029.                 $posData = array(
  3030.                     'ts' => $dtTs,
  3031.                     'lat' => $d['lat'],
  3032.                     'lng' => $d['lng'],
  3033.                     'marker' => $d['markerId'],
  3034.                     'src' => 2,
  3035.                 );
  3036.                 $posDataArray = array(
  3037.                     $dtTs,
  3038.                     $d['lat'],
  3039.                     $d['lng'],
  3040.                     $d['markerId'],
  3041.                     2
  3042.                 );
  3043.                 $dataByAttId[$attendanceInfo->getId()]['markerId'] = $d['markerId'];
  3044.                 //this markerId will be calclulted and modified to check if user is in our out of office/workplace later
  3045.                 $dataByAttId[$attendanceInfo->getId()]['attendanceInfo'] = $attendanceInfo;
  3046.                 $dataByAttId[$attendanceInfo->getId()]['positionArray'][] = $posData;
  3047.                 $dataByAttId[$attendanceInfo->getId()]['lat'] = $d['lat'];  //for last lat lng etc
  3048.                 $dataByAttId[$attendanceInfo->getId()]['lng'] = $d['lng'];  //for last lat lng etc
  3049.                 if (isset($d['address']))
  3050.                     $dataByAttId[$attendanceInfo->getId()]['address'] = $d['address'];  //for last lat lng etc
  3051. //                $dataByAttId[$attendanceInfo->getId()]['positionArray'][]=$posDataArray;
  3052.             }
  3053.             $response = array(
  3054.                 'success' => true,
  3055.             );
  3056.             foreach ($dataByAttId as $attInfoId => $d) {
  3057.                 $response HumanResource::setAttendanceLogFlutterApp($em,
  3058.                     $d['empId'],
  3059.                     $d['sysUserId'],
  3060.                     $d['companyId'],
  3061.                     $d['appId'],
  3062.                     $data,
  3063.                     $d['attendanceInfo'],
  3064.                     $options,
  3065.                     $d['positionArray'],
  3066.                     $d['lat'],
  3067.                     $d['lng'],
  3068.                     $d['address'],
  3069.                     $d['markerId']
  3070.                 );
  3071.             }
  3072.             if ($data->request->get('requestFromMobile')) {
  3073.                 $today = new \DateTime(date('y-m-d'));
  3074.                 $repository $this->getDoctrine()->getRepository(EmployeeAttendance::class);
  3075.                 $ActivitiesTemplate HumanResource::getCurrentStatusFromDb($repository$empId$today);
  3076.                 return new JsonResponse(array(
  3077.                     'success' => $response['success'] == true true false,
  3078.                     'msg' => $response['success'] == true 'Employee activities successfully updated.' 'Action Failed',
  3079.                     'workPlaceType' => $workPlaceType,
  3080.                     'data' => $ActivitiesTemplate
  3081.                 ));
  3082.             }
  3083.             return new JsonResponse(
  3084.                 array(
  3085.                     'success' => true,
  3086.                     'msg' => 'Employee activities successfully updated.',
  3087.                     'workPlaceType' => $workPlaceType,
  3088.                 )
  3089.             );
  3090.         } else if ($data->get('autoAttendance')) {
  3091.             $sysUserId 0;
  3092.             $userId 0;
  3093.             $empId 0;
  3094.             $dtTs 0;
  3095. //            $timeZoneStr = '+0600';
  3096.             $timeZoneStr '+0000';
  3097.             if ($data->request->get('requestFromMobile')) {
  3098.                 $empId $data->request->get('employeeId');
  3099.                 $userId $data->request->get('userId'0);
  3100.                 $sysUserId $data->request->get('id'0);
  3101. //        $empId = $em->getRepository(Employee::class)
  3102. //            ->findOneBy(['userId' => $userId])->getEmployeeId();
  3103.             } else {
  3104.                 $empId $data->request->get('employeeId'0);
  3105.                 $sysUserId $data->request->get('userId'0);
  3106.             }
  3107.             $dtTs $data->request->get('timeTs'0);
  3108.             if ($sysUserId == 0)
  3109.                 $sysUserId $userId;
  3110.             if ($sysUserId == 0)
  3111.                 $sysUserId $em->getRepository(Employee::class)
  3112.                     ->findOneBy(['employeeId' => $empId])->getUserId();
  3113.             if ($dtTs == 0) {
  3114.                 $currTsTime = new \DateTime();
  3115.                 $dtTs $currTsTime->format('U');
  3116.             } else {
  3117.                 $currTsTime = new \DateTime('@' $dtTs);
  3118.             }
  3119.             if ($sysUserId == 0)
  3120.                 $sysUserId $userId;
  3121.             if ($sysUserId == 0)
  3122.                 $sysUserId $em->getRepository(Employee::class)
  3123.                     ->findOneBy(['employeeId' => $empId])->getUserId();
  3124.             $today = new \DateTime(date('y-m-d'));
  3125.             $currTsTime->setTimezone(new \DateTimeZone('UTC'));
  3126.             $attDate = new \DateTime($currTsTime->format('Y-m-d') . ' 00:00:00' $timeZoneStr);
  3127.             $EmployeeAttendance $this->getDoctrine()
  3128.                 ->getRepository(EmployeeAttendance::class)
  3129.                 ->findOneBy(array('employeeId' => $empId'date' => $attDate));
  3130.             if (!$EmployeeAttendance)
  3131.                 $EmployeeAttendance = new EmployeeAttendance;
  3132. //            return new JsonResponse(["success" => true, "data" => $ActivitiesTemplate]);
  3133. //            $attendanceInfo = HumanResource::StoreAttendance($em, $empId, $sysUserId, $data, $EmployeeAttendance, $customTime);
  3134.             $attendanceInfo HumanResource::StoreAttendance($em$empId$sysUserId$data$EmployeeAttendance$attDate$dtTs$timeZoneStrHumanResourceConstant::ATTENDANCE_MARKER_START_WORKING_FORCED);
  3135.             if (!isset($dataByAttId[$attendanceInfo->getId()]))
  3136.                 $dataByAttId[$attendanceInfo->getId()] = array(
  3137.                     'attendanceInfo' => $attendanceInfo,
  3138.                     'empId' => $empId,
  3139.                     'lat' => 0,
  3140.                     'lng' => 0,
  3141.                     'address' => 0,
  3142.                     'sysUserId' => $sysUserId,
  3143.                     'companyId' => $data->getSession()->get(UserConstants::USER_COMPANY_ID),
  3144.                     'appId' => $data->getSession()->get(UserConstants::USER_APP_ID),
  3145.                     'positionArray' => []
  3146.                 );
  3147.             $posData = array(
  3148.                 'ts' => $dtTs,
  3149.                 'lat' => 0,
  3150.                 'lng' => 0,
  3151.                 'marker' => HumanResourceConstant::ATTENDANCE_MARKER_START_WORKING_FORCED,
  3152.                 'src' => 1,
  3153.             );
  3154.             $posDataArray = array(
  3155.                 $dtTs,
  3156.                 0,
  3157.                 0,
  3158.                 HumanResourceConstant::ATTENDANCE_MARKER_START_WORKING_FORCED,
  3159.                 1
  3160.             );
  3161.             $dataByAttId[$attendanceInfo->getId()]['markerId'] = HumanResourceConstant::ATTENDANCE_MARKER_START_WORKING_FORCED;
  3162.             //this markerId will be calclulted and modified to check if user is in our out of office/workplace later
  3163.             $dataByAttId[$attendanceInfo->getId()]['attendanceInfo'] = $attendanceInfo;
  3164.             $dataByAttId[$attendanceInfo->getId()]['positionArray'][] = $posData;
  3165.             $dataByAttId[$attendanceInfo->getId()]['lat'] = 0;  //for last lat lng etc
  3166.             $dataByAttId[$attendanceInfo->getId()]['lng'] = 0;  //for last lat lng etc
  3167.             if (isset($d['address']))
  3168.                 $dataByAttId[$attendanceInfo->getId()]['address'] = '';  //for last lat lng etc
  3169.             $response = array(
  3170.                 'success' => true
  3171.             );
  3172.             foreach ($dataByAttId as $attInfoId => $d) {
  3173.                 $response HumanResource::setAttendanceLogFlutterApp($em,
  3174.                     $d['empId'],
  3175.                     $d['sysUserId'],
  3176.                     $d['companyId'],
  3177.                     $d['appId'],
  3178.                     $data,
  3179.                     $d['attendanceInfo'],
  3180.                     $options,
  3181.                     $d['positionArray'],
  3182.                     $d['lat'],
  3183.                     $d['lng'],
  3184.                     $d['address'],
  3185.                     $d['markerId']
  3186.                 );
  3187.             }
  3188.             if ($data->request->get('requestFromMobile')) {
  3189.                 return new JsonResponse(array(
  3190.                     'success' => $response['success'] == true true false,
  3191.                     'msg' => $response['success'] == true 'Employee activities successfully updated.' 'Action Failed',
  3192.                 ));
  3193.             }
  3194.             return new JsonResponse(
  3195.                 array(
  3196.                     'success' => true,
  3197.                     'dtTs' => $dtTs,
  3198.                     'attDate' => $attDate->format(DATE_RFC822),
  3199.                     'currTsTime' => $currTsTime->format(DATE_RFC822),
  3200.                     'msg' => 'Employee activities successfully updated.',
  3201.                 )
  3202.             );
  3203. //
  3204. //
  3205. //            $response = HumanResource::setAttendanceLog($em, $empId, $sysUserId,
  3206. //                $data->getSession()->get(UserConstants::USER_COMPANY_ID),
  3207. //                $data->getSession()->get(UserConstants::USER_APP_ID),
  3208. //                $data, $attendanceInfo, $options);
  3209. //
  3210. //            if ($data->request->get('requestFromMobile')) {
  3211. //                return new JsonResponse($response);
  3212. //            }
  3213. //
  3214. //            return new JsonResponse(
  3215. //                array(
  3216. //                    'success' => true,
  3217. //                    'msg' => 'Employee activities successfully updated.'
  3218. //                )
  3219. //            );
  3220.             // }
  3221.             // else {
  3222.             //   return new JsonResponse(
  3223.             //     array(
  3224.             //       'success' => false,
  3225.             //       'msg' => "Invalid employee ID"
  3226.             //     )
  3227.             //   );
  3228.             // }
  3229.         } else {
  3230.             if ($data->get('manualAttendance')) {
  3231.                 return $this->render(
  3232.                     'ApplicationBundle:pages/human_resource/input_forms:manual_attendance.html.twig',
  3233.                     array(
  3234.                         'page_title' => 'Manual Attendance',
  3235.                         'workPolicy' => $workHourPolicy,
  3236. //                        'workTime' => json_decode($workHourPolicy->getRepeatationData()),
  3237. //                        'workTime' => json_decode($workHourPolicy->getRepeatationData()),
  3238. //                        'workTime' => json_decode($workHourPolicy->getEmployeeTypeIds(),true),
  3239.                     )
  3240.                 );
  3241.             }
  3242.             // Show all matching employee list during ajax request
  3243.             // Show current location according to id
  3244.             if ($data->get('getCurrLocById')) {
  3245.                 $Id $data->get("id");
  3246.                 $options = array(
  3247.                     'employeeId' => $Id,
  3248.                     'entityDbaseName' => 'work_hour_policy',
  3249.                     'entityDbaseIdField' => 'id',
  3250.                     'entityDbaseEmployeeIdsField' => 'employeeIds',
  3251.                     'entityDesignationIdsField' => 'designationIds',
  3252.                     'entityDepartmentIdsField' => 'departmentIds',
  3253.                     'entityEmployeeTypeIdsField' => 'employee_types',
  3254.                     'limit' => 1,
  3255.                     'single' => 1,
  3256.                 );
  3257.                 $workHourPolicyData HumanResource::getApplicableSettingsDataForEmployee($em$options);
  3258.                 $today = new \DateTime(date('y-m-d'));
  3259.                 $repository $this->getDoctrine()->getRepository(EmployeeAttendance::class);
  3260.                 $ActivitiesTemplate HumanResource::getActivitiesTemplate($repository$Id$today);
  3261.                 return new JsonResponse(["success" => true"workHourPolicyData" => $workHourPolicyData"template" => $ActivitiesTemplate]);
  3262.             }
  3263.         }
  3264.     }
  3265.     public function getCurrentStatusAction($id)
  3266.     {
  3267.         $today = new \DateTime(date('y-m-d'));
  3268.         $repository $this->getDoctrine()->getRepository(EmployeeAttendance::class);
  3269.         $ActivitiesTemplate HumanResource::getCurrentStatusFromDb($repository$id$today);
  3270.         return new JsonResponse(["success" => true"data" => $ActivitiesTemplate]);
  3271.     }
  3272.     public function CurrentAttendanceAction(Request $data)
  3273.     {
  3274.         $em $this->getDoctrine()->getManager();
  3275.         $options = array(
  3276.             'notification_enabled' => $this->container->getParameter('notification_enabled'),
  3277.             'notification_server' => $this->container->getParameter('notification_server'),
  3278.         );
  3279.         if ($data->get('DataTable')) {
  3280.             $response HumanResource::HandelAjaxRequestForManualAttendance($em$data);
  3281.             return new JsonResponse($response);
  3282.         }
  3283.         if ($data->request->get('getAttendanceStatus')) {
  3284.             $response HumanResource::getAttendanceStatus($em$data);
  3285.             return new JsonResponse($response);
  3286.         }
  3287.         // Auto attendance
  3288.         if ($data->get('autoAttendance')) {
  3289.             $empId $data->query->get('id');
  3290.             $sysUserId 0;
  3291.             if ($data->get('requestFromMobile')) {
  3292.                 $sysUserId $data->request->get('id');
  3293.                 $empId $em->getRepository(Employee::class)
  3294.                     ->findOneBy(['userId' => $sysUserId])->getEmployeeId();
  3295.             } else {
  3296.                 $sysUserId $em->getRepository(Employee::class)
  3297.                     ->findOneBy(['employeeId' => $empId])->getUserId();
  3298.             }
  3299.             $customTime $data->get('time');
  3300.             $today = new \DateTime(date('y-m-d'));
  3301.             $EmployeeAttendance $this->getDoctrine()
  3302.                 ->getRepository(EmployeeAttendance::class)
  3303.                 ->findOneBy(array('employeeId' => $empId'date' => $today));
  3304.             if (!$EmployeeAttendance)
  3305.                 $EmployeeAttendance = new EmployeeAttendance;
  3306.             $attendanceInfo HumanResource::StoreAttendance($em$empId$sysUserId$data$EmployeeAttendance$customTime);
  3307.             $response HumanResource::setAttendanceLog($em$empId$sysUserId,
  3308.                 $data->getSession()->get(UserConstants::USER_COMPANY_ID),
  3309.                 $data->getSession()->get(UserConstants::USER_APP_ID),
  3310.                 $data$attendanceInfo$options);
  3311.             if ($data->get('requestFromMobile')) {
  3312.                 return new JsonResponse([$response]);
  3313.             }
  3314.             return new JsonResponse(
  3315.                 array(
  3316.                     'success' => true,
  3317.                     'msg' => 'Employee activities successfully updated.'
  3318.                 )
  3319.             );
  3320.             // }
  3321.             // else {
  3322.             //   return new JsonResponse(
  3323.             //     array(
  3324.             //       'success' => false,
  3325.             //       'msg' => "Invalid employee ID"
  3326.             //     )
  3327.             //   );
  3328.             // }
  3329.         } else {
  3330.             if ($data->get('manualAttendance')) {
  3331.                 return $this->render(
  3332.                     'ApplicationBundle:pages/human_resource/report:current_attendance.html.twig',
  3333.                     array(
  3334.                         'page_title' => 'Current Attendance Status',
  3335.                     )
  3336.                 );
  3337.             }
  3338.             // Show all matching employee list during ajax request
  3339.             // Show current location according to id
  3340.             if ($data->get('getCurrLocById')) {
  3341.                 $Id $data->get("id");
  3342.                 $today = new \DateTime(date('y-m-d'));
  3343.                 $repository $this->getDoctrine()->getRepository(EmployeeAttendance::class);
  3344.                 $ActivitiesTemplate HumanResource::getActivitiesTemplate($repository$Id$today);
  3345.                 return new JsonResponse(["success" => true"template" => $ActivitiesTemplate]);
  3346.             }
  3347.         }
  3348.     }
  3349.     public function EmployeeLeaveAction(Request $data$id 0)
  3350.     {
  3351.         $em $this->getDoctrine()->getManager();
  3352.         $request $data;
  3353.         if (!$id) {
  3354.             if ($data->isMethod('GET')) {
  3355.                 $EmpID $data->query->get('id');
  3356.                 $LeaveType $data->query->get('leaveType');
  3357.                 if ($data->query->has('id') && $data->query->has('leaveType')) {
  3358.                     $response HumanResource::HandelAjaxRequestForLeaveApp($em$EmpID$LeaveType);
  3359.                     return new JsonResponse($response);
  3360.                 }
  3361.                 if ($data->query->has('id')) {
  3362.                     $Response HumanResource::HandelAjaxRequestForLeaveApp($em$EmpID);
  3363.                     return new JsonResponse($Response);
  3364.                 }
  3365.                 $TemplateData HumanResource::TwigDataForLeaveApp($emFalse);
  3366.                 return $this->render(
  3367.                     'ApplicationBundle:pages/human_resource/input_forms:employee_leave.html.twig',
  3368.                     array(
  3369.                         'page_title' => $TemplateData['Title'],
  3370.                         'EmployeeList' => $TemplateData['EmployeeList'],
  3371.                         'DesignationList' => $TemplateData['DesignationList'],
  3372.                         'HasUpdateMode' => false
  3373.                     )
  3374.                 );
  3375.             } else {
  3376.                 $CompanyId $this->getLoggedUserCompanyId($data);
  3377.                 $Response HumanResource::StoreDataForLeaveApplication($em$id$datafalse$CompanyId);
  3378.                 if ($Response['HasErr']) {
  3379.                     $this->addFlash('error'$Response['msg']);
  3380.                     if ($data->request->has('returnJson')) {
  3381.                         return new JsonResponse(array(
  3382.                             'success' => false,
  3383.                             'errorStr' => $Response['msg'],
  3384.                         ));
  3385.                     } else {
  3386.                         return $this->redirectToRoute('employee_leave');
  3387.                     }
  3388.                 }
  3389.                 $applicationId $Response['applicationId'];
  3390.                 $em_goc $this->getDoctrine()->getManager('company_group');
  3391.                 $file_path_list = [];
  3392.                 if ($applicationId != 0) {
  3393.                     if (!empty($request->files)) {
  3394.                         MiscActions::RemoveFilesForEntityDoc($em_goc'EmployeeLeaveApplication'$applicationId);
  3395.                         $storePath 'uploads/LeaveDoc/';
  3396.                         $path "";
  3397.                         $file_path "";
  3398.                         $session $request->getSession();
  3399.                         MiscActions::RemoveExpiredFiles($em_goc);
  3400.                         foreach ($request->files as $uploadedFileGG) {
  3401.                             //            if($uploadedFile->getImage())
  3402.                             //                var_dump($uploadedFile->getFile());
  3403.                             //                var_dump($uploadedFile);
  3404.                             $tempD $uploadedFileGG;
  3405.                             if (!is_array($uploadedFileGG)) {
  3406.                                 $uploadedFileGG = array();
  3407.                                 $uploadedFileGG[] = $tempD;
  3408.                             }
  3409.                             foreach ($uploadedFileGG as $uploadedFile) {
  3410.                                 if ($uploadedFile != null) {
  3411.                                     $extension $uploadedFile->guessExtension();
  3412.                                     $size $uploadedFile->getSize();
  3413.                                     $fileName 'LDOC_' $applicationId '_' . (md5(uniqid())) . '.' $uploadedFile->guessExtension();
  3414.                                     $path $fileName;
  3415.                                     $upl_dir $this->container->getParameter('kernel.root_dir') . '/../web/' $storePath;
  3416.                                     if (!file_exists($upl_dir)) {
  3417.                                         mkdir($upl_dir0777true);
  3418.                                     }
  3419.                                     if (file_exists($upl_dir '' $path)) {
  3420.                                         chmod($upl_dir '' $path0755);
  3421.                                         unlink($upl_dir '' $path);
  3422.                                     }
  3423.                                     $file $uploadedFile->move($upl_dir$path);
  3424.                                     $expireNever 1;
  3425.                                     $expireTs 0;
  3426.                                     $EntityFile = new EntityFile();
  3427.                                     $EntityFile->setPath($this->container->getParameter('kernel.root_dir') . '/../web/' $storePath $path);
  3428.                                     $EntityFile->setMarker('_GEN_');
  3429.                                     $EntityFile->setExtension($extension);
  3430.                                     $EntityFile->setExpireTs($expireTs);
  3431.                                     $EntityFile->setSize($size);
  3432.                                     $EntityFile->setRelativePath($storePath $path);
  3433.                                     $EntityFile->setEntityName('EmployeeLeaveApplication');
  3434.                                     $EntityFile->setEntityBundle('EmployeeLeaveApplication');
  3435.                                     $EntityFile->setEntityId($applicationId);
  3436.                                     $EntityFile->setEntityIdField('employeeLeaveApplicationId');
  3437.                                     $EntityFile->setModifyFieldSetter('setFiles');
  3438.                                     $EntityFile->setDocIdForApplicant(0);
  3439.                                     $EntityFile->setUserId($session->get(UserConstants::USER_ID0));
  3440.                                     $EntityFile->setAppId($session->get(UserConstants::USER_APP_ID0));
  3441.                                     $EntityFile->setEmployeeId($session->get(UserConstants::USER_EMPLOYEE_ID0));
  3442.                                     $EntityFile->setUserType($session->get(UserConstants::USER_TYPE0));
  3443.                                     $em_goc->persist($EntityFile);
  3444.                                     $em_goc->flush();
  3445.                                     $EntityFileId $EntityFile->getId();
  3446.                                 }
  3447.                                 if ($path != "")
  3448.                                     $file_path_list[] = ($storePath $path);
  3449.                             }
  3450.                         }
  3451.                         $g_path $this->container->getParameter('kernel.root_dir') . '/../web/' $storePath $path;
  3452.                         $v $em->getRepository('ApplicationBundle:EmployeeLeaveApplication')->findOneBy(array(
  3453.                             'employeeLeaveApplicationId' => $applicationId,
  3454.                         ));
  3455.                         if ($v) {
  3456.                             $v->setFiles(implode(','$file_path_list));
  3457.                             $em->flush();
  3458.                         } else {
  3459.                         }
  3460.                     }
  3461.                 }
  3462.                 // $this->addFlash('success', 'Application submitted successfully!');
  3463.                 // return $this->redirectToRoute('leave_application_list');
  3464.                 if ($data->request->has('returnJson')) {
  3465.                     return new JsonResponse(array(
  3466.                         'success' => true,
  3467.                     ));
  3468.                 } else {
  3469.                     return $this->redirectToRoute('view_employee_leave_application', array('id' => $applicationId));
  3470.                 }
  3471.             }
  3472.         } else {
  3473.             if ($data->isMethod('GET')) {
  3474.                 $ApplicationRepo $em->getRepository(EmployeeLeaveApplication::class);
  3475.                 $OldData $ApplicationRepo->find(array('employeeLeaveApplicationId' => $id));
  3476.                 $TemplateData HumanResource::TwigDataForLeaveApp($em$OldData);
  3477.                 return $this->render(
  3478.                     'ApplicationBundle:pages/human_resource/input_forms:employee_leave.html.twig',
  3479.                     array(
  3480.                         'page_title' => $TemplateData['Title'],
  3481.                         'EmployeeList' => $TemplateData['EmployeeList'],
  3482.                         'DesignationList' => $TemplateData['DesignationList'],
  3483.                         'OldData' => $TemplateData['OldData'],
  3484.                         'AvailableLeave' => $TemplateData['AvailableLeave'],
  3485.                         'HasUpdateMode' => true
  3486.                     )
  3487.                 );
  3488.             } else {
  3489.                 $CompanyId $this->getLoggedUserCompanyId($data);
  3490.                 $Response HumanResource::StoreDataForLeaveApplication($em$id$datatrue$CompanyId);
  3491.                 if ($Response['HasErr']) {
  3492.                     $this->addFlash('error'$Response['msg']);
  3493.                     return $this->redirectToRoute('employee_leave');
  3494.                 }
  3495.                 $this->addFlash('success'"Application updated successfully!");
  3496.                 return $this->redirectToRoute('leave_application_list');
  3497.             }
  3498.         }
  3499.     }
  3500.     public function ViewLeaveApplicationAction(Request $request$id)
  3501.     {
  3502.         $em $this->getDoctrine()->getManager();
  3503.         if ($id) {
  3504.             $TwigData HumanResource::TwigDataForViewLeaveApplication($em$request$id);
  3505.             if ($TwigData['HasErr']) {
  3506.                 return new JsonResponse(array(
  3507.                     'success' => false,
  3508.                     'msg' => $TwigData['Msg']
  3509.                 ));
  3510.             }
  3511.             return $this->render(
  3512.                 'ApplicationBundle:pages/human_resource/views:leave_application_view.html.twig',
  3513.                 array(
  3514.                     'page_title' => 'View Leave Application',
  3515.                     'Applicant' => $TwigData['Applicant'],
  3516.                     'Application' => $TwigData['Application'],
  3517.                     'LeaveType' => $TwigData['LeaveType'],
  3518.                     'LeaveCategory' => $TwigData['LeaveCategory'],
  3519.                     'leaveDataArray' => $TwigData['leaveDataArray'],
  3520.                     'FrwdEmp' => $TwigData['FrwdEmp'],
  3521.                     'ApplicantDesg' => $TwigData['ApplicantDesg'],
  3522.                     'approval_status' => $TwigData['approval_status'],
  3523.                     'approval_data' => $TwigData['approval_data'],
  3524.                     'document_log' => $TwigData['document_log'],
  3525.                     'auto_created' => 0,
  3526.                 )
  3527.             );
  3528.         }
  3529.         return new JsonResponse(array(
  3530.             'success' => false,
  3531.             'msg' => 'Wrong URL format! Please try with application ID'
  3532.         ));
  3533.     }
  3534.     public function PrintLeaveApplicationAction(Request $request$id)
  3535.     {
  3536.         if ($id) {
  3537.             $em $this->getDoctrine()->getManager();
  3538.             $company_data Company::getCompanyData($em1);
  3539.             $Authorizations System::getSignatureListForDocumentPrint($emarray_flip(GeneralConstant::$Entity_list)['EmployeeLeaveApplication'], $id);
  3540.             $TwigData HumanResource::TwigDataForViewLeaveApplication($em$request$id);
  3541.             if ($TwigData['HasErr']) {
  3542.                 return new JsonResponse(array(
  3543.                     'success' => false,
  3544.                     'msg' => $TwigData['Msg']
  3545.                 ));
  3546.             }
  3547.             $ApplicationCategory $TwigData['Application']->getLeaveCategory();
  3548.             $ApplicationType = ($ApplicationCategory != && $ApplicationCategory != 2) ? $TwigData['LeaveType'] : '';
  3549.             return $this->render(
  3550.                 'ApplicationBundle:pages/human_resource/print:leave_application_print.html.twig',
  3551.                 array(
  3552.                     'page_title' => 'Print Leave Application',
  3553.                     'export' => 'pdf,print',
  3554.                     'company_name' => $company_data->getName(),
  3555.                     'company_data' => $company_data,
  3556.                     'company_address' => $company_data->getAddress(),
  3557.                     'company_image' => $company_data->getImage(),
  3558.                     'Authorizations' => $Authorizations,
  3559.                     'ApplicationType' => $ApplicationType,
  3560.                     'ApplicationCategory' => $ApplicationCategory,
  3561.                     'Applicant' => $TwigData['Applicant'],
  3562.                     'Application' => $TwigData['Application'],
  3563.                     'LeaveType' => $TwigData['LeaveType'],
  3564.                     'LeaveCategory' => $TwigData['LeaveCategory'],
  3565.                     'leaveDataArray' => $TwigData['leaveDataArray'],
  3566.                     'FrwdEmp' => $TwigData['FrwdEmp'],
  3567.                     'ApplicantDesg' => $TwigData['ApplicantDesg'],
  3568.                     'approval_status' => $TwigData['approval_status'],
  3569.                     'approval_data' => $TwigData['approval_data'],
  3570.                     'document_log' => $TwigData['document_log'],
  3571.                     'red' => 0,
  3572.                     'invoice_footer' => 0
  3573.                 )
  3574.             );
  3575.         }
  3576.         return new JsonResponse(array(
  3577.             'success' => false,
  3578.             'msg' => 'Wrong URL format! Please try with application ID'
  3579.         ));
  3580.     }
  3581.     public function LeaveApplicationListAction(Request $request)
  3582.     {
  3583.         $em $this->getDoctrine()->getManager();
  3584.         $response HumanResource::GetEmployeeLeaveApplicationList($em$request);
  3585.         if ($request->isMethod('GET')) {
  3586.             return $this->render("ApplicationBundle:pages/human_resource/list:leave_application_list.html.twig", array(
  3587.                 'page_title' => 'Leave Application List',
  3588.                 'application_data' => $response,
  3589.             ));
  3590.         }
  3591.     }
  3592.     public function PayrollPolicySettingsAction(Request $request$id)
  3593.     {
  3594.         $em $this->getDoctrine()->getManager();
  3595.         $CompanyId $this->getLoggedUserCompanyId($request);
  3596.         if ($id) {
  3597.             if ($request->isMethod('GET')) {
  3598.                 $Row $em->getRepository(PayrollPolicy::class)->find($id);
  3599.                 if (!$Row) {
  3600.                     $this->addFlash('error''Invalid Payroll Policy Id');
  3601.                     return $this->redirectToRoute('payroll_policy_settings');
  3602.                 }
  3603.                 $TwigData HumanResource::GetPayrollPolicyTwigData($em);
  3604.                 $OldData HumanResource::GetPayrollPolicyTwigData($em$id);
  3605.                 return $this->render('ApplicationBundle:pages/human_resource/input_forms:payroll_policy_settings.html.twig', array(
  3606.                     'page_title' => 'Update Payroll Policy Settings',
  3607.                     'EmployeeIds' => $TwigData['EmployeeIds'],
  3608.                     'EmployeeType' => $TwigData['EmployeeType'],//
  3609.                     'department' => $TwigData['department'],
  3610.                     'Designation' => $TwigData['Designation'],
  3611.                     'WorkingDays' => $TwigData['WorkingDays'],
  3612.                     'OldData' => $OldData['Row'],
  3613.                     'earningAspects' => HumanResourceConstant::$earningAspectsForPayrollPolicy,
  3614.                     'leaveTypes' => HumanResourceConstant::$LeaveTypeForPayrollPolicy,
  3615.                     'leaveTypesArray' => HumanResourceConstant::$LeaveTypeArrayForPayrollPolicy,
  3616.                     'deductionAspects' => HumanResourceConstant::$deductionAspects,
  3617.                     'deductionCondition' => json_decode($Row->getDeductionCondition(), true),
  3618.                     'HasUpdateMode' => true,
  3619.                 ));
  3620.             } else {
  3621.                 $Response HumanResource::StorePayrollPolicyData($em$id$CompanyId$request);
  3622.                 if ($Response['HasErr']) {
  3623.                     $this->addFlash('error'$Response['msg']);
  3624.                     return $this->redirectToRoute('payroll_policy_settings');
  3625.                 }
  3626.                 return $this->redirectToRoute('payroll_policy_settings');
  3627. //        if ($Response['isSuccess']) {
  3628. //          return new JsonResponse(array('success' => true, 'msg' => 'don\'t forget to redirect'));
  3629. //        }
  3630. //        return new JsonResponse(array('success' => false, 'msg' => 'Sorry something went wrong'));
  3631.             }
  3632.         } else {
  3633.             if ($request->isMethod('GET')) {
  3634.                 if ($request->query->get('GetDocHash')) {
  3635.                     $Dochash HumanResource::GenerateDocHashForPayrollSettings($em$request);
  3636.                     return new JsonResponse($Dochash);
  3637.                 }
  3638.                 $TwigData HumanResource::GetPayrollPolicyTwigData($em);
  3639.                 return $this->render(
  3640.                     'ApplicationBundle:pages/human_resource/input_forms:payroll_policy_settings.html.twig',
  3641.                     array(
  3642.                         'page_title' => 'Create Payroll Policy Settings',
  3643.                         'EmployeeIds' => $TwigData['EmployeeIds'],
  3644.                         'EmployeeType' => $TwigData['EmployeeType'],
  3645.                         'WorkingDays' => $TwigData['WorkingDays'],
  3646.                         'Designation' => $TwigData['Designation'],
  3647.                         'department' => $TwigData['department'],
  3648.                         'earningAspects' => HumanResourceConstant::$earningAspectsForPayrollPolicy,
  3649.                         'leaveTypes' => HumanResourceConstant::$LeaveTypeForPayrollPolicy,
  3650.                         'leaveTypesArray' => HumanResourceConstant::$LeaveTypeArrayForPayrollPolicy,
  3651.                         'deductionAspects' => HumanResourceConstant::$deductionAspects,
  3652.                         'HasUpdateMode' => false
  3653.                     )
  3654.                 );
  3655.             } else {
  3656.                 $Response HumanResource::StorePayrollPolicyData($em$id$CompanyId$request);
  3657.                 if ($Response['HasErr']) {
  3658.                     $this->addFlash('error'$Response['msg']);
  3659.                     return $this->redirectToRoute('payroll_policy_settings');
  3660.                 }
  3661.                 return $this->redirectToRoute('payroll_policy_settings');
  3662. //        return new JsonResponse(array("success" => true, 'msg' => 'Dont forget to redirect!'));
  3663.             }
  3664.         }
  3665.     }
  3666.     public function AttendanceReportAction(Request $request$apiKey 'impose')
  3667.     {
  3668.         $em $this->getDoctrine()->getManager();
  3669.         $attendanceSource HumanResourceConstant::$attendanceSources;
  3670.         $routeName $request->attributes->get('_route');
  3671.         if ($routeName == 'app_get_attendendance_data') {
  3672.             $ReportData HumanResource::GenerateAttendanceReport($em$request$request->get('considerCurrTsIfNoOut'1));
  3673.             $newReports = [];
  3674.             foreach ($ReportData['Reports'] as $gg) {
  3675.                 foreach ($gg as $d) {
  3676.                     $newReports[] = $d;
  3677. //                if(!isset($newReports[$d['id']]))
  3678. //                    $newReports[$d['id']]=array();
  3679. //                    $newReports[$d['id']][]=$d;
  3680.                 }
  3681.             }
  3682.             return new JsonResponse (array(
  3683.                 'attendanceSource' => $attendanceSource,
  3684. //                'Reports' => $ReportData['Reports'],
  3685.                 'Reports' => $newReports,
  3686.                 'from_date' => $ReportData['from_date'],
  3687.                 'to_date' => $ReportData['to_date'],
  3688.                 'report_for' => $ReportData['generated_for'],
  3689.                 'attendance' => $ReportData['attendance'],
  3690.             ));
  3691.         } else {
  3692.             $EmployeeIds $em->getRepository(EmployeeDetails::class)->findAll();
  3693.             $Departments $em->getRepository(SysDepartment::class)->findAll();
  3694.             if ($request->isMethod('GET')) {
  3695.                 return $this->render('ApplicationBundle:pages/human_resource/report:attendance_report.html.twig', array(
  3696.                     'page_title' => 'Attendance Report',
  3697.                     'employes' => $EmployeeIds,
  3698.                     'departments' => $Departments,
  3699.                     'isMethodGet' => true,
  3700.                     'from_date' => '',
  3701.                     'to_date' => '',
  3702.                     'report_for' => '',
  3703.                     'attendance' => [],
  3704.                     'Reports' => [],
  3705.                     'qry' => ''
  3706.                 ));
  3707.             }
  3708.             $ReportData HumanResource::GenerateAttendanceReport($em$request$request->request->get('considerCurrTsIfNoOut'0));
  3709.             if ($request->request->get('returnJson'0) == 1) {
  3710.                 return new JsonResponse($ReportData);
  3711.             }
  3712.             $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') : []));
  3713.             return $this->render('ApplicationBundle:pages/human_resource/report:attendance_report.html.twig', array(
  3714.                 'page_title' => 'Attendance Report',
  3715.                 'isMethodGet' => false,
  3716.                 'departments' => $Departments,
  3717.                 'employes' => $EmployeeIds,
  3718.                 'attendanceSource' => $attendanceSource,
  3719.                 'Reports' => $ReportData['Reports'],
  3720.                 'from_date' => $ReportData['from_date'],
  3721.                 'to_date' => $ReportData['to_date'],
  3722.                 'report_for' => $ReportData['generated_for'],
  3723.                 'attendance' => $ReportData['attendance'],
  3724.                 'qry' => $Qry
  3725.             ));
  3726.         }
  3727.     }
  3728.     public function PrintAttendanceReportAction(Request $request)
  3729.     {
  3730.         $em $this->getDoctrine()->getManager();
  3731.         $company_data Company::getCompanyData($em1);
  3732.         $ReportData HumanResource::GenerateAttendanceReport($em$request);
  3733.         return $this->render(
  3734.             'ApplicationBundle:pages/human_resource/print:print_attendance_report.html.twig',
  3735.             array(
  3736.                 'page_title' => 'Print Attendance Report',
  3737.                 'export' => 'pdf,print',
  3738.                 'company_name' => $company_data->getName(),
  3739.                 'company_data' => $company_data,
  3740.                 'company_address' => $company_data->getAddress(),
  3741.                 'company_image' => $company_data->getImage(),
  3742.                 'Reports' => $ReportData['Reports'],
  3743.                 'from_date' => $ReportData['from_date'],
  3744.                 'to_date' => $ReportData['to_date'],
  3745.                 'report_for' => $ReportData['generated_for'],
  3746.                 'attendance' => $ReportData['attendance'],
  3747.                 'red' => 0
  3748.             )
  3749.         );
  3750.     }
  3751.     public function DisburseSalaryAction(Request $request)
  3752.     {
  3753.         $em $this->getDoctrine()->getManager();
  3754.         $EmployeeIds $em->getRepository(EmployeeDetails::class)->findBy(
  3755.             array(
  3756.                 'emp_status' => 1
  3757.             )
  3758.         );
  3759.         $startDate $request->get('salary_start_date''');
  3760.         $endDate $request->get('salary_till_date''');
  3761.         $filterType $request->get('filterType'1);
  3762.         $filterBranchIds $request->get('branchIds', []);
  3763.         $filterBankIds $request->get('bankIds', []);
  3764.         $filterDepartmentIds $request->get('departmentIds', []);
  3765.         $filterEmployeeIds $request->get('employeeIds', []);
  3766.         $Departments $em->getRepository(SysDepartment::class)->findAll();
  3767.         $attendance $em->getRepository(EmployeeAttendanceLog::class)->findAll();
  3768.         $banks $em->getRepository(BankList::class)->findAll();
  3769.         $branches $em->getRepository(Branch::class)->findAll();
  3770.         if ($request->isMethod('GET')) {
  3771.             return $this->render('ApplicationBundle:pages/human_resource/report:disburse_salary.html.twig', array(
  3772.                 'page_title' => 'Disburse Salary',
  3773.                 'EmployeeIds' => $EmployeeIds,
  3774.                 'departments' => $Departments,
  3775.                 'attendance' => $attendance,
  3776.                 'branches' => $branches,
  3777.                 'banks' => $banks,
  3778.                 'SalaryReports' => [],
  3779.                 'from_date' => '',
  3780.                 'to_date' => '',
  3781.                 'Qry' => '',
  3782.                 'isMethodGet' => true,
  3783.                 'filterType' => $filterType,
  3784.                 'startDate' => $startDate,
  3785.                 'endDate' => $endDate,
  3786.                 'filterBranchIds' => $filterBranchIds,
  3787.                 'filterBankIds' => $filterBankIds,
  3788.                 'filterDepartmentIds' => $filterDepartmentIds,
  3789.                 'filterEmployeeIds' => $filterEmployeeIds,
  3790.             ));
  3791.         }
  3792.         $SalaryReports HumanResource::BasicDeduction($em$request);
  3793. //        $SalaryReportsNew = HumanResource::calculateSalary($em,
  3794. //            array(
  3795. //                'startDate' => $request->get('salary_start_date', ''),
  3796. //                'endDate' => $request->get('salary_end_date', ''),
  3797. //                'timeZone' => $request->get('time_zone', '+0600'),
  3798. //                'employeeIds' => $request->get('employeeIds', []),
  3799. //                'departmentIds' => $request->get('department', []),
  3800. //                'allFlag' => $request->get('show_all', 0),
  3801. //
  3802. //            )
  3803. //        );
  3804.         $Qry "salary_till_date=" $endDate '&' "departmentIds=" implode(','$filterDepartmentIds) . '&' "employeeIds=" implode(','$filterEmployeeIds) .
  3805.             '&' "salary_start_date=" $startDate .
  3806.             '&' "filterType=" $filterType .
  3807.             '&' "branchIds=" implode(','$filterBranchIds) .
  3808.             '&' "bankIds=" implode(','$filterBankIds);
  3809. //        if ($request->get('returnJson', 0) == 1) {
  3810.         if ($request->get('returnJson'0) == 1) {
  3811.             return new JsonResponse(array(
  3812.                 'SalaryReports' => $SalaryReports,
  3813.             ));
  3814.         } else {
  3815.             return $this->render('ApplicationBundle:pages/human_resource/report:disburse_salary.html.twig', array(
  3816.                 'page_title' => 'Disburse Salary',
  3817.                 'EmployeeIds' => $EmployeeIds,
  3818.                 'departments' => $Departments,
  3819.                 'branches' => $branches,
  3820.                 'banks' => $banks,
  3821.                 'SalaryReports' => $SalaryReports,
  3822.                 'for_month' => $SalaryReports[0]['for_month'],
  3823.                 'from_date' => $SalaryReports[0]['from_date'],
  3824.                 'to_date' => $SalaryReports[0]['to_date'],
  3825.                 'Qry' => $Qry,
  3826.                 'isMethodGet' => false,
  3827.                 'startDate' => $startDate,
  3828.                 'endDate' => $endDate,
  3829.                 'filterType' => $filterType,
  3830.                 'filterBranchIds' => $filterBranchIds,
  3831.                 'filterBankIds' => $filterBankIds,
  3832.                 'filterDepartmentIds' => $filterDepartmentIds,
  3833.                 'filterEmployeeIds' => $filterEmployeeIds,
  3834.             ));
  3835.         }
  3836.     }
  3837.     public function PrintDisburseSalaryAction(Request $Req)
  3838.     {
  3839.         $em $this->getDoctrine()->getManager();
  3840.         $company_data Company::getCompanyData($em1);
  3841.         $SalaryReports HumanResource::BasicDeduction($em$Req);
  3842.         return $this->render(
  3843.             'ApplicationBundle:pages/human_resource/print:print_disburse_salary.html.twig',
  3844.             array(
  3845.                 'page_title' => 'Print Disburse Salary',
  3846.                 'export' => 'pdf,print',
  3847.                 'company_name' => $company_data->getName(),
  3848.                 'company_data' => $company_data,
  3849.                 'company_address' => $company_data->getAddress(),
  3850.                 'company_image' => $company_data->getImage(),
  3851.                 'SalaryReports' => $SalaryReports,
  3852.                 'for_month' => $SalaryReports[0]['for_month'],
  3853.                 'from_date' => $SalaryReports[0]['from_date'],
  3854.                 'to_date' => $SalaryReports[0]['to_date'],
  3855.                 'red' => 0
  3856.             )
  3857.         );
  3858.     }
  3859.     public function SalaryReportAction(Request $request)
  3860.     {
  3861.         $em $this->getDoctrine()->getManager();
  3862.         $startDate $request->get('salary_start_date''');
  3863.         $endDate $request->get('salary_till_date''');
  3864.         $segregationType $request->get('segregationType'1);
  3865.         $filterBranchIds $request->get('branchIds', []);
  3866.         $filterBankIds $request->get('bankIds', []);
  3867.         $approvalFilterTypes $request->get('approvalFilterTypes', []);
  3868.         $filterDepartmentIds $request->get('departmentIds', []);
  3869.         $filterEmployeeIds $request->get('employeeIds', []);
  3870.         $Departments $em->getRepository(SysDepartment::class)->findAll();
  3871.         $attendance $em->getRepository(EmployeeAttendanceLog::class)->findAll();
  3872.         $banks $em->getRepository(BankList::class)->findAll();
  3873.         $branches $em->getRepository(Branch::class)->findAll();
  3874.         $SalaryReports HumanResource::GenerateSalaryReport($em$request);
  3875. //        dump($SalaryReports);
  3876.         $Qry "salary_till_date=" $endDate '&' "departmentIds=" implode(','$filterDepartmentIds) . '&' "employeeIds=" implode(','$filterEmployeeIds) .
  3877.             '&' "salary_start_date=" $startDate .
  3878.             '&' "segregationType=" $segregationType .
  3879.             '&' "branchIds=" implode(','$filterBranchIds) .
  3880.             '&' "bankIds=" implode(','$filterBankIds);
  3881. //        if ($request->get('returnJson', 0) == 1) {
  3882.         if ($request->get('returnJson'0) == 1) {
  3883.             return new JsonResponse(array(
  3884.                 'SalaryReports' => $SalaryReports,
  3885.             ));
  3886.         } else {
  3887.             return $this->render('ApplicationBundle:pages/human_resource/report:salary_report.html.twig', array(
  3888.                 'page_title' => 'Salary Report',
  3889.                 'departments' => $Departments,
  3890.                 'branches' => $branches,
  3891.                 'banks' => $banks,
  3892.                 'approvalFilterTypes' => $approvalFilterTypes,
  3893.                 'salaryInfo' => $SalaryReports,
  3894.                 'SalaryReports' => $SalaryReports,
  3895.                 'for_month' => '',
  3896.                 'from_date' => $startDate,
  3897.                 'to_date' => $endDate,
  3898.                 'Qry' => $Qry,
  3899.                 'isMethodGet' => false,
  3900.                 'startDate' => $startDate,
  3901.                 'endDate' => $endDate,
  3902.                 'segregationType' => $segregationType,
  3903.                 'filterBranchIds' => $filterBranchIds,
  3904.                 'filterBankIds' => $filterBankIds,
  3905.                 'filterDepartmentIds' => $filterDepartmentIds,
  3906.                 'filterEmployeeIds' => $filterEmployeeIds,
  3907.             ));
  3908.         }
  3909.     }
  3910.     public function createJobRecruitmentAction(Request $request$id 0)
  3911.     {
  3912.         $data = [];
  3913.         $em_goc $this->getDoctrine()->getManager('company_group');
  3914.         $skillDetails $em_goc->getRepository(EntitySkill::class)->findAll();
  3915.         $em $this->getDoctrine()->getManager();
  3916.         $companyId $this->getLoggedUserCompanyId($request);
  3917.         if ($request->isMethod('POST')) {
  3918.             $em $this->getDoctrine()->getManager();
  3919.             $entity_id array_flip(GeneralConstant::$Entity_list)['JobRecruitment']; //change
  3920.             $dochash $request->request->get('docHash'); //change
  3921.             $loginId $request->getSession()->get(UserConstants::USER_LOGIN_ID);
  3922.             $approveRole $request->request->get('approvalRole');
  3923.             $approveHash $request->request->get('approvalHash');
  3924.             if (!DocValidation::isInsertable($em$entity_id$dochash,
  3925.                 $loginId$approveRole$approveHash$id)
  3926.             ) {
  3927.                 $this->addFlash(
  3928.                     'error',
  3929.                     'Sorry Could not insert Data.'
  3930.                 );
  3931.             } else {
  3932.                 $data $request->request;
  3933.                 $docId HumanResource::createJobRecruitment($em$loginId$id$data$companyId);
  3934.                 //now add Approval info
  3935.                 $approveRole $request->request->get('approvalRole');
  3936.                 $options = array(
  3937.                     'notification_enabled' => $this->container->getParameter('notification_enabled'),
  3938.                     'notification_server' => $this->container->getParameter('notification_server'),
  3939.                     'appId' => $request->getSession()->get(UserConstants::USER_APP_ID),
  3940.                     'url' => $this->generateUrl(
  3941.                         GeneralConstant::$Entity_list_details[array_flip(GeneralConstant::$Entity_list)['JobRecruitment']]
  3942.                         ['entity_view_route_path_name']
  3943.                     )
  3944.                 );
  3945.                 System::setApprovalInfo($this->getDoctrine()->getManager(), $options,
  3946.                     array_flip(GeneralConstant::$Entity_list)['JobRecruitment'],
  3947.                     $docId,
  3948.                     $request->getSession()->get(UserConstants::USER_LOGIN_ID)    //journal voucher
  3949.                 );
  3950.                 System::createEditSignatureHash($this->getDoctrine()->getManager(), array_flip(GeneralConstant::$Entity_list)['JobRecruitment'],
  3951.                     $docId,
  3952.                     $loginId,
  3953.                     $approveRole,
  3954.                     $request->request->get('approvalHash'));
  3955.                 $this->addFlash(
  3956.                     'success',
  3957.                     'New Recruitment Document Added.'
  3958.                 );
  3959.                 $url $this->generateUrl(
  3960.                     'view_job_recruitment'
  3961.                 );
  3962.                 return $this->redirect($url "/" $docId);
  3963.             }
  3964.         }
  3965.         if ($id == 0) {
  3966.         } else {
  3967.             $extDoc $em->getRepository('ApplicationBundle:JobRecruitment')->findOneBy(
  3968.                 array(
  3969.                     'jobRecruitmentId' => $id///material
  3970.                 )
  3971.             );
  3972.             //now if its not editable, redirect to view
  3973.             if ($extDoc) {
  3974.                 if ($extDoc->getEditFlag() != 1) {
  3975.                     $url $this->generateUrl(
  3976.                         'view_job_recruitment'
  3977.                     );
  3978.                     return $this->redirect($url "/" $id);
  3979.                 }
  3980.             }
  3981.         }
  3982.         $jobType HumanResourceConstant::$employeeType;
  3983.         //$skillDetails = $em->getRepository(Skill::class)->findAll();
  3984.         $educationDetails $em->getRepository('ApplicationBundle:EducationQualification')->findAll();
  3985.         $employeeIds $em->getRepository('ApplicationBundle:Employee')->findAll();
  3986.         $location HumanResourceConstant::$location;
  3987.         $salaryPer HumanResourceConstant::$salaryPer;
  3988.         $workExperience HumanResourceConstant::$workExperience;
  3989.         $jobOpeningStatus HumanResourceConstant::$jobOpeningStatus;
  3990.         $compatibility HumanResourceConstant::$compatibility;
  3991.         return $this->render('ApplicationBundle:pages/human_resource/input_forms:create_new_job_post.html.twig', [
  3992.             'page_title' => 'Create New Job Post',
  3993.             'jobType' => $jobType,
  3994.             'skillDetails' => $skillDetails,
  3995.             'educationDetails' => $educationDetails,
  3996.             'employeeIds' => $employeeIds,
  3997.             'location' => $location,
  3998.             'salaryPer' => $salaryPer,
  3999.             'workExperience' => $workExperience,
  4000.             'jobOpeningStatus' => $jobOpeningStatus,
  4001.             'compatibility' => $compatibility
  4002.         ]);
  4003.     }
  4004.     public function viewApplicantInfoAction(Request $request$id)
  4005.     {
  4006.         $em $this->getDoctrine()->getManager('company_group');
  4007.         //$session = $request->getSession();
  4008.         $consultantDetails $em->getRepository(EntityApplicantDetails::class)->find($id);
  4009.         $skillDetails $em->getRepository('CompanyGroupBundle:EntitySkill')->findAll();
  4010.         //$companyId = $this->getLoggedUserCompanyId($request);
  4011.         $gender HumanResourceConstant::$sex;
  4012.         $blood HumanResourceConstant::$BloodGroup;
  4013.         //$userId = $session->get(UserConstants::USER_ID);
  4014.         return $this->render('ApplicationBundle:pages/human_resource/views:view_applicant_info.html.twig', [
  4015.             'page_title' => 'Applicant Information',
  4016.             'gender' => $gender,
  4017.             'blood' => $blood,
  4018.             'consultantDetails' => $consultantDetails,
  4019.             'education' => json_decode($consultantDetails->getEducationData(), true),
  4020.             'workExperience' => json_decode($consultantDetails->getWorkExperienceData(), true),
  4021.             'certificate' => json_decode($consultantDetails->getCertificateData(), true),
  4022.             'courses' => json_decode($consultantDetails->getCoursesData(), true),
  4023.             'languages' => json_decode($consultantDetails->getLanguagesData(), true),
  4024.             'skillDetails' => $skillDetails
  4025.         ]);
  4026.     }
  4027.     public function ListJobRecruitmentAction()
  4028.     {
  4029.         $em $this->getDoctrine()->getManager();
  4030.         $jobRecruitmentList = [];
  4031.         $jobRecruitments $em->getRepository('ApplicationBundle:JobRecruitment')->findAll();
  4032.         foreach ($jobRecruitments as $jobRecruitment) {
  4033.             $jobData = array(
  4034.                 'jobRecruitmentId' => $jobRecruitment->getJobRecruitmentId(),
  4035.                 'title' => $jobRecruitment->getTitle(),
  4036.                 'date' => $jobRecruitment->getDate(),
  4037.                 'jobOpeningStatus' => $jobRecruitment->getJobOpeningStatus(),
  4038.                 'applicationOpeningDate' => $jobRecruitment->getApplicationOpeningDate(),
  4039.                 'applicationClosingDate' => $jobRecruitment->getApplicationClosingDate(),
  4040.             );
  4041.             $jobRecruitmentList[] = $jobData;
  4042.         }
  4043.         return $this->render('ApplicationBundle:pages/human_resource/list:job_recruitment_list.html.twig', [
  4044.             'page_title' => 'Job RecruitmentAction List',
  4045.             'jobRecruitments' => $jobRecruitmentList
  4046.         ]);
  4047.     }
  4048.     public function ViewJobRecruitmentAction(Request $request$id 0)
  4049.     {
  4050.         $em_goc $this->getDoctrine()->getManager('company_group');
  4051.         $skillDetails $em_goc->getRepository('CompanyGroupBundle:EntitySkill')->findAll();
  4052.         $em $this->getDoctrine()->getManager();
  4053.         $companyId $this->getLoggedUserCompanyId($request);
  4054.         $company_data Company::getCompanyData($em$companyId);
  4055. //        return new JsonResponse($encryptedDataArray);
  4056.         $location HumanResourceConstant::$location;
  4057.         $salaryPer HumanResourceConstant::$salaryPer;
  4058.         $workExperience HumanResourceConstant::$workExperience;
  4059.         $jobOpeningStatus HumanResourceConstant::$jobOpeningStatus;
  4060.         $compatibility HumanResourceConstant::$compatibility;
  4061.         $jobType HumanResourceConstant::$employeeType;
  4062.         $educationDetail $em->getRepository(EducationQualification::class)->findAll();
  4063.         $jobRecruitments $em->getRepository('ApplicationBundle:JobRecruitment')->find($id);
  4064.         $em_goc $this->getDoctrine()->getManager('company_group');
  4065.         $applicantApplicationList $em_goc->getRepository("CompanyGroupBundle:EntityApplicantApplicationList")->findBy(
  4066.             array(
  4067.                 'jobPostId' => $id,
  4068.                 'CompanyId' => $companyId,
  4069.                 'appId' => $company_data->getAppId()
  4070.             )
  4071.         );
  4072.         $applicantIdList = [];
  4073.         foreach ($applicantApplicationList as $dt) {
  4074.             $applicantIdList[] = $dt->getApplicantId();
  4075.         }
  4076.         $applicantList ApplicantM::getApplicantList($em_goc$applicantIdList);
  4077.         $Approval_data = [
  4078.             'exists' => 0,
  4079.             'approvalId' => 0,
  4080.             'roleType' => 0,
  4081.             'required' => 0,
  4082.             'acted' => 0,
  4083.             'entity' => array_flip(GeneralConstant::$Entity_list)['JobRecruitment'],
  4084.             'entityId' => $id,
  4085.         ];
  4086.         if (in_array($request->getSession()->get(UserConstants::USER_TYPE), [125]))
  4087.             $Approval_data System::checkIfApprovalExists(
  4088.                 $em,
  4089.                 array_flip(GeneralConstant::$Entity_list)['JobRecruitment'],
  4090.                 $id,
  4091.                 $request->getSession()->get(UserConstants::USER_LOGIN_ID)
  4092.             );
  4093.         return $this->render('ApplicationBundle:pages/human_resource/views:view_job_recruitment.html.twig', [
  4094.             'page_title' => 'View Job RecruitmentAction',
  4095.             'jobRecruitments' => $jobRecruitments,
  4096.             'applicantApplicationList' => $applicantApplicationList,
  4097.             'applicantList' => $applicantList,
  4098. //            'encryptedData' => $encryptedData,
  4099.             'skills' => json_decode($jobRecruitments->getskills()),
  4100.             'skillDetails' => $skillDetails,
  4101.             'education' => json_decode($jobRecruitments->getEducations()),
  4102.             'educationDetails' => $educationDetail,
  4103.             'location' => $location,
  4104.             'salaryPer' => $salaryPer,
  4105.             'workExperience' => $workExperience,
  4106.             'jobType' => $jobType,
  4107.             'compatibility' => $compatibility,
  4108.             'approval_status' => $jobRecruitments->getApproved(),
  4109.             'jobOpeningStatus' => $jobOpeningStatus,
  4110.             'approval_data' => $Approval_data,
  4111.             'auto_created' => $jobRecruitments->getAutocreated(),
  4112.             'document_log' => $jobRecruitments->getAutocreated() == System::getDocumentLog(
  4113.                 $em,
  4114.                 array_flip(GeneralConstant::$Entity_list)['JobRecruitment'],
  4115.                 $id,
  4116.                 $jobRecruitments->getCreatedLoginId(),
  4117.                 $jobRecruitments->getEditedLoginId()
  4118.             ) : []
  4119.         ]);
  4120.     }
  4121.     public function ViewApplicantScheduleAction(Request $request$id 0)
  4122.     {
  4123.         $em $this->getDoctrine()->getManager();
  4124.         $companyId $this->getLoggedUserCompanyId($request);
  4125.         $company_data Company::getCompanyData($em$companyId);
  4126.         $em_goc $this->getDoctrine()->getManager('company_group');
  4127.         $applicantApplicationList $em_goc->getRepository("CompanyGroupBundle:EntityApplicantApplicationList")->findBy(
  4128.             array(
  4129.                 'jobPostId' => $id,
  4130.                 'CompanyId' => $companyId,
  4131.                 'appId' => $company_data->getAppId()
  4132.             )
  4133.         );
  4134.         $applicantIdList = [];
  4135.         foreach ($applicantApplicationList as $dt) {
  4136.             $applicantIdList[] = $dt->getApplicantId();
  4137.         }
  4138.         $applicantList ApplicantM::getApplicantList($em_goc$applicantIdList);
  4139.         return $this->render('ApplicationBundle:pages/human_resource/views:view_applicant_scheduled.html.twig', [
  4140.             'page_title' => 'View Applicant Scheduled',
  4141.             'applicantApplicationList' => $applicantApplicationList,
  4142.             'applicantList' => $applicantList,
  4143.         ]);
  4144.     }
  4145.     public function ViewApplicantReportAction(Request $request$id 0)
  4146.     {
  4147.         $em $this->getDoctrine()->getManager();
  4148.         $companyId $this->getLoggedUserCompanyId($request);
  4149.         $company_data Company::getCompanyData($em$companyId);
  4150.         $em_goc $this->getDoctrine()->getManager('company_group');
  4151.         $applicantApplicationList $em_goc->getRepository("CompanyGroupBundle:EntityApplicantApplicationList")->findBy(
  4152.             array(
  4153.                 'jobPostId' => $id,
  4154.                 'CompanyId' => $companyId,
  4155.                 'appId' => $company_data->getAppId()
  4156.             )
  4157.         );
  4158.         $applicantIdList = [];
  4159.         foreach ($applicantApplicationList as $dt) {
  4160.             $applicantIdList[] = $dt->getApplicantId();
  4161.         }
  4162.         $applicantList ApplicantM::getApplicantList($em_goc$applicantIdList);
  4163.         return $this->render('ApplicationBundle:pages/human_resource/views:view_applicant_report.html.twig', [
  4164.             'page_title' => 'View Applicant Report',
  4165.             'applicantApplicationList' => $applicantApplicationList,
  4166.             'applicantList' => $applicantList,
  4167.         ]);
  4168.     }
  4169.     public function createEmployeePerformanceEvaluationAction(Request $request$id 0)
  4170.     {
  4171.         $data = [];
  4172.         $em $this->getDoctrine()->getManager();
  4173.         $companyId $this->getLoggedUserCompanyId($request);
  4174.         if ($request->isMethod('POST')) {
  4175.             $em $this->getDoctrine()->getManager();
  4176.             $entity_id array_flip(GeneralConstant::$Entity_list)['EmployeePerformanceEvolution']; //change
  4177.             $dochash $request->request->get('docHash'); //change
  4178.             $loginId $request->getSession()->get(UserConstants::USER_LOGIN_ID);
  4179.             $approveRole $request->request->get('approvalRole');
  4180.             $approveHash $request->request->get('approvalHash');
  4181.             if (!DocValidation::isInsertable($em$entity_id$dochash,
  4182.                 $loginId$approveRole$approveHash$id)
  4183.             ) {
  4184.                 $this->addFlash(
  4185.                     'error',
  4186.                     'Sorry Could not insert Data.'
  4187.                 );
  4188.             } else {
  4189.                 $data $request->request;
  4190.                 $docId HumanResource::createEmployeePerformanceEvaluation($em$loginId$id$data$companyId);
  4191.                 //now add Approval info
  4192.                 $approveRole $request->request->get('approvalRole');
  4193.                 $options = array(
  4194.                     'notification_enabled' => $this->container->getParameter('notification_enabled'),
  4195.                     'notification_server' => $this->container->getParameter('notification_server'),
  4196.                     'appId' => $request->getSession()->get(UserConstants::USER_APP_ID),
  4197.                     'url' => $this->generateUrl(
  4198.                         GeneralConstant::$Entity_list_details[array_flip(GeneralConstant::$Entity_list)['EmployeePerformanceEvolution']]
  4199.                         ['entity_view_route_path_name']
  4200.                     )
  4201.                 );
  4202.                 System::setApprovalInfo($this->getDoctrine()->getManager(), $options,
  4203.                     array_flip(GeneralConstant::$Entity_list)['JobRecruitment'],
  4204.                     $docId,
  4205.                     $request->getSession()->get(UserConstants::USER_LOGIN_ID)    //journal voucher
  4206.                 );
  4207.                 System::createEditSignatureHash($this->getDoctrine()->getManager(), array_flip(GeneralConstant::$Entity_list)['EmployeePerformanceEvolution'],
  4208.                     $docId,
  4209.                     $loginId,
  4210.                     $approveRole,
  4211.                     $request->request->get('approvalHash'));
  4212.                 $this->addFlash(
  4213.                     'success',
  4214.                     'New Recruitment Document Added.'
  4215.                 );
  4216.                 $url $this->generateUrl(
  4217.                     'view_employee_performance_evolution'
  4218.                 );
  4219.                 return $this->redirect($url "/" $docId);
  4220.             }
  4221.         }
  4222.         $skill $em->getRepository(Skill::class)->findAll();
  4223.         $educationDetail $em->getRepository(EducationQualification::class)->findAll();
  4224.         $employeeIds $em->getRepository(EmployeeDetails::class)->findAll();
  4225.         $employeeType HumanResourceConstant::$employeeType;
  4226.         $Designation $em->getRepository(SysDepartmentPosition::class)->findAll();
  4227.         $branch $em->getRepository(Branch::class)->findAll();
  4228.         $departments $em->getRepository(SysDepartment::class)->findAll();
  4229.         $department = [];
  4230.         foreach ($departments as $entry) {
  4231.             $department[$entry->getDepartmentId()] = array(
  4232.                 'id' => $entry->getDepartmentId(),
  4233.                 'name' => $entry->getDepartmentName(),
  4234.             );
  4235.         }
  4236.         return $this->render('ApplicationBundle:pages/human_resource/input_forms:employee_performance_evolution.html.twig',
  4237.             array(
  4238.                 'page_title' => 'Create Employee Performance Evaluation',
  4239.                 'employeeIds' => $employeeIds,
  4240.                 'employeeType' => $employeeType,
  4241.                 'Designation' => $Designation,
  4242.                 'branch' => $branch,
  4243.                 'department' => $department,
  4244.                 'skill' => $skill,
  4245.                 'educationDetail' => $educationDetail
  4246.             )
  4247.         );
  4248.     }
  4249.     public function ViewIndividualReviewAction()
  4250.     {
  4251.         return $this->render('ApplicationBundle:pages/human_resource/views:individual_review.html.twig',
  4252.             array(
  4253.                 'page_title' => 'Individual Performance View',
  4254.             )
  4255.         );
  4256.     }
  4257.     public function EmployeeListBySkillPerformanceAction()
  4258.     {
  4259.         $em $this->getDoctrine()->getManager();
  4260.         $employee $em->getRepository('ApplicationBundle:EmployeeDetails')->findAll();
  4261.         $skill $em->getRepository('ApplicationBundle:Skill')->findAll();
  4262.         return $this->render('ApplicationBundle:pages/human_resource/list:employee_performance_evolution_list.html.twig',
  4263.             array(
  4264.                 'page_title' => 'Employee Skill & Performance',
  4265.                 'employee' => $employee,
  4266.                 //'employeeSkill' => json_decode($employee->getSkill(),true),
  4267.                 'skill' => $skill,
  4268.             )
  4269.         );
  4270.     }
  4271.     public function setWorkPlaceAction(Request $req)
  4272.     {
  4273.         $em $this->getDoctrine()->getManager();
  4274.         $companyId $this->getLoggedUserCompanyId($req);
  4275.         $docHash '';
  4276.         if ($req->request->has('XHRreq')) {
  4277.             $docHash HumanResource::HandelXHRreqForEmpWorkplace($em$req);
  4278.             return new JsonResponse([$docHash]);
  4279.         }
  4280.         if ($req->isMethod('GET')) {
  4281.             $TwigData HumanResource::TwigDataForEmployeeWorkplace($em);
  4282.             return $this->render(
  4283.                 'ApplicationBundle:pages/human_resource/input_forms:update_workplace.html.twig',
  4284.                 [
  4285.                     'page_title' => 'Set Workplace',
  4286.                     'employeeIds' => $TwigData['employeeIds']
  4287.                 ]
  4288.             );
  4289.         }
  4290.         if ($req->isMethod('POST')) {
  4291.             $approveHash $req->request->get('approvalHash');
  4292.             $loginId $req->getSession()->get(UserConstants::USER_LOGIN_ID);
  4293.             $isSignatureOk DocValidation::isSignatureOk($em$loginId$approveHash);
  4294.             if ($isSignatureOk) {
  4295.                 $isSuccess HumanResource::CreateOrUpdateForEmpWorkplace($em$req$companyIdfalse$docHash);
  4296.                 if ($isSuccess) {
  4297.                     $this->addFlash(
  4298.                         'success',
  4299.                         'Workplace set!'
  4300.                     );
  4301.                     return $this->redirectToRoute('set_workplace');
  4302.                 }
  4303.             } else {
  4304.                 $this->addFlash(
  4305.                     'error',
  4306.                     'Invalid Approval Hash!'
  4307.                 );
  4308.                 return $this->redirectToRoute('set_workplace');
  4309.             }
  4310.         }
  4311.     }
  4312.     public function setWorkPlaceForAppAction(Request $req)
  4313.     {
  4314.         $em $this->getDoctrine()->getManager();
  4315.         $companyId $this->getLoggedUserCompanyId($req);
  4316.         $docHash HumanResource::HandelXHRreqForEmpWorkplace($em$req);
  4317.         if ($req->isMethod('GET')) {
  4318.             $TwigData HumanResource::TwigDataForEmployeeWorkplace($em);
  4319.             return $this->render(
  4320.                 'ApplicationBundle:pages/human_resource/input_forms:update_workplace.html.twig',
  4321.                 [
  4322.                     'page_title' => 'Set Workplace',
  4323.                     'employeeIds' => $TwigData['employeeIds']
  4324.                 ]
  4325.             );
  4326.         }
  4327.         if ($req->isMethod('POST')) {
  4328.             $approveHash $req->request->get('approvalHash');
  4329.             $loginId $req->getSession()->get(UserConstants::USER_LOGIN_ID);
  4330.             $isSignatureOk DocValidation::isSignatureOk($em$loginId$approveHash);
  4331.             if ($isSignatureOk) {
  4332.                 $isSuccess HumanResource::CreateOrUpdateForEmpWorkplace($em$req$companyIdfalse$docHash);
  4333.                 if ($isSuccess) {
  4334.                     $this->addFlash(
  4335.                         'success',
  4336.                         'Workplace set!'
  4337.                     );
  4338. //                    return $this->redirectToRoute('set_workplace');
  4339.                     return new JsonResponse(array(
  4340.                         "success" => true
  4341.                     ));
  4342.                 }
  4343.             } else {
  4344.                 $this->addFlash(
  4345.                     'error',
  4346.                     'Invalid Approval Hash!'
  4347.                 );
  4348. //                return $this->redirectToRoute('set_workplace');
  4349.             }
  4350.         }
  4351.     }
  4352.     public function ViewMeetingAction(Request $req$action 0$id 0)
  4353.     {
  4354.         $em $this->getDoctrine()->getManager();
  4355.         $companyId $this->getLoggedUserCompanyId($req);
  4356.         if ($req->request->has('XHRreq')) {
  4357.             return new JsonResponse([HumanResource::HandelXHRreqForMeetingScheduling($em$req)]);
  4358.         }
  4359.         if ($action === 'view') {
  4360.             $response HumanResource::TwigDataForScheduledMeetingView($em$req$id);
  4361.             return $this->render(
  4362.                 'ApplicationBundle:pages/human_resource/views:scheduled_meeting_view.html.twig',
  4363.                 [
  4364.                     'page_title' => 'View Scheduled Meeting',
  4365.                     'duration' => $response['duration'],
  4366.                     'appId' => $response['appId'],
  4367.                     'publicView' => 0,
  4368.                     'meeting_data' => $response['meeting_data'],
  4369.                     'agenda_list' => $response['agenda_list'],
  4370.                     'id' => $req->query->get('view_meeting'),
  4371.                     'approval_data' => $response['approval_data'],
  4372.                     'document_log' => $response['document_log'],
  4373.                     'approval_status' => $response['approval_status'],
  4374.                     'created_by' => $response['created_by'],
  4375.                     'updated_at' => $response['updated_at'],
  4376.                     'auto_created' => 0,
  4377.                 ]
  4378.             );
  4379.         }
  4380.         if ($action === 'print') {
  4381.             $response HumanResource::TwigDataForScheduledMeetingView($em$req$id);
  4382. //      $id = $req->query->get('print_meeting');
  4383.             $em $this->getDoctrine()->getManager();
  4384.             $company_data Company::getCompanyData($em1);
  4385.             $Authorizations System::getSignatureListForDocumentPrint($emarray_flip(GeneralConstant::$Entity_list)['ScheduledMeeting'], $id);
  4386.             return $this->render(
  4387.                 'ApplicationBundle:pages/human_resource/print:scheduled_meeting_print.html.twig',
  4388.                 array(
  4389.                     'page_title' => 'View Scheduled Meeting',
  4390.                     'duration' => $response['duration'],
  4391.                     'meeting_data' => $response['meeting_data'],
  4392.                     'agenda_list' => $response['agenda_list'],
  4393.                     'export' => 'pdf,print',
  4394.                     'company_name' => $company_data->getName(),
  4395.                     'company_data' => $company_data,
  4396.                     'company_address' => $company_data->getAddress(),
  4397.                     'company_image' => $company_data->getImage(),
  4398.                     'Authorizations' => $Authorizations,
  4399.                     'red' => 0
  4400.                 )
  4401.             );
  4402.         }
  4403.     }
  4404.     public function UpdateMeetingMinutesAction(Request $req$action 0$id 0)
  4405.     {
  4406.         $em $this->getDoctrine()->getManager();
  4407.         $companyId $this->getLoggedUserCompanyId($req);
  4408.         $scheduleId $req->request->get('scheduleId');
  4409.         $minuteText $req->request->get('minuteText');
  4410.         $agendaKey $req->request->get('key');
  4411.         $scheduledMeeting $em->getRepository(ScheduledMeeting::class)
  4412.             ->find($scheduleId);
  4413.         $agendaList json_decode($scheduledMeeting->getAgendaList(), true);
  4414.         foreach ($agendaList as $key => $item) {
  4415.             if ($key == $agendaKey)
  4416.                 $agendaList[$key]['minutes'] = $minuteText;
  4417.         }
  4418.         $scheduledMeeting->setAgendaList(json_encode($agendaList));
  4419.         $em->flush();
  4420.         return new JsonResponse(array(
  4421.             'success' => true
  4422.         ));
  4423.     }
  4424.     public function deleteLastAttendanceAction(Request $request)
  4425.     {
  4426.         $em $this->getDoctrine()->getManager();
  4427.         $lastAttendance $em->getRepository('ApplicationBundle:EmployeeAttendance')
  4428.             ->createQueryBuilder('ea')
  4429.             ->orderBy('ea.id''DESC')
  4430.             ->setMaxResults(1)
  4431.             ->getQuery()
  4432.             ->getOneOrNullResult();
  4433.         $lastAttendanceLog $em->getRepository('ApplicationBundle:EmployeeAttendanceLog')
  4434.             ->createQueryBuilder('eal')
  4435.             ->orderBy('eal.id''DESC')
  4436.             ->setMaxResults(1)
  4437.             ->getQuery()
  4438.             ->getOneOrNullResult();
  4439.         $deletedCount 0;
  4440.         if ($lastAttendance) {
  4441.             $em->remove($lastAttendance);
  4442.             $deletedCount++;
  4443.         }
  4444.         if ($lastAttendanceLog) {
  4445.             $em->remove($lastAttendanceLog);
  4446.             $deletedCount++;
  4447.         }
  4448.         $em->flush();
  4449.         return new JsonResponse(
  4450.             [
  4451.                 'success' => true,
  4452.                 'message' => "Deleted `$deletedCount` rows from attendance tables."
  4453.             ]
  4454.         );
  4455.     }
  4456.     public function SendMeetingUpdatesAction(Request $req$action 0$id 0)
  4457.     {
  4458.         $em $this->getDoctrine()->getManager();
  4459.         $companyId $this->getLoggedUserCompanyId($req);
  4460.         $session $req->getSession();
  4461.         $companyData Company::getCompanyData($em$companyId);
  4462.         $scheduleId $req->request->get('scheduleId');
  4463.         $minuteText $req->request->get('minuteText');
  4464.         $agendaKey $req->request->get('key');
  4465.         $scheduledMeeting $em->getRepository(ScheduledMeeting::class)
  4466.             ->find($scheduleId);
  4467.         $sendEmailInvitationTo json_decode($scheduledMeeting->getAllParticipantsNameEmail(), true);
  4468.         if ($sendEmailInvitationTo == null)
  4469.             $sendEmailInvitationTo = [];
  4470.         $agendaList json_decode($scheduledMeeting->getAgendaList(), true);
  4471.         if ($agendaList == null)
  4472.             $agendaList = [];
  4473.         $EmployeeList HumanResource::GetEmployeeList($em, []);
  4474.         $meetingType MeetingSchedulingConstant::$meetingType[$scheduledMeeting->getMeetingType()];
  4475.         foreach ($sendEmailInvitationTo as $key => $email) {
  4476.             $name ucWords(str_replace("_"" "$key));
  4477.             $bodyHtml '';
  4478.             $bodyTemplate 'ApplicationBundle:email/meeting_scheduling:scheduled_meeting_update.html.twig';
  4479.             $bodyData = array(
  4480.                 'name' => $name,
  4481.                 'gocId' => $session->get(UserConstants::USER_GOC_ID),
  4482.                 'appId' => $session->get(UserConstants::USER_APP_ID),
  4483.                 'email' => $email,
  4484.                 'meetingData' => $scheduledMeeting,
  4485.                 'meeting_type' => $meetingType,
  4486.                 'agenda_list' => $agendaList,
  4487.                 'companyData' => $companyData,
  4488.                 'employeeList' => $EmployeeList,
  4489.             );
  4490.             $attachments = [];
  4491.             $new_mail $this->get('mail_module');
  4492.             $new_mail->sendMyMail(array(
  4493.                 'senderHash' => '_MEETING_',
  4494.                 'forwardToMailAddress' => $email,
  4495.                 'subject' => "Meeting Updates Arranged By - " $companyData->getName() . " on " $scheduledMeeting->getTitle() . ". ",
  4496.                 'fileName' => '',
  4497.                 'attachments' => $attachments,
  4498.                 'toAddress' => $email,
  4499.                 'mailTemplate' => $bodyTemplate,
  4500.                 'templateData' => $bodyData,
  4501.                 'embedCompanyImage' => 1,
  4502.                 'companyId' => $companyId,
  4503.                 'companyImagePath' => $companyData->getImage()
  4504.             ));
  4505.         }
  4506.         return new JsonResponse(array(
  4507.             'success' => true
  4508.         ));
  4509.     }
  4510.     public function meetingSchedulingAction(Request $req$action 0)
  4511.     {
  4512.         $em $this->getDoctrine()->getManager();
  4513.         $companyId $this->getLoggedUserCompanyId($req);
  4514.         $session $req->getSession();
  4515.         if ($req->request->has('XHRreq')) {
  4516.             return new JsonResponse([HumanResource::HandelXHRreqForMeetingScheduling($em$req)]);
  4517.         }
  4518.         if ($action === 'list') {
  4519.             $response HumanResource::TwigDataForScheduledMeetingList($em, [0null]);
  4520.             return $this->render(
  4521.                 'ApplicationBundle:pages/human_resource/list:scheduled_meeting_list.html.twig',
  4522.                 [
  4523.                     'page_title' => 'Scheduled Meeting List',
  4524.                     'list' => $response
  4525.                 ]
  4526.             );
  4527.         }
  4528.         if ($req->isMethod('GET')) {
  4529.             $response HumanResource::twigDataForMeetingScheduling($em);
  4530.             return $this->render(
  4531.                 'ApplicationBundle:pages/human_resource/input_forms:meeting_scheduling.html.twig',
  4532.                 [
  4533.                     'page_title' => 'Schedule a Meeting',
  4534.                     'employeeIds' => $response['employeeIds'],
  4535.                     'branches' => $response['branches'],
  4536.                     'asset' => $response['asset'],
  4537.                     'rooms' => $response['rooms'],
  4538.                     'sales_orders' => $response['salesOrders'],
  4539.                     'purchase_orders' => $response['purchaseOrders'],
  4540.                     'meeting_types' => $response['meetingType'],
  4541.                 ]
  4542.             );
  4543.         }
  4544.         if ($req->isMethod('POST')) {
  4545.             $approveHash $req->request->get('approvalHash');
  4546.             $approveRole $req->request->get('approvalRole');
  4547.             $loginId $req->getSession()->get(UserConstants::USER_LOGIN_ID);
  4548.             $isSignatureOk DocValidation::isSignatureOk($em$loginId$approveHash);
  4549.             $companyData Company::getCompanyData($em$companyId);
  4550.             if ($isSignatureOk) {
  4551.                 $isSuccess HumanResource::createOrUpdateDataForMeetingScheduling($em$req);
  4552.                 if ($isSuccess) {
  4553.                     $options = array(
  4554.                         'notification_enabled' => $this->container->getParameter('notification_enabled'),
  4555.                         'notification_server' => $this->container->getParameter('notification_server'),
  4556.                         'appId' => $req->getSession()->get(UserConstants::USER_APP_ID),
  4557.                         'url' => $this->generateUrl(
  4558.                             GeneralConstant::$Entity_list_details[array_flip(GeneralConstant::$Entity_list)['ScheduledMeeting']]['entity_view_route_path_name']
  4559.                         )
  4560.                     );
  4561.                     $meetingId $isSuccess[1];
  4562.                     System::setApprovalInfo(
  4563.                         $this->getDoctrine()->getManager(),
  4564.                         $options,
  4565.                         array_flip(GeneralConstant::$Entity_list)['ScheduledMeeting'],
  4566.                         $meetingId,
  4567.                         $req->getSession()->get(UserConstants::USER_LOGIN_ID),
  4568.                         0//normal meeting
  4569.                         0,
  4570.                         $this->get('mail_module')
  4571.                     );
  4572.                     System::createEditSignatureHash(
  4573.                         $this->getDoctrine()->getManager(),
  4574.                         array_flip(GeneralConstant::$Entity_list)['ScheduledMeeting'],
  4575.                         $meetingId,
  4576.                         $loginId,
  4577.                         $approveRole,
  4578.                         $req->request->get('approvalHash')
  4579.                     );
  4580.                     $url $this->generateUrl(
  4581.                         'view_scheduled_meeting'
  4582.                     );
  4583.                     return $this->redirect($url "/" $meetingId);
  4584.                 } else {
  4585.                     return new JsonResponse(array(
  4586.                         'success' => false
  4587.                     ));
  4588.                 }
  4589.             } else {
  4590.                 $this->addFlash(
  4591.                     'error',
  4592.                     'Invalid Approval Hash!'
  4593.                 );
  4594.                 return $this->redirectToRoute('meeting_scheduling');
  4595.             }
  4596.         }
  4597.         return $this->redirectToRoute('meeting_scheduling');
  4598.     }
  4599.     public function MeetingSchedulingForAppAction(Request $request): JsonResponse
  4600.     {
  4601.         $em $this->getDoctrine()->getManager();
  4602.         $session $request->getSession();
  4603.         $mailer $this->get('mail_module');
  4604.         $helper = new HumanResourceHelper($em$mailer);
  4605.         try {
  4606.             $data $request->request->all();
  4607.             $files $request->files->all();
  4608.             $companyId $this->getLoggedUserCompanyId($request);
  4609.             $meeting $helper->prepareMeeting($data$session);
  4610.             $agendaList = [];
  4611.             if (!empty($data['agendaList']) && is_array($data['agendaList'])) {
  4612.                 foreach ($data['agendaList'] as $index => $agendaData) {
  4613.                     $agenda = [
  4614.                         'title' => $agendaData['title'] ?? null,
  4615.                         'desc' => $agendaData['desc'] ?? null,
  4616.                         'notes' => $agendaData['notes'] ?? null,
  4617.                         'taggedDocuments' => $agendaData['taggedDocuments'] ?? [],
  4618.                         'otherDocuments' => [],
  4619.                     ];
  4620.                     if (!empty($files['agendaList'][$index]['otherDocuments'])) {
  4621.                         foreach ($files['agendaList'][$index]['otherDocuments'] as $uploadedFile) {
  4622.                             $uploadedFilePath $this->uploadMeetingFile($uploadedFile$request);
  4623.                             if ($uploadedFilePath) {
  4624.                                 $agenda['otherDocuments'][] = [
  4625.                                     'fileName' => basename($uploadedFilePath),
  4626.                                     'path' => $uploadedFilePath,
  4627.                                     'type' => $uploadedFile->getClientOriginalExtension(),
  4628.                                 ];
  4629.                             }
  4630.                         }
  4631.                     }
  4632.                     $agendaList[] = $agenda;
  4633.                 }
  4634.             }
  4635.             $meeting->setAgendaList(json_encode($agendaList));
  4636.             [$internalInfo$otherInfo$internalIds] = $helper->resolveParticipants(
  4637.                 $data['guests'] ?? [],
  4638.                 $session->get('userEmployeeId')
  4639.             );
  4640.             // Save **full participant objects** to DB
  4641.             $meeting->setInternalParticipantIds(!empty($internalInfo) ? json_encode($internalInfo) : null);
  4642.             $meeting->setOtherParticipantInfo(!empty($otherInfo) ? json_encode($otherInfo) : null);
  4643.             $meeting->setParticipantInfo(json_encode([
  4644.                 'internal' => $internalInfo,
  4645.                 'other' => $otherInfo,
  4646.             ]));
  4647.             // Persist the meeting
  4648.             $em->persist($meeting);
  4649.             $em->flush();
  4650.             // Send invitations
  4651.             $helper->sendInvitations($meeting$internalIds$otherInfo$companyId);
  4652.             return new JsonResponse([
  4653.                 'success' => true,
  4654.                 'message' => 'Meeting scheduled successfully',
  4655.                 'meetingId' => $meeting->getScheduleId(),
  4656.                 'documentHas' => $meeting->getDocumentHash(),
  4657.             ]);
  4658.         } catch (\Exception $e) {
  4659.             return new JsonResponse(['success' => false'error' => $e->getMessage()], 500);
  4660.         }
  4661.     }
  4662.     public function updateMeetingForAppAction(Request $requestint $meetingId): JsonResponse
  4663.     {
  4664.         $em $this->getDoctrine()->getManager();
  4665.         $session $request->getSession();
  4666.         $mailer $this->get('mail_module');
  4667.         $helper = new HumanResourceHelper($em$mailer);
  4668.         try {
  4669.             $data $request->request->all();
  4670.             $files $request->files->all();
  4671.             $meeting $em->getRepository(ScheduledMeeting::class)->find($meetingId);
  4672.             if (!$meeting) {
  4673.                 return new JsonResponse(['success' => false'error' => 'Meeting not found'], 404);
  4674.             }
  4675.             $meeting->setTitle($data['title'] ?? $meeting->getTitle());
  4676.             $meeting->setSpecialType($data['specialType'] ?? $meeting->getSpecialType());
  4677.             $meeting->setStartAt(!empty($data['startAt']) ? new \DateTime($data['startAt']) : $meeting->getStartAt());
  4678.             $meeting->setEndAt(!empty($data['endAt']) ? new \DateTime($data['endAt']) : $meeting->getEndAt());
  4679.             $meeting->setMeetingType($data['meetingType'] ?? $meeting->getMeetingType());
  4680.             $meeting->setLocation($data['location'] ?? $meeting->getLocation());
  4681.             $meeting->setRoomId($data['roomId'] ?? $meeting->getRoomId());
  4682.             $meeting->setDesc($data['desc'] ?? $meeting->getDesc());
  4683.             $meeting->setLastModifiedDate(new \DateTime());
  4684.             if (isset($data['agendaList']) && is_array($data['agendaList'])) {
  4685.                 $agendaList = [];
  4686.                 foreach ($data['agendaList'] as $index => $agendaData) {
  4687.                     $agenda = [
  4688.                         'title' => $agendaData['title'] ?? null,
  4689.                         'desc' => $agendaData['desc'] ?? null,
  4690.                         'notes' => $agendaData['notes'] ?? null,
  4691.                         'taggedDocuments' => $agendaData['taggedDocuments'] ?? [],
  4692.                         'otherDocuments' => [],
  4693.                     ];
  4694.                     if (!empty($files['agendaList'][$index]['otherDocuments'])) {
  4695.                         foreach ($files['agendaList'][$index]['otherDocuments'] as $uploadedFile) {
  4696.                             $uploadedFilePath $this->uploadMeetingFile($uploadedFile$request);
  4697.                             if ($uploadedFilePath) {
  4698.                                 $agenda['otherDocuments'][] = [
  4699.                                     'fileName' => basename($uploadedFilePath),
  4700.                                     'path' => $uploadedFilePath,
  4701.                                     'type' => $uploadedFile->getClientOriginalExtension(),
  4702.                                 ];
  4703.                             }
  4704.                         }
  4705.                     }
  4706.                     if (!empty($agendaData['otherDocumentsExisting'])) {
  4707.                         $agenda['otherDocuments'] = array_merge(
  4708.                             $agenda['otherDocuments'],
  4709.                             $agendaData['otherDocumentsExisting']
  4710.                         );
  4711.                     }
  4712.                     $agendaList[] = $agenda;
  4713.                 }
  4714.                 $meeting->setAgendaList(json_encode($agendaList));
  4715.             }
  4716.             if (isset($data['guests'])) {
  4717.                 [$internalIds$otherInfo] = $helper->resolveParticipants($data['guests'], $session->get('userEmployeeId'));
  4718.                 $meeting->setInternalParticipantIds(!empty($internalIds) ? json_encode($internalIds) : null);
  4719.                 $meeting->setOtherParticipantInfo(!empty($otherInfo) ? json_encode($otherInfo) : null);
  4720.             }
  4721.             $em->persist($meeting);
  4722.             $em->flush();
  4723.             if (isset($internalIds) || isset($otherInfo)) {
  4724.                 $helper->sendInvitations($meeting$internalIds ?? [], $otherInfo ?? [], $meeting->getCompanyId());
  4725.             }
  4726.             return new JsonResponse([
  4727.                 'success' => true,
  4728.                 'message' => 'Meeting updated successfully',
  4729.                 'meetingId' => $meeting->getScheduleId(),
  4730.                 'facilitator' => ['id' => $meeting->getFacilitatorId(), 'name' => $meeting->getFacilitatorName()],
  4731.                 'companyId' => $meeting->getCompanyId(),
  4732.                 'branchId' => $meeting->getBranchId(),
  4733.                 'internalParticipants' => json_decode($meeting->getInternalParticipantIds(), true) ?? [],
  4734.                 'otherParticipants' => json_decode($meeting->getOtherParticipantInfo(), true) ?? [],
  4735.                 'agendas' => json_decode($meeting->getAgendaList(), true) ?? [],
  4736.             ]);
  4737.         } catch (\Exception $e) {
  4738.             return new JsonResponse(['success' => false'error' => $e->getMessage()], 500);
  4739.         }
  4740.     }
  4741.     public function GetDocumentsForMeetingScheduleAppAction(Request $request): JsonResponse
  4742.     {
  4743.         $em $this->getDoctrine()->getManager();
  4744.         $hrHelper = new HumanResourceHelper($em);
  4745.         try {
  4746.             $documents $hrHelper->getAllDocumentsFromApproval($request);
  4747.             return ResponseStructure::success($documents'Documents fetched successfully');
  4748.         } catch (\Exception $e) {
  4749.             return ResponseStructure::error($e->getMessage());
  4750.         }
  4751.     }
  4752.     public function getMeetingsByDateAction(Request $request): JsonResponse
  4753.     {
  4754.         $em $this->getDoctrine()->getManager();
  4755.         $type $request->query->get('type'); // Day, Week, Month, Yearly, Custom
  4756.         $repo $em->getRepository(ScheduledMeeting::class);
  4757.         $today = new \DateTime();
  4758.         $fromDate null;
  4759.         $toDate = (clone $today)->setTime(235959);
  4760.         switch ($type) {
  4761.             case 'Day':
  4762.                 $fromDate = (clone $today)->setTime(000);
  4763.                 break;
  4764.             case 'Week':
  4765.                 $fromDate = (clone $today)->modify('-6 days')->setTime(000);
  4766.                 break;
  4767.             case 'Month':
  4768.                 $fromDate = (clone $today)->modify('-30 days')->setTime(000);
  4769.                 break;
  4770.             case 'Yearly':
  4771.                 $fromDate = (clone $today)->modify('-1 year')->setTime(000);
  4772.                 break;
  4773.             case 'Custom':
  4774.                 $start $request->query->get('start');
  4775.                 $end $request->query->get('end');
  4776.                 if (!$start || !$end) {
  4777.                     return new JsonResponse(['error' => 'Start and end date are required for Custom type'], 400);
  4778.                 }
  4779.                 $fromDate = new \DateTime($start " 00:00:00");
  4780.                 $toDate = new \DateTime($end " 23:59:59");
  4781.                 break;
  4782.             default:
  4783.                 return new JsonResponse(['error' => 'Invalid type parameter'], 400);
  4784.         }
  4785.         $meetings $repo->createQueryBuilder('pv')
  4786.             ->where('pv.startAt >= :fromDate')
  4787.             ->andWhere('pv.startAt <= :toDate')
  4788.             ->setParameter('fromDate'$fromDate)
  4789.             ->setParameter('toDate'$toDate)
  4790.             ->orderBy('pv.startAt''DESC')
  4791.             ->getQuery()
  4792.             ->getResult();
  4793.         $data = [];
  4794.         foreach ($meetings as $meeting) {
  4795.             $data[] = [
  4796.                 'id' => $meeting->getScheduleId(),
  4797.                 'title' => $meeting->getTitle(),
  4798.                 'desc' => $meeting->getDesc(),
  4799.                 'startAt' => $meeting->getStartAt()->format('Y-m-d H:i:s'),
  4800.                 'endAt' => $meeting->getEndAt() ? $meeting->getEndAt()->format('Y-m-d H:i:s') : null,
  4801.                 'roomId' => $meeting->getRoomId(),
  4802.                 'meetingType' => $meetingType[$meeting->getMeetingType()] ?? null,
  4803.                 'location' => $meeting->getLocation(),
  4804.                 'participant' => json_decode($meeting->getParticipantInfo()),
  4805.                 'status' => $meeting->getStatus(),
  4806.                 'approved' => (bool)$meeting->getApproved(),
  4807.             ];
  4808.         }
  4809.         return new JsonResponse([
  4810.             'success' => true,
  4811.             'message' => 'Scheduled Meeting data retrieved successfully',
  4812.             'type' => $type,
  4813.             'fromDate' => $fromDate->format('Y-m-d'),
  4814.             'toDate' => $toDate->format('Y-m-d'),
  4815.             'count' => count($data),
  4816.             'data' => $data,
  4817.         ]);
  4818.     }
  4819.     public function getMeetingByYearlyAction(Request $request): JsonResponse
  4820.     {
  4821.         $em $this->getDoctrine()->getManager();
  4822.         $yearParam $request->query->get('year');
  4823.         try {
  4824.             $data HumanResourceHelper::GetMeetingByYearlyAction($em$yearParam);
  4825.             return new JsonResponse($data200);
  4826.         } catch (\Exception $e) {
  4827.             return new JsonResponse([
  4828.                 'success' => false,
  4829.                 'error' => $e->getMessage()
  4830.             ], 400);
  4831.         }
  4832.     }
  4833.     public function getMeetingByIdAction(Request $requestint $id): JsonResponse
  4834.     {
  4835.         $em $this->getDoctrine()->getManager();
  4836.         $meeting $em->getRepository(\ApplicationBundle\Entity\ScheduledMeeting::class)->find($id);
  4837.         if (!$meeting) {
  4838.             return new JsonResponse([
  4839.                 'success' => false,
  4840.                 'error' => 'Meeting not found'
  4841.             ], 404);
  4842.         }
  4843.         return new JsonResponse([
  4844.             'success' => true,
  4845.             'meeting' => [
  4846.                 'id' => $meeting->getScheduleId(),
  4847.                 'docHash' => $meeting->getDocumentHash(),
  4848.                 'title' => $meeting->getTitle(),
  4849.                 'desc' => $meeting->getDesc(),
  4850.                 'specialType' => $meeting->getSpecialType(),
  4851.                 'startAt' => $meeting->getStartAt() ? $meeting->getStartAt()->format('Y-m-d H:i:s') : null,
  4852.                 'endAt' => $meeting->getEndAt() ? $meeting->getEndAt()->format('Y-m-d H:i:s') : null,
  4853.                 'meetingType' => $meeting->getMeetingType(),
  4854.                 'location' => $meeting->getLocation(),
  4855.                 'roomId' => $meeting->getRoomId(),
  4856.                 'facilitator' => [
  4857.                     'id' => $meeting->getFacilitatorId(),
  4858.                     'name' => $meeting->getFacilitatorName()
  4859.                 ],
  4860.                 'companyId' => $meeting->getCompanyId(),
  4861.                 'branchId' => $meeting->getBranchId(),
  4862.                 'agendaList' => $meeting->getAgendaList() ? json_decode($meeting->getAgendaList(), true) : [],
  4863.                 'internalParticipants' => $meeting->getInternalParticipantIds() ? json_decode($meeting->getInternalParticipantIds(), true) : [],
  4864.                 'otherParticipants' => $meeting->getOtherParticipantInfo() ? json_decode($meeting->getOtherParticipantInfo(), true) : [],
  4865.                 'createdAt' => $meeting->getCreatedAt()->format('Y-m-d H:i:s'),
  4866.             ]
  4867.         ]);
  4868.     }
  4869.     public function updateMeetingAction(Request $requestint $id): JsonResponse
  4870.     {
  4871.         $em $this->getDoctrine()->getManager();
  4872.         $meeting $em->getRepository(\ApplicationBundle\Entity\ScheduledMeeting::class)->find($id);
  4873.         if (!$meeting) {
  4874.             return new JsonResponse(['success' => false'error' => 'Meeting not found'], 404);
  4875.         }
  4876.         $data json_decode($request->getContent(), true);
  4877.         if (!$data) {
  4878.             $data $request->request->all();
  4879.         }
  4880.         if (!$data) {
  4881.             return new JsonResponse(['success' => false'error' => 'Invalid data'], 400);
  4882.         }
  4883.         if (isset($data['title'])) $meeting->setTitle($data['title']);
  4884.         if (isset($data['desc'])) $meeting->setDesc($data['desc']);
  4885.         if (isset($data['startAt'])) $meeting->setStartAt(new \DateTime($data['startAt']));
  4886.         if (isset($data['endAt'])) $meeting->setEndAt(new \DateTime($data['endAt']));
  4887.         if (isset($data['location'])) $meeting->setLocation($data['location']);
  4888.         if (isset($data['meetingType'])) $meeting->setMeetingType($data['meetingType']);
  4889.         if (isset($data['roomId'])) $meeting->setRoomId($data['roomId']);
  4890.         if (isset($data['agendaList'])) {
  4891.             $agendaList is_array($data['agendaList']) ? $data['agendaList'] : json_decode($data['agendaList'], true);
  4892.             $meeting->setAgendaList(json_encode($agendaList));
  4893.         }
  4894.         $meeting->setLastModifiedDate(new \DateTime());
  4895.         $em->flush();
  4896.         return new JsonResponse([
  4897.             'success' => true,
  4898.             'message' => 'Meeting updated successfully',
  4899.             'meetingId' => $meeting->getScheduleId()
  4900.         ]);
  4901.     }
  4902.     public function deleteMeetingAction(Request $requestint $id): JsonResponse
  4903.     {
  4904.         $em $this->getDoctrine()->getManager();
  4905.         $meeting $em->getRepository(\ApplicationBundle\Entity\ScheduledMeeting::class)->find($id);
  4906.         if (!$meeting) {
  4907.             return new JsonResponse(['success' => false'error' => 'Meeting not found'], 404);
  4908.         }
  4909.         $em->remove($meeting);
  4910.         $em->flush();
  4911.         return new JsonResponse([
  4912.             'success' => true,
  4913.             'message' => 'Meeting deleted successfully',
  4914.             'deletedId' => $id
  4915.         ]);
  4916.     }
  4917.     public function searchParticipantByEmailAction(Request $request): JsonResponse
  4918.     {
  4919.         $em $this->getDoctrine()->getManager();
  4920.         $email trim($request->query->get('email'));
  4921.         if (empty($email)) {
  4922.             return new JsonResponse([
  4923.                 'success' => false,
  4924.                 'error' => 'Email is required'
  4925.             ], 400);
  4926.         }
  4927.         try {
  4928.             $companyId $this->getLoggedUserCompanyId($request);
  4929.             $client $em->getRepository(\ApplicationBundle\Entity\AccClients::class)
  4930.                 ->findOneBy(['email' => $email]);
  4931.             if ($client) {
  4932.                 return new JsonResponse([
  4933.                     'success' => true,
  4934.                     'type' => 'client',
  4935.                     'data' => [
  4936.                         'client_id' => $client->getClientId(),
  4937.                         'company_id' => $client->getCompanyId(),
  4938.                         'client_name' => $client->getClientName(),
  4939.                         'email' => $client->getEmail(),
  4940.                     ]
  4941.                 ]);
  4942.             }
  4943.             $employee $em->getRepository(\ApplicationBundle\Entity\Employee::class)
  4944.                 ->findOneBy(['email' => $email]);
  4945.             if ($employee) {
  4946.                 return new JsonResponse([
  4947.                     'success' => true,
  4948.                     'type' => 'employee',
  4949.                     'data' => [
  4950.                         'name' => $employee->getName(),
  4951.                         'email' => $employee->getEmail(),
  4952.                         'user_id' => $employee->getUserId(),
  4953.                         'address_contact' => $employee->getAddressContact(),
  4954.                     ]
  4955.                 ]);
  4956.             }
  4957.             return new JsonResponse([
  4958.                 'success' => false,
  4959.                 'error' => 'No client or employee found for this email'
  4960.             ], 404);
  4961.         } catch (\Exception $e) {
  4962.             return new JsonResponse([
  4963.                 'success' => false,
  4964.                 'error' => $e->getMessage()
  4965.             ], 500);
  4966.         }
  4967.     }
  4968.     public function GetRoomInformationForMeetingAction(Request $request): JsonResponse
  4969.     {
  4970.         $em $this->getDoctrine()->getManager();
  4971.         $onlyAvailable $request->query->getBoolean('onlyAvailable'false);
  4972.         $rooms HumanResourceHelper::getRooms($em$onlyAvailable);
  4973.         return new JsonResponse([
  4974.             'status' => 'success',
  4975.             'data' => $rooms
  4976.         ]);
  4977.     }
  4978.     public function MeetingTypeAction(Request $request)
  4979.     {
  4980.         return new JsonResponse([
  4981.             'success' => true,
  4982.             'data' => MeetingSchedulingConstant::$meetingType
  4983.         ]);
  4984.     }
  4985.     public function GetPriorityListAction()
  4986.     {
  4987.         $priority HumanResourceHelper::priorityList();
  4988.         return new JsonResponse([
  4989.             'success' => true,
  4990.             'data' => $priority
  4991.         ]);
  4992.     }
  4993.     public function CreateTrainingScheduleAction(Request $req$action 0)
  4994.     {
  4995.         $em $this->getDoctrine()->getManager();
  4996.         $companyId $this->getLoggedUserCompanyId($req);
  4997.         $session $req->getSession();
  4998.         if ($req->request->has('XHRreq')) {
  4999.             return new JsonResponse([HumanResource::HandelXHRreqForMeetingScheduling($em$req)]);
  5000.         }
  5001.         if ($action === 'list') {
  5002.             $response HumanResource::TwigDataForScheduledMeetingList($em, [1]);
  5003.             return $this->render(
  5004.                 'ApplicationBundle:pages/human_resource/list:scheduled_meeting_list.html.twig',
  5005.                 [
  5006.                     'page_title' => 'Training Schedule List',
  5007.                     'list' => $response
  5008.                 ]
  5009.             );
  5010.         }
  5011.         if ($req->isMethod('GET')) {
  5012.         }
  5013.         if ($req->isMethod('POST')) {
  5014.             $approveHash $req->request->get('approvalHash');
  5015.             $approveRole $req->request->get('approvalRole');
  5016.             $loginId $req->getSession()->get(UserConstants::USER_LOGIN_ID);
  5017.             $isSignatureOk DocValidation::isSignatureOk($em$loginId$approveHash);
  5018.             $companyData Company::getCompanyData($em$companyId);
  5019.             if ($isSignatureOk) {
  5020.                 $isSuccess HumanResource::createOrUpdateDataForMeetingScheduling($em$req);
  5021.                 if ($isSuccess) {
  5022.                     $options = array(
  5023.                         'notification_enabled' => $this->container->getParameter('notification_enabled'),
  5024.                         'notification_server' => $this->container->getParameter('notification_server'),
  5025.                         'appId' => $req->getSession()->get(UserConstants::USER_APP_ID),
  5026.                         'url' => $this->generateUrl(
  5027.                             GeneralConstant::$Entity_list_details[array_flip(GeneralConstant::$Entity_list)['ScheduledMeeting']]['entity_view_route_path_name']
  5028.                         )
  5029.                     );
  5030.                     $meetingId $isSuccess[1];
  5031.                     System::setApprovalInfo(
  5032.                         $this->getDoctrine()->getManager(),
  5033.                         $options,
  5034.                         array_flip(GeneralConstant::$Entity_list)['ScheduledMeeting'],
  5035.                         $meetingId,
  5036.                         $req->getSession()->get(UserConstants::USER_LOGIN_ID),
  5037.                         '',
  5038.                         0,
  5039.                         $this->get('mail_module')
  5040.                     );
  5041.                     System::createEditSignatureHash(
  5042.                         $this->getDoctrine()->getManager(),
  5043.                         array_flip(GeneralConstant::$Entity_list)['ScheduledMeeting'],
  5044.                         $meetingId,
  5045.                         $loginId,
  5046.                         $approveRole,
  5047.                         $req->request->get('approvalHash')
  5048.                     );
  5049.                     $url $this->generateUrl(
  5050.                         'view_scheduled_meeting'
  5051.                     );
  5052.                     return $this->redirect($url "/" $meetingId);
  5053.                 } else {
  5054.                     return new JsonResponse(array(
  5055.                         'success' => false
  5056.                     ));
  5057.                 }
  5058.             } else {
  5059.                 $this->addFlash(
  5060.                     'error',
  5061.                     'Invalid Approval Hash!'
  5062.                 );
  5063.                 return $this->redirectToRoute('create_training_schedule');
  5064.             }
  5065.         }
  5066.         $response HumanResource::twigDataForTrainingScheduling($em);
  5067.         return $this->render(
  5068.             'ApplicationBundle:pages/human_resource/input_forms:create_training_schedule.html.twig',
  5069.             [
  5070.                 'page_title' => 'Schedule a Training',
  5071.                 'employeeIds' => $response['employeeIds'],
  5072.                 'branches' => $response['branches'],
  5073.                 'asset' => $response['asset'],
  5074.                 'rooms' => $response['rooms'],
  5075.                 'courseList' => $response['courseList'],
  5076.                 'sales_orders' => $response['salesOrders'],
  5077.                 'purchase_orders' => $response['purchaseOrders'],
  5078.                 'meeting_types' => $response['meetingType'],
  5079.                 'skillList' => $response['skillList'],
  5080.             ]
  5081.         );
  5082.     }
  5083.     public function ScheduledTrainingListAction(Request $req$action 0)
  5084.     {
  5085.         $em $this->getDoctrine()->getManager();
  5086.         $companyId $this->getLoggedUserCompanyId($req);
  5087.         $session $req->getSession();
  5088.         $response HumanResource::TwigDataForScheduledMeetingList($em, [1]);
  5089.         return $this->render(
  5090.             'ApplicationBundle:pages/human_resource/list:scheduled_training_list.html.twig',
  5091.             [
  5092.                 'page_title' => 'Scheduled Trainings ',
  5093.                 'list' => $response
  5094.             ]
  5095.         );
  5096.     }
  5097.     public function ScheduledInterviewListAction(Request $req$action 0)
  5098.     {
  5099.         $em $this->getDoctrine()->getManager();
  5100.         $companyId $this->getLoggedUserCompanyId($req);
  5101.         $session $req->getSession();
  5102.         $response HumanResource::TwigDataForScheduledMeetingList($em, [2]);
  5103.         return $this->render(
  5104.             'ApplicationBundle:pages/human_resource/list:scheduled_interview_list.html.twig',
  5105.             [
  5106.                 'page_title' => 'Scheduled Interviews ',
  5107.                 'list' => $response
  5108.             ]
  5109.         );
  5110.     }
  5111.     public function GetFilteredQuestionsAction(Request $request$search '')
  5112.     {
  5113.         $em $this->getDoctrine()->getManager();
  5114.         $companyId $this->getLoggedUserCompanyId($request);
  5115.         if ($search == '' || $search == '_EMPTY_')
  5116.             $Query "SELECT  * FROM questionnaire WHERE 1 limit 10;";
  5117.         else
  5118.             $Query "SELECT  * FROM questionnaire WHERE question_text like '%$search%'  limit 10;";
  5119.         $stmt $em->getConnection()->prepare($Query);
  5120.         $stmt->execute();
  5121.         $queryResult $stmt->fetchAll();
  5122.         $parent_head_ids = [];
  5123.         $queryResultIndexed = [];
  5124.         foreach ($queryResult as $dt) {
  5125.             $queryResultIndexed[$dt['question_id']] = $dt;
  5126.         }
  5127.         return new JsonResponse(array(
  5128.             'data' => $queryResult,
  5129.             'queryResultIndexed' => $queryResultIndexed,
  5130.         ));
  5131.     }
  5132.     public function CreateTrainingCourseAction(Request $request$id 0)
  5133.     {
  5134.         $em $this->getDoctrine()->getManager();
  5135.         $companyId $this->getLoggedUserCompanyId($request);
  5136.         $skills $em->getRepository('ApplicationBundle:Skill')->findAll();
  5137.         $courses $em->getRepository('ApplicationBundle:TrainingCourse')->findAll();
  5138.         if ($request->isMethod('POST')) {
  5139.             $loginId $request->getSession()->get(UserConstants::USER_LOGIN_ID);
  5140.             $skill = new TrainingCourse;
  5141.             $skill->setTitle($request->request->get('name'));
  5142.             $skill->setCourseHash($request->request->get('coursehash'));
  5143.             $skill->setTrainingMaterialText($request->request->get('overview'));
  5144.             $skill->setTaggedSkillHashes(json_encode($request->request->get('skill')));
  5145.             $skill->setCompanyId($companyId);
  5146.             //$skill->setEditFlag(1); //editable usually
  5147.             $skill->setCreatedLoginId($request->getSession()->get(UserConstants::USER_LOGIN_ID));
  5148.             //$skill->setApproved(GeneralConstant::APPROVAL_STATUS_PENDING);
  5149.             //$skill->setAutocreated(0);
  5150.             $em->persist($skill);
  5151.             $em->flush();
  5152.         }
  5153.         return $this->render(
  5154.             'ApplicationBundle:pages/human_resource/input_forms:create_training_course.html.twig',
  5155.             [
  5156.                 'page_title' => 'Create Training Course',
  5157.                 'skills' => $skills,
  5158.                 'courses' => $courses
  5159.             ]
  5160.         );
  5161.     }
  5162.     public function CreateEmployeeExpenseAllowanceSettingsAction(Request $request$id 0)
  5163.     {
  5164.         $em $this->getDoctrine()->getManager();
  5165.         $companyId $this->getLoggedUserCompanyId($request);
  5166.         $extDocData = [];
  5167.         $extDetailsData = [];
  5168.         if ($request->isMethod('POST')) {
  5169.             //            Generic::debugMessage($_POST);
  5170.             $em $this->getDoctrine()->getManager();
  5171.             $entity_id array_flip(GeneralConstant::$Entity_list)['EmployeeExpenseAllowanceSettings']; //change
  5172.             $dochash $request->request->get('docHash'); //change
  5173.             $loginId $request->getSession()->get(UserConstants::USER_LOGIN_ID);
  5174.             $approveRole $request->request->get('approvalRole');
  5175.             $approveHash $request->request->get('approvalHash');
  5176.             if (!DocValidation::isInsertable(
  5177.                 $em,
  5178.                 $entity_id,
  5179.                 $dochash,
  5180.                 $loginId,
  5181.                 $approveRole,
  5182.                 $approveHash,
  5183.                 $id
  5184.             )
  5185.             ) {
  5186.                 $this->addFlash(
  5187.                     'error',
  5188.                     'Sorry Could not insert Data.'
  5189.                 );
  5190.             } else {
  5191.                 $funcname 'EmployeeExpenseAllowanceSettings';
  5192.                 DeleteDocument::$funcname($em$id0);
  5193.                 $docId HumanResource::CreateSalarySegregationPolicy($em$request$companyId0);
  5194.                 //now add Approval info
  5195.                 $loginId $request->getSession()->get(UserConstants::USER_LOGIN_ID);
  5196.                 $approveRole $request->request->get('approvalRole');
  5197.                 $options = array(
  5198.                     'notification_enabled' => $this->container->getParameter('notification_enabled'),
  5199.                     'notification_server' => $this->container->getParameter('notification_server'),
  5200.                     'appId' => $request->getSession()->get(UserConstants::USER_APP_ID),
  5201.                     'url' => $this->generateUrl(
  5202.                         GeneralConstant::$Entity_list_details[array_flip(GeneralConstant::$Entity_list)['EmployeeExpenseAllowanceSettings']]['entity_view_route_path_name']
  5203.                     )
  5204.                 );
  5205.                 System::setApprovalInfo(
  5206.                     $this->getDoctrine()->getManager(),
  5207.                     $options,
  5208.                     array_flip(GeneralConstant::$Entity_list)['EmployeeExpenseAllowanceSettings'],
  5209.                     $docId,
  5210.                     $request->getSession()->get(UserConstants::USER_LOGIN_ID)
  5211.                 );
  5212.                 System::createEditSignatureHash(
  5213.                     $this->getDoctrine()->getManager(),
  5214.                     array_flip(GeneralConstant::$Entity_list)['EmployeeExpenseAllowanceSettings'],
  5215.                     $docId,
  5216.                     $loginId,
  5217.                     $approveRole,
  5218.                     $request->request->get('approvalHash')
  5219.                 );
  5220.                 $doc_here $this->getDoctrine()
  5221.                     ->getRepository('ApplicationBundle:EmployeeExpenseAllowanceSettings')
  5222.                     ->findOneBy(
  5223.                         array(
  5224.                             'id' => $docId
  5225.                         )
  5226.                     );
  5227.                 //notify
  5228.                 $this->addFlash(
  5229.                     'success',
  5230.                     'Settings Successfully Updated.'
  5231.                 );
  5232.                 $url $this->generateUrl(
  5233.                     GeneralConstant::$Entity_list_details[array_flip(GeneralConstant::$Entity_list)['EmployeeExpenseAllowanceSettings']]['entity_view_route_path_name']
  5234.                 );
  5235.                 System::AddNewNotification(
  5236.                     $this->container->getParameter('notification_enabled'),
  5237.                     $this->container->getParameter('notification_server'),
  5238.                     $request->getSession()->get(UserConstants::USER_APP_ID),
  5239.                     $request->getSession()->get(UserConstants::USER_COMPANY_ID),
  5240.                     "Salary Segregation Policy : " $doc_here->getDocumentHash() . " Has Been Created And is Under Processing",
  5241.                     'pos',
  5242.                     System::getPositionIdsByDepartment($emGeneralConstant::HRM_DEPARTMENT),
  5243.                     'success',
  5244.                     //                    $url . "/" . $TransID,
  5245.                     $url "/" $docId,
  5246.                     "Journal"
  5247.                 );
  5248.                 return $this->redirect($url "/" $docId);
  5249.             }
  5250.         }
  5251.         //for edits
  5252.         if ($id == 0) {
  5253.         } else {
  5254.             $extDocData $em->getRepository('ApplicationBundle:EmployeeExpenseAllowanceSettings')->findOneBy(
  5255.                 array(
  5256.                     'id' => $id///material
  5257.                 )
  5258.             );
  5259.             //now if its not editable, redirect to view
  5260.             if ($extDocData) {
  5261.                 if ($extDocData->getEditFlag() != 1) {
  5262. //          $url = $this->generateUrl(
  5263. ////              'view_salary_segregation_policy'
  5264. //              'salary_segregation_policy'
  5265. //          );
  5266. //          return $this->redirect($url . "/" . $id);
  5267.                 } else {
  5268. //          $extVoucherDetailsData = Accounts::GetVoucherDataForEdit($em, $voucherId);
  5269. //          $extDetailsData = $em->getRepository('ApplicationBundle:SalarySegregationPolicy')->findOneBy(
  5270. //              array(
  5271. //                  'transactionId' => $id, ///material
  5272. //
  5273. //              )
  5274. //          );
  5275.                 }
  5276.             } else {
  5277.             }
  5278.         }
  5279.         $employeeIds $em->getRepository("ApplicationBundle:Employee")->findAll();
  5280.         $employeeType HumanResourceConstant::$employeeType;
  5281.         $employeeExpenseAllowanceTypes HumanResourceConstant::$employeeExpenseAllowanceTypes;
  5282.         $Designation $em->getRepository("ApplicationBundle:SysDepartmentPosition")->findAll();
  5283.         $branch $em->getRepository("ApplicationBundle:Branch")->findAll();
  5284.         $departments $em->getRepository("ApplicationBundle:SysDepartment")->findAll();
  5285.         $department = [];
  5286.         foreach ($departments as $entry) {
  5287.             $department[$entry->getDepartmentId()] = array(
  5288.                 'id' => $entry->getDepartmentId(),
  5289.                 'name' => $entry->getDepartmentName(),
  5290.             );
  5291.         }
  5292.         return $this->render(
  5293.             'ApplicationBundle:pages/human_resource/input_forms:create_employee_expense_allowance_settings.html.twig',
  5294.             [
  5295.                 'page_title' => 'Employee Expense Allowance Settings',
  5296.                 'employeeIds' => $employeeIds,
  5297.                 'extId' => $id,
  5298.                 'extDocData' => $extDocData,
  5299.                 'employeeType' => $employeeType,
  5300.                 'employeeExpenseAllowanceTypes' => $employeeExpenseAllowanceTypes,
  5301.                 'Designation' => $Designation,
  5302.                 'branch' => $branch,
  5303.                 'department' => $department,
  5304.             ]
  5305.         );
  5306.     }
  5307.     public function EmployeeExpenseAllowanceSettingsListAction(Request $request)
  5308.     {
  5309.         $em $this->getDoctrine()->getManager();
  5310.         $allowed_ids = [];
  5311.         $companyId $this->getLoggedUserCompanyId($request);
  5312.         $listData HumanResource::GetDataForEmployeeExpenseAllowanceSettingsListAction($em$request->isMethod('POST') ? 'POST' 'GET'$request->request$companyId);
  5313.         if ($request->isMethod('POST')) {
  5314.             if ($request->query->has('dataTableQry')) {
  5315.                 return new JsonResponse(
  5316.                     $listData
  5317.                 );
  5318.             }
  5319.         }
  5320.         return $this->render('ApplicationBundle:pages/human_resource/list:employee_expense_allowance_settings_list.html.twig',
  5321. //         return $this->render('ApplicationBundle:pages/dashboard:test_pix_invent.html.twig',
  5322.             array(
  5323.                 'page_title' => 'Expense Allowance Settings List',
  5324. //            'data' => SalesOrderM::GetClientList($em, [], $companyId),
  5325. //            'client_types' => Client::GetClientType($em, $companyId),
  5326. //            'region_list' => Client::RegionList($em, $companyId),
  5327. //            'geographical_region_list' => Client::GeographicalRegionList($em, $companyId)
  5328.             )
  5329.         );
  5330.     }
  5331.     public function salarySegAction(Request $request$id 0)
  5332.     {
  5333.         $em $this->getDoctrine()->getManager();
  5334.         $companyId $this->getLoggedUserCompanyId($request);
  5335.         $extDocData = [];
  5336.         $extDetailsData = [];
  5337.         if ($request->isMethod('POST')) {
  5338.             //            Generic::debugMessage($_POST);
  5339.             $em $this->getDoctrine()->getManager();
  5340.             $entity_id array_flip(GeneralConstant::$Entity_list)['SalarySegregationPolicy']; //change
  5341.             $dochash $request->request->get('docHash'); //change
  5342.             $loginId $request->getSession()->get(UserConstants::USER_LOGIN_ID);
  5343.             $approveRole $request->request->get('approvalRole');
  5344.             $approveHash $request->request->get('approvalHash');
  5345.             if (!DocValidation::isInsertable(
  5346.                 $em,
  5347.                 $entity_id,
  5348.                 $dochash,
  5349.                 $loginId,
  5350.                 $approveRole,
  5351.                 $approveHash,
  5352.                 $id
  5353.             )
  5354.             ) {
  5355.                 $this->addFlash(
  5356.                     'error',
  5357.                     'Sorry Couldnot insert Data.'
  5358.                 );
  5359.             } else {
  5360.                 $funcname 'SalarySegregationPolicy';
  5361.                 DeleteDocument::$funcname($em$id0);
  5362.                 $docId HumanResource::CreateSalarySegregationPolicy($em$request$companyId0);
  5363.                 //now add Approval info
  5364.                 $loginId $request->getSession()->get(UserConstants::USER_LOGIN_ID);
  5365.                 $approveRole $request->request->get('approvalRole');
  5366.                 $options = array(
  5367.                     'notification_enabled' => $this->container->getParameter('notification_enabled'),
  5368.                     'notification_server' => $this->container->getParameter('notification_server'),
  5369.                     'appId' => $request->getSession()->get(UserConstants::USER_APP_ID),
  5370.                     'url' => $this->generateUrl(
  5371.                         GeneralConstant::$Entity_list_details[array_flip(GeneralConstant::$Entity_list)['SalarySegregationPolicy']]['entity_view_route_path_name']
  5372.                     )
  5373.                 );
  5374.                 System::setApprovalInfo(
  5375.                     $this->getDoctrine()->getManager(),
  5376.                     $options,
  5377.                     array_flip(GeneralConstant::$Entity_list)['SalarySegregationPolicy'],
  5378.                     $docId,
  5379.                     $request->getSession()->get(UserConstants::USER_LOGIN_ID),
  5380.                     3    //journal voucher
  5381.                 );
  5382.                 System::createEditSignatureHash(
  5383.                     $this->getDoctrine()->getManager(),
  5384.                     array_flip(GeneralConstant::$Entity_list)['SalarySegregationPolicy'],
  5385.                     $docId,
  5386.                     $loginId,
  5387.                     $approveRole,
  5388.                     $request->request->get('approvalHash')
  5389.                 );
  5390.                 $doc_here $this->getDoctrine()
  5391.                     ->getRepository('ApplicationBundle:SalarySegregationPolicy')
  5392.                     ->findOneBy(
  5393.                         array(
  5394.                             'id' => $docId
  5395.                         )
  5396.                     );
  5397.                 //notify
  5398.                 $this->addFlash(
  5399.                     'success',
  5400.                     'Policy Successfully Updated.'
  5401.                 );
  5402.                 $url $this->generateUrl(
  5403.                     'salary_segregation_policy'
  5404.                 );
  5405.                 System::AddNewNotification(
  5406.                     $this->container->getParameter('notification_enabled'),
  5407.                     $this->container->getParameter('notification_server'),
  5408.                     $request->getSession()->get(UserConstants::USER_APP_ID),
  5409.                     $request->getSession()->get(UserConstants::USER_COMPANY_ID),
  5410.                     "Salary Segregation Policy : " $doc_here->getDocumentHash() . " Has Been Created And is Under Processing",
  5411.                     'pos',
  5412.                     System::getPositionIdsByDepartment($emGeneralConstant::HRM_DEPARTMENT),
  5413.                     'success',
  5414.                     //                    $url . "/" . $TransID,
  5415.                     $url "/" $docId,
  5416.                     "Journal"
  5417.                 );
  5418.                 return $this->redirect($url "/" $docId);
  5419.             }
  5420.         }
  5421.         //for edits
  5422.         if ($id == 0) {
  5423.         } else {
  5424.             $extDocData $em->getRepository('ApplicationBundle:SalarySegregationPolicy')->findOneBy(
  5425.                 array(
  5426.                     'id' => $id///material
  5427.                 )
  5428.             );
  5429.             //now if its not editable, redirect to view
  5430.             if ($extDocData) {
  5431.                 if ($extDocData->getEditFlag() != 1) {
  5432. //          $url = $this->generateUrl(
  5433. ////              'view_salary_segregation_policy'
  5434. //              'salary_segregation_policy'
  5435. //          );
  5436. //          return $this->redirect($url . "/" . $id);
  5437.                 } else {
  5438. //          $extVoucherDetailsData = Accounts::GetVoucherDataForEdit($em, $voucherId);
  5439. //          $extDetailsData = $em->getRepository('ApplicationBundle:SalarySegregationPolicy')->findOneBy(
  5440. //              array(
  5441. //                  'transactionId' => $id, ///material
  5442. //
  5443. //              )
  5444. //          );
  5445.                 }
  5446.             } else {
  5447.             }
  5448.         }
  5449.         $employeeIds $em->getRepository(EmployeeDetails::class)->findAll();
  5450.         $employeeType HumanResourceConstant::$employeeType;
  5451.         $Designation $em->getRepository(SysDepartmentPosition::class)->findAll();
  5452.         $branch $em->getRepository(Branch::class)->findAll();
  5453.         $departments $em->getRepository(SysDepartment::class)->findAll();
  5454.         $department = [];
  5455.         foreach ($departments as $entry) {
  5456.             $department[$entry->getDepartmentId()] = array(
  5457.                 'id' => $entry->getDepartmentId(),
  5458.                 'name' => $entry->getDepartmentName(),
  5459.             );
  5460.         }
  5461.         return $this->render(
  5462.             'ApplicationBundle:pages/human_resource/input_forms:salary_segregation_policy.html.twig',
  5463.             [
  5464.                 'page_title' => 'Salary Segregation Policy',
  5465.                 'employeeIds' => $employeeIds,
  5466.                 'extId' => $id,
  5467.                 'extDocData' => $extDocData,
  5468.                 'employeeType' => $employeeType,
  5469.                 'Designation' => $Designation,
  5470.                 'branch' => $branch,
  5471.                 'department' => $department,
  5472.             ]
  5473.         );
  5474.     }
  5475.     public function GetSalarySegregationDataForEmployeeEntryAction(Request $request)
  5476.     {
  5477.         $em $this->getDoctrine()->getManager();
  5478.         $companyId $this->getLoggedUserCompanyId($request);
  5479.         if ($request->request->has('salSagDataReq')) {
  5480.             $ajaxData HumanResource::handelXhrForSalSeg($em$request);
  5481.             return new JsonResponse($ajaxData);
  5482.         }
  5483.         return new JsonResponse(array('success' => false));
  5484.     }
  5485.     public function WorkHourPolicyAction(Request $req$id 0)
  5486.     {
  5487.         $em $this->getDoctrine()->getManager();
  5488.         $companyId $this->getLoggedUserCompanyId($req);
  5489.         $extData = [];
  5490.         if ($id != 0) {
  5491.             $extData $em->getRepository('ApplicationBundle:WorkHourPolicy')
  5492.                 ->findOneBy(
  5493.                     array(
  5494.                         'id' => $id
  5495.                     )
  5496.                 );
  5497.         }
  5498.         if ($req->isMethod('POST')) {
  5499.             $storeDataRes HumanResource::checkSignature($em$req);
  5500.             if ($storeDataRes['hasErr']) {
  5501.                 $msg $storeDataRes['msg'];
  5502.                 $this->addFlash(
  5503.                     'error',
  5504.                     $msg
  5505.                 );
  5506.                 return $this->redirectToRoute('work_hour_policy');
  5507.             } else {
  5508.                 HumanResource::storeDataForWhPolicy($em$req$companyId);
  5509.                 $this->addFlash(
  5510.                     'success',
  5511.                     'Policy Successfully Created!'
  5512.                 );
  5513.                 return $this->redirectToRoute('work_hour_policy');
  5514.             }
  5515.         }
  5516.         $twigData HumanResource::twigDataForWorkHourPolicy($em);
  5517.         $timeZonesArray = array();
  5518.         return $this->render(
  5519.             'ApplicationBundle:pages/human_resource/input_forms:work_hour_policy.html.twig',
  5520.             [
  5521.                 'page_title' => 'Work Hour Policy',
  5522.                 'extId' => $id,
  5523.                 'extData' => $extData,
  5524.                 'employeeIds' => $twigData['employeeIds'],
  5525.                 'employeeType' => $twigData['employeeType'],
  5526.                 'Designation' => $twigData['Designation'],
  5527.                 'branch' => $twigData['branch'],
  5528.                 'department' => $twigData['department'],
  5529.             ]
  5530.         );
  5531.     }
  5532.     public function WorkHourPolicyListAction(Request $request)
  5533.     {
  5534.         $em $this->getDoctrine()->getManager();
  5535.         $allowed_ids = [];
  5536.         $companyId $this->getLoggedUserCompanyId($request);
  5537.         $listData HumanResource::GetDataForWorkHourPolicyListAction($em$request->isMethod('POST') ? 'POST' 'GET'$request->request$companyId);
  5538.         if ($request->isMethod('POST')) {
  5539.             if ($request->query->has('dataTableQry')) {
  5540.                 return new JsonResponse(
  5541.                     $listData
  5542.                 );
  5543.             }
  5544.         }
  5545.         return $this->render('ApplicationBundle:pages/human_resource/list:work_hour_policy_list.html.twig',
  5546. //         return $this->render('ApplicationBundle:pages/dashboard:test_pix_invent.html.twig',
  5547.             array(
  5548.                 'page_title' => 'Work Hour Policy List',
  5549. //            'data' => SalesOrderM::GetClientList($em, [], $companyId),
  5550. //            'client_types' => Client::GetClientType($em, $companyId),
  5551. //            'region_list' => Client::RegionList($em, $companyId),
  5552. //            'geographical_region_list' => Client::GeographicalRegionList($em, $companyId)
  5553.             )
  5554.         );
  5555.     }
  5556.     public function WorkPlacePolicyListAction(Request $request)
  5557.     {
  5558.         $em $this->getDoctrine()->getManager();
  5559.         $workplacePolicyDetails $em->getRepository('ApplicationBundle:EmployeeWorkplace')->findAll();
  5560. //        $employee = $em->getRepository('ApplicationBundle:Employee')->findAll();
  5561.         return $this->render('ApplicationBundle:pages/human_resource/list:work_place_policy_list.html.twig', array(
  5562.             'page_title' => 'Work Place Policy List',
  5563.             'workplacePolicyDetails' => $workplacePolicyDetails,
  5564. //            'employee'=>$employee
  5565.         ));
  5566.     }
  5567.     public function workPlacePolicyAction(Request $data$id)
  5568.     {
  5569.         $em $this->getDoctrine()->getManager();
  5570.         $workPlacePolicy $em->getRepository('ApplicationBundle:EmployeeWorkplace')->find($id);
  5571.         $employee $em->getRepository(Employee::class)->findAll();
  5572.         $Approval_data System::checkIfApprovalExists(
  5573.             $em,
  5574.             array_flip(GeneralConstant::$Entity_list)['EmployeeWorkplace'],
  5575.             $id,
  5576.             $data->getSession()->get(UserConstants::USER_LOGIN_ID)
  5577.         );
  5578.         $ApprovalStatus GeneralConstant::$approvalStatus;
  5579.         return $this->render('ApplicationBundle:pages/human_resource/views:viewWorkPlacePolicy.html.twig', array(
  5580.             'page_title' => 'Work Place Policy  View',
  5581.             'workPlacePolicy' => $workPlacePolicy,
  5582.             'employee' => $employee,
  5583.             'approval_data' => $Approval_data,
  5584.             'approval_status' => $workPlacePolicy->getApproved(),
  5585.             'id' => $id,
  5586.         ));
  5587.     }
  5588.     public function SalarySegregationPolicyListAction(Request $request)
  5589.     {
  5590.         $em $this->getDoctrine()->getManager();
  5591.         $allowed_ids = [];
  5592.         $companyId $this->getLoggedUserCompanyId($request);
  5593.         $listData HumanResource::GetDataForSalarySegregationPolicyListAction($em$request->isMethod('POST') ? 'POST' 'GET'$request->request$companyId);
  5594.         if ($request->isMethod('POST')) {
  5595.             if ($request->query->has('dataTableQry')) {
  5596.                 return new JsonResponse(
  5597.                     $listData
  5598.                 );
  5599.             }
  5600.         }
  5601.         return $this->render('ApplicationBundle:pages/human_resource/list:salary_segregation_policy_list.html.twig',
  5602. //         return $this->render('ApplicationBundle:pages/dashboard:test_pix_invent.html.twig',
  5603.             array(
  5604.                 'page_title' => 'Salary Segregation Policy List',
  5605. //            'data' => SalesOrderM::GetClientList($em, [], $companyId),
  5606. //            'client_types' => Client::GetClientType($em, $companyId),
  5607. //            'region_list' => Client::RegionList($em, $companyId),
  5608. //            'geographical_region_list' => Client::GeographicalRegionList($em, $companyId)
  5609.             )
  5610.         );
  5611.     }
  5612.     public function HolidayCalendarListAction(Request $request)
  5613.     {
  5614.         $q $this->getDoctrine()
  5615.             ->getRepository('ApplicationBundle:HolidayCalendar')
  5616.             ->findBy(
  5617.                 array(
  5618. //                'status' => GeneralConstant::ACTIVE,
  5619.                     'CompanyId' => $this->getLoggedUserCompanyId($request)
  5620. //                    'approved' =>  GeneralConstant::APPROVED,
  5621.                 )
  5622.             );
  5623.         $stage_list = array(
  5624.             => 'Pending',
  5625.             => 'Pending',
  5626.             => 'Complete',
  5627.             => 'Partial',
  5628.         );
  5629.         $data = [];
  5630.         foreach ($q as $entry) {
  5631.             $data[] = array(
  5632. //          'doc_date' => $entry->getSalesReplacementDate(),
  5633.                 'id' => $entry->getHolidayCalendarId(),
  5634.                 'title' => $entry->getHoliDayTitle(),
  5635.                 'approval_status' => GeneralConstant::$approvalStatus[$entry->getApproved()],
  5636. //          'stage' => $stage_list[$entry->getStage()]
  5637.             );
  5638.         }
  5639.         return $this->render('ApplicationBundle:pages/human_resource/list:holiday_calendar_list.html.twig',
  5640.             array(
  5641.                 'page_title' => 'Holiday Calendar List',
  5642.                 'data' => $data
  5643.             )
  5644.         );
  5645.     }
  5646.     public function PayrollPolicyListAction(Request $request)
  5647.     {
  5648.         $em $this->getDoctrine()->getManager();
  5649.         $allowed_ids = [];
  5650.         $companyId $this->getLoggedUserCompanyId($request);
  5651.         $listData HumanResource::GetDataForPayrollPolicyListAction($em$request->isMethod('POST') ? 'POST' 'GET'$request->request$companyId);
  5652.         if ($request->isMethod('POST')) {
  5653.             if ($request->query->has('dataTableQry')) {
  5654.                 return new JsonResponse(
  5655.                     $listData
  5656.                 );
  5657.             }
  5658.         }
  5659.         return $this->render('ApplicationBundle:pages/human_resource/list:payroll_policy_list.html.twig',
  5660. //         return $this->render('ApplicationBundle:pages/dashboard:test_pix_invent.html.twig',
  5661.             array(
  5662.                 'page_title' => 'Payroll Policy List',
  5663. //            'data' => SalesOrderM::GetClientList($em, [], $companyId),
  5664. //            'client_types' => Client::GetClientType($em, $companyId),
  5665. //            'region_list' => Client::RegionList($em, $companyId),
  5666. //            'geographical_region_list' => Client::GeographicalRegionList($em, $companyId)
  5667.             )
  5668.         );
  5669.     }
  5670.     public function payslipAction(Request $req$action 0$id 0)
  5671.     {
  5672.         $em $this->getDoctrine()->getManager();
  5673.         $attendanceSource HumanResourceConstant::$attendanceSources;
  5674.         if ($action === 'list') {
  5675.             $response HumanResource::twigDataForPayslipList($em);
  5676.             $approval_status GeneralConstant::$approvalAction;
  5677.             return $this->render(
  5678.                 'ApplicationBundle:pages/human_resource/list:payslip_list.html.twig',
  5679.                 [
  5680.                     'page_title' => 'Payslip List',
  5681.                     'reports' => $response,
  5682.                     'approval_status' => $approval_status
  5683.                 ]
  5684.             );
  5685.         }
  5686.         if ($action === 'view') {
  5687.             $response HumanResource::twigDataForPayslipViewAndPrint($em$req$id);
  5688.             return $this->render(
  5689.                 'ApplicationBundle:pages/human_resource/views:payslip_view.html.twig',
  5690.                 [
  5691.                     'page_title' => 'View Payslip',
  5692.                     'approval_data' => $response['approval_data'],
  5693.                     'payslip' => $response['payslip'],
  5694.                     'bankAccount' => $response['bankAccount'],
  5695.                     'tin' => $response['tin'],
  5696.                     'employeeCode' => $response['employeeCode'],
  5697.                     'earningValues' => $response['earningValues'],
  5698.                     'facilityValues' => $response['facilityValues'],
  5699.                     'deductionValues' => $response['deductionValues'],
  5700.                     'document_log' => $response['document_log'],
  5701.                     'approval_status' => $response['approval_status'],
  5702.                     'created_by' => $response['created_by'],
  5703.                     'updated_at' => $response['updated_at'],
  5704.                     'employeeId' => $response['employeeId'],
  5705.                     'totalAttendance' => $response['totalPresent'],
  5706.                     'leaveList' => HumanResourceConstant::$LeaveType,
  5707.                     'AttReportData' => $response['AttReportData'],
  5708. //                    'attendanceLog' => $response['attendanceLog'],
  5709.                     'attendanceSource' => $attendanceSource,
  5710.                     'auto_created' => 0,
  5711.                 ]
  5712.             );
  5713.         }
  5714.         if ($action === 'print') {
  5715.             $em $this->getDoctrine()->getManager();
  5716.             $company_data Company::getCompanyData($em1);
  5717.             $Authorizations System::getSignatureListForDocumentPrint($emarray_flip(GeneralConstant::$Entity_list)['Payslip'], $id);
  5718.             $response HumanResource::twigDataForPayslipViewAndPrint($em$req$id);
  5719.             return $this->render(
  5720.                 'ApplicationBundle:pages/human_resource/print:payslip_print.html.twig',
  5721.                 array(
  5722.                     'page_title' => 'Print Payslip',
  5723.                     'export' => 'pdf,print',
  5724.                     'payslip' => $response['payslip'],
  5725.                     'bankAccount' => $response['bankAccount'],
  5726.                     'tin' => $response['tin'],
  5727.                     'employeeCode' => $response['employeeCode'],
  5728.                     'earningValues' => $response['earningValues'],
  5729.                     'facilityValues' => $response['facilityValues'],
  5730.                     'deductionValues' => $response['deductionValues'],
  5731.                     'company_name' => $company_data->getName(),
  5732.                     'company_data' => $company_data,
  5733.                     'company_address' => $company_data->getAddress(),
  5734.                     'company_image' => $company_data->getImage(),
  5735.                     'Authorizations' => $Authorizations,
  5736.                     'totalAttendance' => $response['totalPresent'],
  5737.                     'leaveList' => HumanResourceConstant::$LeaveType,
  5738.                     'AttReportData' => $response['AttReportData'],
  5739.                     'attendanceSource' => $attendanceSource,
  5740.                     'red' => 0
  5741.                 )
  5742.             );
  5743.         }
  5744.         if ($req->isMethod('POST')) {
  5745.             $sigRes HumanResource::checkSignature($em$req);
  5746.             if ($sigRes['hasErr']) {
  5747.                 $msg $sigRes['msg'];
  5748.                 return new JsonResponse(['success' => false'msg' => $msg]);
  5749.             }
  5750.             HumanResource::storeDataForPayslip($em$req);
  5751.             return new JsonResponse(['success' => true]);
  5752.         }
  5753.     }
  5754.     public function applicantInfoAction(Request $request$id)
  5755.     {
  5756.         $em $this->getDoctrine()->getManager('company_group');
  5757.         $session $request->getSession();
  5758.         $consultantDetails $em->getRepository(EntityApplicantDetails::class)->find($session->get(UserConstants::USER_ID));
  5759.         $skillDetails $em->getRepository(EntitySkill::class)->findAll();
  5760.         $companyId $this->getLoggedUserCompanyId($request);
  5761.         $gender HumanResourceConstant::$sex;
  5762.         $blood HumanResourceConstant::$BloodGroup;
  5763.         $userId $session->get(UserConstants::USER_ID);
  5764.         $encData $request->query->has('ref') ? $request->query->get('ref') : '';
  5765.         $education = array(
  5766.             'instituteName' => $request->get('instituteName'),
  5767.             'courseOfStudy' => $request->get('courseOfStudy'),
  5768.             'courseStartDate' => $request->get('courseStartDate'),
  5769.             'courseEndDate' => $request->get('courseEndDate'),
  5770.             'result' => $request->get('result'),
  5771.             'grade' => $request->get('grade'),
  5772.             'degree' => $request->get('degree'),
  5773.         );
  5774.         $workExperience = array(
  5775.             'title' => $request->get('title'),
  5776.             'companyName' => $request->get('companyName'),
  5777.             'jobStartDate' => $request->get('jobStartDate'),
  5778.             'jobEndDate' => $request->get('jobEndDate'),
  5779.             'description' => $request->get('description'),
  5780.         );
  5781.         $certificate = array(
  5782.             'certificatename' => $request->get('certificatename'),
  5783.             'issuedDate' => $request->get('issuedDate'),
  5784.         );
  5785.         $courses = array(
  5786.             'courseName' => $request->get('courseName'),
  5787.             'date' => $request->get('date'),
  5788.             'duration' => $request->get('duration')
  5789.         );
  5790.         $languages = array(
  5791.             'languageName' => $request->get('languageName'),
  5792.             'writtenSkill' => $request->get('writtenSkill'),
  5793.             'verbalSkill' => $request->get('verbalSkill'),
  5794.         );
  5795.         if ($request->isMethod('POST')) {
  5796.             if ($consultantDetails)
  5797.                 $consultant $consultantDetails;
  5798.             else
  5799.                 $consultant = new EntityApplicantDetails();
  5800.             $consultant->setApplicationText($request->request->get('applicationText'));
  5801.             $consultant->setFirstname($request->request->get('firstname'));
  5802.             $consultant->setLastname($request->request->get('lastname'));
  5803.             $consultant->setIsImgLegal($request->request->get('is_img_legal'));
  5804.             $consultant->setNid($request->request->get('nid'));
  5805.             $consultant->setDob(new \DateTime($request->get('dob')));
  5806.             $consultant->setSex($request->request->get('sex'));
  5807.             $consultant->setFather($request->request->get('father'));
  5808.             $consultant->setMother($request->request->get('mother'));
  5809.             $consultant->setBlood($request->request->get('blood'));
  5810.             $consultant->setPhone($request->request->get('phone'));
  5811.             $consultant->setCountry($request->request->get('country'));
  5812.             $consultant->setPostalCode($request->request->get('postalCode'));
  5813.             $consultant->setCurrAddr($request->request->get('curr_addr'));
  5814.             $consultant->setSkill(json_encode($request->request->get('skill')));
  5815.             $consultant->setEmergencyContactNumber($request->request->get('emm_contact'));
  5816.             $consultant->setCurrentEmployment($request->request->get('currentEmployment'));
  5817.             $consultant->setTin($request->request->get('tin'));
  5818.             $consultant->setEducationData(json_encode($education));
  5819.             $consultant->setWorkExperienceData(json_encode($workExperience));
  5820.             $consultant->setCertificateData(json_encode($certificate));
  5821.             $consultant->setCoursesData(json_encode($courses));
  5822.             $consultant->setLanguagesData(json_encode($languages));
  5823.             $consultant->setWorkExperienceYear($request->request->get('workExperienceYear'));
  5824.             //$consultant->setApplyForConsultant(1);
  5825.             $em->persist($consultant);
  5826.             $em->flush();
  5827.             $path "";
  5828.             $defaultProductImage '';
  5829.             $uploadedFile null;
  5830.             $upl_dir $this->container->getParameter('kernel.root_dir') . '/../web/uploads/applicantCv/';
  5831.             $uploadedFile $request->files->get('docUpload');
  5832.             if ($uploadedFile != null) {
  5833.                 $fileName 'cv' $consultantDetails->getApplicantId() . '.' $uploadedFile->guessExtension();
  5834.                 $path $fileName;
  5835. //            $upl_dir = $this->container->getParameter('kernel.root_dir') . '/../web/uploads/Products/';
  5836.                 if (!file_exists($upl_dir)) {
  5837.                     mkdir($upl_dir0777true);
  5838.                 }
  5839.                 $uploadedFile->move($upl_dir$path);
  5840.                 $defaultProductImage 'uploads/applicantCv/' $path;
  5841.                 $consultant->setDocImage($defaultProductImage);
  5842.                 $em->flush();
  5843.             }
  5844.             $this->addFlash(
  5845.                 'success',
  5846.                 'Data Updated.'
  5847.             );
  5848.             if ($encData != '') {
  5849.                 $url $this->generateUrl(
  5850.                     'applicant_job_recruitment_view'
  5851.                 );
  5852.                 return $this->redirect($url '?auto_apply=1&encData=' $encData);
  5853.             }
  5854.             $url $this->generateUrl(
  5855.                 'job_recruitment_list_applicant'
  5856.             );
  5857.             return $this->redirect($url);
  5858.         }
  5859.         return $this->render('ApplicationBundle:pages/human_resource/input_forms:applicant_info.html.twig', array(
  5860.             'page_title' => 'My Information ',
  5861.             'gender' => $gender,
  5862.             'blood' => $blood,
  5863.             'consultantDetails' => $consultantDetails,
  5864.             'education' => json_decode($consultantDetails->getEducationData(), true),
  5865.             'workExperience' => json_decode($consultantDetails->getWorkExperienceData(), true),
  5866.             'certificate' => json_decode($consultantDetails->getCertificateData(), true),
  5867.             'courses' => json_decode($consultantDetails->getCoursesData(), true),
  5868.             'languages' => json_decode($consultantDetails->getLanguagesData(), true),
  5869.             'skill' => json_decode($consultantDetails->getSkill(), true),
  5870.             'skillDetails' => $skillDetails
  5871.         ));
  5872. //        $em = $this->getDoctrine()->getManager('company_group');
  5873. //        $applicantRepo = $em->getRepository(EntityApplicantDetails::class);
  5874. //        $skillDetails = $em->getRepository(EntitySkill::class)->findAll();
  5875. //
  5876. //
  5877. //        if ($req->isMethod('POST')) {
  5878. //            $applicant = $applicantRepo->find($id);
  5879. //
  5880. //            if ($req->files->get('img')) {
  5881. //                $ImgName = HumanResource::StoreFiles($req->files->get('img'), 'Applicant');
  5882. //                $applicant->setImage($ImgName);
  5883. //            }
  5884. //
  5885. //            $applicant->setFirstname($req->request->get('firstname'));
  5886. //            $applicant->setLastname($req->request->get('lastname'));
  5887. //            $applicant->setIsImgLegal($req->request->get('is_img_legal'));
  5888. //            $applicant->setNid($req->request->get('nid'));
  5889. //            $applicant->setDob(HumanResource::StringToDate($req->request->get('dob')));
  5890. //            $applicant->setSex($req->request->get('sex'));
  5891. //            $applicant->setFather($req->request->get('father'));
  5892. //            $applicant->setMother($req->request->get('mother'));
  5893. //            $applicant->setSpouse($req->request->get('spouse'));
  5894. //            $applicant->setChild1($req->request->get('child_1'));
  5895. //            $applicant->setChild2($req->request->get('child_2'));
  5896. //            $applicant->setBlood($req->request->get('blood'));
  5897. //            $applicant->setPhone($req->request->get('phone'));
  5898. //            $applicant->setOAuthEmail($req->request->get('oauth_email'));
  5899. //            $applicant->setCurrAddr($req->request->get('curr_addr'));
  5900. //            $applicant->setPermAddr($req->request->get('perm_addr'));
  5901. //            $applicant->setEmmContact($req->request->get('emm_contact'));
  5902. //
  5903. //            $applicant->setInst1($req->request->get('inst1'));
  5904. //            $applicant->setYr1($req->request->get('yr1'));
  5905. //            $applicant->setDur1($req->request->get('dur1'));
  5906. //            $applicant->setInst2($req->request->get('inst2'));
  5907. //            $applicant->setYr2($req->request->get('yr2'));
  5908. //            $applicant->setDur2($req->request->get('dur2'));
  5909. //            $applicant->setInst3($req->request->get('inst3'));
  5910. //            $applicant->setYr3($req->request->get('yr3'));
  5911. //            $applicant->setDur3($req->request->get('dur3'));
  5912. //            $applicant->setEinst1($req->request->get('einst1'));
  5913. //            $applicant->setEyr1($req->request->get('eyr1'));
  5914. //            $applicant->setEdeg1($req->request->get('edeg1'));
  5915. //            $applicant->setEinst2($req->request->get('einst2'));
  5916. //            $applicant->setEyr2($req->request->get('eyr2'));
  5917. //            $applicant->setEdeg2($req->request->get('edeg2'));
  5918. //            $applicant->setEinst3($req->request->get('einst3'));
  5919. //            $applicant->setEyr3($req->request->get('eyr3'));
  5920. //            $applicant->setEdeg3($req->request->get('edeg3'));
  5921. //
  5922. //            $em->persist($applicant);
  5923. //            $em->flush();
  5924. //
  5925. //            return $this->render(
  5926. //                'ApplicationBundle:pages/human_resource/input_forms:applicant_info.html.twig',
  5927. //                [
  5928. //                    'page_title' => 'Applicant Info',
  5929. //                    'applicant_info' => $applicant,
  5930. //                    'blood' => HumanResourceConstant::$BloodGroup,
  5931. //                    'gender' => HumanResourceConstant::$sex,
  5932. //                    'skillDetails' => $skillDetails,
  5933. //                    'HasUpdateMode' => true,
  5934. //                ]
  5935. //            );
  5936. //        }
  5937. //
  5938. //        if ($id) {
  5939. //            $applicant = $applicantRepo->find($id);
  5940. //
  5941. //            return $this->render(
  5942. //                'ApplicationBundle:pages/human_resource/input_forms:applicant_info.html.twig',
  5943. //                [
  5944. //                    'page_title' => 'Applicant Info',
  5945. //                    'applicant_info' => $applicant,
  5946. //                    'blood' => HumanResourceConstant::$BloodGroup,
  5947. //                    'gender' => HumanResourceConstant::$sex,
  5948. //                    'skillDetails' => $skillDetails,
  5949. //                    'HasUpdateMode' => false,
  5950. //                ]
  5951. //            );
  5952. //        }
  5953. //
  5954. //        $google_client = new Google_Client();
  5955. //        $google_client->setClientId('916737688016-l2qfmb9p37cumudkaqpu8s7ndngq9una.apps.googleusercontent.com');
  5956. //        $google_client->setClientSecret('BEWpEBRvv3-hSoB4cGBrVB3z');
  5957. //        $google_client->setRedirectUri('http://localhost/applicant_info');
  5958. //        $google_client->addScope('email');
  5959. //        $google_client->addScope('profile');
  5960.     }
  5961.     public function applicantDashboardAction()
  5962.     {
  5963.         return new JsonResponse(['this is applicant dashboard']);
  5964.     }
  5965.     public function resignApplicationAction(Request $req$id)
  5966.     {
  5967.         $em $this->getDoctrine()->getManager();
  5968.         if ($req->request->has('xhrReq')) {
  5969.             $response HumanResource::HandelXhrForResignApplication($em$req);
  5970.             return new JsonResponse($response);
  5971.         }
  5972.         if ($req->isMethod('GET')) {
  5973.             $applicant $em->getRepository(EmployeeDetails::class)->findBy(['emp_status' => 1]);
  5974.             $resignReason HumanResourceConstant::$resignReason;
  5975.             return $this->render(
  5976.                 'ApplicationBundle:pages/human_resource/input_forms:resign_application.html.twig',
  5977.                 [
  5978.                     'page_title' => 'Resign Application',
  5979.                     'employeeIds' => $applicant,
  5980.                     'resignReasons' => $resignReason,
  5981.                     'HasUpdateMode' => false,
  5982.                 ]
  5983.             );
  5984.         }
  5985.         if ($req->isMethod('POST')) {
  5986.             $approveHash $req->request->get('approvalHash');
  5987.             $loginId $req->getSession()->get(UserConstants::USER_LOGIN_ID);
  5988.             $isSignatureOk DocValidation::isSignatureOk($em$loginId$approveHash);
  5989.             if ($isSignatureOk) {
  5990.                 $response HumanResource::storeResignApplicationData($em$req);
  5991.                 if ($response) {
  5992.                     return $this->redirectToRoute(
  5993.                         'view_resign_application',
  5994.                         array('id' => $response->getResignApplicationId()),
  5995.                         Response::HTTP_MOVED_PERMANENTLY
  5996.                     );
  5997.                 }
  5998.             } else {
  5999.                 $this->addFlash(
  6000.                     'error',
  6001.                     'Invalid Approval Hash!'
  6002.                 );
  6003.                 return $this->redirectToRoute('resign_application');
  6004.             }
  6005.         }
  6006.     }
  6007.     public function viewResignApplicationAction(Request $req$id 0)
  6008.     {
  6009.         $em $this->getDoctrine()->getManager();
  6010.         $response HumanResource::twigDataForResignApplicationView($em$req$id);
  6011.         return $this->render(
  6012.             'ApplicationBundle:pages/human_resource/views:resign_application_view.html.twig',
  6013.             [
  6014.                 'page_title' => 'View Resign Application',
  6015.                 'approval_data' => $response['approval_data'],
  6016.                 'application' => $response['application'],
  6017.                 'applicant' => $response['applicant'],
  6018.                 'document_log' => $response['document_log'],
  6019.                 'approval_status' => $response['approval_status'],
  6020.                 'created_by' => $response['created_by'],
  6021.                 'updated_at' => $response['updated_at'],
  6022.                 'auto_created' => 0,
  6023.             ]
  6024.         );
  6025.     }
  6026.     public function printResignApplicationAction(Request $req$id)
  6027.     {
  6028.         if ($id) {
  6029.             $em $this->getDoctrine()->getManager();
  6030.             $company_data Company::getCompanyData($em1);
  6031.             $authorizations System::getSignatureListForDocumentPrint($emarray_flip(GeneralConstant::$Entity_list)['ResignApplication'], $id);
  6032.             $response HumanResource::twigDataForResignApplicationView($em$req$id);
  6033.             return $this->render(
  6034.                 'ApplicationBundle:pages/human_resource/print:resign_application_print.html.twig',
  6035.                 array(
  6036.                     'page_title' => 'Print Resign Application',
  6037.                     'export' => 'pdf,print',
  6038.                     'company_name' => $company_data->getName(),
  6039.                     'company_data' => $company_data,
  6040.                     'company_address' => $company_data->getAddress(),
  6041.                     'company_image' => $company_data->getImage(),
  6042.                     'application' => $response['application'],
  6043.                     'applicant' => $response['applicant'],
  6044.                     'Authorizations' => $authorizations,
  6045.                     'red' => 0
  6046.                 )
  6047.             );
  6048.         }
  6049.         return new JsonResponse(array(
  6050.             'success' => false,
  6051.             'msg' => 'Wrong URL format! Please try with application ID'
  6052.         ));
  6053.     }
  6054.     public function listResignApplicationAction(Request $req)
  6055.     {
  6056.         $em $this->getDoctrine()->getManager();
  6057.         $response HumanResource::getResignApplicationList($em$req);
  6058.         return $this->render("ApplicationBundle:pages/human_resource/list:resign_application_list.html.twig", array(
  6059.             'page_title' => 'Resign Application List',
  6060.             'applications' => $response,
  6061.         ));
  6062.     }
  6063.     public function viewNocApprovalAction(Request $req$id)
  6064.     {
  6065.         $em $this->getDoctrine()->getManager();
  6066.         $response HumanResource::twigDataForNocView($em$req$id);
  6067.         return $this->render(
  6068.             'ApplicationBundle:pages/human_resource/views:noc_view.html.twig',
  6069.             [
  6070.                 'page_title' => 'View NOC',
  6071.                 'approval_data' => $response['approval_data'],
  6072.                 'noc_application' => $response['noc_application'],
  6073.                 'resign_application' => $response['resign_application'],
  6074.                 'applicant' => $response['applicant'],
  6075.                 'document_log' => $response['document_log'],
  6076.                 'approval_status' => $response['approval_status'],
  6077.                 'created_by' => $response['created_by'],
  6078.                 'updated_at' => $response['updated_at'],
  6079.                 'auto_created' => 0,
  6080.             ]
  6081.         );
  6082.     }
  6083.     public function printNocApprovalAction(Request $req$id)
  6084.     {
  6085.         $em $this->getDoctrine()->getManager();
  6086.         $company_data Company::getCompanyData($em1);
  6087.         $Authorizations System::getSignatureListForDocumentPrint($emarray_flip(GeneralConstant::$Entity_list)['NocApproval'], $id);
  6088.         $response HumanResource::twigDataForNocView($em$req$id);
  6089.         return $this->render(
  6090.             'ApplicationBundle:pages/human_resource/print:noc_print.html.twig',
  6091.             [
  6092.                 'page_title' => 'Print NOC',
  6093.                 'noc_application' => $response['noc_application'],
  6094.                 'resign_application' => $response['resign_application'],
  6095.                 'applicant' => $response['applicant'],
  6096.                 'export' => 'pdf,print',
  6097.                 'company_name' => $company_data->getName(),
  6098.                 'company_data' => $company_data,
  6099.                 'company_address' => $company_data->getAddress(),
  6100.                 'company_image' => $company_data->getImage(),
  6101.                 'Authorizations' => $Authorizations,
  6102.                 'red' => 0
  6103.             ]
  6104.         );
  6105.     }
  6106.     public function createHolidayAction(Request $request$id)
  6107.     {
  6108.         $em $this->getDoctrine()->getManager();
  6109.         $companyId $this->getLoggedUserCompanyId($request);
  6110.         if ($request->isMethod('POST')) {
  6111.             $entity_id array_flip(GeneralConstant::$Entity_list)['HolidayCalendar']; //change
  6112.             $dochash $request->request->get('doc_hash'); //change
  6113.             $loginId $request->getSession()->get(UserConstants::USER_LOGIN_ID);
  6114.             $approveRole $request->request->get('approvalRole');
  6115.             $approveHash $request->request->get('approvalHash');
  6116.             if (!DocValidation::isInsertable(
  6117.                 $em,
  6118.                 $entity_id,
  6119.                 $dochash,
  6120.                 $loginId,
  6121.                 $approveRole,
  6122.                 $approveHash,
  6123.                 $id
  6124.             )
  6125.             ) {
  6126.                 $this->addFlash(
  6127.                     'error',
  6128.                     'Sorry Couldnot insert Data.'
  6129.                 );
  6130.             } else {
  6131.                 $funcname 'HolidayCalendar';
  6132.                 $doc_id $id;
  6133.                 DeleteDocument::$funcname($em$doc_id0);
  6134.                 if ($id != 0)
  6135.                     $HolidayCalender $em->getRepository(HolidayCalendar::class)->find($id);
  6136.                 else
  6137.                     $HolidayCalender = new HolidayCalendar;
  6138.                 $HolidayCalender->setDocumentHash($request->request->get('doc_hash'));
  6139.                 $HolidayCalender->setHoliDayTitle($request->request->get('holidayCalendarTitle'));
  6140.                 $HolidayCalender->setEmployeeIds(json_encode($request->request->get('employee')));
  6141.                 $HolidayCalender->setEmployeeTypeIds(json_encode($request->request->get('emp_status')));
  6142.                 $HolidayCalender->setDesignationIds(json_encode($request->request->get('desg', [])));
  6143.                 $HolidayCalender->setDepartmentIds(json_encode($request->request->get('dept', [])));
  6144.                 $HolidayCalender->setBranchIds(json_encode($request->request->get('branch', [])));
  6145.                 $HolidayCalender->setLevelSelectionStr($request->get('levelSelectionStr'''));
  6146.                 $HolidayCalender->setLevels(json_encode(HumanResource::getLevelsFromLevelSelectionStr($request->get('levelSelectionStr'''))));
  6147.                 $HolidayCalender->setCompanyId($companyId);
  6148.                 $HolidayCalender->setTypeHash('HD');
  6149.                 $HolidayCalender->setEditFlag(1); //editable usually
  6150.                 $HolidayCalender->setPrefixHash($request->request->get('prefix'));
  6151.                 $HolidayCalender->setAssocHash($request->request->get('assoc'));
  6152.                 $HolidayCalender->setNumberHash($request->request->get('number_hash'));
  6153.                 $HolidayCalender->setCreatedLoginId($request->getSession()->get(UserConstants::USER_LOGIN_ID));
  6154.                 $HolidayCalender->setApproved(GeneralConstant::APPROVAL_STATUS_PENDING);
  6155.                 $HolidayCalender->setAutocreated(0);
  6156. //
  6157. //        $arr = [
  6158. //            'date' =>$request->request->get('start_date'),
  6159. //            'title' => $request->request->get('title'),
  6160. //        ];
  6161. //
  6162. //        $HolidayCalender->setData(json_encode($arr));
  6163.                 $em->persist($HolidayCalender);
  6164.                 $em->flush();
  6165.                 $indHolidays = [];
  6166.                 if ($request->request->has('start_date'))
  6167.                     $indHolidays $request->request->get('start_date');
  6168.                 foreach ($indHolidays as $ind => $dateRangeStr) {
  6169.                     $currRow $request->request->get('row')[$ind];//string
  6170.                     $holidayTitle $request->request->get('title')[$ind];//string
  6171.                     $currStartDate $request->request->get('start_date')[$ind];//string
  6172.                     $currEndDate $request->request->get('end_date')[$ind];//string
  6173.                     $HolidayDate = new HolidayCalendarDates();
  6174.                     $HolidayDate->setHolidayCalendarId($HolidayCalender->getHolidayCalendarId());
  6175.                     $HolidayDate->setDateRange($currStartDate '-' $currEndDate);//string
  6176.                     $HolidayDate->setStartDate(new \DateTime($currStartDate));//date
  6177.                     $HolidayDate->setEndDate(new \DateTime($currEndDate ' 23:59:59'));//date
  6178.                     $HolidayDate->setHolidayTitle($holidayTitle);
  6179. //          $HolidayDate->setIsVariableEachYearFlag($request->request->get('is_variable_each_year',null));
  6180.                     $HolidayDate->setIsVariableEachYearFlag($request->request->get('is_variable_each_year_' $currRownull));
  6181.                     $HolidayDate->setAllDayFlag($request->request->get('all_day_flag_' $currRow1));
  6182.                     $em->persist($HolidayDate);
  6183.                     $em->flush();
  6184.                 }
  6185.                 $options = [];
  6186.                 $entity array_flip(GeneralConstant::$Entity_list)['HolidayCalendar'];
  6187.                 $loginId $request->getSession()->get(UserConstants::USER_LOGIN_ID);
  6188.                 $approveRole $request->request->get('approvalRole');
  6189.                 System::setApprovalInfo(
  6190.                     $em,
  6191.                     $options,
  6192.                     $entity,
  6193.                     $HolidayCalender->getHolidayCalendarId(),
  6194.                     $request->getSession()->get(UserConstants::USER_LOGIN_ID)
  6195.                 );
  6196.                 System::createEditSignatureHash(
  6197.                     $em,
  6198.                     $entity,
  6199.                     $HolidayCalender->getHolidayCalendarId(),
  6200.                     $loginId,
  6201.                     $approveRole,
  6202.                     $request->request->get('approvalHash')
  6203.                 );
  6204.                 $url $this->generateUrl(
  6205.                     'view_holiday_calendar'
  6206.                 );
  6207.                 return $this->redirect($url "/" $HolidayCalender->getHolidayCalendarId());
  6208.             }
  6209.         }
  6210.         $em $this->getDoctrine()->getManager();
  6211.         $branches $em->getRepository(Branch::class)->findAll();
  6212.         $employee $em->getRepository(Employee::class)->findAll();
  6213.         $departments $em->getRepository(SysDepartment::class)->findAll();
  6214.         $departmentPositions $em->getRepository(SysDepartmentPosition::class)->findAll();
  6215.         $EmploymentStatus HumanResourceConstant::$employeeType;
  6216.         $em $this->getDoctrine()->getManager();
  6217.         $extDocData = [];
  6218.         if ($id != 0)
  6219.             $extDocData $em->getRepository(HolidayCalendar::class)->find($id);
  6220.         return $this->render(
  6221.             'ApplicationBundle:pages/human_resource/input_forms:create_holiday.html.twig',
  6222.             [
  6223.                 'page_title' => 'Create Holiday',
  6224.                 'branches' => $branches,
  6225.                 'id' => $id,
  6226.                 'extDocData' => $extDocData,
  6227.                 'departments' => $departments,
  6228.                 'departmentPositions' => $departmentPositions,
  6229.                 'employeeStatus' => $EmploymentStatus,
  6230.                 'employeeIds' => $employee,
  6231.                 'holidayCalendarList' => $em->getRepository('ApplicationBundle:HolidayCalendar')
  6232.                     ->findBy(array())
  6233.             ]
  6234.         );
  6235.     }
  6236.     public function HolidayViewAction(Request $request$id)
  6237.     {
  6238.         $em $this->getDoctrine()->getManager();
  6239.         $HolidaysCalendar $em->getRepository(HolidayCalendar::class)->find($id);
  6240.         $holidayCalendarDetails $em->getRepository('ApplicationBundle:HolidayCalendarDates')
  6241.             ->findBy(array(
  6242.                 'holidayCalendarId' => $id
  6243.             ));
  6244.         $Approval_data System::checkIfApprovalExists(
  6245.             $em,
  6246.             array_flip(GeneralConstant::$Entity_list)['HolidayCalendar'],
  6247.             $id,
  6248.             $request->getSession()->get(UserConstants::USER_LOGIN_ID)
  6249.         );
  6250.         return $this->render('ApplicationBundle:pages/human_resource/views:holidays_view.html.twig', array(
  6251.             'page_title' => 'View Holiday',
  6252.             'holidays' => $HolidaysCalendar,
  6253.             'holidayCalendarDetails' => $holidayCalendarDetails,
  6254.             'approval_status' => $HolidaysCalendar->getApproved(),
  6255.             'approval_data' => $Approval_data,
  6256.             'auto_created' => $HolidaysCalendar->getAutocreated(),
  6257.             'document_log' => $HolidaysCalendar->getAutocreated() == System::getDocumentLog(
  6258.                 $this->getDoctrine()->getManager(),
  6259.                 array_flip(GeneralConstant::$Entity_list)['HolidayCalendar'],
  6260.                 $id,
  6261.                 $HolidaysCalendar->getCreatedLoginId(),
  6262.                 $HolidaysCalendar->getEditedLoginId()
  6263.             ) : []
  6264.         ));
  6265.     }
  6266.     public function GetHolidayDetailsAction(Request $request$id)
  6267.     {
  6268.         $em $this->getDoctrine()->getManager();
  6269.         $holidayCalendar $em->getRepository('ApplicationBundle:HolidayCalendar')
  6270.             ->findOneBy(array(
  6271.                 'holidayCalendarId' => $id
  6272.             ));
  6273.         $holidayCalendarDetails $em->getRepository('ApplicationBundle:HolidayCalendarDates')
  6274.             ->findBy(array(
  6275.                 'holidayCalendarId' => $id
  6276.             ));
  6277.         $holidayList = [];
  6278.         foreach ($holidayCalendarDetails as $det) {
  6279.             $dateDet = array(
  6280.                 'title' => $det->getHolidayTitle(),
  6281.                 'startDate' => $det->getStartDate()->format('Y-m-d'),
  6282.                 'endDate' => $det->getEndDate()->format('Y-m-d'),
  6283.             );
  6284.             $holidayList[] = $dateDet;
  6285.         }
  6286.         return new JsonResponse(
  6287.             array(
  6288.                 'success' => true,
  6289.                 'holidayList' => $holidayList
  6290.             )
  6291.         );
  6292.     }
  6293.     public function GetHolidayListByEmployeeIdAction(Request $request$id)
  6294.     {
  6295.         $em $this->getDoctrine()->getManager();
  6296.         $options = [];
  6297.         $options['employeeId'] = $id;
  6298.         HumanResource::getFilteredHolidaysSingle($em$options);
  6299.         $holidayCalendar $em->getRepository('ApplicationBundle:HolidayCalendar')
  6300.             ->findOneBy(array(
  6301.                 'holidayCalendarId' => $id
  6302.             ));
  6303.         $holidayCalendarDetails $em->getRepository('ApplicationBundle:HolidayCalendarDates')
  6304.             ->findBy(array(
  6305.                 'holidayCalendarId' => $id
  6306.             ));
  6307.         $holidayList = [];
  6308.         foreach ($holidayCalendarDetails as $det) {
  6309.             $dateDet = array(
  6310.                 'title' => $det->getHolidayTitle(),
  6311.                 'startDate' => $det->getStartDate()->format('Y-m-d'),
  6312.                 'endDate' => $det->getEndDate()->format('Y-m-d'),
  6313.             );
  6314.             $holidayList[] = $dateDet;
  6315.         }
  6316.         return new JsonResponse(
  6317.             array(
  6318.                 'success' => true,
  6319.                 'holidayList' => $holidayList
  6320.             )
  6321.         );
  6322.     }
  6323.     public function createQuestionAction(Request $request)
  6324.     {
  6325.         $em $this->getDoctrine()->getManager();
  6326.         $em_goc $this->getDoctrine()->getManager('company_group');
  6327.         $companyId $this->getLoggedUserCompanyId($request);
  6328.         if ($request->isMethod('POST')) {
  6329.             $loginId $request->getSession()->get(UserConstants::USER_LOGIN_ID);
  6330.             $question = new Questionnaire();
  6331.             $question->setQuestionTitle($request->request->get('questionTitle'''));
  6332.             $question->setQuestionText($request->request->get('questionText'''));
  6333.             $question->setIsForPlanningItem($request->request->has('forPlanningItem') ? 0);
  6334.             $question->setIsForInterview($request->request->has('forInterview') ? 0);
  6335.             $question->setIsForMock($request->request->has('forMock') ? 0);
  6336.             $question->setIsForTraining($request->request->has('forTraining') ? 0);
  6337.             $question->setTaggedSkillHashes($request->request->get('skillHash'));
  6338.             $question->setCorrectAnswers(json_encode($request->request->get('correctAns')));
  6339.             $question->setCompanyId($companyId);
  6340.             $optionData = [];
  6341.             foreach ($request->request->get('optionText') as $key => $val) {
  6342.                 $option = array(
  6343.                     'index' => $request->request->get('optionIndex')[$key],
  6344.                     'text' => $val,
  6345.                 );
  6346.                 $optionData[] = $option;
  6347.             }
  6348.             $question->setOptions(json_encode($optionData));
  6349.             $question->setQuestionValueWeight(1);
  6350.             $question->setQuestionText($request->request->get('questionText'));
  6351.             $question->setUniqueHash('_NONE_');
  6352.             $question->setType($request->request->get('type'0));
  6353.             //$skill->setEditFlag(1); //editable usually
  6354.             $question->setCreatedLoginId($request->getSession()->get(UserConstants::USER_LOGIN_ID));
  6355.             //$skill->setApproved(GeneralConstant::APPROVAL_STATUS_PENDING);
  6356.             //$skill->setAutocreated(0);
  6357.             $em->persist($question);
  6358.             $em->flush();
  6359.             $questionId $question->getQuestionId();
  6360.             $file_path_list = [];
  6361.             if ($questionId != 0)
  6362.                 if (!empty($request->files)) {
  6363.                     MiscActions::RemoveFilesForEntityDoc($em_goc'Question'$questionId);
  6364.                     $storePath 'uploads/Questionnaire/';
  6365.                     $path "";
  6366.                     $file_path "";
  6367.                     $session $request->getSession();
  6368. //                    MiscActions::RemoveExpiredFiles($em_goc);
  6369.                     foreach ($request->files as $uploadedFileGG) {
  6370.                         //            if($uploadedFile->getImage())
  6371.                         //                var_dump($uploadedFile->getFile());
  6372.                         //                var_dump($uploadedFile);
  6373.                         $tempD $uploadedFileGG;
  6374.                         if (!is_array($uploadedFileGG)) {
  6375.                             $uploadedFileGG = array();
  6376.                             $uploadedFileGG[] = $tempD;
  6377.                         }
  6378.                         foreach ($uploadedFileGG as $uploadedFile) {
  6379.                             if ($uploadedFile != null) {
  6380.                                 $extension $uploadedFile->guessExtension();
  6381.                                 $size $uploadedFile->getSize();
  6382.                                 $fileName 'QUES_' $questionId '_' . (md5(uniqid())) . '.' $uploadedFile->guessExtension();
  6383.                                 $path $fileName;
  6384.                                 $upl_dir $this->container->getParameter('kernel.root_dir') . '/../web/' $storePath;
  6385.                                 if (!file_exists($upl_dir)) {
  6386.                                     mkdir($upl_dir0777true);
  6387.                                 }
  6388.                                 if (file_exists($upl_dir '' $path)) {
  6389.                                     chmod($upl_dir '' $path0755);
  6390.                                     unlink($upl_dir '' $path);
  6391.                                 }
  6392.                                 $file $uploadedFile->move($upl_dir$path);
  6393.                                 $expireNever 1;
  6394.                                 $expireTs 0;
  6395.                                 $EntityFile = new EntityFile();
  6396.                                 $EntityFile->setPath($this->container->getParameter('kernel.root_dir') . '/../web/' $storePath $path);
  6397.                                 $EntityFile->setMarker('_GEN_');
  6398.                                 $EntityFile->setExtension($extension);
  6399.                                 $EntityFile->setExpireTs($expireTs);
  6400.                                 $EntityFile->setSize($size);
  6401.                                 $EntityFile->setRelativePath($storePath $path);
  6402.                                 $EntityFile->setEntityName('Questionnaire');
  6403.                                 $EntityFile->setEntityBundle('ApplicationBundle');
  6404.                                 $EntityFile->setEntityId($questionId);
  6405.                                 $EntityFile->setEntityIdField('questionId');
  6406.                                 $EntityFile->setModifyFieldSetter('setFiles');
  6407.                                 $EntityFile->setDocIdForApplicant(0);
  6408.                                 $EntityFile->setUserId($session->get(UserConstants::USER_ID0));
  6409.                                 $EntityFile->setAppId($session->get(UserConstants::USER_APP_ID0));
  6410.                                 $EntityFile->setEmployeeId($session->get(UserConstants::USER_EMPLOYEE_ID0));
  6411.                                 $EntityFile->setUserType($session->get(UserConstants::USER_TYPE0));
  6412.                                 $em_goc->persist($EntityFile);
  6413.                                 $em_goc->flush();
  6414.                                 $EntityFileId $EntityFile->getId();
  6415.                             }
  6416.                             if ($path != "")
  6417.                                 $file_path_list[] = ($storePath $path);
  6418.                         }
  6419.                     }
  6420.                     $g_path $this->container->getParameter('kernel.root_dir') . '/../web/' $storePath $path;
  6421.                     $question->setFiles(implode(','$file_path_list));
  6422.                     $em->flush();
  6423.                 }
  6424.             if ($request->request->has('returnJson') || $request->query->has('returnJson')) {
  6425.                 if ($question)
  6426.                     return new JsonResponse(
  6427.                         array(
  6428.                             'id' => $questionId,
  6429.                             'value' => $questionId,
  6430.                             'question_id' => $questionId,
  6431.                             'text' => $question->getQuestionText(),
  6432.                             'question_text' => $question->getQuestionText(),
  6433.                             'question_title' => $question->getQuestionTitle(),
  6434.                             'files' => explode(','$question->getFiles()),
  6435.                             'options' => json_decode($question->getFiles(), true),
  6436.                             'answer_text' => '',
  6437.                             'success' => true
  6438.                         )
  6439.                     );
  6440.                 else
  6441.                     return new JsonResponse(
  6442.                         array(
  6443.                             'success' => false
  6444.                         )
  6445.                     );
  6446.             }
  6447.         }
  6448.         $skillDetails $em->getRepository(Skill::class)->findAll();
  6449.         $skillListObj = [];
  6450.         $skillListArray = [];
  6451.         foreach ($skillDetails as $skillDetail) {
  6452.             $dt = array(
  6453.                 'id' => $skillDetail->getSkillId(),
  6454.                 'name' => $skillDetail->getName(),
  6455.                 'hash' => $skillDetail->getUniqueHash(),
  6456.             );
  6457.             $skillListArray[] = $dt;
  6458.         }
  6459.         return $this->render('ApplicationBundle:pages/human_resource/input_forms:createQuestion.html.twig', array(
  6460.             'page_title' => 'Create Question',
  6461.             'skiillDetails' => $skillDetails,
  6462.             'skillListArray' => $skillListArray,
  6463.         ));
  6464.     }
  6465.     public function createSkillAction(Request $request)
  6466.     {
  6467.         $em $this->getDoctrine()->getManager();
  6468.         $companyId $this->getLoggedUserCompanyId($request);
  6469.         if ($request->isMethod('POST')) {
  6470.             $loginId $request->getSession()->get(UserConstants::USER_LOGIN_ID);
  6471.             $skill = new Skill;
  6472.             $skill->setName($request->request->get('skillName'));
  6473.             $skill->setParentId($request->request->get('parentName'));
  6474.             $skill->setUniqueHash($request->request->get('uniqueHash'));
  6475.             $skill->setCompanyId($companyId);
  6476.             //$skill->setEditFlag(1); //editable usually
  6477.             $skill->setCreatedLoginId($request->getSession()->get(UserConstants::USER_LOGIN_ID));
  6478.             //$skill->setApproved(GeneralConstant::APPROVAL_STATUS_PENDING);
  6479.             //$skill->setAutocreated(0);
  6480.             $em->persist($skill);
  6481.             $em->flush();
  6482.         }
  6483.         $skillDetails $em->getRepository(Skill::class)->findAll();
  6484.         return $this->render('ApplicationBundle:pages/human_resource/input_forms:createSkill.html.twig', array(
  6485.             'page_title' => 'Create Skill',
  6486.             'skiillDetails' => $skillDetails,
  6487.         ));
  6488.     }
  6489.     public function createEducationQualificationAction(Request $request)
  6490.     {
  6491.         $em $this->getDoctrine()->getManager();
  6492.         $companyId $this->getLoggedUserCompanyId($request);
  6493.         if ($request->isMethod('POST')) {
  6494.             $loginId $request->getSession()->get(UserConstants::USER_LOGIN_ID);
  6495.             $new = new EducationQualification;
  6496.             $new->setName($request->request->get('educationName'));
  6497.             $new->setParentId($request->request->get('parentName'));
  6498.             $new->setUniqueHash($request->request->get('uniqueHash'));
  6499.             $new->setCompanyId($companyId);
  6500.             //$skill->setEditFlag(1); //editable usually
  6501.             $new->setCreatedLoginId($request->getSession()->get(UserConstants::USER_LOGIN_ID));
  6502.             //$skill->setApproved(GeneralConstant::APPROVAL_STATUS_PENDING);
  6503.             //$skill->setAutocreated(0);
  6504.             $em->persist($new);
  6505.             $em->flush();
  6506.         }
  6507.         $educationDetails $em->getRepository(EducationQualification::class)->findAll();
  6508.         return $this->render('ApplicationBundle:pages/human_resource/input_forms:create_education.html.twig', array(
  6509.             'page_title' => 'Create Education',
  6510.             'educationDetails' => $educationDetails,
  6511.         ));
  6512.     }
  6513.     public function createEvaluationCategoryAction(Request $request$id 0)
  6514.     {
  6515.         $em $this->getDoctrine()->getManager();
  6516.         $companyId $this->getLoggedUserCompanyId($request);
  6517.         if ($request->isMethod('POST')) {
  6518.             $loginId $request->getSession()->get(UserConstants::USER_LOGIN_ID);
  6519.             $new = new EvaluationCategory;
  6520.             $new->setName($request->request->get('name'));
  6521.             $new->setBranch($request->request->get('branch'));
  6522.             $new->setSelectionType($request->request->get('selection_type'));
  6523.             $new->setEmployeeIds($request->request->get('selected_employeeIds'));
  6524.             $new->setEmployeeTypeIds($request->request->get('employee_types'));
  6525.             $new->setDesignationIds($request->request->get('designation'));
  6526.             $new->setDesignationIds($request->request->get('designation'));
  6527.             $new->setmark($request->request->get('mark'));
  6528.             $new->setSkills(json_encode($request->request->get('skill')));
  6529.             $new->setLevelSelectionStr($request->request->get('levelSelectionStr'));
  6530.             $new->setCompanyId($companyId);
  6531.             $new->setCreatedLoginId($request->getSession()->get(UserConstants::USER_LOGIN_ID));
  6532.             $em->persist($new);
  6533.             $em->flush();
  6534.         }
  6535.         $skill $em->getRepository(Skill::class)->findAll();
  6536.         $employeeIds $em->getRepository(EmployeeDetails::class)->findAll();
  6537.         $employeeType HumanResourceConstant::$employeeType;
  6538.         $Designation $em->getRepository(SysDepartmentPosition::class)->findAll();
  6539.         $branch $em->getRepository(Branch::class)->findAll();
  6540.         $departments $em->getRepository(SysDepartment::class)->findAll();
  6541.         $department = [];
  6542.         foreach ($departments as $entry) {
  6543.             $department[$entry->getDepartmentId()] = array(
  6544.                 'id' => $entry->getDepartmentId(),
  6545.                 'name' => $entry->getDepartmentName(),
  6546.             );
  6547.             return $this->render('ApplicationBundle:pages/human_resource/input_forms:create_evaluation_category.html.twig', array(
  6548.                 'page_title' => 'Create Evaluation Category',
  6549.                 'employeeIds' => $employeeIds,
  6550.                 'employeeType' => $employeeType,
  6551.                 'Designation' => $Designation,
  6552.                 'branch' => $branch,
  6553.                 'department' => $department,
  6554.                 'skill' => $skill,
  6555.             ));
  6556.         }
  6557.     }
  6558.     public function createWorkplaceHarassmentAction(Request $request$id 0)
  6559.     {
  6560.         $em $this->getDoctrine()->getManager();
  6561.         $employeeIds $em->getRepository(EmployeeDetails::class)->findAll();
  6562.         //$employeeType = HumanResourceConstant::$employeeType;
  6563.         $Designation $em->getRepository(SysDepartmentPosition::class)->findAll();
  6564.         $branches $em->getRepository(Branch::class)->findAll();
  6565.         $departments $em->getRepository(SysDepartment::class)->findAll();
  6566.         $harassmentType HumanResourceConstant::$harrasmentType;
  6567.         $department = [];
  6568.         foreach ($departments as $entry) {
  6569.             $department[$entry->getDepartmentId()] = array(
  6570.                 'id' => $entry->getDepartmentId(),
  6571.                 'name' => $entry->getDepartmentName(),
  6572.             );
  6573.         }
  6574.         return $this->render('ApplicationBundle:pages/human_resource/input_forms:create_workplace_harrasment.html.twig', array(
  6575.             'page_title' => 'Create Workplace Harrasment',
  6576.             'employeeIds' => $employeeIds,
  6577.             'branches' => $branches,
  6578.             'harassmentType' => $harassmentType,
  6579.             'departments' => $department,
  6580.             'designationIds' => $Designation
  6581.         ));
  6582.     }
  6583.     public function ViewHarasssmentComplainAction()
  6584.     {
  6585.         return $this->render('ApplicationBundle:pages/human_resource/views:view_harassment_compalin.html.twig', array(
  6586.             'page_title' => 'View Harassment Complain',
  6587.         ));
  6588.     }
  6589.     public function createWorkplaceViolenceAction(Request $request$id 0)
  6590.     {
  6591.         $em $this->getDoctrine()->getManager();
  6592.         $employeeIds $em->getRepository(EmployeeDetails::class)->findAll();
  6593.         //$employeeType = HumanResourceConstant::$employeeType;
  6594.         $Designation $em->getRepository(SysDepartmentPosition::class)->findAll();
  6595.         $branches $em->getRepository(Branch::class)->findAll();
  6596.         $departments $em->getRepository(SysDepartment::class)->findAll();
  6597.         $harassmentType HumanResourceConstant::$harrasmentType;
  6598.         $department = [];
  6599.         foreach ($departments as $entry) {
  6600.             $department[$entry->getDepartmentId()] = array(
  6601.                 'id' => $entry->getDepartmentId(),
  6602.                 'name' => $entry->getDepartmentName(),
  6603.             );
  6604.         }
  6605.         return $this->render('ApplicationBundle:pages/human_resource/input_forms:register_workplace_complaint.html.twig', array(
  6606.             'page_title' => 'Register Complaint',
  6607.             'employeeIds' => $employeeIds,
  6608.             'branches' => $branches,
  6609.             'harassmentType' => $harassmentType,
  6610.             'departments' => $department,
  6611.             'designationIds' => $Designation
  6612.         ));
  6613.     }
  6614.     public function createBonusPolicyAction(Request $request$id 0)
  6615.     {
  6616.         $em $this->getDoctrine()->getManager();
  6617.         $companyId $this->getLoggedUserCompanyId($request);
  6618.         $extDocData = [];
  6619.         $extDetailsData = [];
  6620.         if ($request->isMethod('POST')) {
  6621.             //            Generic::debugMessage($_POST);
  6622.             $em $this->getDoctrine()->getManager();
  6623.             $entity_id array_flip(GeneralConstant::$Entity_list)['BonusPolicy']; //change
  6624.             $dochash $request->request->get('docHash'); //change
  6625.             $loginId $request->getSession()->get(UserConstants::USER_LOGIN_ID);
  6626.             $approveRole $request->request->get('approvalRole');
  6627.             $approveHash $request->request->get('approvalHash');
  6628.             if (!DocValidation::isInsertable(
  6629.                 $em,
  6630.                 $entity_id,
  6631.                 $dochash,
  6632.                 $loginId,
  6633.                 $approveRole,
  6634.                 $approveHash,
  6635.                 $id
  6636.             )
  6637.             ) {
  6638.                 $this->addFlash(
  6639.                     'error',
  6640.                     'Sorry Couldnot insert Data.'
  6641.                 );
  6642.             } else {
  6643.                 $funcname 'BonusPolicy';
  6644.                 DeleteDocument::$funcname($em$id0);
  6645.                 $loginId $request->getSession()->get(UserConstants::USER_LOGIN_ID);
  6646.                 $docId HumanResource::createBonusPolicy($em$request$companyId$loginId0);
  6647.                 //now add Approval info
  6648.                 $approveRole $request->request->get('approvalRole');
  6649.                 $options = array(
  6650.                     'notification_enabled' => $this->container->getParameter('notification_enabled'),
  6651.                     'notification_server' => $this->container->getParameter('notification_server'),
  6652.                     'appId' => $request->getSession()->get(UserConstants::USER_APP_ID),
  6653.                     'url' => $this->generateUrl(
  6654.                         GeneralConstant::$Entity_list_details[array_flip(GeneralConstant::$Entity_list)['BonusPolicy']]['entity_view_route_path_name']
  6655.                     )
  6656.                 );
  6657.                 System::setApprovalInfo(
  6658.                     $this->getDoctrine()->getManager(),
  6659.                     $options,
  6660.                     array_flip(GeneralConstant::$Entity_list)['BonusPolicy'],
  6661.                     $docId,
  6662.                     $request->getSession()->get(UserConstants::USER_LOGIN_ID)
  6663.                 );
  6664.                 System::createEditSignatureHash(
  6665.                     $this->getDoctrine()->getManager(),
  6666.                     array_flip(GeneralConstant::$Entity_list)['BonusPolicy'],
  6667.                     $docId,
  6668.                     $loginId,
  6669.                     $approveRole,
  6670.                     $request->request->get('approvalHash')
  6671.                 );
  6672.                 $doc_here $this->getDoctrine()
  6673.                     ->getRepository('ApplicationBundle:BonusPolicy')
  6674.                     ->findOneBy(
  6675.                         array(
  6676.                             'id' => $docId
  6677.                         )
  6678.                     );
  6679.                 //notify
  6680.                 $this->addFlash(
  6681.                     'success',
  6682.                     'Policy Successfully Updated.'
  6683.                 );
  6684.                 $url $this->generateUrl(
  6685.                     'view_bonus_policy'
  6686.                 );
  6687. //                System::AddNewNotification(
  6688. //                    $this->container->getParameter('notification_enabled'),
  6689. //                    $this->container->getParameter('notification_server'),
  6690. //                    $request->getSession()->get(UserConstants::USER_APP_ID),
  6691. //                    $request->getSession()->get(UserConstants::USER_COMPANY_ID),
  6692. //                    "Salary Segregation Policy : " . $doc_here->getDocumentHash() . " Has Been Created And is Under Processing",
  6693. //                    'pos',
  6694. //                    System::getPositionIdsByDepartment($em, GeneralConstant::HRM_DEPARTMENT),
  6695. //                    'success',
  6696. //                    //                    $url . "/" . $TransID,
  6697. //                    $url . "/" . $docId,
  6698. //                    "Journal"
  6699. //
  6700. //                );
  6701.                 return $this->redirect($url "/" $docId);
  6702.             }
  6703.         }
  6704.         //for edits
  6705.         if ($id == 0) {
  6706.         } else {
  6707.             $extDocData $em->getRepository('ApplicationBundle:BonusPolicy')->findOneBy(
  6708.                 array(
  6709.                     'id' => $id///material
  6710.                 )
  6711.             );
  6712.             //now if its not editable, redirect to view
  6713.             if ($extDocData) {
  6714.                 if ($extDocData->getEditFlag() != 1) {
  6715. //          $url = $this->generateUrl(
  6716. ////              'view_salary_segregation_policy'
  6717. //              'salary_segregation_policy'
  6718. //          );
  6719. //          return $this->redirect($url . "/" . $id);
  6720.                 } else {
  6721. //          $extVoucherDetailsData = Accounts::GetVoucherDataForEdit($em, $voucherId);
  6722. //          $extDetailsData = $em->getRepository('ApplicationBundle:SalarySegregationPolicy')->findOneBy(
  6723. //              array(
  6724. //                  'transactionId' => $id, ///material
  6725. //
  6726. //              )
  6727. //          );
  6728.                 }
  6729.             } else {
  6730.             }
  6731.         }
  6732.         $employeeIds $em->getRepository(EmployeeDetails::class)->findAll();
  6733.         $employeeType HumanResourceConstant::$employeeType;
  6734.         $Designation $em->getRepository(SysDepartmentPosition::class)->findAll();
  6735.         $branch $em->getRepository(Branch::class)->findAll();
  6736.         $departments $em->getRepository(SysDepartment::class)->findAll();
  6737.         $department = [];
  6738.         foreach ($departments as $entry) {
  6739.             $department[$entry->getDepartmentId()] = array(
  6740.                 'id' => $entry->getDepartmentId(),
  6741.                 'name' => $entry->getDepartmentName(),
  6742.             );
  6743.         }
  6744.         return $this->render('ApplicationBundle:pages/human_resource/input_forms:create_bonus_policy.html.twig', array(
  6745.             'page_title' => 'Create Bonus Policy',
  6746.             'employeeIds' => $employeeIds,
  6747.             'employeeType' => $employeeType,
  6748.             'Designation' => $Designation,
  6749.             'branch' => $branch,
  6750.             'department' => $department,
  6751.         ));
  6752.     }
  6753.     public function BonusPolicyListAction()
  6754.     {
  6755.         $em $this->getDoctrine()->getManager();
  6756.         $bonusPolicy $em->getRepository(BonusPolicy::class)->findAll();
  6757.         return $this->render('ApplicationBundle:pages/human_resource/list:bonus_policy_list.html.twig', array(
  6758.             'page_title' => 'Increment Policy List',
  6759.             'bonusPolicy' => $bonusPolicy
  6760.         ));
  6761.     }
  6762.     public function createIncrementPolicyAction(Request $request$id 0)
  6763.     {
  6764.         $em $this->getDoctrine()->getManager();
  6765.         $companyId $this->getLoggedUserCompanyId($request);
  6766.         $extDocData = [];
  6767.         $extDetailsData = [];
  6768.         if ($request->isMethod('POST')) {
  6769.             //            Generic::debugMessage($_POST);
  6770.             $em $this->getDoctrine()->getManager();
  6771.             $entity_id array_flip(GeneralConstant::$Entity_list)['IncrementPolicy']; //change
  6772.             $dochash $request->request->get('docHash'); //change
  6773.             $loginId $request->getSession()->get(UserConstants::USER_LOGIN_ID);
  6774.             $approveRole $request->request->get('approvalRole');
  6775.             $approveHash $request->request->get('approvalHash');
  6776.             if (!DocValidation::isInsertable(
  6777.                 $em,
  6778.                 $entity_id,
  6779.                 $dochash,
  6780.                 $loginId,
  6781.                 $approveRole,
  6782.                 $approveHash,
  6783.                 $id
  6784.             )
  6785.             ) {
  6786.                 $this->addFlash(
  6787.                     'error',
  6788.                     'Sorry Couldnot insert Data.'
  6789.                 );
  6790.             } else {
  6791.                 $funcname 'IncrementPolicy';
  6792.                 DeleteDocument::$funcname($em$id0);
  6793.                 $docId HumanResource::createIncrementPolicy($em$request$companyId0);
  6794.                 //now add Approval info
  6795.                 $loginId $request->getSession()->get(UserConstants::USER_LOGIN_ID);
  6796.                 $approveRole $request->request->get('approvalRole');
  6797.                 $options = array(
  6798.                     'notification_enabled' => $this->container->getParameter('notification_enabled'),
  6799.                     'notification_server' => $this->container->getParameter('notification_server'),
  6800.                     'appId' => $request->getSession()->get(UserConstants::USER_APP_ID),
  6801.                     'url' => $this->generateUrl(
  6802.                         GeneralConstant::$Entity_list_details[array_flip(GeneralConstant::$Entity_list)['IncrementPolicy']]
  6803.                         ['entity_view_route_path_name']
  6804.                     )
  6805.                 );
  6806.                 System::setApprovalInfo(
  6807.                     $this->getDoctrine()->getManager(),
  6808.                     $options,
  6809.                     array_flip(GeneralConstant::$Entity_list)['IncrementPolicy'],
  6810.                     $docId,
  6811.                     $request->getSession()->get(UserConstants::USER_LOGIN_ID),
  6812.                     3    //journal voucher
  6813.                 );
  6814.                 System::createEditSignatureHash(
  6815.                     $this->getDoctrine()->getManager(),
  6816.                     array_flip(GeneralConstant::$Entity_list)['IncrementPolicy'],
  6817.                     $docId,
  6818.                     $loginId,
  6819.                     $approveRole,
  6820.                     $request->request->get('approvalHash')
  6821.                 );
  6822.                 $doc_here $this->getDoctrine()
  6823.                     ->getRepository('ApplicationBundle:IncrementPolicy')
  6824.                     ->findOneBy(
  6825.                         array(
  6826.                             'id' => $docId
  6827.                         )
  6828.                     );
  6829.                 //notify
  6830.                 $this->addFlash(
  6831.                     'success',
  6832.                     'Policy Successfully Updated.'
  6833.                 );
  6834.                 $url $this->generateUrl(
  6835.                     'view_increment_policy'
  6836.                 );
  6837.                 return $this->redirect($url "/" $docId);
  6838.             }
  6839.         }
  6840.         //for edits
  6841.         if ($id == 0) {
  6842.         } else {
  6843.             $extDocData $em->getRepository('ApplicationBundle:IncrementPolicy')->findOneBy(
  6844.                 array(
  6845.                     'id' => $id///material
  6846.                 )
  6847.             );
  6848.             //now if its not editable, redirect to view
  6849.             if ($extDocData) {
  6850.                 if ($extDocData->getEditFlag() != 1) {
  6851. //          $url = $this->generateUrl(
  6852. ////              'view_salary_segregation_policy'
  6853. //              'salary_segregation_policy'
  6854. //          );
  6855. //          return $this->redirect($url . "/" . $id);
  6856.                 } else {
  6857. //          $extVoucherDetailsData = Accounts::GetVoucherDataForEdit($em, $voucherId);
  6858. //          $extDetailsData = $em->getRepository('ApplicationBundle:SalarySegregationPolicy')->findOneBy(
  6859. //              array(
  6860. //                  'transactionId' => $id, ///material
  6861. //
  6862. //              )
  6863. //          );
  6864.                 }
  6865.             } else {
  6866.             }
  6867.         }
  6868.         //$em = $this->getDoctrine()->getManager();
  6869.         $employeeIds $em->getRepository(EmployeeDetails::class)->findAll();
  6870.         $employeeType HumanResourceConstant::$employeeType;
  6871.         $Designation $em->getRepository(SysDepartmentPosition::class)->findAll();
  6872.         $branch $em->getRepository(Branch::class)->findAll();
  6873.         $departments $em->getRepository(SysDepartment::class)->findAll();
  6874.         $department = [];
  6875.         foreach ($departments as $entry) {
  6876.             $department[$entry->getDepartmentId()] = array(
  6877.                 'id' => $entry->getDepartmentId(),
  6878.                 'name' => $entry->getDepartmentName(),
  6879.             );
  6880.         }
  6881.         return $this->render('ApplicationBundle:pages/human_resource/input_forms:create_increment_policy.html.twig', array(
  6882.             'page_title' => 'Create Increment Policy',
  6883.             'employeeIds' => $employeeIds,
  6884.             'employeeType' => $employeeType,
  6885.             'Designation' => $Designation,
  6886.             'branch' => $branch,
  6887.             'department' => $department,
  6888.         ));
  6889.     }
  6890.     public function IncrementPolicyListAction()
  6891.     {
  6892.         $em $this->getDoctrine()->getManager();
  6893.         $incrementPolicy $em->getRepository(IncrementPolicy::class)->findAll();
  6894.         return $this->render('ApplicationBundle:pages/human_resource/list:increment_policy_list.html.twig', array(
  6895.             'page_title' => 'Increment Policy List',
  6896.             'incrementPolicy' => $incrementPolicy
  6897.         ));
  6898.     }
  6899.     public function ViewIncrementPolicyAction(Request $request$id)
  6900.     {
  6901.         $em $this->getDoctrine()->getManager();
  6902.         $incrementPolicy $em->getRepository(IncrementPolicy::class)->find($id);
  6903.         $Approval_data System::checkIfApprovalExists(
  6904.             $em,
  6905.             array_flip(GeneralConstant::$Entity_list)['IncrementPolicy'],
  6906.             $id,
  6907.             $request->getSession()->get(UserConstants::USER_LOGIN_ID)
  6908.         );
  6909.         return $this->render('ApplicationBundle:pages/human_resource/views:view_increment_policy.html.twig', array(
  6910.             'page_title' => 'Increment Policy List',
  6911.             'incrementPolicy' => $incrementPolicy,
  6912.             'approval_status' => $incrementPolicy->getApproved(),
  6913.             'approval_data' => $Approval_data,
  6914.             'auto_created' => $incrementPolicy->getAutocreated(),
  6915.             'id' => $id,
  6916.             'document_log' => $incrementPolicy->getAutocreated() == System::getDocumentLog(
  6917.                 $this->getDoctrine()->getManager(),
  6918.                 array_flip(GeneralConstant::$Entity_list)['FundRequisition'],
  6919.                 $id,
  6920.                 $incrementPolicy->getCreatedLoginId(),
  6921.                 $incrementPolicy->getEditedLoginId()
  6922.             ) : []
  6923.         ));
  6924.     }
  6925.     public function createConsultancyTopicAction(Request $request$id 0)
  6926.     {
  6927.         $em $this->getDoctrine()->getManager();
  6928.         $companyId $this->getLoggedUserCompanyId($request);
  6929.         if ($request->isMethod('POST')) {
  6930.             $loginId $request->getSession()->get(UserConstants::USER_LOGIN_ID);
  6931.             $new = new ConsultancyTopic();
  6932.             $new->setTopicName($request->request->get('topicName'));
  6933.             $new->setParentTopicName($request->request->get('parentTopicName'));
  6934.             $new->setUniqueHash($request->request->get('uniqueHash'));
  6935.             $new->setCompanyId($companyId);
  6936.             $new->setTopicSlug($request->request->get('topicSlug'));
  6937.             $new->setTitle($request->request->get('title'));
  6938.             $new->setSubTitle($request->request->get('subTitle'));
  6939.             $new->setSummary($request->request->get('content'));
  6940.             $new->setVideo($request->request->get('video'));
  6941.             $new->setAuthor($request->request->get('author'));
  6942.             $new->setAuthorSummary($request->request->get('authorSummary'));
  6943.             $new->setCreatedLoginId($request->getSession()->get(UserConstants::USER_LOGIN_ID));
  6944. //            $arr = [
  6945. //                'requirement' => $request->request->get('requirement'),
  6946. //
  6947. //            ];
  6948. //            $new->setRequirementData(json_encode($arr));
  6949.             $em->persist($new);
  6950.             $em->flush();
  6951.         }
  6952. //            $data = [];
  6953. //            $em = $this->getDoctrine()->getManager();
  6954. //            $companyId = $this->getLoggedUserCompanyId($request);
  6955. //            if ($request->isMethod('POST')) {
  6956. //                $em = $this->getDoctrine()->getManager();
  6957. //                $entity_id = array_flip(GeneralConstant::$Entity_list)['ConsultancyTopic'];
  6958. //                //$dochash = $request->request->get('docHash');//change
  6959. //                $approveRole = $request->request->get('approvalRole');
  6960. //                $approveHash = $request->request->get('approvalHash');
  6961. //                $loginId = $request->getSession()->get(UserConstants::USER_LOGIN_ID);
  6962. //                if (!DocValidation::isInsertable($em, $entity_id,
  6963. //                    $loginId, $approveRole, $approveHash, $id)
  6964. //                ) {
  6965. //                    $this->addFlash(
  6966. //                        'error',
  6967. //                        'Sorry Could not insert Data.'
  6968. //                    );
  6969. //                }  else {
  6970. //                    $data = $request->request;
  6971. //                    $docId = HumanResource::createConsultancyTopic($em, $loginId, $id, $data, $companyId);
  6972. ////                    now add Approval info
  6973. //
  6974. //                    $approveRole = $request->request->get('approvalRole');
  6975. //                    $options = array(
  6976. //                        'notification_enabled' => $this->container->getParameter('notification_enabled'),
  6977. //                        'notification_server' => $this->container->getParameter('notification_server'),
  6978. //                        'appId' => $request->getSession()->get(UserConstants::USER_APP_ID),
  6979. ////                        'url' => $this->generateUrl(
  6980. ////                            GeneralConstant::$Entity_list_details[array_flip(GeneralConstant::$Entity_list)['EmployeePerformanceEvolution']]
  6981. ////                            ['entity_view_route_path_name']
  6982. ////                        )
  6983. //                    );
  6984. //                    System::setApprovalInfo($this->getDoctrine()->getManager(), $options,
  6985. //                        array_flip(GeneralConstant::$Entity_list)['ConsultancyTopic'],
  6986. //                        $docId,
  6987. //                        $request->getSession()->get(UserConstants::USER_LOGIN_ID)    //journal voucher
  6988. //                    );
  6989. //                    System::createEditSignatureHash($this->getDoctrine()->getManager(), array_flip(GeneralConstant::$Entity_list)['ConsultancyTopic'],
  6990. //                        $docId,
  6991. //                        $loginId,
  6992. //                        $request->request->get('approvalHash'));
  6993. //                    $this->addFlash(
  6994. //                        'success',
  6995. //                        'New Consultancy Topic Added.'
  6996. //                    );
  6997. ////                    $url = $this->generateUrl(
  6998. ////                        'create_consultancy_topic'
  6999. ////                    );
  7000. //                    //return $this->redirect($url);
  7001. //
  7002. //                }
  7003. //            }
  7004.         $consultancyDetails $em->getRepository('ApplicationBundle:ConsultancyTopic')->findAll();
  7005.         return $this->render('ApplicationBundle:pages/human_resource/input_forms:create_consultancy.html.twig', array(
  7006.             'page_title' => 'Consultancy Topic',
  7007.             'consultancyDetails' => $consultancyDetails,
  7008. //                'requirement' => json_decode($consultancyDetails->getRequirementData())
  7009.         ));
  7010.     }
  7011.     public function createTopicAction(Request $request$id 0)
  7012.     {
  7013.         $em $this->getDoctrine()->getManager('company_group');
  7014.         $companyId $this->getLoggedUserCompanyId($request);
  7015.         $documentQRY $em->getRepository('CompanyGroupBundle:EntityCreateDocument')->findAll();
  7016.         $topicList $em->getRepository('CompanyGroupBundle:EntityCreateTopic')->findAll();
  7017.         $topic = [];
  7018.         $sessionName BuddybeeConstant::$sessionName;
  7019.         $document = [];
  7020.         foreach ($documentQRY as $d) {
  7021.             $document[$d->getId()] = array(
  7022.                 'id' => $d->getId(),
  7023.                 'documentName' => $d->getDocumentName(),
  7024.                 'text' => $d->getDocumentName(),
  7025.             );
  7026.         }
  7027.         $topicId $id;
  7028.         if ($topicId != 0)
  7029.             $topic $em->getRepository('CompanyGroupBundle:EntityCreateTopic')->findOneBy(
  7030.                 array(
  7031.                     'id' => $topicId
  7032.                 )
  7033.             );
  7034.         if ($request->isMethod('POST')) {
  7035.             if ($request->request->has('topicId'))
  7036.                 $topicId $request->request->get('topicId');
  7037. //            $loginId = $request->getSession()->get(UserConstants::USER_LOGIN_ID);
  7038.             if ($topicId != 0)
  7039.                 $new $em->getRepository('CompanyGroupBundle:EntityCreateTopic')->findOneBy(
  7040.                     array(
  7041.                         'id' => $topicId
  7042.                     )
  7043.                 );
  7044.             else
  7045.                 $new = new EntityCreateTopic();
  7046.             $new->setTopicName($request->request->get('topicName'));
  7047.             $new->setParentTopicId($request->request->get('parentTopic'));
  7048.             if ($request->request->get('countryId') != '')
  7049.                 $new->setCountryId($request->request->get('countryId'));
  7050.             else if ($request->request->get('parentTopic') != '') {
  7051.                 $parentTopic $em->getRepository('CompanyGroupBundle:EntityCreateTopic')->findOneBy(
  7052.                     array(
  7053.                         'id' => $request->request->get('parentTopic')
  7054.                     )
  7055.                 );
  7056.                 if ($parentTopic)
  7057.                     $new->setCountryId($parentTopic->getCountryId());
  7058.             }
  7059.             $new->setTimeSlotMultipliers($request->request->get('timeSlotMultipliers'));
  7060.             $new->setOnlyBookableByAdmin($request->request->get('onlyBookableByAdmin'0));
  7061.             $new->setMeetingType($request->request->get('meetingType'0));
  7062.             $new->setConsultantCanUpload($request->request->get('consultantCanUpload'0));
  7063.             $new->setTopicMarker($request->request->get('topicMarker'));
  7064.             $new->setCoinMultiplierValue($request->request->get('coinMultiplierValue'1));
  7065.             $new->setMinLifetimeCoinsBalance($request->request->get('minLifetimeCoinsBalance'0));
  7066.             $new->setMapEmbedIframe($request->request->get('mapEmbedIframe'''));
  7067.             $new->setTopicSummary($request->request->get('topicSummary'));
  7068.             $new->setAddress($request->request->get('address'));
  7069.             $new->setLocationString($request->request->get('locationString'));
  7070.             $new->setLocationLat($request->request->get('locationLat'));
  7071.             $new->setLocationLong($request->request->get('locationLong'));
  7072.             $new->setUniversityRanking($request->request->get('universityRanking'));
  7073.             $new->setIsParent($request->request->get('isParent'));
  7074.             $new->setIsEvent($request->request->get('isEvent'));
  7075.             $new->setConsultancyEnabled($request->request->get('consultancyEnabled'0));
  7076.             $new->setEventExpired($request->request->get('eventExpired'0));
  7077.             $new->setEventDesc($request->request->get('eventDesc'0));
  7078.             $eventStartDate = new \DateTime($request->request->get('eventStartDate'));
  7079.             $eventEndDate = new \DateTime($request->request->get('eventStartDate'));
  7080.             $new->setEventStartDate($eventStartDate);
  7081.             $new->setEventStartDateTs($eventStartDate->format('U'));
  7082.             $new->setEventEndDate($eventEndDate);
  7083.             $new->setEventStartDateTs($eventEndDate->format('U'));
  7084.             $new->setCreatedLoginId($request->getSession()->get(UserConstants::USER_LOGIN_ID));
  7085.             $checkListStringArray = [];
  7086.             if ($request->request->has('checkList'))
  7087.                 foreach ($request->request->get('checkList') as $value) {
  7088.                     $checkListStringArray [] = explode(","$value);
  7089.                 }
  7090.             $docData = [];
  7091.             foreach ($request->request->get('document', []) as $key => $value)
  7092.                 $docData[] = [
  7093.                     'document' => $request->request->get('document')[$key],
  7094.                     'expDays' => $request->request->get('expDays')[$key],
  7095.                     'stage' => $request->request->get('stage')[$key],
  7096.                     'generalProcessingDays' => $request->request->get('generalProcessingDays')[$key],
  7097.                     'emergencyProcessingDays' => $request->request->get('emergencyProcessingDays')[$key],
  7098.                     'thresholdDaysOffset' => $request->request->get('thresholdDaysOffset')[$key],
  7099.                     'checklist' => explode(","$request->request->get('checkList')[$key])
  7100.                 ];
  7101.             $coursePlanData = [];
  7102.             foreach ($request->request->get('coursePlanSessionNo', []) as $key => $value)
  7103.                 if ($request->request->get('coursePlanSessionNo')[$key] != '' and $request->request->get('coursePlanSessionNo')[$key] != null) {
  7104.                     if (!isset($coursePlanData[$request->request->get('coursePlanSessionNo')[$key]]))
  7105.                         $coursePlanData[$request->request->get('coursePlanSessionNo')[$key]] = [];
  7106.                     $coursePlanData[$request->request->get('coursePlanSessionNo')[$key]][] = [
  7107.                         'sessionNo' => $request->request->get('coursePlanSessionNo')[$key],
  7108.                         'subject' => $request->request->get('coursePlanSubject')[$key],
  7109.                         'details' => $request->request->get('coursePlanDetails')[$key],
  7110.                         'optimumMin' => $request->request->get('coursePlanOptimumMin')[$key],
  7111.                     ];
  7112.                 }
  7113.             $routineData = [];
  7114.             foreach ($request->request->get('routine_sequence', []) as $key => $value) {
  7115.                 $routineData[] = [
  7116.                     'sequence' => $request->request->get('routine_sequence')[$key],
  7117.                     'topicId' => $request->request->get('routine_topic_id')[$key],
  7118.                     'topicName' => $request->request->get('routine_topic_name')[$key],
  7119.                     'meetingType' => $request->request->get('routine_topic_meeting_type')[$key],
  7120.                     'duration' => $request->request->get('routine_duration')[$key],
  7121.                     'offset' => $request->request->get('routine_offset')[$key],
  7122.                     'coins' => $request->request->get('routine_coins')[$key],
  7123.                     'nextSequenceStart' => $request->request->has('routine_next_sequence_start_' $value) ? 0,
  7124.                     'modifiable' => $request->request->has('routine_modifiable_' $value) ? 0,
  7125.                 ];
  7126.             }
  7127.             $sessionData = [];
  7128.             foreach ($request->request->get('sessionId', []) as $key => $value)
  7129.                 $sessionData[] = [
  7130.                     'sessionId' => $request->request->get('sessionId')[$key],
  7131.                     'sessionYear' => $request->request->get('year')[$key],
  7132.                     'threshold' => $request->request->get('threshold')[$key],
  7133.                     'sessionStart' => $request->request->get('sessionStart')[$key],
  7134.                     'applicationStartDate' => $request->request->get('applicationStartDate')[$key],
  7135.                 ];
  7136.             $coursesData = [];
  7137.             foreach ($request->request->get('courseName', []) as $key => $value)
  7138.                 $coursesData[] = [
  7139.                     'courseName' => $request->request->get('courseName')[$key],
  7140.                 ];
  7141.             $departmentData = [];
  7142.             foreach ($request->request->get('departmentName', []) as $key => $value)
  7143.                 $departmentData[] = [
  7144.                     'departmentName' => $request->request->get('departmentName')[$key],
  7145.                 ];
  7146.             $benefitsData = [];
  7147.             foreach ($request->request->get('benefit', []) as $key => $value)
  7148.                 $benefitsData[] = [
  7149.                     'benefit' => $request->request->get('benefit')[$key],
  7150.                 ];
  7151.             $new->setRoutineData(json_encode($routineData));
  7152.             $new->setDocumentData(json_encode($docData));
  7153.             $new->setCoursePlanData(json_encode($coursePlanData));
  7154.             $new->setSessionData(json_encode($sessionData));
  7155.             $new->setCourses(json_encode($coursesData));
  7156.             $new->setDepartments(json_encode($departmentData));
  7157.             $new->setBenefits(json_encode($benefitsData));
  7158.             $otherDataObj = [];
  7159.             foreach (BuddybeeConstant::$otherDataByHash as $ohash => $otherDataGroup)
  7160.                 foreach ($otherDataGroup as $otherData) {
  7161.                     $fieldExists $request->request->has($ohash '_' $otherData['field']);
  7162.                     if ($fieldExists) {
  7163.                         $fieldValue $request->request->get($ohash '_' $otherData['field'], '');
  7164.                         $otherDataObj[$ohash '_' $otherData['field']] = $fieldValue;
  7165.                     }
  7166.                 }
  7167.             $new->setOtherData(json_encode($otherDataObj));
  7168.             $new->setBenefits(json_encode($benefitsData));
  7169.             $em->persist($new);
  7170.             $em->flush();
  7171.             $path "";
  7172.             $defaultProductImage '';
  7173.             $uploadedFile null;
  7174.             $upl_dir $this->container->getParameter('kernel.root_dir') . '/../web/uploads/topicImage/';
  7175.             $uploadedFile $request->files->get('topicSummaryImage');
  7176.             if ($uploadedFile != null) {
  7177.                 $fileName 'TSI' $new->getId() . '.' $uploadedFile->guessExtension();
  7178.                 $path $fileName;
  7179. //            $upl_dir = $this->container->getParameter('kernel.root_dir') . '/../web/uploads/Products/';
  7180.                 if (!file_exists($upl_dir)) {
  7181.                     mkdir($upl_dir0777true);
  7182.                 }
  7183.                 $uploadedFile->move($upl_dir$path);
  7184.                 $defaultProductImage 'uploads/topicImage/' $path;
  7185.                 $new->setTopicSummaryImage($defaultProductImage);
  7186.                 $em->flush();
  7187.             }
  7188.             $path "";
  7189.             $defaultProductImage '';
  7190.             $uploadedFile null;
  7191.             $upl_dir $this->container->getParameter('kernel.root_dir') . '/../web/uploads/topicImage/';
  7192.             $uploadedFile $request->files->get('topicImage');
  7193.             if ($uploadedFile != null) {
  7194.                 $fileName 'TI' $new->getId() . '.' $uploadedFile->guessExtension();
  7195.                 $path $fileName;
  7196. //            $upl_dir = $this->container->getParameter('kernel.root_dir') . '/../web/uploads/Products/';
  7197.                 if (!file_exists($upl_dir)) {
  7198.                     mkdir($upl_dir0777true);
  7199.                 }
  7200.                 $uploadedFile->move($upl_dir$path);
  7201.                 $defaultProductImage 'uploads/topicImage/' $path;
  7202.                 $new->setTopicImage($defaultProductImage);
  7203.                 $em->flush();
  7204.             }
  7205.             $this->addFlash(
  7206.                 'success',
  7207.                 'Topic Added.'
  7208.             );
  7209.         }
  7210.         return $this->render('ApplicationBundle:pages/human_resource/input_forms:create_topic.html.twig', array(
  7211.             'page_title' => 'Create Topic',
  7212.             'defaultCoursePlan' => BuddybeeConstant::$defaultCoursePlan,
  7213.             'coursePlanSessionTitle' => BuddybeeConstant::$coursePlanSessionTitle,
  7214.             'coursePlanSessionTitleShort' => BuddybeeConstant::$coursePlanSessionTitleShort,
  7215.             'document' => $document,
  7216.             'topic' => $topic,
  7217.             'otherDataByHash' => BuddybeeConstant::$otherDataByHash,
  7218.             'topicId' => $topicId,
  7219.             'topicList' => $topicList,
  7220.             'topicMarker' => BuddybeeConstant::$topicMarkup,
  7221.             'sessionName' => $sessionName,
  7222.         ));
  7223.     }
  7224.     public function ConsultancyRequirementSettingsAction(Request $request$id 0)
  7225.     {
  7226.         $em $this->getDoctrine()->getManager('company_group');
  7227.         $entityList $em->getRepository('CompanyGroupBundle:EntityCountryConsultantRequirements')->findAll();
  7228.         $documentQRY $em->getRepository('CompanyGroupBundle:EntityCreateDocument')->findAll();
  7229.         $entity = [];
  7230.         $sessionName BuddybeeConstant::$sessionName;
  7231.         $document = [];
  7232.         foreach ($documentQRY as $d) {
  7233.             $document[$d->getId()] = array(
  7234.                 'id' => $d->getId(),
  7235.                 'documentName' => $d->getDocumentName(),
  7236.                 'text' => $d->getDocumentName(),
  7237.             );
  7238.         }
  7239.         $countryId $id;
  7240.         if ($countryId != 0)
  7241.             $entity $em->getRepository('CompanyGroupBundle:EntityCountryConsultantRequirements')->findOneBy(
  7242.                 array(
  7243.                     'countryId' => $countryId
  7244.                 )
  7245.             );
  7246.         if ($request->isMethod('POST')) {
  7247.             if ($request->request->has('countryId'))
  7248.                 $countryId $request->request->get('countryId');
  7249. //            $loginId = $request->getSession()->get(UserConstants::USER_LOGIN_ID);
  7250.             if ($countryId != 0) {
  7251.                 $new $em->getRepository('CompanyGroupBundle:EntityCountryConsultantRequirements')->findOneBy(
  7252.                     array(
  7253.                         'countryId' => $countryId
  7254.                     )
  7255.                 );
  7256.                 if (!$new)
  7257.                     $new = new EntityCountryConsultantRequirements();
  7258.             } else
  7259.                 $new = new EntityCountryConsultantRequirements();
  7260.             $new->setCountryId($request->request->get('countryId'));
  7261.             $new->setContractLetterHtml($request->request->get('contractLetterHtml'));
  7262.             $new->setRequiredFields($request->request->get('requiredFields'));
  7263.             $new->setAllowedWorkingHoursPerDay($request->request->get('allowedWorkingHoursPerDay'));
  7264.             $new->setAllowedWorkingHoursPerMonth($request->request->get('allowedWorkingHoursPerMonth'));
  7265.             $new->setAllowedWorkingHoursPerWeek($request->request->get('allowedWorkingHoursPerWeek'));
  7266.             $new->setAllowedWorkingHoursPerYear($request->request->get('allowedWorkingHoursPerYear'));
  7267.             $new->setAllowedEarningPerDay($request->request->get('allowedEarningPerDay'));
  7268.             $new->setAllowedEarningPerMonth($request->request->get('allowedEarningPerMonth'));
  7269.             $new->setAllowedEarningPerWeek($request->request->get('allowedEarningPerWeek'));
  7270.             $new->setAllowedEarningPerYear($request->request->get('allowedEarningPerYear'));
  7271.             $new->setRevenuePercentagePerSession($request->request->get('revenuePercentagePerSession'));
  7272.             $docData = [];
  7273.             foreach ($request->request->get('document', []) as $key => $value)
  7274.                 $docData[] = [
  7275.                     'document' => $request->request->get('document')[$key],
  7276.                     'expDays' => $request->request->get('expDays')[$key],
  7277.                     'stage' => $request->request->get('stage')[$key],
  7278.                     'generalProcessingDays' => $request->request->get('generalProcessingDays')[$key],
  7279.                     'emergencyProcessingDays' => $request->request->get('emergencyProcessingDays')[$key],
  7280.                     'thresholdDaysOffset' => $request->request->get('thresholdDaysOffset')[$key],
  7281.                     'checklist' => explode(","$request->request->get('checkList')[$key])
  7282.                 ];
  7283.             $new->setDocumentList(json_encode($docData));
  7284.             $em->persist($new);
  7285.             $em->flush();
  7286.             $this->addFlash(
  7287.                 'success',
  7288.                 'Restriction Updated.'
  7289.             );
  7290.         }
  7291.         return $this->render('@Buddybee/pages/create_consultancy_requirements.html.twig', array(
  7292.             'page_title' => 'Create Requirements',
  7293.             'defaultCoursePlan' => BuddybeeConstant::$defaultCoursePlan,
  7294.             'coursePlanSessionTitle' => BuddybeeConstant::$coursePlanSessionTitle,
  7295.             'coursePlanSessionTitleShort' => BuddybeeConstant::$coursePlanSessionTitleShort,
  7296.             'document' => $document,
  7297.             'entity' => $entity,
  7298.             'otherDataByHash' => BuddybeeConstant::$otherDataByHash,
  7299.             'countryId' => $countryId,
  7300.             'entityList' => $entityList,
  7301.             'topicMarker' => BuddybeeConstant::$topicMarkup,
  7302.             'sessionName' => $sessionName,
  7303.         ));
  7304.     }
  7305.     public function PromoCodeSettingsAction(Request $request$id 0)
  7306.     {
  7307.         $em $this->getDoctrine()->getManager('company_group');
  7308.         $entityList $em->getRepository('CompanyGroupBundle:PromoCode')->findAll();
  7309.         $applicantList $em->getRepository('CompanyGroupBundle:EntityApplicantDetails')->findAll();
  7310.         $promoCodeId $id;
  7311.         $entity = [];
  7312.         if ($promoCodeId != 0)
  7313.             $entity $em->getRepository('CompanyGroupBundle:PromoCode')->findOneBy(
  7314.                 array(
  7315.                     'id' => $promoCodeId
  7316.                 )
  7317.             );
  7318.         if ($request->isMethod('POST')) {
  7319.             if ($request->request->has('promoCodeId'))
  7320.                 $promoCodeId $request->request->get('promoCodeId');
  7321. //            $loginId = $request->getSession()->get(UserConstants::USER_LOGIN_ID);
  7322.             if ($promoCodeId != 0) {
  7323.                 $new $em->getRepository('CompanyGroupBundle:PromoCode')->findOneBy(
  7324.                     array(
  7325.                         'id' => $promoCodeId
  7326.                     )
  7327.                 );
  7328.                 if (!$new)
  7329.                     $new = new PromoCode();
  7330.             } else
  7331.                 $new = new PromoCode();
  7332. //            $new->setCountryId($request->request->get('countryId'));
  7333.             $new->setCode($request->request->get('code'''));
  7334.             $new->setPromoType($request->request->get('promoType'1));
  7335.             $new->setPromoCodeType($request->request->get('promoCodeType'1));
  7336.             $new->setPromoValue($request->request->get('promoValue'0));
  7337.             $new->setPerpetual($request->request->get('perpetual'0));
  7338.             $new->setMaxDiscountAmount($request->request->get('maxDiscountAmount', -1));
  7339.             $new->setMaxCoinAddition($request->request->get('maxCoinAddition', -1));
  7340.             $new->setMinAmountForApplication($request->request->get('minAmountForApplication'0));
  7341.             $new->setMinCoinForApplication($request->request->get('minCoinForApplication'0));
  7342.             $new->setNextApplicationEachCoinCount($request->request->get('nextApplicationEachCoinCount', -1));
  7343.             $new->setMaxUseCount($request->request->get('maxUseCount', -1));
  7344.             $new->setMaxUseCountPerUser($request->request->get('maxUseCountPerUser', -1));
  7345.             $new->setUseCountBalance($request->request->get('useCountBalance', -1));
  7346.             $new->setReferralApplicantId($request->request->get('referralApplicantId'0));
  7347.             $new->setMaxReferralCommissionCount($request->request->get('maxReferralCommissionCount'0));
  7348.             $new->setReferralCommissionCountBalance($request->request->get('referralCommissionCountBalance'0));
  7349.             $new->setReferralCommissionType($request->request->get('referralCommissionType'1));
  7350.             $new->setReferralAmount($request->request->get('referralAmount'0));
  7351.             $startsAt = new \DateTime($request->request->get('startsAt'''));
  7352.             $expiresAt = new \DateTime($request->request->get('expiresAt'''));
  7353.             $new->setStartsAtTs($startsAt->format('U'));
  7354.             $new->setExpiresAtTs($expiresAt->format('U'));
  7355. //
  7356. //        startsAtTs:
  7357. //            type: integer
  7358. //            nullable: true
  7359. //        expiresAtTs:
  7360. //            type: integer
  7361. //            nullable: true
  7362.             $em->persist($new);
  7363.             $em->flush();
  7364.             $this->addFlash(
  7365.                 'success',
  7366.                 'Promo Code Updated.'
  7367.             );
  7368.         }
  7369.         return $this->render('@Buddybee/pages/buddybee_promo_code_settings.html.twig', array(
  7370.             'page_title' => 'Promo Codes',
  7371.             'entity' => $entity,
  7372.             'promoCodeId' => $promoCodeId,
  7373.             'entityList' => $entityList,
  7374.             'applicantList' => $applicantList,
  7375.         ));
  7376.     }
  7377.     public function createDocumentAction(Request $request$id 0)
  7378.     {
  7379.         $em $this->getDoctrine()->getManager('company_group');
  7380.         $companyId $this->getLoggedUserCompanyId($request);
  7381.         $document $em->getRepository('CompanyGroupBundle:EntityCreateDocument')->findAll();
  7382.         $thisDoc = [];
  7383.         if ($id != 0)
  7384.             $thisDoc $em->getRepository('CompanyGroupBundle:EntityCreateDocument')->findOneBy(
  7385.                 array(
  7386.                     'Id' => $id
  7387.                 )
  7388.             );
  7389.         if ($request->isMethod('POST')) {
  7390.             if ($id != 0)
  7391.                 $new $thisDoc;
  7392.             else
  7393.                 $new = new EntityCreateDocument();
  7394.             $new->setDocumentName($request->request->get('docName'));
  7395.             $new->setExpiryDays($request->request->get('expDays'));
  7396.             $new->setProcessingDays($request->request->get('processingDays'));
  7397.             $new->setEmergencyProcessingDays($request->request->get('emergencyProcessingDays'));
  7398.             $new->setDocVideo($request->request->get('docVideoLink'));
  7399.             $new->setRequiredDocument(json_encode($request->request->get('requiredDoc')));
  7400.             $new->setCreatedLoginId($request->getSession()->get(UserConstants::USER_LOGIN_ID));
  7401.             $arr = [
  7402.                 'checkListName' => $request->request->get('checkListName'),
  7403.             ];
  7404.             $new->setCheckList(json_encode($arr));
  7405.             $em->persist($new);
  7406.             $em->flush();
  7407.         }
  7408.         $this->addFlash(
  7409.             'Document Added',
  7410.             'Topic Added.'
  7411.         );
  7412.         return $this->render('ApplicationBundle:pages/human_resource/input_forms:create_document.html.twig', array(
  7413.             'page_title' => 'Create Document',
  7414.             'document' => $document,
  7415.             'thisDoc' => $thisDoc
  7416.         ));
  7417.     }
  7418.     public function getIndividualDocumentAction(Request $request$id)
  7419.     {
  7420.         $em $this->getDoctrine()->getManager('company_group');
  7421.         if ($id == 0) {
  7422.             if ($request->request->has('documentId'))
  7423.                 $id $request->request->get('documentId');
  7424.         }
  7425.         $document $em->getRepository('CompanyGroupBundle:EntityCreateDocument')->find($id);
  7426.         return new JsonResponse(
  7427.             array(
  7428.                 'success' => true,
  7429.                 'rowId' => $request->request->get('rowId'),
  7430.                 'expiryDays' => $document->getExpiryDays(),
  7431.                 'processingDays' => $document->getProcessingDays(),
  7432.                 'emergencyProcessing' => $document->getEmergencyProcessingDays(),
  7433.                 'checklist' => json_decode($document->getCheckList()),
  7434.             )
  7435.         );
  7436.     }
  7437.     public function createBlogAction(Request $request$id)
  7438.     {
  7439.         if (!$id) {
  7440.             if ($request->isMethod('POST')) {
  7441.                 $em $this->getDoctrine()->getManager('company_group');
  7442.                 $loginId $request->getSession()->get(UserConstants::USER_LOGIN_ID);
  7443.                 $new = new EntityCreateBlog();
  7444.                 $new->setTopicId($request->request->get('topicId'));
  7445.                 $new->setTitle($request->request->get('title'));
  7446.                 $new->setSubtitle($request->request->get('subTitle'));
  7447.                 $new->setContent($request->request->get('content'));
  7448.                 $new->setVideoLink($request->request->get('videoLink'));
  7449.                 $new->setAuthorName($request->request->get('authorName'));
  7450.                 $new->setAuthorSummary($request->request->get('authorSummary'));
  7451.                 $new->setIsPrimaryBlog($request->request->get('checkPrimaryBlog'));
  7452.                 $em->persist($new);
  7453.                 $em->flush();
  7454.                 //$fileName = 'cv' . $consultantDetails->getApplicantId() . '.' . $uploadedFile->guessExtension();
  7455.                 $path "";
  7456.                 $defaultProductImage '';
  7457.                 $uploadedFile null;
  7458.                 $upl_dir $this->container->getParameter('kernel.root_dir') . '/../web/uploads/authorImage/';
  7459.                 $uploadedFile $request->files->get('authorImage');
  7460.                 if ($uploadedFile != null) {
  7461.                     $fileName 'authorImage' $new->getId() . '.' $uploadedFile->guessExtension();
  7462.                     $path $fileName;
  7463. //            $upl_dir = $this->container->getParameter('kernel.root_dir') . '/../web/uploads/Products/';
  7464.                     if (!file_exists($upl_dir)) {
  7465.                         mkdir($upl_dir0777true);
  7466.                     }
  7467.                     $uploadedFile->move($upl_dir$path);
  7468.                     $defaultProductImage 'uploads/authorImage/' $path;
  7469.                     $new->setAuthorImage($defaultProductImage);
  7470.                     $em->flush();
  7471.                 }
  7472.                 $path "";
  7473.                 $defaultProductImage '';
  7474.                 $uploadedFile null;
  7475.                 $upl_dir $this->container->getParameter('kernel.root_dir') . '/../web/uploads/mainImage/';
  7476.                 $uploadedFile $request->files->get('main_img');
  7477.                 if ($uploadedFile != null) {
  7478.                     $fileName 'mainImage' $new->getId() . '.' $uploadedFile->guessExtension();
  7479.                     $path $fileName;
  7480. //            $upl_dir = $this->container->getParameter('kernel.root_dir') . '/../web/uploads/Products/';
  7481.                     if (!file_exists($upl_dir)) {
  7482.                         mkdir($upl_dir0777true);
  7483.                     }
  7484.                     $uploadedFile->move($upl_dir$path);
  7485.                     $defaultProductImage 'uploads/mainImage/' $path;
  7486.                     $new->setMainImage($defaultProductImage);
  7487.                     $em->flush();
  7488.                 }
  7489.                 $topicDetails $em->getRepository('CompanyGroupBundle:EntityCreateTopic')->findOneBy(
  7490.                     array(
  7491.                         'id' => $request->request->get('topicId')
  7492.                     )
  7493.                 );
  7494.                 if ($new->getIsPrimaryBlog() == 1) {
  7495.                     if ($topicDetails)
  7496.                         $topic $topicDetails;
  7497.                     else
  7498.                         $topic = new EntityCreateTopic();
  7499.                     $topic->setPrimaryBlogId($new->getId());
  7500.                     $em->flush();
  7501.                 }
  7502.                 $this->addFlash(
  7503.                     'success',
  7504.                     'Blog Added.'
  7505.                 );
  7506.             } else {
  7507.                 $em $this->getDoctrine()->getManager('company_group');
  7508.                 $topic $em->getRepository('CompanyGroupBundle:EntityCreateTopic')->findAll();
  7509.                 $applicant $em->getRepository('CompanyGroupBundle:EntityApplicantDetails')->findAll();
  7510.                 $blogs $em->getRepository('CompanyGroupBundle:EntityCreateBlog')->findAll();
  7511.                 $topicIds = [];
  7512.                 foreach ($blogs as $blog) {
  7513.                     $topicIds [] = $blog->getTopicId();
  7514.                 }
  7515. //                $topic = $em->getRepository('CompanyGroupBundle:EntityCreateTopic')->findBy(
  7516. //                    array(
  7517. //                        'id' => $topicIds
  7518. //                    )
  7519. //                );
  7520.                 return $this->render('ApplicationBundle:pages/human_resource/input_forms:create_blog.html.twig', array(
  7521.                     'page_title' => 'Create Blog',
  7522.                     'topic' => $topic,
  7523.                     'applicant' => $applicant,
  7524.                     'blog' => $blogs,
  7525.                     'id' => $id,
  7526.                 ));
  7527.             }
  7528.         } else {
  7529.             if ($request->isMethod('GET')) {
  7530.                 $em $this->getDoctrine()->getManager('company_group');
  7531.                 $topic $em->getRepository('CompanyGroupBundle:EntityCreateTopic')->findAll();
  7532.                 $applicant $em->getRepository('CompanyGroupBundle:EntityApplicantDetails')->findAll();
  7533.                 $blogs $em->getRepository('CompanyGroupBundle:EntityCreateBlog')->find($id);
  7534.                 return $this->render('ApplicationBundle:pages/human_resource/input_forms:create_blog.html.twig', array(
  7535.                     'page_title' => 'Create Blog',
  7536.                     'topic' => $topic,
  7537.                     'applicant' => $applicant,
  7538.                     'blog' => $blogs,
  7539.                     'id' => $id,
  7540.                 ));
  7541.             } else {
  7542.                 $em $this->getDoctrine()->getManager('company_group');
  7543.                 $new = new EntityCreateBlog();
  7544.                 $new->setTopicId($request->request->get('topicId'));
  7545.                 $new->setTitle($request->request->get('title'));
  7546.                 $new->setSubtitle($request->request->get('subTitle'));
  7547.                 $new->setContent($request->request->get('content'));
  7548.                 $new->setVideoLink($request->request->get('videoLink'));
  7549.                 $new->setAuthorName($request->request->get('authorName'));
  7550.                 $new->setAuthorSummary($request->request->get('authorSummary'));
  7551.                 //$em->persist($new);
  7552.                 $em->flush();
  7553.                 $path "";
  7554.                 $defaultProductImage '';
  7555.                 $uploadedFile null;
  7556.                 $upl_dir $this->container->getParameter('kernel.root_dir') . '/../web/uploads/authorImage/';
  7557.                 $uploadedFile $request->files->get('authorImage');
  7558.                 if ($uploadedFile != null) {
  7559.                     $fileName 'authorImage' '.' $uploadedFile->guessExtension();
  7560.                     $path $fileName;
  7561. //            $upl_dir = $this->container->getParameter('kernel.root_dir') . '/../web/uploads/Products/';
  7562.                     if (!file_exists($upl_dir)) {
  7563.                         mkdir($upl_dir0777true);
  7564.                     }
  7565.                     $uploadedFile->move($upl_dir$path);
  7566.                     $defaultProductImage 'uploads/authorImage/' $path;
  7567.                     $new->setAuthorImage($defaultProductImage);
  7568.                     $em->flush();
  7569.                 }
  7570.                 $this->addFlash(
  7571.                     'success',
  7572.                     'Blog Updated.'
  7573.                 );
  7574.             }
  7575.         }
  7576.         return new JsonResponse(
  7577.             array(
  7578.                 'success' => true,
  7579.             )
  7580.         );
  7581. //        if ($request->isMethod('POST')) {
  7582. //            $loginId = $request->getSession()->get(UserConstants::USER_LOGIN_ID);
  7583. //
  7584. //            $new = new EntityCreateBlog();
  7585. //
  7586. //            $new->setTopicId($request->request->get('topicId'));
  7587. //            $new->setTitle($request->request->get('title'));
  7588. //            $new->setSubtitle($request->request->get('subTitle'));
  7589. //            $new->setContent($request->request->get('content'));
  7590. //            $new->setVideoLink($request->request->get('videoLink'));
  7591. //            $new->setAuthorName($request->request->get('authorName'));
  7592. //            $new->setAuthorSummary($request->request->get('authorSummary'));
  7593. //
  7594. //            $em->persist($new);
  7595. //            $em->flush();
  7596. //
  7597. //
  7598. //            $path = "";
  7599. //            $defaultProductImage = '';
  7600. //            $uploadedFile = null;
  7601. //            $upl_dir = $this->container->getParameter('kernel.root_dir') . '/../web/uploads/authorImage/';
  7602. //            $uploadedFile=  $request->files->get('authorImage');
  7603. //
  7604. //            if ($uploadedFile != null) {
  7605. //
  7606. //                $fileName = 'authorImage' .'.' . $uploadedFile->guessExtension();
  7607. //                $path = $fileName;
  7608. ////            $upl_dir = $this->container->getParameter('kernel.root_dir') . '/../web/uploads/Products/';
  7609. //                if (!file_exists($upl_dir)) {
  7610. //                    mkdir($upl_dir, 0777, true);
  7611. //                }
  7612. //                $uploadedFile->move($upl_dir, $path);
  7613. //                $defaultProductImage = 'uploads/authorImage/' . $path;
  7614. //                $new->setAuthorImage($defaultProductImage);
  7615. //                $em->flush();
  7616. //
  7617. //            }
  7618. //            $this->addFlash(
  7619. //                'success',
  7620. //                'Blog Added.'
  7621. //            );
  7622. //        }
  7623. //        return $this->render('ApplicationBundle:pages/human_resource/input_forms:create_blog.html.twig', array(
  7624. //            'page_title' => 'Create Blog',
  7625. //            'topic'=> $topic,
  7626. //            'applicant' => $applicant,
  7627. //            'blog' => $blogs
  7628. //        ));
  7629.     }
  7630.     public function applicantConsultancyAction()
  7631.     {
  7632.         return $this->render('ApplicationBundle:pages/human_resource/input_forms:consultancy.html.twig', array(
  7633.             'page_title' => 'Consultancy',
  7634.         ));
  7635.     }
  7636.     public function viewConsultantDetailsAction(Request $request$id 0)
  7637.     {
  7638.         $gocEnabled 1;
  7639.         $currAppId 4;
  7640.         $honeybeeAppId 1;
  7641.         $buddybeeAppId 4;
  7642.         $em_goc $this->getDoctrine()->getManager('company_group');
  7643.         $em $this->getDoctrine()->getManager();
  7644.         $option = [];
  7645.         $option['appId'] = $currAppId//honeybee
  7646.         $option['departmentId'] = 18//consultancy
  7647.         $option['designationId'] = 50;
  7648. //        $dataToConnect = System::changeDoctrineManagerByAppId(
  7649. //            $this->getDoctrine()->getManager('company_group'),
  7650. //            $gocEnabled,
  7651. //            $currAppId
  7652. //        );
  7653. //        if (!empty($dataToConnect)) {
  7654. //            $connector = $this->container->get('application_connector');
  7655. //            $connector->resetConnection(
  7656. //                'default',
  7657. //                $dataToConnect['dbName'],
  7658. //                $dataToConnect['dbUser'],
  7659. //                $dataToConnect['dbPass'],
  7660. //                $dataToConnect['dbHost'],
  7661. //                $reset = true
  7662. //            );
  7663. //            $em = $this->getDoctrine()->getManager();
  7664. //        } else {
  7665. //            $currAppId = $honeybeeAppId;
  7666. //            $dataToConnectAgain = System::changeDoctrineManagerByAppId(
  7667. //                $this->getDoctrine()->getManager('company_group'),
  7668. //                $gocEnabled,
  7669. //                $currAppId
  7670. //            );
  7671. //            if (!empty($dataToConnectAgain)) {
  7672. //                $connector = $this->container->get('application_connector');
  7673. //                $connector->resetConnection(
  7674. //                    'default',
  7675. //                    $dataToConnect['dbName'],
  7676. //                    $dataToConnect['dbUser'],
  7677. //                    $dataToConnect['dbPass'],
  7678. //                    $dataToConnect['dbHost'],
  7679. //                    $reset = true
  7680. //                );
  7681. //                $em = $this->getDoctrine()->getManager();
  7682. //            }
  7683. //
  7684. //        }
  7685.         $consultantDetails $em_goc->getRepository(EntityApplicantDetails::class)->find($id);
  7686.         $skill $em_goc->getRepository(EntitySkill::class)->findAll();
  7687.         $gender HumanResourceConstant::$sex;
  7688.         $blood HumanResourceConstant::$BloodGroup;
  7689.         $consultantLevel HumanResourceConstant::$consultantLevel;
  7690.         $companyId $this->getLoggedUserCompanyId($request);
  7691.         $designation $em->getRepository("ApplicationBundle:SysDepartmentPosition")->findAll();
  7692.         $departments $em->getRepository("ApplicationBundle:SysDepartment")->findAll();
  7693.         $companyData Company::getCompanyData($em$companyId);
  7694.         $currDate = new \DateTime();
  7695.         if ($request->isMethod('POST')) {
  7696.             //for consultant only
  7697.             $convertToConsultant HumanResource::convertToConsultant($em_goc$em$id$option$request->request);
  7698.             if ($request->request->get('confirmStatus'0) == 1) {
  7699.                 $bodyTemplate 'ApplicationBundle:email/templates:consultantApprovalEmail.html.twig';
  7700.                 $contractLetterHtml '';
  7701.                 $bodyData = array(
  7702.                     'name' => $consultantDetails->getFirstname() . ' ' $consultantDetails->getLastname(),
  7703.                     'companyData' => $companyData,
  7704.                     'contractLetterHtml' => $contractLetterHtml,
  7705.                     'commentText' => $request->request->get('commentText'),
  7706.                 );
  7707.                 $new_mail $this->get('mail_module');
  7708.                 $new_mail->sendMyMail(array(
  7709.                     'senderHash' => '_CUSTOM_',
  7710.                     'encryptionMethod' => 'ssl',
  7711.                     'userName' => 'management@buddybee.eu',
  7712.                     'fromAddress' => 'management@buddybee.eu',
  7713.                     'password' => 'Eco@0112',
  7714.                     'smtpServer' => 'smtp.hostinger.com',
  7715.                     'smtpPort' => '465',
  7716.                     'forwardToMailAddress' => $consultantDetails->getEmail(),
  7717.                     'subject' => 'Consultant Contract Letter Of ' $consultantDetails->getFirstName(),
  7718.                     'fileName' => '',
  7719.                     //'attachments' => $attachments,
  7720.                     'toAddress' => $consultantDetails->getEmail(),
  7721.                     'mailTemplate' => $bodyTemplate,
  7722.                     'templateData' => $bodyData,
  7723.                     'embedCompanyImage' => 1,
  7724.                     'companyId' => $companyId,
  7725.                     'companyImagePath' => ""
  7726.                 ));
  7727.             }
  7728.             if ($request->request->get('confirmStatus'0) == 0) {
  7729.                 $bodyTemplate 'ApplicationBundle:email/templates:consultantRejectionEmail.html.twig';
  7730.                 $contractLetterHtml '';
  7731.                 $bodyData = array(
  7732.                     'name' => $consultantDetails->getFirstname() . ' ' $consultantDetails->getLastname(),
  7733.                     'companyData' => $companyData,
  7734.                     'contractLetterHtml' => $contractLetterHtml,
  7735.                     'commentText' => $request->request->get('commentText'),
  7736.                 );
  7737.                 $new_mail $this->get('mail_module');
  7738.                 $new_mail->sendMyMail(array(
  7739.                     'senderHash' => '_CUSTOM_',
  7740.                     'encryptionMethod' => 'ssl',
  7741.                     'userName' => 'management@buddybee.eu',
  7742.                     'fromAddress' => 'management@buddybee.eu',
  7743.                     'password' => 'Eco@0112',
  7744.                     'smtpServer' => 'smtp.hostinger.com',
  7745.                     'smtpPort' => '465',
  7746.                     'forwardToMailAddress' => $consultantDetails->getEmail(),
  7747.                     'subject' => 'Rejection Letter Of ' $consultantDetails->getFirstName(),
  7748.                     'fileName' => '',
  7749.                     //'attachments' => $attachments,
  7750.                     'toAddress' => $consultantDetails->getEmail(),
  7751.                     'mailTemplate' => $bodyTemplate,
  7752.                     'templateData' => $bodyData,
  7753.                     'embedCompanyImage' => 1,
  7754.                     'companyId' => $companyId,
  7755.                     'companyImagePath' => ""
  7756.                 ));
  7757.             }
  7758.         }
  7759.         $docList MiscActions::GetDocumentDataForBuddybeeConsultantApply($em_goc,
  7760.             $id,
  7761.             $consultantDetails->getCurrentCountryId()
  7762.         );
  7763.         return $this->render('ApplicationBundle:pages/human_resource/views:viewConsultantDetails.html.twig', array(
  7764.             'page_title' => 'Consultant Details',
  7765.             'applicantId' => $id,
  7766.             'consultantDetails' => $consultantDetails,
  7767.             'education' => json_decode($consultantDetails->getEducationData(), true),
  7768.             'workExperience' => json_decode($consultantDetails->getWorkExperienceData(), true),
  7769.             'certificate' => json_decode($consultantDetails->getCertificateData(), true),
  7770.             'gender' => $gender,
  7771.             'blood' => $blood,
  7772.             'skill' => $skill,
  7773.             'docList' => $docList,
  7774.             'countryId' => $consultantDetails->getCurrentCountryId(),
  7775.             'consultantLevel' => $consultantLevel,
  7776.             'designation' => $designation,
  7777.             'department' => $departments
  7778.         ));
  7779.     }
  7780.     public function ApplicableEmployeSettingsAction()
  7781.     {
  7782.         $em $this->getDoctrine()->getManager();
  7783.         $employeeIds $em->getRepository(Employee::class)->findAll();
  7784.         return $this->render('ApplicationBundle:pages/human_resource/input_forms:applicable_employee_settings.html.twig', array(
  7785.             'page_title' => 'Applicable Employee Settings',
  7786.             'employeeIds' => $employeeIds
  7787.         ));
  7788.     }
  7789.     public function GetApplicableSettingsForSingleEmployeeAction($id)
  7790.     {
  7791.         $em $this->getDoctrine()->getManager();
  7792.         $bankLists $em->getRepository(WorkHourPolicy::class)->findAll();
  7793.         if (json_decode($bankLists->getEmployeeIds()) == $id) {
  7794.             return new JsonResponse(
  7795.                 array(
  7796.                     'success' => true,
  7797.                     'msg' => 'employee found'
  7798.                 )
  7799.             );
  7800.         } else {
  7801.             return new JsonResponse(
  7802.                 array(
  7803.                     'success' => true,
  7804.                     'msg' => 'employee not found'
  7805.                 )
  7806.             );
  7807.         }
  7808.     }
  7809. //    public function  getEmployeeDataAction(){
  7810. //        $em = $this->getDoctrine()->getManager();
  7811. //        $emplyeeDetails =  $em->getRepository('ApplicationBundle:EmployeeDeatils')->findAll();
  7812. //        $days = HumanResourceConstant::$days;
  7813. //        $holidays = ;
  7814. //        $workHourPolicies = ;
  7815. //
  7816. //    }
  7817.     public function meetingSchedulingForTabAction()
  7818.     {
  7819.         $em $this->getDoctrine()->getManager();
  7820.         $date date('Y-m-d');
  7821.         $month date('m');
  7822.         $year date('Y');
  7823.         $monthName date("F"mktime(000$month));
  7824.         $totalDayOfMonth cal_days_in_month(CAL_GREGORIAN$month$year);
  7825.         $fromdt date('Y-m-01 'strtotime("First Day Of  $monthName $year"));
  7826. //        echo "Start Date : $fromdt" . "<br>";
  7827.         $todt date('Y-m-d 'strtotime("Last Day of $monthName $year"));
  7828. //        echo "End Date : $todt" . "<br>";
  7829.         $num_friday '';
  7830.         for ($i 0$i < ((strtotime($todt) - strtotime($fromdt)) / 86400); $i++) {
  7831.             if (date('l'strtotime($fromdt) + ($i 86400)) == 'Friday') {
  7832.                 $num_friday++;
  7833.             }
  7834.         }
  7835.         $num_saturday '';
  7836.         for ($i 0$i < ((strtotime($todt) - strtotime($fromdt)) / 86400); $i++) {
  7837.             if (date('l'strtotime($fromdt) + ($i 86400)) == 'Saturday') {
  7838.                 $num_saturday++;
  7839.             }
  7840.         }
  7841.         $totalWeekends $num_saturday $num_friday;
  7842.         $totalCompanyWorkingDay $totalDayOfMonth $totalWeekends;
  7843. //        $attendanceData=$em->getRepository('ApplicationBundle:EmployeeAttendanceLog')->findOneBy(
  7844. //            array(
  7845. //                'employeeId' => 3
  7846. //            )
  7847. //        );
  7848.         $DateRange = [];
  7849.         $holidayDates $em->getRepository('ApplicationBundle:HolidayCalendarDates')->findAll();
  7850.         foreach ($holidayDates as $holiday) {
  7851.             $holidaayData = array(
  7852.                 'startDate' => $holiday->getStartDate(),
  7853.                 'endDate' => $holiday->getEndDate(),
  7854.             );
  7855.             $DateRange $holidaayData;
  7856.         }
  7857.         $employeeDataDetail = [];
  7858.         $employeeDetail $em->getRepository('ApplicationBundle:EmployeeDetails')->findOneBy(
  7859.             array(
  7860.                 'id' => 3
  7861.             )
  7862.         );
  7863. //        foreach($employeeDetail as $employee){
  7864.         $employeeData = array(
  7865.             'firstName' => $employeeDetail->getFirstname(),
  7866.             'basic' => $employeeDetail->getEar1(),
  7867.             'dearness' => $employeeDetail->getEar2(),
  7868.             'houseRent' => $employeeDetail->getEar3(),
  7869.             'medical' => $employeeDetail->getEar4(),
  7870.             'leaveTravel' => $employeeDetail->getEar5(),
  7871.             'childEducation' => $employeeDetail->getEar6(),
  7872.             'totalEarning' => $employeeDetail->getEart(),
  7873.         );
  7874.         $employeeDataDetail $employeeData;
  7875. //        }
  7876.         $attendanceData $em->getRepository(EmployeeAttendanceLog::class);
  7877. //        $employeeId = $attendanceData->getEmployeeId();
  7878. //        $countId = count($employeeId);
  7879.         $totalPresent $attendanceData->createQueryBuilder('a')
  7880.             // Filter by some parameter if you want
  7881.             ->where('a.employeeId = 3')
  7882.             ->andWhere('a.isPresent = 1')
  7883.             ->select('a.isPresent')
  7884.             ->getQuery()
  7885.             ->getResult();
  7886. //        $countAt = 0;
  7887.         $count count($totalPresent);
  7888. //        $count = $countAt+$count;
  7889.         //get holiday
  7890.         $holidayStartDate $DateRange['startDate']->format('Y-m-d');
  7891.         $holidayEndDate $DateRange['endDate']->format('Y-m-d');
  7892.         $dates HumanResource::getBetweenDates($holidayStartDate$holidayEndDate);
  7893.         $dateCount count($dates);
  7894.         $totalOffDay $totalWeekends $dateCount;
  7895.         $totalCompanyWorkingDay $totalDayOfMonth $totalOffDay;
  7896.         $totalAbsent $totalCompanyWorkingDay $count;
  7897. //        foreach($dates as $compDate ){
  7898. //
  7899. //
  7900. //
  7901. //            if($date == $compDate){
  7902. //                echo $date;
  7903. //                echo $compDate;
  7904. //                echo "holiday" ;
  7905. //
  7906. //            }
  7907. //            else{
  7908. //                echo "no holiday" ;
  7909. //            }
  7910. //        }
  7911.         $twigData HumanResource::twigDataForWorkHourPolicy($em);
  7912.         return $this->render('ApplicationBundle:pages/human_resource/list:meeting_schedule_list_for_tab.html.twig', array(
  7913.             'page_title' => 'Meeting Schedule List',
  7914.             'date' => $date,
  7915.             'totalWeekends' => $totalWeekends,
  7916.             'totalCompanyWorkingDay' => $totalCompanyWorkingDay,
  7917. //            'attendanceData' => $attendanceData,
  7918. //            'employeeId' => $employeeId,
  7919.             'count' => $count,
  7920.             'totalAbsent' => $totalAbsent,
  7921.             'employeeDataDetail' => $employeeDataDetail,
  7922.             'holiday' => $DateRange,
  7923.             'holidayStartDate' => $holidayStartDate,
  7924.             'holidayEndDate' => $holidayEndDate,
  7925.             'holidayCount' => $dateCount,
  7926.             'totalOffDay' => $totalOffDay,
  7927.             'employeeIds' => $twigData['employeeIds'],
  7928.         ));
  7929.     }
  7930.     public function getEmployeeDataForDisburseAction($id)
  7931.     {
  7932.         $em $this->getDoctrine()->getManager();
  7933.         $employeeDetail $em->getRepository('ApplicationBundle:EmployeeDetails')->find($id);
  7934.         return new JsonResponse(
  7935.             array(
  7936.                 'success' => true,
  7937.                 'firstName' => $employeeDetail->getFirstName(),
  7938.             )
  7939.         );
  7940.     }
  7941.     public function BulkAttendanceAction(Request $request)
  7942.     {
  7943.         $em $this->getDoctrine()->getManager();
  7944.         $companyId $this->getLoggedUserCompanyId($request);
  7945.         if ($request->isMethod('POST')) {
  7946.             $attendance = [];
  7947.             foreach ($request->request->get('date') as $key => $val) {
  7948.                 $loginId $request->getSession()->get(UserConstants::USER_LOGIN_ID);
  7949.                 $bulkAttendance null;
  7950.                 if ($request->request->get('attId')[$key] != 0)
  7951.                     $bulkAttendance $em->getRepository('ApplicationBundle:EmployeeAttendance')->findOneBy(array(
  7952.                         'id' => $request->request->get('attId')[$key],
  7953.                     ));
  7954.                 if (!$bulkAttendance)
  7955.                     $bulkAttendance = new EmployeeAttendance;
  7956.                 $theDate = new \DateTime($request->request->get('date')[$key]);
  7957.                 $bulkAttendance->setEmployeeId($request->request->get('employeeId'));
  7958.                 $bulkAttendance->setDate($theDate);
  7959.                 $bulkAttendance->setEntry(
  7960.                     ($request->request->get('startTimeTs')[$key] == '' ||
  7961.                         $request->request->get('startTimeTs')[$key] == 'NaN' ||
  7962.                         $request->request->get('startTimeTs')[$key] == 0) ? null :
  7963.                         new \DateTime('@' $request->request->get('startTimeTs')[$key])
  7964.                 );
  7965.                 $bulkAttendance->setLastOut(($request->request->get('endTimeTs')[$key] == '' ||
  7966.                     $request->request->get('endTimeTs')[$key] == 'NaN' ||
  7967.                     $request->request->get('endTimeTs')[$key] == 0) ? null :
  7968.                     new \DateTime('@' $request->request->get('endTimeTs')[$key]));
  7969.                 $bulkAttendance->setData(json_encode(
  7970.                     array(
  7971.                         "in" => json_decode($request->request->get('entryDataIn')[$key], true),
  7972.                         "out" => json_decode($request->request->get('entryDataOut')[$key], true)
  7973.                     )
  7974.                 ));
  7975. //                $bulkAttendance->setLastStartTime(new \DateTime($request->request->get('startDate')));
  7976. //                $bulkAttendance->setIsPresent(1);
  7977.                 $bulkAttendance->setLastStartTimeTs($request->request->get('startTimeTs')[$key]);
  7978.                 $bulkAttendance->setLastEndTimeTs($request->request->get('endTimeTs')[$key]);
  7979. //                $bulkAttendance->setTotalWorkHour($request->request->get('totalWorkHour')[$key]);
  7980.                 $em->persist($bulkAttendance);
  7981.                 $em->flush();
  7982.                 $bulkAttendanceLog $em->getRepository('ApplicationBundle:EmployeeAttendanceLog')->findOneBy(array(
  7983.                     'attendance_id' => $bulkAttendance->getId(),
  7984.                 ));
  7985.                 if (!$bulkAttendanceLog)
  7986.                     $bulkAttendanceLog = new EmployeeAttendanceLog;
  7987.                 $bulkAttendanceLog->setAttendanceId($bulkAttendance->getId());
  7988.                 $bulkAttendanceLog->setEmployeeId($request->request->get('employeeId'));
  7989.                 $bulkAttendanceLog->setLastStartTime(
  7990.                     ($request->request->get('startTimeTs')[$key] == '' ||
  7991.                         $request->request->get('startTimeTs')[$key] == 'NaN' ||
  7992.                         $request->request->get('startTimeTs')[$key] == 0) ? null :
  7993.                         new \DateTime('@' $request->request->get('startTimeTs')[$key])
  7994.                 );
  7995.                 $bulkAttendanceLog->setLastEndTime(($request->request->get('endTimeTs')[$key] == '' ||
  7996.                     $request->request->get('endTimeTs')[$key] == 'NaN' ||
  7997.                     $request->request->get('endTimeTs')[$key] == 0) ? null :
  7998.                     new \DateTime('@' $request->request->get('endTimeTs')[$key]));
  7999. //                $bulkAttendance->setLastStartTime(new \DateTime($request->request->get('startDate')));
  8000.                 $bulkAttendanceLog->setIsPresent(1);
  8001.                 $bulkAttendanceLog->setLastStartTimeTs($request->request->get('startTimeTs')[$key]);
  8002.                 $bulkAttendanceLog->setLastEndTimeTs($request->request->get('endTimeTs')[$key]);
  8003.                 $bulkAttendanceLog->setTotalWorkHour($request->request->get('totalWorkHour')[$key]);
  8004. //                $bulkAttendanceLog->setPositionArray(json_encode($request->request->get('locations')[$key]));
  8005.                 $em->persist($bulkAttendanceLog);
  8006.                 $em->flush();
  8007.             }
  8008.         }
  8009.         $startDate $request->query->get('start_date''');
  8010.         $endDate $request->query->get('end_date''');
  8011.         $employeeId $request->query->get('employee_id'0);
  8012.         $existingData = [];
  8013.         $startDateTs 0;
  8014.         $endDateTs 0;
  8015.         $returnData = array(
  8016.             'page_title' => 'Bulk Attendance',
  8017.             'existingData' => $existingData,
  8018.             'startDateTs' => $startDateTs,
  8019.             'endDateTs' => $endDateTs,
  8020.         );
  8021.         if ($request->query->has('returnJson')) {
  8022.             if ($startDate != '' && $endDate != '' && $employeeId != 0) {
  8023.                 $startDateDt = new \DateTime($startDate);
  8024.                 $endDateDt = new \DateTime($endDate);
  8025.                 $startDateTs $startDateDt->format('U');
  8026.                 $endDateTs $endDateDt->format('U');
  8027.                 $attendanceQuery $em->getRepository('ApplicationBundle:EmployeeAttendance')
  8028.                     ->createQueryBuilder('p')
  8029.                     ->where("p.employeeId = " $employeeId)
  8030. //                ->andWhere("p.date => '" . ($startDateDt->format('Y-m-d'))."'")
  8031.                     ->andWhere("p.date <= :last")
  8032.                     ->andWhere("p.date >= :start")
  8033.                     ->setParameter('start'$startDateDt)
  8034.                     ->setParameter('last'$endDateDt);
  8035.                 $attendanceResults $attendanceQuery->getQuery()->getResult();
  8036.                 foreach ($attendanceResults as $att) {
  8037.                     $entryDateTime null;
  8038.                     $outDateTime null;
  8039.                     if ($att->getEntry()) $entryDateTime = new \DateTime($att->getDate()->format('Y-m-d') . ' ' $att->getEntry()->format('H:i:00 +0000'));
  8040.                     if ($att->getLastOut()) $outDateTime = new \DateTime($att->getDate()->format('Y-m-d') . ' ' $att->getLastOut()->format('H:i:00 +0000'));
  8041.                     $attData = array(
  8042.                         'id' => $att->getId(),
  8043.                         'date_str' => $att->getDate()->format('Y-m-d'),
  8044.                         'date_str_full' => $att->getDate()->format('Y-m-d H:i:s'),
  8045.                         'in_time_full' => $entryDateTime $entryDateTime->format(DATE_RFC2822) : '',
  8046.                         'date_ts' => $att->getDate()->format('U'),
  8047.                         'in_time' => $entryDateTime $entryDateTime->format('H:i:s') : '',
  8048.                         'in_time_ts' => $entryDateTime $entryDateTime->format('U') : 0,
  8049.                         'last_out_time' => $outDateTime $outDateTime->format('H:i:s') : '',
  8050.                         'last_out_time_ts' => $outDateTime $outDateTime->format('U') : '',
  8051.                     );
  8052.                     $locations = [];
  8053.                     $locList = [];
  8054.                     $logHere $em->getRepository('ApplicationBundle:EmployeeAttendanceLog')->findOneBy(array(
  8055.                         'attendance_id' => $att->getId(),
  8056.                     ));
  8057.                     if ($logHere)
  8058.                         $locList json_decode($logHere->getPositionArray(), true);
  8059.                     if ($locList == null)
  8060.                         $locList = [];
  8061.                     $entry_data json_decode($att->getData(), true);
  8062.                     if ($entry_data == null$entry_data = [];
  8063.                     $lastLat 0;
  8064.                     $lastLng 0;
  8065.                     foreach ($locList as $lg) {
  8066.                         $dist 0;
  8067.                         if (isset($lg['lat'])) {
  8068.                             if ($lastLat == 0) {
  8069.                                 $lastLat $lg['lat'];
  8070.                                 $lastLng $lg['lng'];
  8071.                             }
  8072.                             $theta $lastLng $lg['lng'];
  8073.                             $dist sin(deg2rad($lastLat)) * sin(deg2rad($lg['lat'])) + cos(deg2rad($lastLat)) * cos(deg2rad($lg['lat'])) * cos(deg2rad($theta));
  8074.                             $dist acos($dist);
  8075.                             $dist rad2deg($dist);
  8076.                             $miles $dist 60 1.1515;
  8077.                             $dist $miles 1609.344;
  8078.                             if (abs($dist) > 1000) {
  8079.                                 $locations[] = array(
  8080.                                     'ts' => $lg['ts'],
  8081.                                     'lat' => $lg['lat'],
  8082.                                     'lng' => $lg['lng'],
  8083.                                 );
  8084.                                 $lastLat $lg['lat'];
  8085.                                 $lastLng $lg['lng'];
  8086.                             }
  8087.                         }
  8088.                     }
  8089.                     $attData['locations'] = $locations;
  8090.                     $attData['entryData'] = $entry_data;
  8091.                     $existingData[$att->getDate()->format('U')] = $attData;
  8092.                 }
  8093.             }
  8094.             $returnData = array(
  8095.                 'page_title' => 'Bulk Attendance',
  8096.                 'existingData' => $existingData,
  8097.                 'startDateTs' => $startDateTs,
  8098.                 'endDateTs' => $endDateTs,
  8099.             );
  8100.             return new JsonResponse($returnData);
  8101.         } else
  8102.             return $this->render('ApplicationBundle:pages/human_resource/attendance:bulk_attendance.html.twig'$returnData);
  8103.     }
  8104.     public function CreateAttendanceAmendmentAction(Request $request$id 0)
  8105.     {
  8106.         $em $this->getDoctrine()->getManager();
  8107.         $companyId $this->getLoggedUserCompanyId($request);
  8108.         $extDocData = [];
  8109.         if ($request->isMethod('POST')) {
  8110.             $em $this->getDoctrine()->getManager();
  8111.             $entity_id array_flip(GeneralConstant::$Entity_list)['AttendanceAmendment']; //change
  8112.             $dochash $request->request->get('docHash'); //change
  8113.             $loginId $request->getSession()->get(UserConstants::USER_LOGIN_ID);
  8114.             $approveRole $request->request->get('approvalRole');
  8115.             $approveHash $request->request->get('approvalHash');
  8116.             if ($dochash == '') {
  8117.                 $numberHash MiscActions::GetNumberHash($em'ATAM'$request->request->get('prefix_hash'$request->request->get('employeeId'0)), $request->request->get('assoc_hash'0), ''1);
  8118.                 $dochash 'ATAM' '/' $request->request->get('prefix_hash'$request->request->get('employeeId'0)) . '/' $request->request->get('assoc_hash'0) . '/' $numberHash;
  8119.             } else
  8120.                 $numberHash $request->request->get('number_hash');
  8121.             if (!DocValidation::isInsertable($em$entity_id$dochash,
  8122.                 $loginId$approveRole$approveHash$id)
  8123.             ) {
  8124.                 if ($request->request->has('returnJson')) {
  8125.                     return new JsonResponse(array(
  8126.                         'success' => false,
  8127.                         'documentHash' => 0,
  8128.                         'documentId' => 0,
  8129.                     ));
  8130.                 } else
  8131.                     $this->addFlash(
  8132.                         'error',
  8133.                         'Sorry Could not insert Data.'
  8134.                     );
  8135.             } else {
  8136.                 $funcname 'AttendanceAmendment';
  8137.                 $doc_id $id;
  8138.                 DeleteDocument::$funcname($em$doc_id0);
  8139.                 $attendanceAmendment = new AttendanceAmendment();
  8140.                 $attendanceAmendment->setDocumentHash($dochash);
  8141.                 $attendanceAmendment->setAttendanceAmendmentDate(new \DateTime($request->request->get('docDate''')));
  8142.                 $attendanceAmendment->setStartDate(new \DateTime($request->request->get('startDate''')));
  8143.                 $attendanceAmendment->setEndDate(new \DateTime($request->request->get('endDate''')));
  8144.                 $attendanceAmendment->setTypeHash('ATAM');
  8145.                 $attendanceAmendment->setPrefixHash($request->request->get('prefix_hash'0));
  8146.                 $attendanceAmendment->setAssocHash($request->request->get('assoc_hash'0));
  8147.                 $attendanceAmendment->setNumberHash($numberHash);
  8148.                 $attendanceAmendment->setCreatedLoginId($request->getSession()->get(UserConstants::USER_LOGIN_ID));
  8149.                 $attendanceAmendment->setApproved(array_flip(GeneralConstant::$approvalStatus)['pending']);
  8150.                 $attendanceAmendment->setAutoCreated($request->request->get('fullApprove'0));
  8151.                 $attendanceAmendment->setEmployeeId($request->request->get('forcedEmployeeId'$request->request->get('employeeId'0)));
  8152. //                $attendanceAmendment->setAutocreated(0);
  8153.                 if ($request->request->has('dataArrayJson')) {
  8154.                     $attendanceAmendment->setData($request->request->get('dataArrayJson''[]'));
  8155.                 } else {
  8156.                     $arr = [
  8157.                     ];
  8158.                     //dump($arr);
  8159.                     foreach ($request->request->get('date', []) as $key => $val) {
  8160.                         if ($request->request->get('isChanged')[$key] == 1) {
  8161.                             $dt = array(
  8162.                                 'enabled' => 1,
  8163.                                 'attId' => $request->request->get('attId')[$key],
  8164.                                 'note' => $request->request->get('note')[$key],
  8165.                                 'startTimeTs' => $request->request->get('startTimeTs')[$key],
  8166.                                 'endTimeTs' => $request->request->get('endTimeTs')[$key],
  8167.                                 'totalWorkHour' => $request->request->get('totalWorkHour')[$key],
  8168.                                 'entryDataIn' => json_decode($request->request->get('entryDataIn')[$key], true),
  8169.                                 'entryDataOut' => json_decode($request->request->get('entryDataOut')[$key], true),
  8170.                             );
  8171.                             $arr[$val] = $dt;
  8172.                         }
  8173.                     }
  8174.                     $attendanceAmendment->setData(json_encode($arr));
  8175.                 }
  8176.                 $em->persist($attendanceAmendment);
  8177.                 $em->flush();
  8178.                 $ID $attendanceAmendment->getAttendanceAmendmentId();
  8179.                 //now add Approval info
  8180.                 $loginId $request->getSession()->get(UserConstants::USER_LOGIN_ID);
  8181.                 $approveRole 1;  //created
  8182.                 $options = array(
  8183.                     'notification_enabled' => $this->container->getParameter('notification_enabled'),
  8184.                     'notification_server' => $this->container->getParameter('notification_server'),
  8185.                     'appId' => $request->getSession()->get(UserConstants::USER_APP_ID),
  8186.                     'url' => $this->generateUrl(
  8187.                         GeneralConstant::$Entity_list_details[array_flip(GeneralConstant::$Entity_list)['AttendanceAmendment']]
  8188.                         ['entity_view_route_path_name']
  8189.                     )
  8190.                 );
  8191.                 System::setApprovalInfo($this->getDoctrine()->getManager(), $options,
  8192.                     array_flip(GeneralConstant::$Entity_list)['AttendanceAmendment'],
  8193.                     $ID,
  8194.                     $request->getSession()->get(UserConstants::USER_LOGIN_ID)    //journal voucher
  8195.                 );
  8196.                 if ($request->request->get('fullApprove'0) == 1) {
  8197.                     DeleteDocument::AttendanceAmendment($em$ID);
  8198.                 } else {
  8199.                     System::createEditSignatureHash($this->getDoctrine()->getManager(), array_flip(GeneralConstant::$Entity_list)['AttendanceAmendment'], $ID,
  8200.                         $loginId,
  8201.                         $approveRole,
  8202.                         $request->request->get('approvalHash'));
  8203.                     $url $this->generateUrl(
  8204.                         'view_attendance_amendment'
  8205.                     );
  8206.                     if ($request->request->has('returnJson')) {
  8207.                         return new JsonResponse(array(
  8208.                             'success' => true,
  8209.                             'documentHash' => $dochash,
  8210.                             'documentId' => $ID,
  8211.                             'viewUrl' => $url "/" $ID,
  8212.                         ));
  8213.                     } else {
  8214.                         $this->addFlash(
  8215.                             'success',
  8216.                             'Attendance Amendment Note Added.'
  8217.                         );
  8218.                         return $this->redirect($url "/" $ID);
  8219.                     }
  8220.                 }
  8221.             }
  8222.         }
  8223.         if ($id == 0) {
  8224.         } else {
  8225.             $extDoc $em->getRepository('ApplicationBundle:AttendanceAmendment')->findOneBy(
  8226.                 array(
  8227.                     'salesOrderId' => $id///material
  8228.                 )
  8229.             );
  8230.             //now if its not editable, redirect to view
  8231.             if ($extDoc) {
  8232.                 if ($extDoc->getEditFlag() != 1) {
  8233.                     $url $this->generateUrl(
  8234.                         'view_attendance_amendment'
  8235.                     );
  8236.                     return $this->redirect($url "/" $id);
  8237.                 } else {
  8238.                     $extDocData $extDoc;
  8239.                 }
  8240.             } else {
  8241.             }
  8242.         }
  8243.         $startDate $request->query->get('start_date''');
  8244.         $endDate $request->query->get('end_date''');
  8245.         $employeeId $request->query->get('employee_id'0);
  8246.         $existingData = [];
  8247.         $startDateTs 0;
  8248.         $endDateTs 0;
  8249.         $returnData = array(
  8250.             'page_title' => 'Attendance Amendment',
  8251.             'existingData' => $existingData,
  8252.             'startDateTs' => $startDateTs,
  8253.             'extDocData' => $extDocData,
  8254.             'endDateTs' => $endDateTs,
  8255.         );
  8256.         if ($request->query->has('returnJson')) {
  8257.             if ($startDate != '' && $endDate != '' && $employeeId != 0) {
  8258.                 $startDateDt = new \DateTime($startDate);
  8259.                 $endDateDt = new \DateTime($endDate);
  8260.                 $startDateTs $startDateDt->format('U');
  8261.                 $endDateTs $endDateDt->format('U');
  8262.                 $attendanceQuery $em->getRepository('ApplicationBundle:EmployeeAttendance')
  8263.                     ->createQueryBuilder('p')
  8264.                     ->where("p.employeeId = " $employeeId)
  8265. //                ->andWhere("p.date => '" . ($startDateDt->format('Y-m-d'))."'")
  8266.                     ->andWhere("p.date <= :last")
  8267.                     ->andWhere("p.date >= :start")
  8268.                     ->setParameter('start'$startDateDt)
  8269.                     ->setParameter('last'$endDateDt);
  8270.                 $attendanceResults $attendanceQuery->getQuery()->getResult();
  8271.                 foreach ($attendanceResults as $att) {
  8272.                     $entryDateTime null;
  8273.                     $outDateTime null;
  8274.                     if ($att->getEntry()) $entryDateTime = new \DateTime($att->getDate()->format('Y-m-d') . ' ' $att->getEntry()->format('H:i:00 +0000'));
  8275.                     if ($att->getLastOut()) $outDateTime = new \DateTime($att->getDate()->format('Y-m-d') . ' ' $att->getLastOut()->format('H:i:00 +0000'));
  8276.                     $attData = array(
  8277.                         'id' => $att->getId(),
  8278.                         'date_str' => $att->getDate()->format('Y-m-d'),
  8279.                         'date_str_full' => $att->getDate()->format('Y-m-d H:i:s'),
  8280.                         'in_time_full' => $entryDateTime $entryDateTime->format(DATE_RFC2822) : '',
  8281.                         'date_ts' => $att->getDate()->format('U'),
  8282.                         'in_time' => $entryDateTime $entryDateTime->format('H:i:s') : '',
  8283.                         'in_time_ts' => $entryDateTime $entryDateTime->format('U') : 0,
  8284.                         'last_out_time' => $outDateTime $outDateTime->format('H:i:s') : '',
  8285.                         'last_out_time_ts' => $outDateTime $outDateTime->format('U') : '',
  8286.                     );
  8287.                     $locations = [];
  8288.                     $locList = [];
  8289.                     $logHere $em->getRepository('ApplicationBundle:EmployeeAttendanceLog')->findOneBy(array(
  8290.                         'attendance_id' => $att->getId(),
  8291.                     ));
  8292.                     if ($logHere)
  8293.                         $locList json_decode($logHere->getPositionArray(), true);
  8294.                     if ($locList == null)
  8295.                         $locList = [];
  8296.                     $entry_data json_decode($att->getData(), true);
  8297.                     if ($entry_data == null$entry_data = [];
  8298.                     $lastLat 0;
  8299.                     $lastLng 0;
  8300.                     foreach ($locList as $lg) {
  8301.                         $dist 0;
  8302.                         if (isset($lg['lat'])) {
  8303.                             if ($lastLat == 0) {
  8304.                                 $lastLat $lg['lat'];
  8305.                                 $lastLng $lg['lng'];
  8306.                             }
  8307.                             $theta $lastLng $lg['lng'];
  8308.                             $dist sin(deg2rad($lastLat)) * sin(deg2rad($lg['lat'])) + cos(deg2rad($lastLat)) * cos(deg2rad($lg['lat'])) * cos(deg2rad($theta));
  8309.                             $dist acos($dist);
  8310.                             $dist rad2deg($dist);
  8311.                             $miles $dist 60 1.1515;
  8312.                             $dist $miles 1609.344;
  8313.                             if (abs($dist) > 1000) {
  8314.                                 $locations[] = array(
  8315.                                     'ts' => $lg['ts'],
  8316.                                     'lat' => $lg['lat'],
  8317.                                     'lng' => $lg['lng'],
  8318.                                 );
  8319.                                 $lastLat $lg['lat'];
  8320.                                 $lastLng $lg['lng'];
  8321.                             }
  8322.                         }
  8323.                     }
  8324.                     $attData['locations'] = $locations;
  8325.                     $attData['entryData'] = $entry_data;
  8326.                     $existingData[$att->getDate()->format('U')] = $attData;
  8327.                 }
  8328.             }
  8329.             $returnData = array(
  8330.                 'page_title' => 'Attendance Amendment',
  8331.                 'existingData' => $existingData,
  8332.                 'startDateTs' => $startDateTs,
  8333.                 'extDocData' => $extDocData,
  8334.                 'endDateTs' => $endDateTs,
  8335.             );
  8336.             return new JsonResponse($returnData);
  8337.         } else
  8338.             return $this->render('ApplicationBundle:pages/human_resource/attendance:create_attendance_amendment.html.twig'$returnData);
  8339.     }
  8340.     public function AttendanceAmendmentListAction(Request $request)
  8341.     {
  8342.         $data = [];
  8343.         return $this->render('ApplicationBundle:pages/human_resource/list:attendance_amendment_list.html.twig',
  8344.             array(
  8345.                 'page_title' => 'Attendance Amendment List',
  8346.                 'data' => $data
  8347.             )
  8348.         );
  8349.     }
  8350.     public function ViewAttendanceAmendmentAction(Request $request$id)
  8351.     {
  8352.         $em $this->getDoctrine()->getManager();
  8353.         $dt HumanResource::GetAttendanceAmendmentDetails($em$id);
  8354.         return $this->render('ApplicationBundle:pages/human_resource/views:view_attendance_amendment.html.twig',
  8355.             array(
  8356.                 'page_title' => 'Attendance Amendment',
  8357.                 'data' => $dt,
  8358.                 'approval_data' => System::checkIfApprovalExists($emarray_flip(GeneralConstant::$Entity_list)['AttendanceAmendment'],
  8359.                     $id$request->getSession()->get(UserConstants::USER_LOGIN_ID)),
  8360.                 'document_log' => System::getDocumentLog($this->getDoctrine()->getManager(),
  8361.                     array_flip(GeneralConstant::$Entity_list)['AttendanceAmendment'],
  8362.                     $id,
  8363.                     $dt['created_by'],
  8364.                     $dt['edited_by'])
  8365.             )
  8366.         );
  8367.     }
  8368.     public function PrintAttendanceAmendmentAction(Request $request$id)
  8369.     {
  8370.         $em $this->getDoctrine()->getManager();
  8371.         $dt HumanResource::GetAttendanceAmendmentDetails($em$id);
  8372.         $company_data Company::getCompanyData($em1);
  8373.         $document_mark = array(
  8374.             'original' => '/images/Original-Stamp-PNG-Picture.png',
  8375.             'copy' => ''
  8376.         );
  8377.         if ($request->query->has('pdf') && $this->get('knp_snappy.pdf')) {
  8378.             $html $this->renderView('@Inventory/pages/print/print_stock_received_note.html.twig',
  8379.                 array(
  8380.                     //full array here
  8381.                     'pdf' => true,
  8382.                     'page_title' => 'Stock Received Note',
  8383.                     'export' => 'pdf,print',
  8384.                     'data' => $dt,
  8385.                     'approval_data' => System::checkIfApprovalExists($emarray_flip(GeneralConstant::$Entity_list)['AttendanceAmendment'],
  8386.                         $id$request->getSession()->get(UserConstants::USER_LOGIN_ID)),
  8387.                     'document_log' => System::getDocumentLog($this->getDoctrine()->getManager(),
  8388.                         array_flip(GeneralConstant::$Entity_list)['AttendanceAmendment'],
  8389.                         $id,
  8390.                         $dt['created_by'],
  8391.                         $dt['edited_by']),
  8392.                     'document_mark_image' => $document_mark['original'],
  8393.                     'company_name' => $company_data->getName(),
  8394.                     'company_data' => $company_data,
  8395.                     'company_address' => $company_data->getAddress(),
  8396.                     'company_image' => $company_data->getImage(),
  8397.                     'invoice_footer' => $company_data->getInvoiceFooter(),
  8398.                     'red' => 0
  8399.                 )
  8400.             );
  8401.             $pdf_response $this->get('knp_snappy.pdf')->getOutputFromHtml($html, array(
  8402. //                'orientation' => 'landscape',
  8403. //                'enable-javascript' => true,
  8404. //                'javascript-delay' => 1000,0
  8405.                 'no-stop-slow-scripts' => false,
  8406.                 'no-background' => false,
  8407.                 'lowquality' => false,
  8408.                 'encoding' => 'utf-8',
  8409. //            'images' => true,
  8410. //            'cookie' => array(),
  8411.                 'dpi' => 300,
  8412.                 'image-dpi' => 300,
  8413. //                'enable-external-links' => true,
  8414. //                'enable-internal-links' => true
  8415.             ));
  8416.             return new Response(
  8417.                 $pdf_response,
  8418.                 200,
  8419.                 array(
  8420.                     'Content-Type' => 'application/pdf',
  8421.                     'Content-Disposition' => 'attachment; filename="stock_received_note_' $id '.pdf"'
  8422.                 )
  8423.             );
  8424.         }
  8425.         return $this->render('ApplicationBundle:pages/human_resource/views:view_attendance_amendment.html.twig',
  8426.             array(
  8427.                 'page_title' => 'Attendance Amendment',
  8428.                 'data' => $dt,
  8429.                 'approval_data' => System::checkIfApprovalExists($emarray_flip(GeneralConstant::$Entity_list)['AttendanceAmendment'],
  8430.                     $id$request->getSession()->get(UserConstants::USER_LOGIN_ID)),
  8431.                 'document_log' => System::getDocumentLog($this->getDoctrine()->getManager(),
  8432.                     array_flip(GeneralConstant::$Entity_list)['AttendanceAmendment'],
  8433.                     $id,
  8434.                     $dt['created_by'],
  8435.                     $dt['edited_by'])
  8436.             )
  8437.         );
  8438.     }
  8439.     public function createRoomAction(Request $request)
  8440.     {
  8441.         $em $this->getDoctrine()->getManager();
  8442.         $companyId $this->getLoggedUserCompanyId($request);
  8443.         if ($request->isMethod('POST')) {
  8444.             $loginId $request->getSession()->get(UserConstants::USER_LOGIN_ID);
  8445.             $room = new Room;
  8446.             $room->setRoomNo($request->request->get('RoomNo'));
  8447.             //$room->setRoomName($request->request->get('RoomName'));
  8448.             $room->setBuilding($request->request->get('buildingName'));
  8449.             $room->setFloor($request->request->get('floor'));
  8450.             $room->setCapacity($request->request->get('capacity'));
  8451.             $room->setCreatedLoginId($request->getSession()->get(UserConstants::USER_LOGIN_ID));
  8452.             $em->persist($room);
  8453.             $em->flush();
  8454.         }
  8455.         return $this->render('ApplicationBundle:pages/human_resource/input_forms:create_room.html.twig', array(
  8456.             'page_title' => 'Add Room',
  8457.         ));
  8458.     }
  8459.     public function ExpenseTypeAction()
  8460.     {
  8461.         $expenseType HumanResourceConstant::$employeeExpenseAllowanceTypes;
  8462.         $expenseTypeArray = [];
  8463.         foreach ($expenseType as $k => $dt) {
  8464.             $dt['id'] = $k;
  8465.             $newSegs = [];
  8466.             foreach ($dt['segregations'] as $l => $s) {
  8467.                 $newOptions = [];
  8468.                 foreach ($s['options'] as $l2 => $s2) {
  8469.                     $s3 = array(
  8470.                         'value' => $l2,
  8471.                         'text' => $s2,
  8472.                     );
  8473.                     $newOptions[] = $s3;
  8474.                 }
  8475.                 $s['options'] = $newOptions;
  8476.                 if (is_string($s['defaultVal'])) $s['defaultVal'] = [$s['defaultVal']];
  8477.                 $newSegs[] = $s;
  8478.             }
  8479.             $dt['segregations'] = $newSegs;
  8480.             $expenseTypeArray[] = $dt;
  8481.         }
  8482.         return new JsonResponse(
  8483.             array(
  8484.                 'success' => true,
  8485.                 'expenseType' => $expenseType,
  8486.                 'expenseTypeArray' => $expenseTypeArray,
  8487.             )
  8488.         );
  8489.     }
  8490.     public function DemoDataTableAction()
  8491.     {
  8492.         return $this->render('ApplicationBundle:pages/human_resource/list:demo_data_table.html.twig', array(
  8493.             'page_title' => 'Add Room',
  8494.         ));
  8495.     }
  8496.     public function workEnrtyAction(Request $request)
  8497.     {
  8498. //        $em = $this->getDoctrine()->getManager();
  8499. //        $companyId = $this->getLoggedUserCompanyId($request);
  8500. //        if ($request->isMethod('POST')) {
  8501. //            $loginId = $request->getSession()->get(UserConstants::USER_LOGIN_ID);
  8502. //            $labour = new Labour();
  8503. //            $labour->setLabourName($request->request->get('labourName'));
  8504. //            $labour->setNidNumber($request->request->get('nidNumber'));
  8505. //            $em->persist($labour);
  8506. //            $em->flush();
  8507. //            $this->addFlash(
  8508. //                'success',
  8509. //                'Labour Added'
  8510. //            );
  8511. //        }
  8512.         return $this->render('ApplicationBundle:pages/human_resource/input_forms:work_entry.html.twig', array(
  8513.             'page_title' => 'Work Entry',
  8514.         ));
  8515.     }
  8516.     public function ViewContractLetterAction(Request $request$id)
  8517.     {
  8518.         $em $this->getDoctrine()->getManager();
  8519.         $employeeDetail $em->getRepository('ApplicationBundle:EmployeeDetails')->find($id);
  8520. //        $employeeData = [];
  8521. //        foreach ($employeeDetails as $employeeDetail) {
  8522. //            $data = array(
  8523. //                'firstName' => $employeeDetail->getNid(),
  8524. //
  8525. //
  8526. //
  8527. //            );
  8528. //
  8529. //
  8530. //            $employeeData[] = $data;
  8531. //        }
  8532.         return $this->render('ApplicationBundle:pages/human_resource/views:viewContractLetter.html.twig', array(
  8533.             'page_title' => 'Contract Letter',
  8534.             'employeeDetail' => $employeeDetail
  8535.         ));
  8536.     }
  8537.     public function getAttendanceReportForEmployeeAction(Request $request)
  8538.     {
  8539.         $em $this->getDoctrine()->getManager();
  8540.         $session $request->getSession();
  8541.         $fromDateRow = (new \DateTime($request->get('start_date''')));
  8542. //        $fromDate = $fromDateRow->format("M d, Y");
  8543.         $toDateRow = (new \DateTime($request->get('end_date'$fromDateRow) . ' 23:59:59'));
  8544. //        $toDate = $toDateRow->format("M d, Y");
  8545. //        $startDate = "2025-02-13";
  8546. //        $endDate = "2025-02-16";
  8547.         $userId $session->get(UserConstants::USER_ID);
  8548.         $attendanceDetails $em->getRepository('ApplicationBundle:EmployeeAttendance')->createQueryBuilder('A')
  8549. //            ->select('A.createdAt','A.data')
  8550.             ->where('A.sysId = :userId')
  8551.             ->andWhere('A.createdAt >=  :startDate')
  8552.             ->andWhere('A.createdAt <=  :endDate')
  8553.             ->setParameter('userId'$userId)
  8554.             ->setParameter('startDate'$fromDateRow)
  8555.             ->setParameter('endDate'$toDateRow)
  8556.             ->getQuery()
  8557.             ->getResult();
  8558.         $attendance = [];
  8559.         $dt = [];
  8560.         foreach ($attendanceDetails as $data) {
  8561.             $in_out_data json_decode($data->getData(), true);
  8562.             $new_in_data = [];
  8563.             $elapsed_data = [];
  8564.             $new_out_data = [];
  8565.             if ($in_out_data == null$in_out_data = [];
  8566.             if (isset($in_out_data['in'])) {
  8567.                 foreach ($in_out_data['in'] as $ind => $g) {
  8568.                     if (!isset($elapsed_data[$ind])) {
  8569.                         $elapsed_data[$ind] = 0;
  8570.                     }
  8571.                     $the_time = new \DateTime($data->getDate()->format('Y-m-d ') . $g ' +0000');
  8572.                     $new_in_data[] = $the_time->format('U');
  8573.                 }
  8574.             }
  8575.             if (isset($in_out_data['out'])) {
  8576.                 foreach ($in_out_data['out'] as $ind => $g) {
  8577.                     if (!isset($elapsed_data[$ind])) {
  8578.                         $elapsed_data[$ind] = 0;
  8579.                     }
  8580.                     $the_time = new \DateTime($data->getDate()->format('Y-m-d ') . $g ' +0000');
  8581.                     $new_out_data[] = $the_time->format('U');
  8582.                     if (isset($new_in_data[$ind])) {
  8583.                         $elapsed_data[$ind] = $new_out_data[$ind] - $new_in_data[$ind];
  8584.                     }
  8585.                 }
  8586.             }
  8587.             $list = array(
  8588.                 'date' => $data->getDate()->format('F d Y'),
  8589.                 'attendanceData' => [
  8590.                     'in' => $new_in_data,
  8591.                     'out' => $new_out_data,
  8592.                     'elapsedSec' => $elapsed_data,
  8593.                 ]
  8594.             );
  8595.             $dt[] = $list;
  8596.         }
  8597.         $count count($attendance);
  8598. //        for ($i=0;$i < $count; $i++){
  8599. //            $dt[] = $attendance[$i]['date'];
  8600. //            $dt[] = ($attendance[$i]['attendanceData']);
  8601. //        }
  8602. ////        $decodeData = json_decode($dt, true);
  8603. //
  8604. //        $work_hours = [];
  8605. //
  8606. //        foreach ($dt as $index => $entry) {
  8607. //            $in_times = $entry['in'];
  8608. //            $out_times = $entry['out'];
  8609. //
  8610. //
  8611. //            $count = min(count($in_times), count($out_times));
  8612. //
  8613. //            for ($i = 0; $i < $count; $i++) {
  8614. //                $time_in = new DateTime($in_times[$i]);
  8615. //                $time_out = new DateTime($out_times[$i]);
  8616. //
  8617. //
  8618. //                $interval = $time_in->diff($time_out);
  8619. //                $total_hours = $interval->format('%h');
  8620. //                $total_minutes = $interval->format('%i');
  8621. //
  8622. //
  8623. //                $work_hours[] = [
  8624. ////                    "set" => $index + 1,
  8625. //                    "in" => $in_times[$i],
  8626. //                    "out" => $out_times[$i],
  8627. //                    "worked" => "$total_hours hours, $total_minutes minutes"
  8628. //                ];
  8629. //            }
  8630. //        }
  8631. //
  8632. ////        foreach ($work_hours as $work) {
  8633. ////           return new  JsonResponse(
  8634. ////               array(
  8635. ////                   'in'=>$work['in'],
  8636. ////                   'out' => $work['out'],
  8637. ////                   'hour' => $work['worked']
  8638. ////               )
  8639. ////           ) ;
  8640. //////            echo "Set {$work['set']} - IN: {$work['in']} - OUT: {$work['out']} => Worked: {$work['worked']}\n";
  8641. ////        }
  8642.         return new JsonResponse($dt);
  8643.     }
  8644.     public function getTotalWorkHourAction(Request $request)
  8645.     {
  8646.         $em $this->getDoctrine()->getManager();
  8647.         $currentDate = new \DateTime(date('y-m-d'));
  8648.         $session $request->getSession();
  8649.         $token $session->get(UserConstants::USER_TOKEN);
  8650.         $employeeId $session->get(UserConstants::USER_EMPLOYEE_ID);
  8651.         $planningItemId $session->get(UserConstants::USER_CURRENT_PLANNING_ITEM_ID);
  8652.         $attendanceData $em->getRepository('ApplicationBundle:EmployeeAttendance');
  8653.         $currentStatus HumanResource::getCurrentStatusFromDb($attendanceData$employeeId$currentDate);
  8654.         $providedToken $request->headers->get('auth-token');
  8655.         if (empty($providedToken) || $providedToken !== $token) {
  8656.             return new JsonResponse([
  8657.                 'status' => 'error',
  8658.                 'message' => 'Token not match or missing',
  8659.             ], 401);
  8660.         }
  8661.         $planningItemDetails $em->getRepository(PlanningItem::class)->createQueryBuilder('p')
  8662.             ->select('p.itemAlias')
  8663.             ->where('p.id = :planningItemId')
  8664.             ->setParameter('planningItemId'$planningItemId)
  8665.             ->getQuery()
  8666.             ->getResult();
  8667.         // Check if "data" key exists and contains "in" times
  8668.         if (empty($currentStatus["data"]["in"])) {
  8669.             return new JsonResponse([
  8670. //                'message' => 'No attendance data available',
  8671.                 'currentStatus' => $currentStatus,
  8672.                 'totalWorkingTime' => '00:00:00'
  8673.             ]);
  8674.         }
  8675.         $totalSeconds 0;
  8676.         for ($i 0$i count($currentStatus["data"]["in"]); $i++) {
  8677.             $inTime $currentStatus["data"]["in"][$i];
  8678.             // Check if "out" time exists for this "in" time
  8679.             if (!isset($currentStatus["data"]["out"][$i])) {
  8680.                 continue; // Skip this entry if there is no out time
  8681.             }
  8682.             $outTime $currentStatus["data"]["out"][$i];
  8683.             // Calculate the difference
  8684.             $totalSeconds += ($outTime $inTime);
  8685.         }
  8686.         // If no valid time pairs were found, return 00:00:00
  8687. //        if ($totalSeconds == 0) {
  8688. //            return new JsonResponse([
  8689. //                'message' => 'No complete in-out records found',
  8690. //                'totalWorkingTime' => '00:00:00'
  8691. //            ]);
  8692. //        }
  8693.         // Convert total seconds to hours, minutes, and seconds
  8694.         $hours floor($totalSeconds 3600);
  8695.         $minutes floor(($totalSeconds 3600) / 60);
  8696.         $seconds $totalSeconds 60;
  8697.         $totalWorkingTime sprintf("%02d:%02d:%02d"$hours$minutes$seconds);
  8698.         return new JsonResponse([
  8699.             'taskName' => isset($planningItemDetails[0]) ? $planningItemDetails[0]['itemAlias'] : '',
  8700.             'currentStatus' => $currentStatus,
  8701.             'totalWorkingTime' => $totalWorkingTime,
  8702.         ]);
  8703.     }
  8704. //    public function getEmployeeDataAction(Request $request)
  8705. //    {
  8706. //        $em = $this->getDoctrine()->getManager();
  8707. //        $session = $request->getSession();
  8708. //        $employeeId = $session->get(UserConstants::USER_EMPLOYEE_ID);
  8709. //
  8710. //
  8711. //        $employeeDetails = $em->getRepository('ApplicationBundle:EmployeeDetails')->createQueryBuilder('E')
  8712. //            ->select('E.firstname', 'E.lastname', 'E.nid', 'E.tin','E.image', 'P.positionName')
  8713. //            ->addSelect('A.current_balance')
  8714. //            ->leftJoin('ApplicationBundle:SysDepartmentPosition', 'P', 'WITH', 'E.desg = P.positionId')
  8715. //            ->leftJoin('ApplicationBundle:Employee', 'EMP', 'WITH', 'EMP.employeeId = E.id')
  8716. //            ->leftJoin('ApplicationBundle:AccAccountsHead', 'A', 'WITH', 'EMP.accountsHeadId = A.accountsHeadId')
  8717. //            ->where('E.id = :employeeId')
  8718. //            ->setParameter('employeeId', $employeeId)
  8719. //            ->getQuery()
  8720. //            ->getResult();
  8721. //
  8722. //        return new JsonResponse($employeeDetails[0]);
  8723. //    }
  8724. //    public function getEmployeeDataAction(Request $request)
  8725. //    {
  8726. //        $em = $this->getDoctrine()->getManager();
  8727. //        $session = $request->getSession();
  8728. //        $employeeId = $session->get(UserConstants::USER_EMPLOYEE_ID);
  8729. //        $image = $session->get(UserConstants::USER_IMAGE);
  8730. //        $absoluteUrl = $this->generateUrl('dashboard', [], UrlGenerator::ABSOLUTE_URL);
  8731. //
  8732. //        $employeeDetails = $em->getRepository('ApplicationBundle:EmployeeDetails')->createQueryBuilder('E')
  8733. //            ->select('E.firstname', 'E.lastname', 'E.nid', 'E.tin', 'E.image', 'P.positionName')
  8734. //            ->addSelect('A.current_balance')
  8735. //            ->leftJoin('ApplicationBundle:SysDepartmentPosition', 'P', 'WITH', 'E.desg = P.positionId')
  8736. //            ->leftJoin('ApplicationBundle:Employee', 'EMP', 'WITH', 'EMP.employeeId = E.id')
  8737. //            ->leftJoin('ApplicationBundle:AccAccountsHead', 'A', 'WITH', 'EMP.accountsHeadId = A.accountsHeadId')
  8738. //            ->where('E.id = :employeeId')
  8739. //            ->setParameter('employeeId', $employeeId)
  8740. //            ->getQuery()
  8741. //            ->getResult();
  8742. //
  8743. //        // If image is null or empty, assign empty string
  8744. //        if (empty($employeeDetails['image'])) {
  8745. //            $employeeDetails['image'] =  $image;
  8746. //        }
  8747. //
  8748. //        return new JsonResponse($employeeDetails);
  8749. //    }
  8750.     public function getEmployeeDataAction(Request $request)
  8751.     {
  8752.         $em $this->getDoctrine()->getManager();
  8753.         $session $request->getSession();
  8754.         $employeeId $session->get(UserConstants::USER_EMPLOYEE_ID);
  8755.         $image $session->get(UserConstants::USER_IMAGE);
  8756.         $absoluteUrl $this->generateUrl('dashboard', [], UrlGenerator::ABSOLUTE_URL);
  8757.         $userImage $session->get(UserConstants::USER_IMAGE);
  8758.         $employeeDetails $em->getRepository('ApplicationBundle:EmployeeDetails')->createQueryBuilder('E')
  8759.             ->select('E.firstname''E.lastname''E.nid''E.tin''E.image''P.positionName')
  8760.             ->addSelect('A.current_balance')
  8761.             ->leftJoin('ApplicationBundle:SysDepartmentPosition''P''WITH''E.desg = P.positionId')
  8762.             ->leftJoin('ApplicationBundle:Employee''EMP''WITH''EMP.employeeId = E.id')
  8763.             ->leftJoin('ApplicationBundle:AccAccountsHead''A''WITH''EMP.accountsHeadId = A.accountsHeadId')
  8764.             ->where('E.id = :employeeId')
  8765.             ->setParameter('employeeId'$employeeId)
  8766.             ->getQuery()
  8767.             ->getOneOrNullResult(\Doctrine\ORM\Query::HYDRATE_ARRAY); // Only one employee expected
  8768.         if (!$employeeDetails) {
  8769.             return new JsonResponse(['error' => 'Employee not found'], 404);
  8770.         }
  8771.         // If image is missing, fallback to session image
  8772.         if (empty($employeeDetails['image'])) {
  8773.             $employeeDetails['image'] = $image;
  8774.         }
  8775.         // If image is still available, prefix it with absolute URL
  8776.         if (!empty($employeeDetails['image'])) {
  8777.             $employeeDetails['image_url'] = $absoluteUrl '' $userImage;
  8778.         } else {
  8779.             $employeeDetails['image_url'] = ''// no image
  8780.         }
  8781.         return new JsonResponse($employeeDetails);
  8782.     }
  8783.     public function updateEmployeeDataForAppAction(Request $request)
  8784.     {
  8785.         $em $this->getDoctrine()->getManager();
  8786.         $session $request->getSession();
  8787.         $employeeId $session->get(UserConstants::USER_EMPLOYEE_ID);
  8788.         $employeeDetails $em->getRepository('ApplicationBundle:EmployeeDetails')->find($employeeId);
  8789.         if ($request->isMethod('POST')) {
  8790.             $firstname $request->request->get('firstname');
  8791.             $lastname $request->request->get('lastname');
  8792.             $nid $request->request->get('nid');
  8793.             $tin $request->request->get('tin');
  8794.             if ($firstname !== null) {
  8795.                 $employeeDetails->setFirstName($firstname);
  8796.             }
  8797.             if ($lastname !== null) {
  8798.                 $employeeDetails->setLastName($lastname);
  8799.             }
  8800.             if ($nid !== null) {
  8801.                 $employeeDetails->setNid($nid);
  8802.             }
  8803.             if ($tin !== null) {
  8804.                 $employeeDetails->setTin($tin);
  8805.             }
  8806.             $em->flush();
  8807.             return new JsonResponse(['success' => true]);
  8808.         }
  8809.         return new JsonResponse(['success' => false'message' => 'Invalid request method']);
  8810.     }
  8811. //    public function updateEmployeeDataForAppAction(Request $request){
  8812. //        $em = $this->getDoctrine()->getManager();
  8813. //        $session = $request->getSession();
  8814. //        $employeeId = $session->get(UserConstants::USER_EMPLOYEE_ID);
  8815. //        $employeeDetails = $em->getRepository('ApplicationBundle:EmployeeDetails')->find($employeeId);
  8816. //
  8817. //        if ($request->isMethod('POST')) {
  8818. //            $employeeDetails->setFirstName(($request->request->get('firstname',$employeeDetails->getFirstName())));
  8819. //            $employeeDetails->setLastName($request->request->get('lastname',$employeeDetails->getLastName()));
  8820. //            $employeeDetails->setNid($request->request->get('nid'),$employeeDetails->getNid());
  8821. //            $employeeDetails->setTin($request->request->get('tin'),$employeeDetails->getTin());
  8822. //
  8823. //            $em->flush(); //
  8824. //
  8825. //            return new JsonResponse(['success' => true]);
  8826. //        }
  8827. //
  8828. //
  8829. //    }
  8830.     public function leaveApplicationListForAppAction(Request $request)
  8831.     {
  8832.         $em $this->getDoctrine()->getManager();
  8833.         $session $request->getSession();
  8834.         $employeeId $session->get(UserConstants::USER_EMPLOYEE_ID);
  8835.         $leaveType HumanResourceConstant::$LeaveType;
  8836.         $approvalStatus GeneralConstant::$approvalAction;
  8837.         $leaveCategory HumanResourceConstant::$leavCategory;
  8838.         // Get page and limit from request (default: page=1, limit=10)
  8839.         $page max((int)$request->query->get('page'1), 1);
  8840.         $limit max((int)$request->query->get('limit'10), 1);
  8841.         $offset = ($page 1) * $limit;
  8842.         // Get total count
  8843.         $total $em->getRepository('ApplicationBundle:EmployeeLeaveApplication')
  8844.             ->createQueryBuilder('L')
  8845.             ->select('COUNT(L.employeeLeaveApplicationId)')
  8846.             ->where('L.employeeId = :employeeId')
  8847.             ->setParameter('employeeId'$employeeId)
  8848.             ->getQuery()
  8849.             ->getSingleScalarResult();
  8850.         // Get paginated results
  8851.         $leaveRecords $em->getRepository('ApplicationBundle:EmployeeLeaveApplication')
  8852.             ->createQueryBuilder('L')
  8853.             ->select(
  8854.                 'L.documentHash',
  8855.                 'L.employeeLeaveApplicationId',
  8856.                 'L.leaveStartDate',
  8857.                 'L.leaveEndDate',
  8858.                 'L.leaveTypeId',
  8859.                 'L.leaveCategory',
  8860.                 'L.approved',
  8861.                 'L.createdAt',
  8862.                 'L.alternateDate',
  8863.                 'L.leaveComment',
  8864.                 'L.createdAt',
  8865.                 'L.approved_by'
  8866.             )
  8867.             ->where('L.employeeId = :employeeId')
  8868.             ->setParameter('employeeId'$employeeId)
  8869.             ->setFirstResult($offset)
  8870.             ->setMaxResults($limit)
  8871.             ->orderBy('L.employeeLeaveApplicationId''DESC')   //
  8872.             ->getQuery()
  8873.             ->getResult();
  8874.         // Count total approved (approved = 1)
  8875.         $totalApproved $em->getRepository('ApplicationBundle:EmployeeLeaveApplication')
  8876.             ->createQueryBuilder('L')
  8877.             ->select('COUNT(L.employeeLeaveApplicationId)')
  8878.             ->where('L.employeeId = :employeeId')
  8879.             ->andWhere('L.approved = 1')
  8880.             ->setParameter('employeeId'$employeeId)
  8881.             ->getQuery()
  8882.             ->getSingleScalarResult();
  8883. // Count total pending (approved = 3)
  8884.         $totalPending $em->getRepository('ApplicationBundle:EmployeeLeaveApplication')
  8885.             ->createQueryBuilder('L')
  8886.             ->select('COUNT(L.employeeLeaveApplicationId)')
  8887.             ->where('L.employeeId = :employeeId')
  8888.             ->andWhere('L.approved = 3')
  8889.             ->setParameter('employeeId'$employeeId)
  8890.             ->getQuery()
  8891.             ->getSingleScalarResult();
  8892. // Count total cancelled (approved = 0)
  8893.         $totalCancelled $em->getRepository('ApplicationBundle:EmployeeLeaveApplication')
  8894.             ->createQueryBuilder('L')
  8895.             ->select('COUNT(L.employeeLeaveApplicationId)')
  8896.             ->where('L.employeeId = :employeeId')
  8897.             ->andWhere('L.approved = 0')
  8898.             ->setParameter('employeeId'$employeeId)
  8899.             ->getQuery()
  8900.             ->getSingleScalarResult();
  8901.         // Format the results
  8902.         $formattedData = [];
  8903.         foreach ($leaveRecords as $leave) {
  8904.             $formattedData[] = [
  8905.                 'documentHash' => $leave['documentHash'],
  8906.                 'employeeLeaveApplicationId' => $leave['employeeLeaveApplicationId'],
  8907.                 'leaveStartDate' => $leave['leaveStartDate'] ? $leave['leaveStartDate']->getTimestamp() : 0,
  8908.                 'leaveEndDate' => $leave['leaveEndDate'] ? $leave['leaveEndDate']->getTimestamp() : 0,
  8909.                 'leaveType' => $leaveType[$leave['leaveTypeId']] ?? 'Unknown',
  8910.                 'leaveCategory' => $leaveCategory[$leave['leaveCategory']] ?? 'Unknown',
  8911.                 'approved' => $approvalStatus[$leave['approved']] ?? 'Unknown',
  8912.                 'createdAt' => $leave['createdAt'] ? $leave['createdAt']->getTimestamp() : 0,
  8913.                 'alternateDate' => $leave['alternateDate'] ? $leave['alternateDate']->getTimestamp() : 0,
  8914.                 'note' => $leave['leaveComment'] ? $leave['leaveComment'] : '',
  8915.                 'appliedOn' => $leave['createdAt'] ? $leave['createdAt']->getTimestamp() : 0,
  8916.                 'approvedBy' => $leave['approved_by'] ? $leave['approved_by'] : 'automatically approved',
  8917.             ];
  8918.         }
  8919.         $employee $em->getRepository('ApplicationBundle:EmployeeDetails')
  8920.             ->find($employeeId);
  8921.         $totalLeaveBalance 0;
  8922.         for ($i 1$i <= 10$i++) {
  8923.             $getter "getLeave{$i}Tkn";
  8924.             $totalLeaveBalance +=$employee->$getter();
  8925.         }
  8926.         // Final response with pagination meta
  8927.         return new JsonResponse([
  8928.             'success' => true,
  8929.             'message' => 'Leave application list fetched successfully',
  8930.             'totalLeaveBalance' => (int) ($totalLeaveBalance ?? 0),
  8931.             'totalApproved' => (int) ($totalApproved ?? 0),
  8932.             'totalPending' => (int) ($totalPending ?? 0),
  8933.             'totalCancelled' => (int) ($totalCancelled ?? 0),
  8934.             'data' => $formattedData,
  8935.             'CurrentPage' => $page,
  8936.             'limit' => $limit,
  8937.             'total' =>$total,
  8938.         ]);
  8939.     }
  8940.     public function PublicProfilePageAction(Request $request)
  8941.     {
  8942.         return new JsonResponse(['success' => true]);
  8943.     }
  8944.     public function leaveSettingsAction(Request $request)
  8945.     {
  8946.         $em $this->getDoctrine()->getManager();
  8947.         if ($request->isMethod('POST')) {
  8948.             $ids $request->request->get('id', []);
  8949.             $leaveTitles $request->request->get('leaveTitle', []);
  8950.             $carryForwardTypes $request->request->get('carryForwardType', []);
  8951.             $carryForwardQtys $request->request->get('number', []);
  8952.             $totalLeaves $request->request->get('totalLeave', []);
  8953.             $resetFreqTypes $request->request->get('resetFrequencyType', []);
  8954.             $resetFreqQtys $request->request->get('resetFrequencyQty', []);
  8955.             $additionConditions $request->request->get('additionCondition', []);
  8956.             $additionDurations $request->request->get('additionConditionDuration', []);
  8957.             for ($i 0$i count($leaveTitles); $i++) {
  8958.                 if (
  8959.                     isset(
  8960.                         $carryForwardTypes[$i],
  8961.                         $carryForwardQtys[$i],
  8962.                         $totalLeaves[$i],
  8963.                         $resetFreqTypes[$i],
  8964.                         $resetFreqQtys[$i],
  8965.                         $additionConditions[$i],
  8966.                         $additionDurations[$i]
  8967.                     )
  8968.                 ) {
  8969.                     $id $ids[$i] ?? null;
  8970.                     $leaveSetting null;
  8971.                     if ($id) {
  8972.                         $leaveSetting $em->getRepository('ApplicationBundle:LeaveSettings')->find($id);
  8973.                     }
  8974.                     if (!$leaveSetting) {
  8975.                         $leaveSetting = new LeaveSettings();
  8976.                     }
  8977.                     $leaveSetting->setId($id);
  8978.                     $leaveSetting->setLeaveTitle($leaveTitles[$i]);
  8979.                     $leaveSetting->setCarryForwardType((int)$carryForwardTypes[$i]);
  8980.                     $leaveSetting->setCarryForwardQty((int)$carryForwardQtys[$i]);
  8981.                     $leaveSetting->setTotalLeave((int)$totalLeaves[$i]);
  8982.                     $leaveSetting->setResetFrequencyType((int)$resetFreqTypes[$i]);
  8983.                     $leaveSetting->setResetFrequencyQty((int)$resetFreqQtys[$i]);
  8984.                     $leaveSetting->setAdditionCondition((int)$additionConditions[$i]);
  8985.                     $leaveSetting->setAdditionConditionDuration((int)$additionDurations[$i]);
  8986.                     $em->persist($leaveSetting);
  8987.                 }
  8988.             }
  8989.             $em->flush();
  8990.             $this->addFlash('success''Leave settings saved successfully!');
  8991.             return $this->redirectToRoute('leave_settings_list');
  8992.         }
  8993.         $defaultLeaveType HumanResourceConstant::$defaultLeaveType;
  8994.         $savedLeaveSettings $em->getRepository('ApplicationBundle:LeaveSettings')->findAll();
  8995.         $useDefaultLeave count($savedLeaveSettings) === 0;
  8996.         $leaveSettings array_map(function ($setting) {
  8997.             return [
  8998.                 'id' => $setting->getId(),
  8999.                 'leaveTitle' => $setting->getLeaveTitle(),
  9000.                 'carryForwardType' => $setting->getCarryForwardType(),
  9001.                 'carryForwardQty' => $setting->getCarryForwardQty(),
  9002.                 'totalLeave' => $setting->getTotalLeave(),
  9003.                 'resetFrequencyType' => $setting->getResetFrequencyType(),
  9004.                 'resetFrequencyQty' => $setting->getResetFrequencyQty(),
  9005.                 'additionCondition' => $setting->getAdditionCondition(),
  9006.                 'additionConditionDuration' => $setting->getAdditionConditionDuration(),
  9007.             ];
  9008.         }, $savedLeaveSettings);
  9009.         return $this->render('ApplicationBundle:pages/human_resource/input_forms:leave_settings.html.twig', [
  9010.             'page_title' => 'Leave Settings',
  9011.             'defaultLeaveType' => $defaultLeaveType,
  9012.             'leaveSettings' => $leaveSettings,
  9013.             'useDefaultLeave' => $useDefaultLeave,
  9014.         ]);
  9015.     }
  9016.     public function leavePolicyListAction()
  9017.     {
  9018.         return $this->render("ApplicationBundle:pages/human_resource/list:leaveApplicationSettingsList.html.twig", array(
  9019.             'page_title' => 'Leave PolicyList',
  9020.         ));
  9021.     }
  9022.     public function getEmployeeProfileDataAction(Request $request)
  9023.     {
  9024.         $em $this->getDoctrine()->getManager();
  9025.         $session $request->getSession();
  9026.         $userId $session->get(UserConstants::USER_ID);
  9027.         $absoluteUrl $this->generateUrl('dashboard', [], UrlGenerator::ABSOLUTE_URL);
  9028.         $employeeData $em->getRepository('ApplicationBundle:Employee')
  9029.             ->findOneBy(
  9030.                 array(
  9031.                     'userId' => $userId
  9032.                 )
  9033.             );
  9034.         $data = [
  9035.             'firstname' => $employeeData->getFirstname(),
  9036.             'lastname' => $employeeData->getLastname(),
  9037.             'userImage' => $absoluteUrl '' $employeeData->getImage()
  9038.         ];
  9039.         return new JsonResponse([
  9040.             'success' => true,
  9041.             'data' => $data
  9042.         ]);
  9043.     }
  9044. }