IMMREX7

aku nok ndi : /home/spdtg/www/schoolmis/app/Http/Controllers/School/
File Up :
aku nok ndi : /home/spdtg/www/schoolmis/app/Http/Controllers/School/EmpPaymentController.php

<?php

namespace App\Http\Controllers\School;

use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use Auth;
use Carbon\Carbon;
use DB;
use PDF;
use Session;

class EmpPaymentController extends SchoolController {

    /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function index(Request $request) {
        $month = \App\Month::where('idMonth', '=', $request->idMonth)->first();
        $departments = ['' => '--Select--'] + \App\Department::where('idSchool', '=', Auth::guard('school')->user()->idSchool)
                        ->orderBy('departmentName')->get()->pluck('departmentName', 'idDepartment')->toArray();
        $employees = \App\Employee::where('idSchool', '=', Auth::guard('school')->user()->idSchool)
                ->orderBy('idEmployee', 'desc');
        if (($request->has('employees') && count($request->employees) > 0) && ($request->has('idMonth') && $request->idMonth != null)) {
            $employees = $employees->whereIn('idEmployee', $request->employees)->get();
        } elseif (($request->has('designations') && count($request->designations) > 0) && ($request->has('idMonth') && $request->idMonth != null)) {
            $employees = $employees->whereIn('idDesignation', $request->designations)->get();
        } else if (($request->has('idDepartment') && $request->idDepartment != null) && ($request->has('idMonth') && $request->idMonth != null)) {
            $employees = $employees->where('idDepartment', '=', $request->idDepartment)->get();
        } else if ($request->has('idMonth') && $request->idMonth != null) {
            $employees = $employees->get();
        }
        return view('schools.hrms.empayment', compact('employees', 'departments', 'month'));
    }

    public function removePayData(Request $request){
        $ifSalaryExists = \App\EmpPayment::where('idMonth',$request->idMonth)->where('idFinancialYear',$request->fy)->where('idSchool',Auth::guard('school')->user()->idSchool)->where('idEmployee', $request->idEmployee)->first();
        if($ifSalaryExists != null){
            $ifSalaryExists->delete();
            $data["idEmployee"] = $request->idEmployee;
            return response()->json(['message' => 'Deleted','data' => $data], 200);
        }                
        return response()->json(['message' => 'Failed'], 404);
    }

    public function removePaySlipData(Request $request){
        $ifSalaryExists = \App\EmpPayment::where('idMonth',$request->idMonth)->where('idFinancialYear',$request->fy)->where('idSchool',Auth::guard('school')->user()->idSchool)->where('idEmployee', $request->idEmployee)->first();
        if($ifSalaryExists != null){
            $ifSalaryExists->isPaid = 'N';
            $ifSalaryExists->payDate = null;
            $ifSalaryExists->paymentMode = null;
            $ifSalaryExists->transId = null;
            $ifSalaryExists->advanceSalary = null;
            $ifSalaryExists->extraEarning = null;
            $ifSalaryExists->earningRemarks = null;
            $ifSalaryExists->extraDeduction = null;
            $ifSalaryExists->deductionRemarks = null;
            $ifSalaryExists->update();
            $data["idEmployee"] = $request->idEmployee;
            $data["month"] = $request->idMonth;
            $data["fy"] = $request->fy;
            $data["link"] = url('/school/empsalary/'.$ifSalaryExists->idEmpPayment.'/'.$request->idMonth.'/pay');
            return response()->json(['message' => 'Deleted','data' => $data], 200);
        }                
        return response()->json(['message' => 'Failed'], 404);
    }

    /**
     * Show the form for creating a new resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function create() {
        //
    }

    /**
     * Store a newly created resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return \Illuminate\Http\Response
     */
    public function store(Request $request) {
        $rules = [
            'idMonth' => 'required',
            'idTeacher' => 'required'
        ];
        $messages = [
            'idTeacher.required' => 'Select Enrollment no first.',
            'idMonth.required' => 'Select Paymenet Month'
        ];
        $this->validate($request, $rules, $messages);
        $emppayment = new \App\EmpPayment();
        $emppayment->fill($request->all());
        $emppayment->idSchool = Auth::guard('school')->user()->idSchool;
        $emppayment->idFinancialYear = Session::get('idFinancialYear');
        $emppayment->save();
        return redirect('school/emppayments');
    }

    /**
     * Display the specified resource.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function show($id) {
        //
    }

    /**
     * Show the form for editing the specified resource.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function edit($id) {
        $emppayments = \App\EmpPayment::where('idSchool', '=', Auth::guard('school')->user()->idSchool)
                        ->where('idFinancialYear', '=', Session::get('idFinancialYear'))
                        ->orderBy('idEmpPayment', 'desc')->get();
        $teachers = ['' => '--Select--'] + \App\Employee::where('idSchool', '=', Auth::guard('school')->user()->idSchool)
                        ->orderBy('idTeacher', 'desc')->get()->pluck('name', 'idTeacher')->toArray();
        $emppay = \App\EmpPayment::where('idEmpPayment', '=', $id)->first();
        return view('schools.employees.payment_edit', compact('teachers', 'emppayments', 'emppay'));
    }

    /**
     * Update the specified resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function update(Request $request, $id) {
        $rules = [
            'idMonth' => 'required',
            'idTeacher' => 'required'
        ];
        $messages = [
            'idTeacher.required' => 'Select Enrollment no first.',
            'idMonth.required' => 'Select Paymenet Month'
        ];
        $this->validate($request, $rules, $messages);
        $emppay = \App\EmpPayment::where('idEmpPayment', '=', $id)->first();
        $emppay->fill($request->all());
        $emppay->idSchool = Auth::guard('school')->user()->idSchool;
        $emppay->update();
        //flash('Employee Payment has been updated successfully.');
        return redirect('school/emppayments');
    }

    /**
     * Remove the specified resource from storage.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function destroy($id) {
        //
    }

    public function salaryGeneration(Request $request) {
        $departments = ['' => '--Select--'] + \App\Department::where('idSchool', '=', Auth::guard('school')->user()->idSchool)
                        ->orderBy('departmentName')->get()->pluck('departmentName', 'idDepartment')->toArray();
        $employees = \App\Employee::where('idSchool', '=', Auth::guard('school')->user()->idSchool)
                ->orderBy('idEmployee', 'desc')->where('isActive','Y');
        if ($request->has('employees') && count($request->employees) > 0) {
            $employees = $employees->whereIn('idEmployee', $request->employees)->get();
        } elseif ($request->has('designations') && count($request->designations) > 0) {
            $employees = $employees->whereIn('idDesignation', $request->designations)->get();
        } else if ($request->has('idDepartment') && $request->idDepartment != null) {
            $employees = $employees->whereIn('idDepartment', $request->departments)->get();
        } else {
            $employees = $employees->get();
        }
        $financialYear = $request->get('fy');
        $month = $request->get('idMonth');
        $year = $request->get('year');
        if(Auth::guard('school')->user()->idSchool == 25 || Auth::guard('school')->user()->idSchool == 163)
        return view('schools.hrms.salary_generation_royal', compact('employees', 'departments','financialYear','month','year'));
        else
        return view('schools.hrms.salary_generation', compact('employees', 'departments','financialYear','month','year'));
    }

    public function generateSalary(\App\Http\Requests\GenerateSalary $request){
        if ($request->has('idEmployee')) {
            $employee = \App\Employee::where('idSchool', '=', Auth::guard('school')->user()->idSchool)->where('idEmployee',$request->idEmployee)->first();
            if($employee != null){
                $month = \App\Month::where('idMonth', '=', $request->idMonth)->first();
                $school = \App\School::where('idSchool', '=', Auth::guard('school')->user()->idSchool)->first();
                $fy = $request->fy;
                $idMonth = $month->idMonth;
                $pos = $request->pos;
                $now = Carbon::now();
                if(isset($request->year))
                $year = $request->year;
                else $year = $now->year;
                /*$data = array();
                $totalEarnings = 0;
                $totalDeductionFixed = 0;
                $totalDeductionDynamic = 0;
                
                $emp_shift = \App\AssignShift::where('idEmployee', '=', $employee->idEmployee)->first();
                if($emp_shift != null){
                    $emp_salstr = \App\SalaryStructure::where('idEmployee', '=', $employee->idEmployee)->where('idFinancialYear', '=', $request->fy)->first();
                    if($emp_salstr != null){
                        //Fetch salary
                        $earnings = \App\SalaryStrAllowances::where('idSalaryStr', '=', $emp_salstr->idSalaryStr)->get();
                        foreach($earnings as $earning){
                            $totalEarnings = $totalEarnings + $earning->amount;
                        }
                        //Fetch Deduction
                        $deductions = \App\SalaryStrDeduction::where('idSalaryStr', '=', $emp_salstr->idSalaryStr)->get();
                        foreach($deductions as $deduction){
                            if($deduction->deduction_type == "fixed"){
                                $totalDeductionFixed = $totalDeductionFixed+ $deduction->amount;
                            }else{
                                $totalDeductionDynamic = $totalDeductionDynamic+ $deduction->amount;
                            }
                        }

                        $now = Carbon::now();
                        $late = "00:00";
                        $isLateEnded = "N";
                        $lateHalf = "00:00";
                        $lateDays = 0;
                        $allowedMinutes = 0;
                        $lateMinutes = 0;
                        $earlyLeave = 0;
                        $earlyMinutes = 0;
                        $otMinutes = 0;
                        
                        $m = $month->idMonth;
                        if(isset($request->year))
                        $y = $request->year;
                        else $y = $now->year;
                        $p = 0;
                        $ab = 0;
                        $pl = 0;
                        $l = 0;
                        $inc = 0;
                        $hf = 0;
                        $loan = 0;
                        $previous_month_leave = 0;
                        $current_month_leave = 0;
                        $leave_deduction = 0;
                        $leave_deduction_amount = 0;
                        $salary_deduction = 0;
                        $gross_salary_month = 0;
                        $totalLeave = 0;
                        $leave_count = 0;
                        
                        $designationYearWise = \App\LeaveMaster::where('idSchool', '=', $employee->idSchool)
                                                    ->where('idDesignation',$employee->idDesignation)
                                                    ->where('idFinancialYear',$request->fy)
                                                    ->where('leaveType',"yearly")
                                                    ->whereNull('idEmployee')
                                                    ->sum('paidLeaves');
                        $paidYearLeaves = \App\LeaveMaster::where('idSchool', '=', $employee->idSchool)
                                                    ->where('idDesignation',$employee->idDesignation)
                                                    ->where('idEmployee',$employee->idEmployee)
                                                    ->where('idFinancialYear',$request->fy)
                                                    ->where('leaveType',"yearly")
                                                    ->sum('paidLeaves');

                        $designationMonthWise = \App\LeaveMaster::where('idSchool', '=', $employee->idSchool)
                                                    ->where('idDesignation',$employee->idDesignation)
                                                    ->where('idFinancialYear',$request->fy)
                                                    ->where('leaveType',"monthly")
                                                    ->whereNull('idEmployee')
                                                    ->sum('paidLeaves') * 12;
                        $paidMonthLeaves = \App\LeaveMaster::where('idSchool', '=', $employee->idSchool)
                                                    ->where('idDesignation',$employee->idDesignation)
                                                    ->where('idEmployee',$employee->idEmployee)
                                                    ->where('idFinancialYear',$request->fy)
                                                    ->where('leaveType',"monthly")
                                                    ->sum('paidLeaves') * 12;
                        //calculate allowed leave in a finanacial year
                        $totalLeave = $designationYearWise + $paidYearLeaves + $designationMonthWise + $paidMonthLeaves;
                        //start the loop    
                        $pDate = '01' . '-' . $m . '-' . $y;
                        if($m == 1)
                        {
                            $previousYear = $y - 1;
                            $pMaxDate = '01' . '-12-' .  $previousYear; //in case this is the new year
                        }
                        else {
                            $previousMonth = $m - 1;
                            $pMaxDate = '01' . '-' .$previousMonth. '-' . $y;
                        }
                        //check if leave exist in the previous month
                        $previous_month_leave = DB::table('employee_leave')
                                ->whereDate('leave_from', '<', Carbon::parse($pDate))
                                ->whereDate('leave_from', '>', Carbon::parse($pMaxDate))
                                ->where('idEmployee', $employee->idEmployee)
                                ->where('idEmployee',$request->fy)
                                ->where('status','Approve with PL(Paid Leave)')
                                ->count();

                        //Fetch late avarival master
                        $lateMaster = \App\LateArrivalMaster::where('idEmployee', '=', $employee->idEmployee)->where('idFinancialYear', '=', $request->fy)->first();
                        if($lateMaster == null){
                            $lateMaster = \App\LateArrivalMaster::where('idDesignation', '=', $employee->idDesignation)->where('idFinancialYear', '=', $request->fy)->first();
                        }
                        //Fetch early avarival master
                        $earlyMaster = \App\EarlyGoingMaster::where('idEmployee', '=', $employee->idEmployee)->where('idFinancialYear', '=', $request->fy)->first();
                        if($earlyMaster == null){
                            $earlyMaster = \App\EarlyGoingMaster::where('idDesignation', '=', $employee->idDesignation)->where('idFinancialYear', '=', $request->fy)->first();
                        }

                        for ($i = 1; $i <= $month->noOfDays; $i++) {
                            $dt = $i . '-' . $m . '-' . $y;
                            $tdate = Carbon::parse($dt);
                            $jdate = $tdate->format('Y-m-d');
                            //check for leave approved 
                            $unpaidLeave = DB::table('employee_leave')
                                        ->whereDate('leave_from', '<=', $jdate)
                                        ->whereDate('leave_to', '>=', $jdate)
                                        ->where('idEmployee', $employee->idEmployee)
                                        ->where('status','Approve Without PL')
                                        ->first();
                            if($unpaidLeave != null){
                                $l++;
                            }else{
                                //check for holiday week off and employee only leave    
                                $paidLeave = DB::table('employee_leave')
                                    ->whereDate('leave_from', '<=', $jdate)
                                    ->whereDate('leave_to', '>=', $jdate)
                                    ->where('idEmployee', $employee->idEmployee)
                                    ->where('status','Approve with PL(Paid Leave)')
                                    ->first();
                                if($paidLeave != null){
                                    $pl++;
                                }else{
                                    //check for week day and holiday
                                    $shifts = DB::table('shift_details')
                                            ->select('fromTime','toTime','shift_from','shift_to','weekOff')
                                            ->join('weekdays', 'shift_details.idWeekday', '=', 'weekdays.idWeekday')
                                            ->where('idShift', '=', $emp_shift->idShift)
                                            ->where('dayName', '=', date('l', strtotime($tdate)))
                                            ->first();
                                    //check for special shift         

                                    if($shifts != null){
                                        $holiday = \App\HrmsHoliday::where('idSchool', '=', Auth::guard('school')->user()->idSchool)
                                                    ->where('idEmployee',$employee->idEmployee)
                                                    ->whereDate('fromDate', '<=', $jdate)
                                                    ->whereDate('toDate', '>=', $jdate)
                                                    ->first();
                                        $pholiday = \App\HrmsHoliday::where('idSchool', '=', Auth::guard('school')->user()->idSchool)
                                                    ->where('designation',$employee->idDesignation)
                                                    ->where('department',$employee->idDepartment)
                                                    ->whereNull('idEmployee')
                                                    ->whereDate('fromDate', '<=', $jdate)
                                                    ->whereDate('toDate', '>=', $jdate)
                                                    ->first();
                                        //check for holiday week off and employee only leave            
                                        if($holiday != null){
                                            $p++;
                                        }else if($pholiday != null){
                                            $p++;
                                        }            
                                        else if($shifts->weekOff == "Y"){ //scan for sunday
                                            $p++;
                                        }else if($shifts->weekOff == "N"){
                                            //check for working days
                                            $aintime = \App\EmpAttendance::where('Enrollment_Number', '=', $employee->enrollmentNo)
                                            ->where('Device_ID', '=', $school->Device_ID)
                                            ->whereDate('date', '=', $jdate)
                                            ->where('status','P')
                                            ->first();
                                            if($aintime != null){
                                                //mark manualy present
                                                $p++;    
                                            }else{
                                                $intime = \App\EmpAttendance::where('Enrollment_Number', '=', $employee->enrollmentNo)
                                                        ->where('Device_ID', '=', $school->Device_ID)
                                                        ->whereDate('date', '=', $jdate)
                                                        ->where('status', '=', 'IN')
                                                        ->where('idType', '=', 'A')
                                                        ->first();
                                                $outtime = \App\EmpAttendance::where('Enrollment_Number', '=', $employee->enrollmentNo)
                                                            ->where('Device_ID', '=', $school->Device_ID)
                                                            ->whereDate('date', '=', $jdate)
                                                            ->where('status', '=', 'OUT')
                                                            ->where('idType', '=', 'A')
                                                            ->first();
                                                if($intime  == null && $outtime == null && $aintime == null){
                                                    $ab++;
                                                }else{
                                                    if($intime == null || $outtime == null){
                                                        //check for incomplete attendance
                                                        $inc++;
                                                    }else{
                                                        $dayNight = "AM";
                                                        if($shifts != null){
                                                            if($shifts->shift_from == "pm")
                                                            $dayNight = "PM";
                                                        }    

                                                        $nightDay = "AM";
                                                        if($shifts != null){
                                                            if($shifts->shift_to == "pm")
                                                            $nightDay = "PM";
                                                        }

                                                        $chekStatus = "PR";
                                                        //check for late arrival
                                                        $start = Carbon::parse($shifts->fromTime.' '.$dayNight);
                                                        $arrival = Carbon::parse($intime->TimeStamp->format('h:i:s'));
                                                        $lateRequired = $arrival->diffForHumans($start,[]);
                                                        if(str_contains($lateRequired, 'after')){
                                                            //late master required
                                                            if($lateMaster != null){
                                                                $allowedTime = explode(':',$lateMaster->lateAllowed);
                                                                $addOnMinutes = $allowedTime[0]*60 + $allowedTime[1]; //calculate minutes
                                                                if($lateMaster->lateAllowedTimes == "daily"){
                                                                    //add minutes to shift
                                                                    $sr = Carbon::parse($shifts->fromTime.' '.$dayNight)->addMinutes($addOnMinutes);
                                                                    $allowed = $arrival->diffForHumans($sr,[]);
                                                                    if(str_contains($allowed, 'after')){
                                                                        $checkForHalfDay = $arrival->diffInMinutes($sr);
                                                                        $halfTime = explode(':',$lateMaster->halfDayAfter);
                                                                        $halfOnMinutes = $halfTime[0]*60 + $halfTime[1]; //calculate minutes
                                                                        $haf = Carbon::parse($shifts->fromTime.' '.$dayNight)->addMinutes($halfOnMinutes);
                                                                        $halfTouch = $arrival->diffForHumans($haf,[]); //check for half day
                                                                        if(str_contains($halfTouch, 'after')){
                                                                            $chekStatus = "HF";
                                                                        }else{
                                                                            $chekStatus = "LT";

                                                                        }
                                                                    }
                                                                    //TODO
                                                                    //add deduction amount to the employee of being late
                                                                    if($chekStatus == "LT"){
                                                                        $lateMinutes += $arrival->diffInMinutes($sr);
                                                                    }
                                                                }else{
                                                                    $sr = Carbon::parse($shifts->fromTime.' '.$dayNight)->addMinutes($addOnMinutes);
                                                                    $allowedMinutes = $allowedMinutes + $arrival->diffInMinutes($sr);
                                                                    if($allowedMinutes > $addOnMinutes){
                                                                        //check for half Day
                                                                        $checkForHalfDay = $arrival->diffInMinutes($sr);
                                                                        $halfTime = explode(':',$lateMaster->halfDayAfter);
                                                                        $halfOnMinutes = $halfTime[0]*60 + $halfTime[1]; //calculate minutes
                                                                        $haf = Carbon::parse($shifts->fromTime.' '.$dayNight)->addMinutes($halfOnMinutes);
                                                                        $halfTouch = $arrival->diffForHumans($haf,[]); //check for half day
                                                                        if(str_contains($halfTouch, 'after')){
                                                                            $chekStatus = "HF";
                                                                        }else{
                                                                            $chekStatus = "LT";
                                                                        }
                                                                        //TODO
                                                                        //add deduction amount to the employee of being late
                                                                        if($chekStatus == "LT"){
                                                                            $lateMinutes += $arrival->diffInMinutes($sr);
                                                                        }
                                                                    }
                                                                }
                                                                //mark half aur late
                                                                if($chekStatus == "LT") {
                                                                    $lateDays++;
                                                                    if($lateMaster != null){
                                                                        //check for late days to mark half days
                                                                        if($lateMaster->maxDays > 0){
                                                                            if($lateMaster->maxDays == $lateDays){
                                                                                $lateDays = 0;
                                                                                $hf++;
                                                                            }
                                                                        }else if($lateMaster->maxLeave > 0){
                                                                            if($lateMaster->maxDays == $lateDays){
                                                                                $lateDays = 0;
                                                                                //TODO check for auto leave if not mark leave
                                                                            }
                                                                        }
                                                                        
                                                                    }
                                                                }
                                                                else if($chekStatus == "HF") $hf++;
                                                            }
                                                        }

                                                        $earlyStatus = "PR";
                                                        //check for  early going
                                                        $end = Carbon::parse($shifts->toTime.' '.$nightDay);
                                                        $departure = Carbon::parse($outtime->TimeStamp->format('h:i:s'));
                                                        $lateRequired = $departure->diffForHumans($end,[]);
                                                        if(str_contains($lateRequired, 'after')){
                                                            //late master required
                                                            if($earlyMaster != null){
                                                                $allowedTime = explode(':',$earlyMaster->earlyAllowed);
                                                                $addOnMinutes = $allowedTime[0]*60 + $allowedTime[1]; //calculate minutes
                                                                if($earlyMaster->earlyAllowedTimes == "daily"){
                                                                    //add minutes to shift
                                                                    $sr = Carbon::parse($shifts->toTime.' '.$nightDay)->addMinutes($addOnMinutes);
                                                                    $allowed = $departure->diffForHumans($sr,[]);
                                                                    if(str_contains($allowed, 'after')){
                                                                        $checkForHalfDay = $departure->diffInMinutes($sr);
                                                                        $halfTime = explode(':',$earlyMaster->halfDayAfter);
                                                                        $halfOnMinutes = $halfTime[0]*60 + $halfTime[1]; //calculate minutes
                                                                        $haf = Carbon::parse($shifts->toTime.' '.$nightDay)->addMinutes($halfOnMinutes);
                                                                        $halfTouch = $departure->diffForHumans($haf,[]); //check for half day
                                                                        if(str_contains($halfTouch, 'after')){
                                                                            $earlyStatus = "HF";
                                                                        }else{
                                                                            $earlyStatus = "LT";

                                                                        }
                                                                    }
                                                                    //TODO
                                                                    //add deduction amount to the employee of being late
                                                                    if($earlyStatus == "LT"){
                                                                        $earlyMinutes += $departure->diffInMinutes($sr);
                                                                    }
                                                                }else{
                                                                    $sr = Carbon::parse($shifts->toTime.' '.$nightDay)->addMinutes($addOnMinutes);
                                                                    $allowedMinutes = $allowedMinutes + $departure->diffInMinutes($sr);
                                                                    if($allowedMinutes > $addOnMinutes){
                                                                        //check for half Day
                                                                        $checkForHalfDay = $departure->diffInMinutes($sr);
                                                                        $halfTime = explode(':',$earlyMaster->halfDayAfter);
                                                                        $halfOnMinutes = $halfTime[0]*60 + $halfTime[1]; //calculate minutes
                                                                        $haf = Carbon::parse($shifts->toTime.' '.$nightDay)->addMinutes($halfOnMinutes);
                                                                        $halfTouch = $departure->diffForHumans($haf,[]); //check for half day
                                                                        if(str_contains($halfTouch, 'after')){
                                                                            $earlyStatus = "HF";
                                                                        }else{
                                                                            $earlyStatus = "LT";
                                                                        }
                                                                        //TODO
                                                                        //add deduction amount to the employee of being late
                                                                        if($earlyStatus == "LT"){
                                                                            $earlyMinutes += $departure->diffInMinutes($sr);
                                                                        }
                                                                    }
                                                                }
                                                                //mark half aur late
                                                                if($earlyStatus == "LT") {
                                                                    $earlyLeave++;
                                                                    if($earlyMaster != null){
                                                                        //check for late days to mark half days
                                                                        if($earlyMaster->maxDays > 0){
                                                                            if($earlyMaster->maxDays == $earlyLeave){
                                                                                $earlyLeave = 0;
                                                                                $hf++;
                                                                            }
                                                                        }else if($earlyMaster->maxLeave > 0){
                                                                            if($earlyMaster->maxDays == $earlyLeave){
                                                                                $earlyLeave = 0;
                                                                                //TODO check for auto leave if not mark leave
                                                                            }
                                                                        }
                                                                        
                                                                    }
                                                                }
                                                                else if($earlyStatus == "HF") $hf++;
                                                            }
                                                        }

                                                        if($chekStatus == $earlyStatus)
                                                        $p++;
                                                        

                                                        //aplicable if serive total is greater than shift total
                                                        $shift_start = Carbon::parse($shifts->fromTime.' '.$dayNight);
                                                        $shift_end =Carbon::parse($shifts->toTime.' '.$nightDay);
                                                        $shiftTotal = $shift_end->diffInMinutes($shift_start);

                                                        $departure = Carbon::parse($outtime->TimeStamp->format('h:i:s'));
                                                        $arrival = Carbon::parse($intime->TimeStamp->format('h:i:s'));
                                                        $serviceTotal = $departure->diffInMinutes($arrival);
                                                        //check for overtime
                                                        if($serviceTotal > $shiftTotal){
                                                            $ot = DB::table('overtime')->where('idSchool', '=', Auth::guard('school')->user()->idSchool)->where('idEmployee',$employee->idEmployee)->first();
                                                            if($ot != null){
                                                                $overtime = explode(':',$ot->otAfter);
                                                                $overMinutes = $overtime[0]*60 + $overtime[1];
                                                                $overstart = Carbon::parse($shifts->toTime.' '.$nightDay)->addMinutes($overMinutes);
                                                                $overarrival =  Carbon::parse($outtime->TimeStamp->format('h:i:s'));
                                                                if(str_contains($overarrival->diffForHumans($overstart,[]) ,"after")){
                                                                    //overtime found
                                                                    $otMinutes += $overarrival->diffInMinutes($overstart);
                                                                }
                                                            }else{
                                                                $eot = DB::table('overtime')->where('idSchool', '=', Auth::guard('school')->user()->idSchool)->whereNull('idEmployee')->first();
                                                                if($eot != null){
                                                                    $overtime = explode(':',$eot->otAfter);
                                                                    $overMinutes = $overtime[0]*60 + $overtime[1];
                                                                    $overstart = Carbon::parse($shifts->toTime.' '.$nightDay)->addMinutes($overMinutes);
                                                                    $overarrival = Carbon::parse($outtime->TimeStamp->format('h:i:s'));
                                                                    if(str_contains($overarrival->diffForHumans($overstart,[]) ,"after")){
                                                                        //overtime found
                                                                        $otMinutes += $overarrival->diffInMinutes($overstart);
                                                                    }
                                                                }
                                                            }
                                                        }
                                                    } 
                                                }
                                                           
                                            }
                                        }
                                    }            
                                } 
                            }            
                        }
                        
                        $current_month_leave = $pl;
                        $leave_count = $ab;
                        $ifSalaryExists = \App\EmpPayment::where('idMonth',$request->idMonth)->where('idFinancialYear',$request->fy)->where('idSchool',Auth::guard('school')->user()->idSchool)->where('idEmployee', $employee->idEmployee)->first();
                        if($employee->idSchool == 25){
                            $perSal = $totalEarnings / 30;
                            $halfSal = $perSal/2;
                            $leave_deduction = intval($perSal*$leave_count) + ($halfSal * $hf); 
                            $salary_deduction = $leave_deduction;
                            $gross_salary_month = $totalEarnings - $salary_deduction;
                            $totalSal = $gross_salary_month - $totalDeductionFixed;
                        }else{
                            $perSal = $totalEarnings / $month->noOfDays;
                            $halfSal = $perSal/2;
                            $totalSal = ( ( ($p+$pl) * $perSal) + ($hf * $halfSal) ) - $totalDeductionFixed;
                        }
                        $data["half_day"] = $hf;
                        $data["present"] = $p;
                        $data["leave"] = $l;
                        $data["absent"] = $ab;
                        $data["incomplete"] = $inc;
                        $data["paid_leave"] = $pl;
                        $data["salary"] = ceil($totalSal);
                        $data["idEmployee"] = $request->idEmployee;
                        $data["pos"] = $request->pos;
                        $data["loan"] = $loan;
                        $data["prev"] = $previous_month_leave;
                        $data["current"] = $current_month_leave;
                        $data["total"] = $previous_month_leave + $current_month_leave;
                        $data["balance"] = $totalLeave - ($previous_month_leave + $current_month_leave);
                        $data["leave_count"] = $leave_count;
                        $data["deduction"] = $leave_deduction;
                        $data["salary_deduction"] = $salary_deduction;
                        $data["gross_salary"] = $gross_salary_month;
                        if($ifSalaryExists == null || $inc == 0) $data["btEnable"] = 1;
                        else $data["btEnable"] = 0;*/
                        $emp_shift = \App\AssignShift::where('idEmployee', '=',$request->idEmployee)->first();
                        if ($emp_shift == null) {
                            $data["half_day"] = 0;
                            $data["present"] = 0;
                            $data["leave"] = 0;
                            $data["absent"] = 0;
                            $data["incomplete"] = 0;
                            $data["paid_leave"] = 0;
                            $data["salary"] = 0;
                            $data["idEmployee"] = $request->idEmployee;
                            $data["pos"] = $pos;
                            $data["loan"] = 0;
                            $data["canteen"] = 0;
                            $data["epf"] = 0;
                            $data["pt"] = 0;
                            $data["prev"] = 0;//previous month leave
                            $data["current"] = 0; //current month leave
                            $data["total"] = 0; //total leave taken
                            $data["balance"] = 0; //balance leave available
                            $data["leave_count"] = 0; //no of leave taken and leave marked
                            $data["deduction"] = 0; // deduction based on leave
                            $data["salary_deduction"] = 0; //salary deduction
                            $data["gross_salary"] = 0; //salary to be paid
                            return response()->json(['data' => $data], 200);
                        }

                        $data = $request->generate("Y",$month,$employee,$fy,$year,$pos,$idMonth);
                        Session::put($request->idEmployee."_".$request->idMonth."_".$request->fy,json_encode($data));
                        return response()->json(['data' => $data], 200);
                    //}
                //}
                //return response()->json(['data' => $data], 200);
            }
        }
        //return response()->json(['message' => 'No employee data found'], 200);
    }

    public function payGeneration(\App\Http\Requests\GenerateSalary $request){
        if ($request->has('employees')) {
            $employee =  \App\Employee::where('idEmployee', '=', $request->employees)->first();
            $month = \App\Month::where('idMonth', '=', $request->idMonth)->first();

            $emp_shift = \App\AssignShift::where('idEmployee', '=', $employee->idEmployee)->first(); 
            $emp_salstr = \App\SalaryStructure::where('idEmployee', '=', $employee->idEmployee)->where('idFinancialYear', '=', $request->fy)->first();
            $ifSalaryExists = \App\EmpPayment::where('idMonth',$month->idMonth)->where('idFinancialYear',$request->fy)->where('idSchool',Auth::guard('school')->user()->idSchool)->where('idEmployee', $employee->idEmployee)->first();
            $now = Carbon::now();
            if($emp_shift == null || $emp_salstr  == null || $ifSalaryExists != null){
                return response()->json(['message' => 'No employee data found'], 404);
            }
            $fy = $request->fy;
            if(isset($request->year))
                $year = $request->year;
                else $year = $now->year;
            $idMonth = $month->idMonth;
            $pos = 0;
            $request->generate("Y",$month,$employee,$fy,$year,$pos,$idMonth);
            $data["idEmployee"] = $employee->idEmployee;
            return response()->json(['message' => 'Generated','data' => $data], 200);
        }
        return response()->json(['message' => 'No employee data found'], 404);
    }

    /*public function generateSalary(\App\Http\Requests\GenerateSalary $request) {
        if ($request->has('employees')) {
            foreach ($request->employees as $var) {
                $data = "Salary Report";
                $month = \App\Month::where('idMonth', '=', $request->idMonth)->first();
                $school = \App\School::where('idSchool', '=', Auth::guard('school')->user()->idSchool)->first();
                $data .= "\nMonth  ".$month->monthName;
                $employee = \App\Employee::where('idEmployee', '=', $var)->first();
                $data .= "\nEmployee Name ".$employee->firstName;
                $emp_shift = \App\AssignShift::where('idEmployee', '=', $var)->first();
                $data .= "\n Shift Id ".$emp_shift->idShift;
                $emp_salstr = \App\SalaryStructure::where('idEmployee', '=', $employee->idEmployee)->first();
                if($emp_shift == null){
                    //redirect saying shift not added
                }
                if($emp_salstr == null){
                    //redirect saying salary structure not added
                }

                $totalEarnings = 0;
                if($emp_salstr != null){
                    $earnings = \App\SalaryStrAllowances::where('idSalaryStr', '=', $emp_salstr->idSalaryStr)->get();
                    foreach($earnings as $earning){
                        $data .= "\nEarnings : ".$earning->amount;
                        $totalEarnings = $totalEarnings + $earning->amount;
                    }
                }
                
                $totalDeductionFixed = 0;
                $totalDeductionDynamic = 0;
                if($emp_salstr != null){
                    $deductions = \App\SalaryStrDeduction::where('idSalaryStr', '=', $emp_salstr->idSalaryStr)->get();
                    foreach($deductions as $deduction){
                        $data .= "\nDeduction : ".$deduction->amount."(".$deduction->deduction_type.")";
                        if($deduction->deduction_type == "fixed"){
                            $totalDeductionFixed = $totalDeductionFixed+ $deduction->amount;
                        }else{
                            $totalDeductionDynamic = $totalDeductionDynamic+ $deduction->amount;
                        }
                    }
                }
                $calendar = "\n ";
                $now = Carbon::now();
                $m = $month->idMonth;
                $y = $now->year;
                $p = 0;
                $a = 0;
                $hf = 0;
                $ho = 0;

                $lateMaster = \App\LateArrivalMaster::where('idEmployee', '=', $employee->idEmployee)->where('idFinancialYear', '=', Session::get('idFinancialYear'))->first();
                if($lateMaster != null){
                    $data .= "\n late Allowed : ".$lateMaster->lateAllowed."(".$lateMaster->maxDays.")";
                }
                
                for ($i = 1; $i <= $month->noOfDays; $i++) {
                    $dt = $i . '-' . $m . '-' . $y;
                   
                    $tdate = Carbon::parse($dt);
                    $jdate = $tdate->format('Y-m-d');
                    $shifts = DB::table('shift_details')
                                            ->select('fromTime','toTime')
                                            ->join('weekdays', 'shift_details.idWeekday', '=', 'weekdays.idWeekday')
                                            ->where('idShift', '=', $emp_shift->idShift)
                                            ->where('dayName', '=', date('l', strtotime($tdate)))
                                            ->first(); 
                                                                 
                    $aintime = \App\EmpAttendance::where('Enrollment_Number', '=', $employee->enrollmentNo)
                                ->where('Device_ID', '=', $school->Device_ID)
                                ->whereDate('date', '=', $jdate)
                                ->whereIn('status', ['IN','OUT','P'])
                                ->first();
                        $intime = \App\EmpAttendance::where('Enrollment_Number', '=', $employee->enrollmentNo)
                                ->where('Device_ID', '=', $school->Device_ID)
                                ->whereDate('date', '=', $jdate)
                                ->where('status', '=', 'IN')
                                ->where('idType', '=', 'A')
                                ->first();
                        $outtime = \App\EmpAttendance::where('Enrollment_Number', '=', $employee->enrollmentNo)
                                ->where('Device_ID', '=', $school->Device_ID)
                                ->whereDate('date', '=', $jdate)
                                ->where('status', '=', 'OUT')
                                ->where('idType', '=', 'A')
                                ->first();
                             
                        if(isset($intime->TimeStamp)){
                            $start = Carbon::parse($shifts->fromTime);
                            $arrival = Carbon::parse($intime->TimeStamp->format('h:i:s'));
                            $lateTime = $arrival->diffForHumans($start,[]);

                            if($lateMaster != null && str_contains($lateTime ,"after")){
                                $allowedTime = explode(':',$lateMaster->lateAllowed);
                                $addOnMinutes = $allowedTime[0]*60 + $allowedTime[1];
                                $cstart = Carbon::parse($shifts->fromTime)->addMinutes($addOnMinutes);
                                $carrival = Carbon::parse($intime->TimeStamp->format('h:i:s'));
                                if(str_contains($carrival->diffForHumans($cstart,[]) ,"after")){
                                    $calendar .= "\n Calendar  ".$carrival->diffForHumans($cstart,[]) ."==> Late today By ".$arrival.' == '.$start;
                                }
                            }
                        }            
                    
                    $holiday = \App\HrmsHoliday::where('idSchool', '=', Auth::guard('school')->user()->idSchool)
                            ->whereDate('fromDate', '<=', $jdate)
                            ->whereDate('toDate', '>=', $jdate)
                            ->first();
                    $hd = '';
                    if ($holiday != null) {
                        $hd = $holiday->holidayName;
                        $ho++;
                        $calendar .= "\n Calendar  ".$jdate."==>".$tdate->dayOfWeek."==>".$holiday->holidayName;
                    } else if ($tdate->dayOfWeek == '0') {
                        $hd = 'SUNDAY';
                        $ho++;
                        $calendar .= "\n Calendar  ".$dt."==>".$hd;
                    }else {
                        $shifts = DB::table('shift_details')
                                        ->where('idShift', '=', $emp_shift->idShift)
                                        ->where('idWeekday', '=', $tdate->dayOfWeek)
                                        ->where('weekOff', '=', 'Y')
                                        ->first(); 
                        if($shifts != null)                
                        {
                            $ho++;
                            $calendar .= "\n Calendar  ".$dt."==> Week OFF";
                        }
                        else if($aintime != null){
                            {
                                if($intime  == null || $outtime == null){
                                    $calendar .= "\n Calendar  ".$dt."==> Incomplete Attendance";
                                }else{
                                    $p++;
                                    $calendar .= "\n Calendar  ".$dt."==> P";
                                }
                                
                            }
                        }else {
                            $a++;
                            $calendar .= "\n Calendar  ".$dt."==> A";
                        }
                    }
                }

                $calendar .= "\n Total Days ".$month->noOfDays;
                $calendar .= "\n Total Present  ".$p;
                $calendar .= "\n Total Absent  ".$a;
                $calendar .= "\n Total Half Day  ".$hf;
                $calendar .= "\n Total Week Off  ".$ho;
                $perDay = $totalEarnings / $month->noOfDays;
                $calendar .= "\n Salary Per Day ".$perDay;
                $calendar .= "\n Salary IS ".($perDay * ($p + $ho));
                $calendar .= "\n Deduction Fixed IS ". $totalDeductionFixed;
                $dyDeduction = ($totalDeductionDynamic / $month->noOfDays) * ($p + $ho);
                $calendar .= "\n Deduction Dynamic IS ". $dyDeduction;
                $total = ($perDay * ($p + $ho)) - ($totalDeductionFixed + $dyDeduction);
                $calendar .= "\n Total Payable ". $total;
                dd($data.'\n'.$calendar);
            }
        }




        /*if ($request->has('employees')) {

            $weekArray = [0 => 'Sunday', 1 => 'Monday', 2 => 'Tuesday', 3 => 'Wednesday', 4 => 'Thursday', 5 => 'Friday', 6 => 'Saturday'];

            $weekTotals = ['Sunday' => 0, 'Monday' => 0, 'Tuesday' => 0, 'Wednesday' => 0, 'Thursday' => 0, 'Friday' => 0, 'Saturday' => 0];

            $month = \App\Month::where('idMonth', '=', $request->idMonth)->first();
            $now = \Carbon\Carbon::now();
            $y = $now->year;
            $month_firstday = $y . '-' . $month->idMonth . '-01';
            $month_firstDate = \Carbon\Carbon::parse($month_firstday);
            $weekDay = $month_firstDate->dayOfWeek;
            $weekTotals[$weekArray[$weekDay]] = $weekTotals[$weekArray[$weekDay]] + 1;
            for ($i = 1; $i < $month->noOfDays; $i++) {
                $month_firstDate = $month_firstDate->addDays(1);
                $weekDay = $month_firstDate->dayOfWeek;
                $weekTotals[$weekArray[$weekDay]] = $weekTotals[$weekArray[$weekDay]] + 1;
            }

//            dd($weekTotals);
            foreach ($request->employees as $var) {
                $employee = \App\Employee::where('idEmployee', '=', $var)
                        ->first();
                $month = \App\Month::where('idMonth', '=', $request->idMonth)->first();
                // check Salary Already Generated
                $emp_sal_generated = \App\EmpPayment::where('idEmployee', '=', $var)->where('idMonth', '=', $request->idMonth)
                        ->where('idFinancialYear', '=', $request->fy)
                        ->first();
                if (empty($emp_sal_generated)) {
                    $now = \Carbon\Carbon::now();
                    $y = $now->year;

                    // $month_firstday = $y . '-' . $month->idMonth . '-01';
                    if ($month->noOfDays == '31') {
                        $monthlast_date = $y . '-' . $month->idMonth . '-' . $month->noOfDays;
                    } else {
                        $monthlast_date = $y . '-' . $month->idMonth . '-' . $month->noOfDays;
                    }

                    //get Total work days,holidays,weekoff, total present days,approved paid leave.
                    $holiday = \App\Holiday::where('idSchool', '=', Auth::guard('school')->user()->idSchool)
                                    ->whereDate('fromDate', '>', $month_firstday)
                                    ->whereDate('toDate', '<', $monthlast_date)
                                    ->get()->count();
                    $total_present = \App\EmpAttendance::where('idSchool', '=', Auth::guard('school')->user()->idSchool)->where('idMonth', '=', $request->idMonth)
                                    ->where('Enrollment_Number', '=', $employee->enrollmentNo)
                                    ->where(function($query) {
                                        $query->where('status', '=', 'In');
                                        $query->orWhere('status', '=', 'P');
                                    })
                                    ->get()->count();
                    $paid_leave = 0;
                    $paid_leave_empwise = \App\LeaveMaster::where('idEmployee', '=', $var)
                                     ->where('idFinancialYear', '=', $request->fy)
                                    ->first();
                    if(!empty($paid_leave_empwise)){
                        $paid_leave = $paid_leave_empwise->paidLeaves;
                    }else{
                        $paid_leave_desigwise = \App\LeaveMaster::where('idDesignation', '=', $employee->idDesignation)
                                    ->where('idFinancialYear', '=', $request->fy)
                                    ->first();
                        if(!empty($paid_leave_desigwise)){
                             $paid_leave = $paid_leave_desigwise->paidLeaves;
                        }
                    }
                   
                    //dd($paid_leave);
                    $emp_leave = \App\EmployeeLeave::where('idEmployee', '=', $var)
                                    ->whereDate('fromDate', '>', $month_firstday)
                                    ->whereDate('toDate', '<', $monthlast_date)
                                    ->where('status', '=', 'PL')
                                    ->get()->count();
//                dd($emp_leave);
                    //  //GET WEEKOFF
                    $emp_shift = \App\AssignShift::where('idEmployee', '=', $var)->first();
                    $weekofftotal = 0;
                    if ($emp_shift != null) {
                        $weekoff = DB::table('shift_details')
                                        ->join('weekdays', 'shift_details.idWeekday', '=', 'weekdays.idWeekday')
                                        ->where('idShift', '=', $emp_shift->idShift)
                                        ->where('weekOff', '=', 'Y')->get()->pluck('dayName')->toArray();

                        foreach ($weekoff as $k => $v) {
                            if (isset($weekTotals[$v])) {
                                $weekofftotal += $weekTotals[$v];
                            } else {
                                $weekofftotal = 0;
                            }
                        }                
                    } else {
                        $desigshift = \App\AssignShift::where('idDesignation', '=', $employee->idDesignation)
                                ->whereNull('idEmployee')
                                ->first();
                        if(isset($desigshift->idShift)){
                            $weekoff = DB::table('shift_details')
                            ->join('weekdays', 'shift_details.idWeekday', '=', 'weekdays.idWeekday')
                            ->where('idShift', '=', $desigshift->idShift)
                            ->where('weekOff', '=', 'Y')->get()->pluck('dayName')->toArray();
                            foreach ($weekoff as $k => $v) {
                                if (isset($weekTotals[$v])) {
                                    $weekofftotal += $weekTotals[$v];
                                } else {
                                    $weekofftotal = 0;
                                }
                            } 
                        }else{
                            flash('Shift not assigned for employee '. $employee->firstName);
                            return redirect('school/salgen');
                        }        
                      
                    }
                    $salarydays = $holiday + $total_present + $emp_leave + $weekofftotal;
//                dd($salarydays);
                    $request->salGeneration($salarydays, $month, $employee,$request->fy);
                }
            }
        }
        flash('Salary generated Successfully');
        return redirect('school/emppayments');
    }*/

    public function paySalary($id, $idmonth) {
        $empsalary = \App\EmpPayment::where('idEmpPayment', '=', $id)->first();
        if($empsalary == null) {
            return redirect('/school/emppayments');
        }
        $month = \App\Month::where('idMonth', '=', $idmonth)->first();
        $employee = \App\Employee::where('idEmployee', '=', $empsalary->idEmployee)->first();
        $now = \Carbon\Carbon::now();
        $y = $now->year;
        $earnings = \App\SalaryStrAllowances::where('idSalaryStr', '=', $empsalary->idSalaryStr)->get();
        $deductions = \App\SalaryStrDeduction::where('idSalaryStr', '=', $empsalary->idSalaryStr)->get();

        /*$month_firstday = $y . '-' . $month->idMonth . '-01';
        if ($month->noOfDays == '31') {
            $monthlast_date = $y . '-' . $month->idMonth . '-' . $month->noOfDays;
        } else {
            $monthlast_date = $y . '-' . $month->idMonth . '-' . $month->noOfDays;
        }
        $holiday = \App\Holiday::where('idSchool', '=', Auth::guard('school')->user()->idSchool)
                        ->whereDate('fromDate', '>', $month_firstday)
                        ->whereDate('toDate', '<', $monthlast_date)
                        ->get()->count();
        $total_present = \App\EmpAttendance::where('idMonth', '=', $idmonth)
                        ->where('Enrollment_Number', '=', $employee->enrollmentNo)
                        ->where(function($query) {
                            $query->where('status', '=', 'In');
                            $query->orWhere('status', '=', 'P');
                        })
                        ->get()->count();
        $emp_leave = \App\EmployeeLeave::where('idEmployee', '=', $employee->idEmployee)
                        ->whereDate('fromDate', '>', $month_firstday)
                        ->whereDate('toDate', '<', $monthlast_date)
                        ->where('status', '=', 'PL')
                        ->get()->count();
        $emp_salstr = \App\SalaryStructure::where('idEmployee', '=', $employee->idEmployee)->first();
        if ($emp_salstr != null) {
            $earnings = \App\SalaryStrAllowances::where('idSalaryStr', '=', $emp_salstr->idSalaryStr)->get();
            $deductions = \App\SalaryStrDeduction::where('idSalaryStr', '=', $emp_salstr->idSalaryStr)->get();
        } else {
            $desigsalstr = \App\SalaryStructure::where('idDesignation', '=', $employee->idDesignation)->whereNull('idEmployee')->first();
            $earnings = \App\SalaryStrAllowances::where('idSalaryStr', '=', $desigsalstr->idSalaryStr)->get();
            $deductions = \App\SalaryStrDeduction::where('idSalaryStr', '=', $desigsalstr->idSalaryStr)->get();, 'total_present', 'holiday', 'emp_leave'
        }*/
        return view('schools.hrms.paysalary', compact('empsalary', 'month', 'employee','earnings', 'deductions'));
    }

    public function payEmployeeSalary(Request $request) {
        // dd($request->all());
        $empsalary = \App\EmpPayment::where('idEmpPayment', '=', $request->idEmpPayment)->first();
        $empsalary->fill($request->all());
        $empsalary->totalSalary = ($empsalary->totalSalary + $request->extraEarning) - $request->extraDeduction;
        $empsalary->isPaid = 'Y';
        $empsalary->payDate = Carbon::now()->format('Y-m-d');
        $empsalary->update();
        return redirect('school/empsalary/' . $empsalary->idEmpPayment . '/' . $empsalary->idMonth . '/pay');
    }

    public function printSalarySlip($id, $idmonth) {
        $empsalary = \App\EmpPayment::where('idEmpPayment', '=', $id)->first();
        $school = \App\School::where('idSchool', '=', $empsalary->idSchool)->first();
        $month = \App\Month::where('idMonth', '=', $idmonth)->first();
        $employee = \App\Employee::where('idEmployee', '=', $empsalary->idEmployee)->first();
        $now = \Carbon\Carbon::now();
        $pay_start = '01' . '-' . $month->idMonth . '-' . $now->year;
        $pay_end = $month->noOfDays . '-' . $month->idMonth . '-' . $now->year;
        $y = $now->year;
        $earnings = \App\SalaryStrAllowances::where('idSalaryStr', '=', $empsalary->idSalaryStr)->get();
        $deductions = \App\SalaryStrDeduction::where('idSalaryStr', '=', $empsalary->idSalaryStr)->get();

        /*$month_firstday = $y . '-' . $month->idMonth . '-01';
        if ($month->noOfDays == '31') {
            $monthlast_date = $y . '-' . $month->idMonth . '-' . $month->noOfDays;
        } else {
            $monthlast_date = $y . '-' . $month->idMonth . '-' . $month->noOfDays;
        }
        $employee = \App\Employee::where('idEmployee', '=', $empsalary->idEmployee)->first();
        $holiday = \App\Holiday::where('idSchool', '=', Auth::guard('school')->user()->idSchool)
                        ->whereDate('fromDate', '>', $month_firstday)
                        ->whereDate('toDate', '<', $monthlast_date)
                        ->get()->count();
        $total_present = \App\EmpAttendance::where('idMonth', '=', $idmonth)
                        ->where('Enrollment_Number', '=', $employee->enrollmentNo)
                        ->where(function($query) {
                            $query->where('status', '=', 'In');
                            $query->orWhere('status', '=', 'P');
                        })
                        ->get()->count();
        $emp_leave = \App\EmployeeLeave::where('idEmployee', '=', $employee->idEmployee)
                        ->whereDate('fromDate', '>', $month_firstday)
                        ->whereDate('toDate', '<', $monthlast_date)
                        ->where('status', '=', 'PL')
                        ->get()->count();
        $emp_salstr = \App\SalaryStructure::where('idEmployee', '=', $employee->idEmployee)->first();
        if ($emp_salstr != null) {
            $earnings = \App\SalaryStrAllowances::where('idSalaryStr', '=', $emp_salstr->idSalaryStr)->get();
            $deductions = \App\SalaryStrDeduction::where('idSalaryStr', '=', $emp_salstr->idSalaryStr)->get();
        } else {
            $desigsalstr = \App\SalaryStructure::where('idDesignation', '=', $employee->idDesignation)->whereNull('idEmployee')->first();
            $earnings = \App\SalaryStrAllowances::where('idSalaryStr', '=', $desigsalstr->idSalaryStr)->get();
            $deductions = \App\SalaryStrDeduction::where('idSalaryStr', '=', $desigsalstr->idSalaryStr)->get();
        }*/
        $pdf = PDF::loadView('schools.hrms.print_salaryslip', ['margin_top' => 20], compact('pay_start','pay_end','school', 'empsalary', 'month', 'employee', 'earnings', 'deductions'));
        return $pdf->stream('salaryslip.pdf');
    }

    public function printGeneration(Request $request){
        $school = \App\School::where('idSchool', '=', Auth::guard('school')->user()->idSchool)->first();
        $employees = \App\Employee::where('idSchool', '=', Auth::guard('school')->user()->idSchool)
                ->orderBy('firstName', 'asc');
        if ($request->has('employees') && count($request->employees) > 0) {
            $employees = $employees->whereIn('idEmployee', $request->employees)->get();
        } elseif ($request->has('designations') && count($request->designations) > 0) {
            $employees = $employees->whereIn('idDesignation', $request->designations)->get();
        } else if ($request->has('idDepartment') && $request->idDepartment != null) {
            $employees = $employees->whereIn('idDepartment', $request->departments)->get();
        } else {
            $employees = $employees->get();
        }
        $financialYear = $request->get('fy');
        $month = $request->get('idMonth');

        $pdf = PDF::loadView('schools.hrms.print_salary', ['margin_top' => 20], compact('school', 'month', 'employees', 'financialYear'));
        return $pdf->stream('salary.pdf');
    }

    public function fetchLoan(){
        $departments = ['' => '--Select--'] + \App\Department::where('idSchool', '=', Auth::guard('school')->user()->idSchool)
        ->orderBy('departmentName')->get()->pluck('departmentName', 'idDepartment')->toArray();
        $loan =  \App\SalaryLoan::where('idSchool', '=', Auth::guard('school')->user()->idSchool)
        ->where('idFinancialYear', '=', Session::get('idFinancialYear'))
        ->orderBy('id','DESC')->get();
        return view('schools.hrms.salary_loan',compact('departments','loan'));
    }

    public function deleteLoan($id){
        $late = \App\SalaryLoan::where('id', '=', $id)->first();
        $late->delete();
        return response()->json(['success' => "SUCCESS"], 200, ['app-status' => 'success']);
    }

    public function storeLoan(Request $request){
        $rules = [
            'idDepartment' => 'required',
            'loan_amount'=>'required',
            'monthly_emi'=>'required'
        ];
        if (count($request->designations) == 0) {
            $rules += ['idDesignation' => 'required'];
        }
        $messages = [
            'idDepartment.required' => 'Department must be selected.',
            'loan_amount.required'=>'Please enter a valid amount.',
            'monthly_emi.required'=>'Please enter a valid monthly amount.',
        ];
        $this->validate($request, $rules, $messages);
        if ($request->has('employees')) {
            foreach ($request->employees as $key => $value) {
                $emp = \App\Employee::where('idEmployee', '=', $value)->first();
                $late = new \App\SalaryLoan();
                $late->fill($request->all());
                $late->idEmployee = $value;
                $late->idDesignation = $emp->idDesignation;
                $late->idFinancialYear =  Session::get('idFinancialYear');
                $late->idSchool = Auth::guard('school')->user()->idSchool;
                $late->save();
            }
        } else {
            foreach ($request->designations as $key1 => $value1) {
                $late = new \App\SalaryLoan();
                $late->fill($request->all());
                $late->idDesignation = $value1;
                $late->idFinancialYear =  Session::get('idFinancialYear');
                $late->idSchool = Auth::guard('school')->user()->idSchool;
                $late->save();
            }
        }
        flash('Loan has been added successfully !!');
        return redirect('school/salary-loan');
    }

    public function fetchCanteen(Request $request){
        $departments = ['' => '--Select--'] + \App\Department::where('idSchool', '=', Auth::guard('school')->user()->idSchool)
                        ->orderBy('departmentName')->get()->pluck('departmentName', 'idDepartment')->toArray();
        $canteen = [];        
        if($request->get('month') != ""){
            $canteen =  \App\SalaryCanteen::where('idSchool', '=', Auth::guard('school')->user()->idSchool)
            ->where('idFinancialYear', '=', Session::get('idFinancialYear'))
            ->where('idMonth', '=', $request->get('month'))
            ->orderBy('id','DESC')->get();
        }    
        
        return view('schools.hrms.salary_canteen',compact('departments','canteen'));
    }

    public function deleteCanteen($id){
        $late = \App\SalaryCanteen::where('id', '=', $id)->first();
        $late->delete();
        return response()->json(['success' => "SUCCESS"], 200, ['app-status' => 'success']);
    }

    public function storeCanteen(Request $request){
        $rules = [
            'idDepartment' => 'required',
            'amount'=>'required'
        ];
        if (count($request->designations) == 0) {
            $rules += ['idDesignation' => 'required'];
        }
        $messages = [
            'idDepartment.required' => 'Department must be selected.',
            'amount.required'=>'Please enter a valid amount.',
        ];
        $this->validate($request, $rules, $messages);
        if ($request->has('employees')) {
            foreach ($request->employees as $key => $value) {
                $emp = \App\Employee::where('idEmployee', '=', $value)->first();
                $late = new \App\SalaryCanteen();
                $late->fill($request->all());
                $late->idEmployee = $value;
                $late->idMonth = $request->idMonth;
                $late->idDesignation = $emp->idDesignation;
                $late->idFinancialYear =  Session::get('idFinancialYear');
                $late->idSchool = Auth::guard('school')->user()->idSchool;
                $late->save();
            }
        } else {
            foreach ($request->designations as $key1 => $value1) {
                $late = new \App\SalaryCanteen();
                $late->fill($request->all());
                $late->idDesignation = $value1;
                $late->idMonth = $request->idMonth;
                $late->idFinancialYear =  Session::get('idFinancialYear');
                $late->idSchool = Auth::guard('school')->user()->idSchool;
                $late->save();
            }
        }
        flash('Canteen expense has been added successfully !!');
        return redirect('school/canteen-expense');
    }

}

Copyright © 2021 - 2025 IMMREX7