IMMREX7

aku nok ndi : /home/spdtg/www/schoolmis/app/Http/Requests/
File Up :
aku nok ndi : /home/spdtg/www/schoolmis/app/Http/Requests/GenerateSalary.php

<?php

namespace App\Http\Requests;

use Illuminate\Foundation\Http\FormRequest;
use DB;
use Log;
use Auth;
use Session;
use Carbon\Carbon;

class GenerateSalary extends FormRequest {

    /**
     * Determine if the user is authorized to make this request.
     *
     * @return bool
     */
    public function authorize() {
        return true;
    }

    /**
     * Get the validation rules that apply to the request.
     *
     * @return array
     */
    public function rules() {
        $rules = [];
        if ($this->has('employees') || $this->has('idEmployee')) {
            $rules = [];
        } else {
            $rules += ['employee' => 'required'];
        }
        return $rules;
    }

    public function messages() {
        $messages = ['employee.required' => 'At least one employee must be selected for Salary Generation.'];
        return $messages;
    }

    public function generate($saveRequire,$month,$employee,$fy,$year,$pos,$idMonth){
        if($employee != null){
            $school = \App\School::where('idSchool', '=', Auth::guard('school')->user()->idSchool)->first();
            $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"] = $employee->idEmployee;
            $data["pos"] = $pos;
            $data["loan"] = 0;
            $data["canteen"] = 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
            $totalEarnings = 0;
            $totalDeduction = 0;
            $dynamic = 0;
            $emp_salstr = \App\SalaryStructure::where('idEmployee', '=', $employee->idEmployee)->where('idFinancialYear', '=', $fy)->first();
            if($emp_salstr != null){
                $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"){
                        $totalDeduction = $totalDeduction + $deduction->amount;
                    }else{
                        $dynamic = $dynamic  + (($deduction->amount/$totalEarnings) * 100);
                    }
                }
                //check total leave
                $designationYearWise = \App\LeaveMaster::where('idSchool', '=', $employee->idSchool)
                    ->where('idDesignation', $employee->idDesignation)
                    ->where('idFinancialYear', $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', $fy)
                    ->where('leaveType', "yearly")
                    ->sum('paidLeaves');

                $designationMonthWise = \App\LeaveMaster::where('idSchool', '=', $employee->idSchool)
                    ->where('idDesignation', $employee->idDesignation)
                    ->where('idFinancialYear', $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', $fy)
                    ->where('leaveType', "monthly")
                    ->sum('paidLeaves') * 12;
                //calculate allowed leave in a finanacial year
                $totalLeave = $designationYearWise + $paidYearLeaves + $designationMonthWise + $paidMonthLeaves;
                $data['total_leave'] = $totalLeave;
                //check for total leave taken added in master
                $leaveBalance = DB::table('leave_balance_master')->where('idSchool', '=', $employee->idSchool)
                ->where('idDesignation', $employee->idDesignation)
                ->where('idFinancialYear', $fy)
                ->whereNull('idEmployee')->sum('balance') + DB::table('leave_balance_master')->where('idSchool', '=', $employee->idSchool)
                ->where('idEmployee', $employee->idEmployee)
                ->where('idFinancialYear', $fy)->sum('balance');
                $m = $month->idMonth;
                $y = $year;
                $pDate = '01' . '-' . $m . '-' . $y;
                //new year check 
                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
                $data["prev"] = DB::table('employee_leave')
                ->whereDate('leave_from', '<', Carbon::parse($pDate))
                ->whereDate('leave_from', '>', Carbon::parse($pMaxDate))
                ->where('idEmployee', $employee->idEmployee)
                ->where('idFinancialYear',$fy)
                ->where('status','Approve with PL(Paid Leave)')
                ->count();
                $leaveTaken = DB::table('employee_leaves')->where('idFinancialYear',$fy)->where('idSchool', '=',$employee->idSchool)->where('idEmployee', '=', $employee->idEmployee)->count() + $leaveBalance;
                $data['balance'] = $totalLeave - $leaveTaken;
                $data['total'] = $leaveTaken;
                $totalLateDays = 0;
                $totalEarlyDays = 0;
                $allowedLateMinutes = 0;
                $allowedEarlyMinutes = 0;
                $totalLateDays = 0;
                $totalEarlyDays = 0;
                $empDays = [];
                $chDays = [];
                $leaveMaster = fetchLeaveMaster($employee,$fy);
                for ($i = 1; $i <= $month->noOfDays; $i++) {
                    $dt = $i . '-' . $m . '-' . $y;
                    $tdate = Carbon::parse($dt);
                    $now = Carbon::now();
                    $jdate = $tdate->format('Y-m-d');
                    $cdate = intval($tdate->format('d'));
                    $length = $tdate->diffInDays($now);
                    $otHr = 0;
                    $otAmount = 0;
                    //check for holiday 
                    $holiday = getHoliday($employee,$jdate);
                    $shifts = fetchShift($employee,$jdate);
                    $dayNight = "AM";
                    $nightDay = "AM";
                    $isPaidLeaveMaster = "N";
                    $isLeaveMaster = "N";
                    $empDays[$cdate] = "A";
                    if($shifts != null && $holiday == null){
                        
                        $dayNight = strtoupper($shifts->shift_from);
                        $nightDay = strtoupper($shifts->shift_to);
                        $arrival = checkArrival($employee,$jdate,$shifts,$school,$dayNight,$fy,$allowedLateMinutes,$totalLateDays);
                        $departure = checkDeparture($employee,$jdate,$shifts,$school,$nightDay,$fy,$allowedEarlyMinutes,$totalEarlyDays);
                        $overtime = fetchOvertime($employee,$shifts,$dayNight,$nightDay,$school,$jdate,$fy);
                        $totalEarlyDays = $departure['days'];
                        $totalLateDays = $arrival['days'];


                        if(fetchPaidLeave($jdate,$employee) == 1){
                            $isPaidLeaveMaster = "Y";
                        }else
                        if($leaveMaster != null){
                            if($leaveMaster->leave_allocation == "A"){
                                $monthV = \App\Month::where('monthName', '=', $tdate->format('F'))->first();
                                if($cdate > 1 && $cdate < $month->noOfDays){
                                    if(isset($leaveMaster->exclude_month)){
                                        $monthV = \App\Month::where('monthName',$tdate->format('F'))->whereIn('idMonth',json_decode($leaveMaster->exclude_month,true))->get();
                                        if(count($monthV) == 0){
                                            //check for sandwich leave
                                            if($holiday != null){
                                                if(checkForSandwich($employee,$leaveMaster->sandwich,$empDays,$tdate,$cdate,$school) == 1){
                                                    $isLeaveMaster = "Y";
                                                }
                                            }

                                            if($shifts->weekOff  == "Y"){
                                                if(checkForSandwich($employee,$leaveMaster->sandwich,$empDays,$tdate,$cdate,$school) == 1){
                                                    $isLeaveMaster = "Y";
                                                }
                                            }
                                        }
                                    }else{
                                        //check for sandwich leave
                                    }
                                }
                            }
                        }
                    }

                    $nonPaidLeave = 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($nonPaidLeave != null){
                            $data["leave"]++;
                            $empDays[$cdate] = "A";
                        }else if($isPaidLeaveMaster == "Y"){
                            $data["current"]++;
                            $data["paid_leave"]++;
                            $empDays[$cdate] = "P";
                        }else{
                            if($isLeaveMaster == "Y" && $shifts != null){
                                $data["absent"]++;
                                $empDays[$cdate] = "A";
                            }else{
                                if($holiday != null){
                                    $data["present"]++;
                                    $empDays[$cdate] = "H";
                                }else{
                                    if($shifts != null){
                                        if($shifts->weekOff  == "Y"){
                                            $data["present"]++;
                                            $empDays[$cdate] = "H";
                                        }else{
                                            $empDays[$cdate] = "P";
                                            if(isset($shifts->fromTime) && isset($shifts->toTime)){
                                                if($arrival['status'] == "A"){
                                                    $data["absent"]++;
                                                    $empDays[$cdate] = "AB";
                                                }else if($departure['status'] == "A"){
                                                    $data["absent"]++;
                                                    $empDays[$cdate] = "AB";
                                                }else if($arrival['status'] == "I" && $departure['status'] == "I"){
                                                    $data["absent"]++;
                                                    $empDays[$cdate] = "A";
                                                }else if($arrival['status'] == "I" || $departure['status'] == "I"){
                                                    $data["incomplete"]++;
                                                }else if($departure['status'] == "P" && $arrival['status'] == "P"){
                                                    $data["present"]++;
                                                }else if( ( $departure['status'] == "LT" || $departure['status'] == "P") && ( $arrival['status'] == "LT" || $arrival['status'] == "P")){
                                                    $data["present"]++;
                                                }else if($departure['status'] == "HF" || $arrival['status'] == "HF"){
                                                    $data["half_day"]++;
                                                }

                                                if($overtime['status'] == "Y"){
                                                    $otHr = $otHr + $overtime['otHour'];
                                                    $otAmount = $otAmount + $overtime['otEarning'];
                                                }
                                            }
                                        }
                                    }
                                }
                            }
                        }
                }
            }
            $data["absent"] = $data["absent"] + $data['leave'];
            $adjustAbsent = 0;
            $autoLeave = 0;
            if(isset($leaveMaster)){
                if($leaveMaster != null){
                    if($leaveMaster->leave_allocation == "A"){
                        if(isset($leaveMaster->max_allowed)){
                            if($data["paid_leave"] < $leaveMaster->max_allowed){
                                $balnceLeave = $leaveMaster->max_allowed - $data["paid_leave"];
                                if( $balnceLeave > 0 &&  $balnceLeave < $data["absent"]){
                                    $adjustAbsent = $balnceLeave;
                                    $autoLeave = $balnceLeave;
                                    $data["paid_leave"] = $data["paid_leave"] + $balnceLeave;
                                    $data['balance'] = $totalLeave - ($leaveTaken + $balnceLeave);
                                    $data['total'] = $leaveTaken + $balnceLeave;
                                }else{
                                    $adjustAbsent = $data["absent"];
                                    $autoLeave = $data["absent"];
                                    $data["paid_leave"] = $data["paid_leave"] + $data["absent"];
                                    $data['balance'] = $totalLeave - ($leaveTaken + $data["absent"]);
                                    $data['total'] = $leaveTaken + $data["absent"];
                                }
                            }

                            
                        }
                    }
                }
            }
            
            $data["absent"] = $data["absent"] - $adjustAbsent;
            if(Auth::guard('school')->user()->idSchool == 25 || Auth::guard('school')->user()->idSchool == 163)
            {
                $perSal = $totalEarnings / 30;
                $data["absent"] = $data["absent"] + $data["incomplete"];
                $data["incomplete"] = 0;
            }
            else $perSal = $totalEarnings / $month->noOfDays;
            $halfSal = $perSal/2;
            $rawSal = (($data["present"]+$data["paid_leave"]) * $perSal) + ($data["half_day"] * $halfSal);
            $data["leave_count"] = $data["absent"] + round(($data["half_day"]/2),1);
            $data["deduction"] =  round($data["leave_count"] * ($totalEarnings / 30));

            $totalSal = $rawSal - $totalDeduction;
            if($dynamic > 0){
                $totalDeduction = $totalDeduction + (($totalSal * $dynamic) /100);
                $totalSal = $totalSal - (($totalSal * $dynamic) /100);
            }
            $data["salary_deduction"] = round($totalDeduction);
            $data["gross_salary"] = round($totalEarnings - ( $data["salary_deduction"] + $data["deduction"]) );
            //check epf
            $epfTotal = 0;
            if($emp_salstr != null){
                $epfTotal = fetchEpf($fy,$emp_salstr,$employee,$rawSal, $data["deduction"]);
            }
            $data['epf'] = $epfTotal;
            //check pt
            $ptTotal = 0;
            if($emp_salstr != null){
                $ptTotal = fetchPt($fy,$emp_salstr,$employee,$rawSal,$data["gross_salary"]);
            }
            $data['pt'] = intval($ptTotal);
            $totalSal = $totalSal - $ptTotal;
            $totalSal = $totalSal - $epfTotal;
            if(Auth::guard('school')->user()->idSchool == 25 || Auth::guard('school')->user()->idSchool == 163){
                $data["salary"] = $data["gross_salary"] - ($ptTotal + $epfTotal);
            }else
            $data["salary"] = round($totalSal);
            $ifSalaryExists = \App\EmpPayment::where('idMonth',$idMonth)->where('idFinancialYear',$fy)->where('idSchool',Auth::guard('school')->user()->idSchool)->where('idEmployee', $employee->idEmployee)->first();
            if($ifSalaryExists == null && $data["incomplete"] == 0) $data["btEnable"] = 1;
            else $data["btEnable"] = 0;

            $loan = \App\SalaryLoan::where('idFinancialYear',$fy)->where('idEmployee',$employee->idEmployee)->where('isPaid','N')->first();
            if($loan != null){
                $data['loan'] = intval($loan->monthly_emi);
                $data["salary"] = $data["salary"] - $loan->monthly_emi;
            }

            $canteen = \App\SalaryCanteen::where('idFinancialYear',$fy)->where('idEmployee',$employee->idEmployee)->where('idMonth',$idMonth)->first();
            if($canteen != null){
                $data['canteen'] =  intval($canteen->amount);
                $data["salary"] = $data["salary"] - $canteen->amount;
            }

            if($saveRequire == "Y" && $data["incomplete"] == 0 && $emp_salstr != null){
                $data["salary_deduction"] = $data["salary_deduction"] + $data["deduction"];
                \App\EmpPayment::where('idSchool',Auth::guard('school')->user()->idSchool)
                ->where('idMonth',$month->idMonth)->where('idFinancialYear',$fy)->where('idEmployee',$employee->idEmployee)->delete();
                $savesalry = new \App\EmpPayment();
                $savesalry->idMonth = $month->idMonth;
                $savesalry->idFinancialYear = $fy;
                $savesalry->idSchool = Auth::guard('school')->user()->idSchool;
                $savesalry->idEmployee = $employee->idEmployee;
                $savesalry->salaryDays = $data["present"];
                $savesalry->idSalaryStr = $emp_salstr->idSalaryStr;
                $savesalry->totalEarning = $data["salary"] + $totalDeduction + ceil($otAmount);
                $savesalry->totalDeduction = $totalDeduction;
                $savesalry->otHours =  round($otHr/60);
                $savesalry->otEarning = ceil($otAmount);
                $savesalry->laHours = 0;
                $savesalry->laDeduction = ceil($data["half_day"]* $halfSal);
                $savesalry->totalSalary = $data["salary"] + ceil($otAmount);
                $savesalry->half_day = $data["half_day"];
                $savesalry->leave_day = $data["leave"];
                $savesalry->absent_day = $data["absent"];
                $savesalry->paid_leave = $data["paid_leave"];
                $savesalry->pt_data = $ptTotal;
                $savesalry->epf_data = $epfTotal;
                if(Auth::guard('school')->user()->idSchool == 25 || Auth::guard('school')->user()->idSchool == 163){
                    $savesalry->totalDeduction = $data["salary_deduction"] + $data["deduction"];
                    $savesalry->laDeduction = $data["deduction"];
                    $savesalry->salary_offered = $totalEarnings;
                    $savesalry->increment = 0;
                    $savesalry->gross = $totalEarnings;
                    $savesalry->basic = $totalEarnings;
                    $savesalry->other = 0;
                    $savesalry->total_leaves = $totalLeave;
                    $savesalry->prev_month = $data["prev"];
                    $savesalry->during_month = $data["paid_leave"];
                    $savesalry->total_availed = $data["total"];
                    $savesalry->leave_balance = $data["balance"];
                    $savesalry->incomplete = $data["incomplete"];
                    $savesalry->leave_deduction = $data["leave_count"];
                    $savesalry->leave_deduction_amount = $data["deduction"];
                    $savesalry->salary_deduction =  $savesalry->totalDeduction;
                    $savesalry->gross_salary_month = $data["gross_salary"];
                    $savesalry->loan_deduction = $data["loan"];
                    $savesalry->canteen_deduction = $data["canteen"];
                    $this->storeLoanData($employee->idEmployee,$fy,$idMonth);
                }
                //add leave for auto leave
                $param = '-' . $m . '-' . $y;
                $this->storeLeaveData($empDays,$autoLeave,$employee->idEmployee,$param);
                $savesalry->save();
            }

            return $data;
        }
    }

    private function storeLoanData($idEmployee,$fy,$idMonth){
        $loan = \App\SalaryLoan::where('idFinancialYear',$fy)->where('idEmployee',$idEmployee)->where('isPaid','N')->first();
        if($loan != null){
            DB::table('employee_loan_history')->where('idLoan',$loan->id)
            ->where('month',$idMonth)->where('idFinancialYear',$fy)->where('idEmployee',$idEmployee)->delete();
            DB::table('employee_loan_history')->insert([
                'idFinancialYear' => $fy,
                'idLoan' => $loan->id,
                'month' => $idMonth,
                'amount' => $loan->monthly_emi,
                'idEmployee' => $idEmployee,
                'paid_on' => Carbon::now()->format('Y-m-d')
            ]);

            $total = DB::table('employee_loan_history')->where('idLoan',$loan->id)
            ->where('month',$idMonth)->where('idFinancialYear',$fy)->where('idEmployee',$idEmployee)->sum('amount');
            if($total == $loan->loan_amount){
                $loan->isPaid = "Y";
                $loan->paid_on = Carbon::now()->format('Y-m-d H:i:s');
            }
            $emi_paid = DB::table('employee_loan_history')->where('idLoan',$loan->id)
            ->where('month',$idMonth)->where('idFinancialYear',$fy)->where('idEmployee',$idEmployee)->count();
            $loan->emi_paid = $emi_paid;
            $loan->loan_paid = $total;
            $loan->update();
        }
    }

    private function storeLeaveData($empData,$leaveBalance,$idEmployee,$param){
        if($leaveBalance < 1) return 1;
        foreach($empData as  $key => $value){
            if($leaveBalance > 0){
                if($value == "A"){
                    \App\EmployeeLeave::where('leave_from',Carbon::parse($key.$param)->format("Y-m-d"))
                    ->where('leave_to',Carbon::parse($key.$param)->format("Y-m-d"))
                    ->where('idEmployee',$idEmployee)->where('remarks',"Auto Leave")->delete();

                    $employee = \App\Employee::where('idEmployee', '=', $idEmployee)->first();
                    $empleave = new \App\EmployeeLeave();
                    $empleave->idSchool =$employee ->idSchool;
                    $empleave->idEmployee = $employee ->idEmployee;
                    $empleave->leave_type = "Casual Leave (CL)";
                    $empleave->leave_from =Carbon::parse($key.$param)->format("Y-m-d");
                    $empleave->leave_to = Carbon::parse($key.$param)->format("Y-m-d");
                    $empleave->leave_message = "Leave auto assigned on salary generation";
                    $empleave->paid_avialable = "Auto Assign";
                    $empleave->idFinancialYear = Session::get('idFinancialYear');
                    $empleave->status = "Approve with PL(Paid Leave)";
                    $empleave->remarks = "Auto Leave";
                    $empleave->status_date = Carbon::now()->format("Y-m-d");
                    $empleave->status_by = Auth::guard('school')->user()->idSchoolUser;
                    $empleave->save();
                    $date = Carbon::parse($empleave->leave_from);
                    $now = Carbon::parse($empleave->leave_to);
                    $diff = $date->diffInDays($now) + 1;
                    DB::table('employee_leaves')
                    ->where('idEmployee',$empleave->idEmployee)
                    ->where('leave_date',$date->format("Y-m-d"))->delete();
                    
                    DB::table('employee_leaves')->insert([
                        "idSchool" =>  Auth::guard('school')->user()->idSchool,
                        "idEmployee" => $empleave->idEmployee,
                        "idFinancialYear" =>  Session::get('idFinancialYear'),
                        "idLeave" => $empleave->idLeave,
                        "idMonth" => $date->format('m'),
                        "leave_date" => $date->format("Y-m-d")
                    ]);
                    if($empleave->leave_from != $empleave->leave_to){
                        for ($x = 1; $x < $diff; $x++) {
                            $currentDay = $date->addDays(1);
                            DB::table('employee_leaves')
                            ->where('idEmployee',$empleave->idEmployee)
                            ->where('leave_date',$currentDay->format("Y-m-d"))->delete();
                            DB::table('employee_leaves')->insert([
                                "idSchool" =>  Auth::guard('school')->user()->idSchool,
                                "idEmployee" => $empleave->idEmployee,
                                "idFinancialYear" =>  Session::get('idFinancialYear'),
                                "idLeave" => $empleave->idLeave,
                                "idMonth" => $currentDay->format("m"),
                                "leave_date" => $currentDay->format("Y-m-d")
                            ]);
                        } 
                    }
                    $leaveBalance--;
                }
            }else
            return 0;
        }
        return 0;
    }

    public function salGeneration($salarydays, $month, $employee,$fy,$year) {
        if($employee != null){
                $data = array();
                $totalEarnings = 0;
                $totalDeductionFixed = 0;
                $totalDeductionDynamic = 0;
                $school = \App\School::where('idSchool', '=', Auth::guard('school')->user()->idSchool)->first();
                $emp_shift = \App\AssignShift::where('idEmployee', '=', $employee->idEmployee)->first();
                if($emp_shift != null){
                    $emp_salstr = \App\SalaryStructure::where('idEmployee', '=', $employee->idEmployee)->where('idFinancialYear', '=', $fy)->first();
                    if($emp_salstr != null){
                        $earnings = \App\SalaryStrAllowances::where('idSalaryStr', '=', $emp_salstr->idSalaryStr)->get();
                        foreach($earnings as $earning){
                            $totalEarnings = $totalEarnings + $earning->amount;
                        }

                        $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";
                        $lateHalf = "00:00";
                        $lateDays = 0;
                        $lateLeave = 0;
                        $currentLateDay = 0;
                        
                        $m = $month->idMonth;
                        if(isset($year))
                        $y = $year;
                        else $y = $now->year;
                        $p = 0;
                        $ab = 0;
                        $pl = 0;
                        $l = 0;
                        $inc = 0;
                        $hf = 0;
                        $otAmount = 0;
                        $otHr = 0;

                        $lateMaster = \App\LateArrivalMaster::where('idEmployee', '=', $employee->idEmployee)->where('idFinancialYear', '=', $fy)->first();
                        if($lateMaster != null){
                            $late = $lateMaster->lateAllowed;
                            $lateHalf = $lateMaster->halfDayAfter;
                            if($lateMaster->maxLeave != null)
                            $lateLeave = $lateMaster->maxLeave;
                            if($lateMaster->maxDays != null)
                            $lateDays = $lateMaster->maxDays;
                        }

                        $perSal = $totalEarnings / $month->noOfDays;
                        for ($i = 1; $i <= $month->noOfDays; $i++) {
                            $dt = $i . '-' . $m . '-' . $y;
                   
                            $tdate = Carbon::parse($dt);
                            $jdate = $tdate->format('Y-m-d');
                            if ($tdate->dayOfWeek == '0'){
                                $abstime = \App\EmpAttendance::where('Enrollment_Number', '=', $employee->enrollmentNo)
                                ->where('Device_ID', '=', $school->Device_ID)
                                ->whereDate('date', '=', $jdate)
                                ->where('status','A')
                                ->first();
                                if($abstime == null)
                                {
                                    $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)
                                    $p++;
                                    else $ab++;
                                }else $ab++;
                            }else{
                                //check paid 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){
                                //check unpaid leave
                                $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){
                                //check is holiday
                                $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();


                                if($holiday == null && $pholiday == null){

                                $shifts = DB::table('shift_details')
                                ->select('fromTime','toTime','weekOff')
                                ->join('weekdays', 'shift_details.idWeekday', '=', 'weekdays.idWeekday')
                                ->where('idShift', '=', $emp_shift->idShift)
                                ->where('dayName', '=', date('l', strtotime($tdate)))
                                ->first(); 

                                if($shifts->weekOff == "N"){
                                $aintime = \App\EmpAttendance::where('Enrollment_Number', '=', $employee->enrollmentNo)
                                            ->where('Device_ID', '=', $school->Device_ID)
                                            ->whereDate('date', '=', $jdate)
                                            ->where('status','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( $intime  == null && $outtime == null && $aintime == null){
                                                $ab++;
                                            }else if( $intime  == null || $outtime == null){
                                                //incomplete attendance
                                                if( $aintime =! null){
                                                    //od 
                                                    $p++;
                                                }else
                                                $inc++;
                                            }else{
                                    //complete attendance
                                    $isUpdate = 0;
                                    if(isset($intime->TimeStamp)){
                                        $start = Carbon::parse($shifts->fromTime);
                                        $arrival = Carbon::parse($intime->TimeStamp->format('h:i:s'));
                                        $lateTime = $arrival->diffForHumans($start,[]);
                                        //check for late arrival   
                                        if(str_contains($lateTime ,"after")){
                                            if($late != "00:00"){
                                                $allowedTime = explode(':',$late);
                                                $addOnMinutes = $allowedTime[0]*60 + $allowedTime[1];
                                                $cstart = Carbon::parse($shifts->fromTime)->addMinutes($addOnMinutes);
                                                $carrival = Carbon::parse($intime->TimeStamp->format('h:i:s'));
                                                
                                                //check of half day arrival
                                                if($lateHalf != "00:00"){
                                                    $kllowedTime = explode(':',$lateHalf);
                                                    $kddOnMinutes = $kllowedTime[0]*60 + $kllowedTime[1];
                                                    $kstart = Carbon::parse($shifts->fromTime)->addMinutes($kddOnMinutes);
                                                    $karrival = Carbon::parse($intime->TimeStamp->format('h:i:s'));
                                                    if(str_contains($karrival->diffForHumans($kstart,[]) ,"after")){
                                                        $hf++;
                                                        $isUpdate++;
                                                    }else if(str_contains($carrival->diffForHumans($cstart,[]) ,"after")){
                                                        $currentLateDay++;
                                                        if($lateDays > 0){
                                                            if($currentLateDay >= $lateDays){
                                                                $hf++;
                                                                $currentLateDay = 0;
                                                                $isUpdate++;
                                                            }
                                                        }

                                                        if($lateLeave > 0){
                                                            if($currentLateDay >= $lateLeave){
                                                                $ab++;
                                                                $currentLateDay = 0;
                                                                $isUpdate++;
                                                            }
                                                        }
                                                    }  
                                                }else
                                                if(str_contains($carrival->diffForHumans($cstart,[]) ,"after")){
                                                    $currentLateDay++;
                                                    if($lateDays > 0){
                                                        if($currentLateDay >= $lateDays){
                                                            $hf++;
                                                            $currentLateDay = 0;
                                                            $isUpdate++;
                                                        }
                                                    }

                                                    if($lateLeave > 0){
                                                        if($currentLateDay >= $lateLeave){
                                                            $ab++;
                                                            $currentLateDay = 0;
                                                            $isUpdate++;
                                                        }
                                                    }
                                                }
                                            }
                                        }else{
                                        //check for overtime
                                            $out_time =  explode(':',$outtime->TimeStamp->format('h:i:s'));
                                            if($out_time[0] > 7 && $out_time[0] < 12)
                                            $warrival =  ' AM';
                                            else $warrival = ' PM';

                                        $ot = DB::table('overtime')->where('idSchool', '=', Auth::guard('school')->user()->idSchool)->where('idEmployee',$employee->idEmployee)->first();
                                        if($ot == null){
                                                $aot = DB::table('overtime')->where('idSchool', '=', Auth::guard('school')->user()->idSchool)->whereNull('idEmployee')->first();
                                                if($aot != null){
                                                    $overtime = explode(':',$aot->otAfter);
                                                    $overMinutes = $overtime[0]*60 + $overtime[1];
                                                    $overstart = Carbon::parse($shifts->toTime.' PM')->addMinutes($overMinutes);
                                                    $overarrival = Carbon::parse($outtime->TimeStamp->format('h:i:s').$warrival);
                                                    if(str_contains($overarrival->diffForHumans($overstart,[]) ,"after")){
                                                        //overtime found
                                                        $totalDuration = $overarrival->diffInMinutes($overstart);
                                                        if(str_contains($aot->otRatio,":")){
                                                            $ratio = explode(':',$aot->otRatio);
                                                            if($ratio[0] > 0 && $ratio[1] > 0){
                                                                $shStart = Carbon::parse($shifts->fromTime);
                                                                $shStop = Carbon::parse($shifts->toTime.' PM');
                                                                $totalSh = $shStop->diffInMinutes($shStart);

                                                                $shiftHr = $perSal/($totalSh/60);
                                                                $otHr = $otHr + ($totalDuration/60);
                                                                $otAmount =  $otAmount + ( ($shiftH *  $ratio[1]) * ($totalDuration/60) );
                                                            }
                                                        }
                                                    }
                                                }
                                            }else{
                                                $overtime = explode(':',$ot->otAfter);
                                                $overMinutes = $overtime[0]*60 + $overtime[1];
                                                $overstart = Carbon::parse($shifts->toTime.' PM')->addMinutes($overMinutes);
                                                $overarrival = Carbon::parse($outtime->TimeStamp->format('h:i:s').$warrival);
                                                if(str_contains($overarrival->diffForHumans($overstart,[]) ,"after")){
                                                    //overtime found
                                                    $totalDuration = $overarrival->diffInMinutes($overstart);
                                                    if(str_contains($ot->otRatio,":")){
                                                        $ratio = explode(':',$ot->otRatio);
                                                        if($ratio[0] > 0 && $ratio[1] > 0){
                                                            $shStart = Carbon::parse($shifts->fromTime);
                                                            $shStop = Carbon::parse($shifts->toTime.' PM');
                                                            $totalSh = $shStop->diffInMinutes($shStart);

                                                            $shiftHr = $perSal/($totalSh/60);
                                                            $otHr = $otHr + ($totalDuration/60);
                                                            $otAmount =  $otAmount + ( ($shiftH *  $ratio[1]) * ($totalDuration/60) );
                                                        }
                                                    }   
                                                }
                                            }  
                                        }

                                        if($isUpdate == 0){
                                            $p++;
                                        }
                                    }   
                                }

                                }else{
                                //week off  
                                $p++;
                                }
                                }else{
                                //holiday
                                $p++;
                                } 
                                }else{
                                $l++;
                                }                
                                }else{
                                $pl++;
                                }
                            }

                                
                        }
                        
                        $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);
                        $ifSalaryExists = \App\EmpPayment::where('idMonth',$month->idMonth)->where('idFinancialYear',$fy)->where('idSchool',Auth::guard('school')->user()->idSchool)->where('idEmployee', $employee->idEmployee)->first();
                        if($ifSalaryExists == null && $inc == 0){
                            $savesalry = new \App\EmpPayment();
                            $savesalry->idMonth = $month->idMonth;
                            $savesalry->idFinancialYear = $fy;
                            $savesalry->idSchool = Auth::guard('school')->user()->idSchool;
                            $savesalry->idEmployee = $employee->idEmployee;
                            $savesalry->salaryDays = $p;
                            $savesalry->idSalaryStr = $emp_salstr->idSalaryStr;
                            $savesalry->totalEarning = $totalEarnings;
                            $savesalry->totalDeduction = $totalDeductionFixed + $totalDeductionDynamic;
                            $savesalry->otHours =  round($otHr);
                            $savesalry->otEarning = ceil($otAmount);
                            $savesalry->laHours = 0;
                            $savesalry->laDeduction = ceil($hf*$halfSal);
                            $savesalry->totalSalary = $data["salary"];
                            $savesalry->half_day = $data["half_day"];
                            $savesalry->leave_day = $data["leave"];
                            $savesalry->absent_day = $data["absent"];
                            $savesalry->paid_leave = $data["paid_leave"];
                            $savesalry->save();
                        }
                    }
                }
        }



        //$emp_shift = \App\AssignShift::where('idEmployee', '=', $employee->idEmployee)->first();
        //dd($emp_shift);


//        dd($salarydays);
        /*$workdays = $month->noOfDays;
        // Get Total Hours of shift
        
        $emp_latearrival = \App\LateArrivalMaster::where('idEmployee', '=', $employee->idEmployee)->first();
        $emp_overtime = \App\AssignOvertime::where('idEmployee', '=', $employee->idEmployee)->first();

        //Get Shift
        if (!empty($emp_shift)) {
            $shiftdet = \App\ShiftDetail::where('idShift', '=', $emp_shift->idShift)->where('weekOff', '=', 'N')->first();
        } else {
            $desigshift = \App\AssignShift::where('idDesignation', '=', $employee->idDesignation)->whereNull('idEmployee')->first();
            if (!empty($desigshift)) {
                $shiftdet = \App\ShiftDetail::where('idShift', '=', $desigshift->idShift)->where('weekOff', '=', 'N')->first();
            }
        }

        // Get Late Arrival If ANy

        if (!empty($emp_latearrival)) {
            $deduction_ratio = $emp_latearrival->deductionRatio;
            $ded_ratio = explode(':', $deduction_ratio);
        } else {
            $desigs_latearrival = \App\LateArrivalMaster::where('idDesignation', '=', $employee->idDesignation)->whereNull('idEmployee')->first();
            if (!empty($desigs_latearrival)) {
                $deduction_ratio = $desigs_latearrival->deductionRatio;
                $ded_ratio = explode(':', $deduction_ratio);
            }
        }

        // Get Overtime If ANy
        if (!empty($emp_overtime)) {
            $earning_ratio = $emp_overtime->otRatio;
            $otratio = explode(':', $earning_ratio);
        } else {
            $desigs_overtime = \App\AssignOvertime::where('idDesignation', '=', $employee->idDesignation)->whereNull('idEmployee')->first();
            if (!empty($desigs_overtime)) {
                $earning_ratio = $desigs_overtime->otRatio;
                $otratio = explode(':', $earning_ratio);
            }
        }

        $shift_fromtime = \Carbon\Carbon::parse($shiftdet->fromTime);

        $shift_totime = \Carbon\Carbon::parse($shiftdet->toTime);
        $duration = $shift_totime->diffInHours($shift_fromtime);

        // Get Total Late Arrivals
        $latearrivals = \App\EmpAttendance::where('idMonth', '=', $month->idMonth)
                        ->where('Enrollment_Number', '=', $employee->enrollmentNo)
                        ->where(function($query) {
                            $query->where('status', '=', 'In');
                            $query->orWhere('status', '=', 'P');
                        })
                        ->select(DB::raw('SUM(lateHours) as lateHours'))->first();

        // Get Total Overtime

        $overtime = \App\EmpAttendance::where('idMonth', '=', $month->idMonth)
                        ->where('Enrollment_Number', '=', $employee->enrollmentNo)
                        ->where(function($query) {
                            $query->where('status', '=', 'OUT');
                            $query->orWhere('status', '=', 'P');
                        })
                        ->select(DB::raw('SUM(otHours) as otHours'))->first();

        $emp_salstr = \App\SalaryStructure::where('idEmployee', '=', $employee->idEmployee)->first();

        if (!empty($emp_salstr)) {
            $earnings = \App\SalaryStrAllowances::where('idSalaryStr', '=', $emp_salstr->idSalaryStr)->get();
            $deductions = \App\SalaryStrDeduction::where('idSalaryStr', '=', $emp_salstr->idSalaryStr)->get();
            // Get Total Earnings and Deductions
            $salstr_earnings = \App\SalaryStrAllowances::where('idSalaryStr', '=', $emp_salstr->idSalaryStr)
                            ->select(DB::raw('SUM(amount) as earnings'))->first();
            $salstr_deduction = \App\SalaryStrDeduction::where('idSalaryStr', '=', $emp_salstr->idSalaryStr)
                            ->select(DB::raw('SUM(amount) as deductions'))->first();
            $totSal = $salstr_earnings->earnings - $salstr_deduction->deductions;

            $perdaysalary = $totSal / $workdays;
            $salary_calculated = $perdaysalary * $salarydays;

            $hourlyrate = $perdaysalary / $duration;
            if (isset($otratio)) {
                $overtime_earning = ($overtime->otHours) * ($hourlyrate * $otratio[1]);
            } else {
                $overtime_earning = 0;
            }

            if (isset($ded_ratio)) {
                $latededuction = ($latearrivals->lateHours) * ($hourlyrate * $ded_ratio[1]);
            } else {
                $latededuction = 0;
            }

            $salpaid = $salary_calculated + $overtime_earning - $latededuction;

            $ifSalaryExists = \App\EmpPayment::where('idMonth',$month->idMonth)->where('idFinancialYear',$fy)->where('idSchool',Auth::guard('school')->user()->idSchool)->where('idEmployee', $employee->idEmployee)->first();
            if($ifSalaryExists == null){
                $savesalry = new \App\EmpPayment();
                $savesalry->idMonth = $month->idMonth;
                $savesalry->idFinancialYear = $fy;
                $savesalry->idSchool = Auth::guard('school')->user()->idSchool;
                $savesalry->idEmployee = $employee->idEmployee;
                $savesalry->salaryDays = $salarydays;
                $savesalry->idSalaryStr = $emp_salstr->idSalaryStr;
                $savesalry->totalEarning = $salstr_earnings->earnings;
                $savesalry->totalDeduction = $salstr_deduction->deductions;
                $savesalry->otHours = $overtime->otHours;
                $savesalry->otEarning = $overtime_earning;
                $savesalry->laHours = $latearrivals->lateHours;
                $savesalry->laDeduction = $latededuction;
                $savesalry->totalSalary = $salpaid;
                $savesalry->save();
            }
            
        } 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();
            // Get Total Earnings and Deductions
            $salstr_earnings = \App\SalaryStrAllowances::where('idSalaryStr', '=', $desigsalstr->idSalaryStr)
                            ->select(DB::raw('SUM(amount) as earnings'))->first();
            $salstr_deduction = \App\SalaryStrDeduction::where('idSalaryStr', '=', $desigsalstr->idSalaryStr)
                            ->select(DB::raw('SUM(amount) as deductions'))->first();

            $totSal = $salstr_earnings->earnings - $salstr_deduction->deductions;
            $perdaysalary = $totSal / $workdays;
            $salary_calculated = $perdaysalary * $salarydays;
            $hourlyrate = $perdaysalary / $duration;

            if (isset($otratio)) {
                $overtime_earning = ($overtime->otHours) * ($hourlyrate * $otratio[1]);
            } else {
                $overtime_earning = 0;
            }

            if (isset($ded_ratio)) {
                $latededuction = ($latearrivals->lateHours) * ($hourlyrate * $ded_ratio[1]);
            } else {
                $latededuction = 0;
            }

            $salpaid = $salary_calculated + $overtime_earning - $latededuction;

            $ifSalaryExists = \App\EmpPayment::where('idMonth',$month->idMonth)->where('idFinancialYear',$fy)->where('idSchool',Auth::guard('school')->user()->idSchool)->where('idEmployee', $employee->idEmployee)->first();
            if($ifSalaryExists == null){
                $savesalry = new \App\EmpPayment();
                $savesalry->idMonth = $month->idMonth;
                $savesalry->idFinancialYear = $fy;
                $savesalry->idSchool = Auth::guard('school')->user()->idSchool;
                $savesalry->idEmployee = $employee->idEmployee;
                $savesalry->salaryDays = $salarydays;
                $savesalry->idSalaryStr = $desigsalstr->idSalaryStr;
                $savesalry->totalEarning = $salstr_earnings->earnings;
                $savesalry->totalDeduction = $salstr_deduction->deductions;
                $savesalry->otHours = $overtime->otHours;
                $savesalry->otEarning = $overtime_earning;
                $savesalry->laHours = $latearrivals->lateHours;
                $savesalry->laDeduction = $latededuction;
                $savesalry->totalSalary = $salpaid;
                $savesalry->save();
            }
        }*/
    }

}

Copyright © 2021 - 2025 IMMREX7