IMMREX7

aku nok ndi : /home/spdtg/www/schoolmis/app/
File Up :
aku nok ndi : /home/spdtg/www/schoolmis/app/helpers.php

<?php

/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */

function checkActive($path, $active = 'active badge-info') {
    if (is_string($path)) {
        return request()->is($path) ? $active : '';
    }
    foreach ($path as $str) {
        if (checkActive($str) == $active)
            return $active;
    }
}

function fetchStudentAttendance($date){
    $now =  \Carbon\Carbon::parse($date);
    return DB::table('attandance')->where('idSchool', '=', Auth::guard('school')->user()->idSchool)
               ->select('Enrollment_Number')->whereDate('date',$now->format('Y-m-d'))->whereIn('status',['IN','P','p'])->groupBy('Enrollment_Number')->get()->count();
}

function checkNumeric($num){
    return is_null($num)?0:$num;
}

function bestofTwo($a,$b,$c){
    if($a == null || $a =="") $a = 0;
    if($b == null || $b =="") $b = 0;
    if($c == null || $c =="") $c = 0;

    $lar = max($a,$b,$c);
    if($a === $lar) $sec = max($b,$c);
    else if($b === $lar) $sec = max($a,$c);
    else $sec = max($a,$b);
    return [$lar,$sec];
}

function returnGrade($g){
    $gradeRange = [
        "A1" => "91-100",
        "A2" => "81-90",
        "B1" => "71-80",
        "B2" => "61-70",
        "C1" => "51-60",
        "C2" => "41-50",
        "D" => "33-40",
        "E" => "0-32"
    ];
    foreach($gradeRange as $key =>$value){
        $numbers = explode("-",$value);
        if($g <= $numbers[1] && $g >= $numbers[0]) return $key;
    }
    return "-";
}

function returnGrade40($g){
    $gradeRange = [
        "A+" => "33-40",
        "A" => "25-32",
        "B" => "17-24",
        "C" => "10-16",
        "D" => "0-9",
    ];
    foreach($gradeRange as $key =>$value){
        $numbers = explode("-",$value);
        if($g <= $numbers[1] && $g >= $numbers[0]) return $key;
    }
    return "-";
}

function returnGrade20($g){
    $gradeRange = [
        "A+" => "17-20",
        "A" => "13-16",
        "B" => "9-12",
        "C" => "5-8",
        "D" => "0-4",
    ];
    foreach($gradeRange as $key =>$value){
        $numbers = explode("-",$value);
        if($g <= $numbers[1] && $g >= $numbers[0]) return $key;
    }
    return "-";
}

function expandActive($path, $active = 'active') {
    if (is_string($path)) {
        return request()->is($path) ? $active : '';
    }
    foreach ($path as $str) {
        if (expandActive($str) == $active)
            return 'border: 2px solid;';
    }
}

function rand_color($k) {
    $colors = ["#F44336","#9C27B0","#E91E63","#673AB7","#3F51B5","#2196F3","#03A9F4","#00BCD4","#009688","#4CAF50","#8BC34A","#FFC107","#FF9800","#FF5722","#795548","#9E9E9E","#607D8B","#000000"];
    if($k < count($colors)) return $colors[$k];
    else return '#' . str_pad(dechex(mt_rand(0, 0xFFFFFF)), 6, '0', STR_PAD_LEFT);
}

function deny($redirect = '') {
    if (strlen($redirect) > 0) {
        return redirect($redirect);
    } else {
        flash()->warning("You don't have access to this resource!!");
    }
    return redirect()->back();
}

function next_admno() {
    $no = App\NoGenerator::firstOrCreate(['idSchool' => Auth::guard('school')->user()->idSchool, 'type' => 'admno']);
    $no->increment('no', 1);
    return $no->no;
}

function next_receiptno() {
    $no = App\NoGenerator::firstOrCreate(['idSchool' => Auth::guard('school')->user()->idSchool, 'type' => 'receipt']);
    $no->increment('no', 1);
    return $no->no;
}

function extra_receiptno() {
    $no = App\NoGenerator::firstOrCreate(['idSchool' => Auth::guard('school')->user()->idSchool, 'type' => 'receipt_extra']);
    $no->increment('no', 1);
    return $no->no;
}

function next_libraryreceiptno() {
    $no = App\NoGenerator::firstOrCreate(['idSchool' => Auth::guard('school')->user()->idSchool, 'type' => 'library-receipt']);
    $no->increment('no', 1);
    return $no->no;
}

function next_goodsreceiptno() {
    $no = App\NoGenerator::firstOrCreate(['idSchool' => Auth::guard('school')->user()->idSchool, 'type' => 'goods-received']);
    $no->increment('no', 1);
    return $no->no;
}

function next_invoice_receiptno() {
    $no = App\NoGenerator::firstOrCreate(['idSchool' => Auth::guard('school')->user()->idSchool, 'type' => 'invoice-receipt']);
    $no->increment('no', 1);
    return $no->no;
}

function next_productreceiptno() {
    $no = App\NoGenerator::firstOrCreate(['idSchool' => Auth::guard('school')->user()->idSchool, 'type' => 'product-receipt']);
    $no->increment('no', 1);
    return $no->no;
}

function next_purchaseno() {
    $no = App\NoGenerator::firstOrCreate(['idSchool' => Auth::guard('school')->user()->idSchool, 'type' => 'purchase']);
    $no->increment('no', 1);
    return $no->no;
}

function next_invoiceno() {
    $no = App\NoGenerator::firstOrCreate(['idSchool' => Auth::guard('school')->user()->idSchool, 'type' => 'invoice']);
    $no->increment('no', 1);
    return $no->no;
}
function next_virtualNo() {
    $no = App\NoGenerator::firstOrCreate(['idSchool' => 1, 'type' => 'virtual']);
    $no->increment('no', 1);
    return $no->no;
}

function student_receiptno() {
    $student = \App\AdmEntry::where('idStudent', '=', Session::get('idStudent'))->first();
    $no = App\NoGenerator::firstOrCreate(['idSchool' => $student->idSchool, 'type' => 'receipt']);
    $no->increment('no', 1);
    return $no->no;
}

function next_vno() {
    $no = App\NoGenerator::firstOrCreate(['idSchool' => Auth::guard('school')->user()->idSchool, 'type' => 'vno']);
    $no->increment('no', 1);
    return $no->no;
}

function today_date() {
    return Carbon\Carbon::today()->format('d-m-Y');
}

function yesterday_date() {
    return Carbon\Carbon::yesterday()->format('d-m-Y');
}

function tomorrow_date() {
    return Carbon\Carbon::tomorrow()->format('d-m-Y');
}

function getMonths() {
    $months = ['' => '--Select Month---'] + \App\Month::get()->pluck('monthName', 'idMonth')->toArray();
    return $months;
}

function getHolidaytype() {
    $type = ['' => '--Select---', 'Holiday' => 'Holiday', 'Weekly-Off' => 'Weekly-Off', 'PTM' => 'PTM', 'Other Event' => 'Other Event'];
    return $type;
}

function cardholderType() {
    $type = ['' => 'Select', 'Student' => 'Student']+ \App\Department::where('idSchool', '=', Auth::guard('school')->user()->idSchool)->get()->pluck('departmentName', 'idDepartment')->toArray();
    return $type;
}

function weekdays() {
    $days = \App\Weekday::where('isActive', '=', 'Y')->orderBy('idWeekday')->get()->pluck('dayName', 'idWeekday')->toArray();
    return $days;
}

function payMode() {
    $mode = ['Online' => 'By Online', 'Cash' => 'By Cash', 'Card' => 'By Card', 'Cheque' => 'By Cheque', 'DD' => 'By DD', 'IMPS' => 'By Bank Transfer'];
    return $mode;
}

function payModeReport() {
    $mode = ['All' => 'All', 'Cash' => 'Cash', 'Card' => 'Card', 'Cheque' => 'Cheque', 'DD' => 'DD','Online' => 'By Online','IMPS' => 'By Bank Transfer'];
    return $mode;
}

function getChequeStatus() {
    $status = ['In-Process' => 'In-Process', 'Cleared' => 'Cleared', 'Bounced' => 'Bounced'];
    return $status;
}

function getOnlineStatus() {
    $status = ['Bounced' => 'Bounced'];
    return $status;
}

function banks() {
    $banks = ['' => '--Select--'] + \App\Bank::orderBy('bankName')->get()->pluck('bankName', 'idBank')->toArray();
    return $banks;
}

function fetchAccounts(){
    $banks = ['' => '--Select--']+ \App\PaidAccounts::join('banks','account_paid.idPayBank','=','banks.idBank')->select(DB::raw("UPPER(CONCAT(accountName,'-',accountNo,'-',bankName)) as banks"),'idAccount')->where('idSchool', '=', Auth::guard('school')->user()->idSchool)->orderBy('idAccount')->get()->pluck('banks', 'idAccount')->toArray();;
    return $banks;
}

function figToWord($number) {
    $array = array('01' => 'One', '02' => 'Two', '03' => 'Three', '04' => 'Four', '05' => 'Five', '06' => 'Six', '07' => 'Seven', '08' => 'Eight', '09' => 'Nine', '10' => 'Ten', '11' => 'Eleven', '12' => 'Twelve', '13' => 'Thirteen', '14' => 'Fourteen', '15' => 'Fifteen', '16' => 'Sixteen', '17' => 'Seventeen', '18' => 'Eighteen', '19' => 'Nineteen', '20' => 'Twenty', '30' => 'Thirty', '40' => 'Fourty', '50' => 'Fifty', '60' => 'Sixty', '70' => 'Seventy', '80' => 'Eighty', '90' => 'Ninety', '00' => '');
    $fig1 = getNumToString($number, 13, 2);
    $count = 13 - strlen(trim($fig1));
    $word2 = "";
    while ($count <= 11) {
        if ($count == '1' || $count == '3' || $count == '5' || $count == '8' || $count == '11') {
            $fig2 = trim(substr($fig1, $count - 1, 2));
            if (isset($array[$fig2]) && $array[$fig2] != '') {
                $word1 = trim($array[$fig2]);
            } else {
                $fig2 = trim(substr($fig1, $count - 1, 1));
                $fig2 = $fig2 . "0";
                if ($fig2 == '00') {
                    $count = $count + 2;
                    continue;
                }
                $word1 = trim($array[$fig2]);
                $fig3 = trim(substr($fig1, ($count + 1 - 1), 1));
                $fig3 = '0' . $fig3;
                $word1 = trim($word1) . ' ' . trim($array[$fig3]);
            }
            $count = $count + 2;
        } else {
            $fig2 = trim(substr($fig1, $count - 1, 1));
            $fig2 = '0' . $fig2;
            $count = $count + 1;
            if (!isset($array[$fig2]))
                $array[$fig2] = '';
            $word1 = trim($array[$fig2]);
            if ($fig2 == '00') {
                continue;
            }
        }

        switch ($count) {
            case '3':
                $word2 = trim($word2) . ' ' . trim($word1) . ' ' . 'Crore';
                break;
            case '5':
                $word2 = trim($word2) . ' ' . trim($word1) . ' ' . 'Lac';
                break;
            case '7':
                $word2 = trim($word2) . ' ' . trim($word1) . ' ' . 'Thousand';
                break;
            case '8':
                $word2 = trim($word2) . ' ' . trim($word1) . ' ' . 'Hundred';
                break;
            case '10':
                $count = $count + 1;
                if (trim(substr($fig1, $count - 1, 2)) == '00') {
                    $word2 = trim($word2) . ' ' . trim($word1) . ' ' . 'Only';
                    $count = $count + 1;
                } else {
                    $word2 = trim($word2) . ' ' . trim($word1) . ' ' . 'and';
                }
                break;
            case '13':
                $word2 = trim($word2) . ' ' . trim($word1) . ' ' . 'Paise Only';
                break;
        }
    }
    return $word2;
}
function figToWordDob($number) {
    $array = array('01' => 'One', '02' => 'Two', '03' => 'Three', '04' => 'Four', '05' => 'Five', '06' => 'Six', '07' => 'Seven', '08' => 'Eight', '09' => 'Nine', '10' => 'Ten', '11' => 'Eleven', '12' => 'Twelve', '13' => 'Thirteen', '14' => 'Fourteen', '15' => 'Fifteen', '16' => 'Sixteen', '17' => 'Seventeen', '18' => 'Eighteen', '19' => 'Nineteen', '20' => 'Twenty', '30' => 'Thirty', '40' => 'Fourty', '50' => 'Fifty', '60' => 'Sixty', '70' => 'Seventy', '80' => 'Eighty', '90' => 'Ninety', '00' => '');
    $fig1 = getNumToString($number, 13, 2);
    $count = 13 - strlen(trim($fig1));
    $word2 = "";
    while ($count <= 11) {
        if ($count == '1' || $count == '3' || $count == '5' || $count == '8' || $count == '11') {
            $fig2 = trim(substr($fig1, $count - 1, 2));
            if (isset($array[$fig2]) && $array[$fig2] != '') {
                $word1 = trim($array[$fig2]);
            } else {
                $fig2 = trim(substr($fig1, $count - 1, 1));
                $fig2 = $fig2 . "0";
                if ($fig2 == '00') {
                    $count = $count + 2;
                    continue;
                }
                $word1 = trim($array[$fig2]);
                $fig3 = trim(substr($fig1, ($count + 1 - 1), 1));
                $fig3 = '0' . $fig3;
                $word1 = trim($word1) . ' ' . trim($array[$fig3]);
            }
            $count = $count + 2;
        } else {
            $fig2 = trim(substr($fig1, $count - 1, 1));
            $fig2 = '0' . $fig2;
            $count = $count + 1;
            if (!isset($array[$fig2]))
                $array[$fig2] = '';
            $word1 = trim($array[$fig2]);
            if ($fig2 == '00') {
                continue;
            }
        }

        switch ($count) {
            case '3':
                $word2 = trim($word2) . ' ' . trim($word1) . ' ' . 'Crore';
                break;
            case '5':
                $word2 = trim($word2) . ' ' . trim($word1) . ' ' . 'Lac';
                break;
            case '7':
                $word2 = trim($word2) . ' ' . trim($word1) . ' ' . 'Thousand';
                break;
            case '8':
                $word2 = trim($word2) . ' ' . trim($word1) . ' ' . 'Hundred';
                break;
            case '10':
                $count = $count + 1;
                if (trim(substr($fig1, $count - 1, 2)) == '00') {
                    $word2 = trim($word2) . ' ' . trim($word1) . ' ' . '';
                    $count = $count + 1;
                } else {
                    $word2 = trim($word2) . ' ' . trim($word1) . ' ' . 'and';
                }
                break;
            case '13':
                $word2 = trim($word2) . ' ' . trim($word1) . ' ' . '';
                break;
        }
    }
    return $word2;
}

function getNumToString($varNumeric, $length, $decimal = 0) {
    $varNumeric = number_format(round($varNumeric, $decimal), $decimal, '.', '');
    $varNumeric = str_pad($varNumeric, $length - strlen(settype($varNumeric, 'string')), ' ', STR_PAD_LEFT);
    return $varNumeric;
}

function states() {
    $states = \App\State::orderBy('stateName')->get()->pluck('stateName', 'idState')->toArray();
    return $states;
}

function statesQatar() {
    $states = \App\StateQatar::orderBy('stateName')->get()->pluck('stateName', 'idState')->toArray();
    return $states;
}

function getFinancialYear() {
    $now = \Carbon\Carbon::now();
    if (Auth::guard('student')->check()) {
        $student = \App\AdmEntry::where('father_mobile', '=', Auth::guard('student')->user()->mobile)
                ->orWhere('mother_mobile', '=', Auth::guard('student')->user()->mobile)
                ->first();
        $finyear = \App\FinancialYear::where('idSchool', '=', $student->idSchool)->get();
    } else if (Auth::guard('teacher')->check()) {
        $teacher = \App\Employee::where('idEmployee', '=', Auth::guard('teacher')->user()->idEmployee)->first();
        $finyear = \App\FinancialYear::where('idSchool', '=', $teacher->idSchool)->get();
    } else {
        $finyear = \App\FinancialYear::where('idSchool', '=', Auth::guard('school')->user()->idSchool)->get();
    }
    foreach ($finyear as $fy) {
        $start_date = \Carbon\Carbon::parse($fy->startDate);
        $end_date = \Carbon\Carbon::parse($fy->endDate);
        if ($now->between($start_date, $end_date) == true || $end_date->diffInDays($now) == 0) {
            return $fy->idFinancialYear;
        }
    }
}

function fys() {
    $current_fy = [];
    $now = \Carbon\Carbon::now();
    if (Auth::guard('student')->check()) {
        $student = \App\AdmEntry::where('father_mobile', '=', Auth::guard('student')->user()->mobile)
                ->orWhere('mother_mobile', '=', Auth::guard('student')->user()->mobile)
                ->first();
        $finyear = \App\FinancialYear::where('idSchool', '=', $student->idSchool)->get();
    } else if (Auth::guard('teacher')->check()) {
        $teacher = \App\Employee::where('idEmployee', '=', Auth::guard('teacher')->user()->idEmployee)->first();
        $finyear = \App\FinancialYear::where('idSchool', '=', $teacher->idSchool)->get();
    } else {
        $finyear = \App\FinancialYear::where('idSchool', '=', Auth::guard('school')->user()->idSchool)->get();
    }
    foreach ($finyear as $fy) {
        $start_date = \Carbon\Carbon::parse($fy->startDate);
        $end_date = \Carbon\Carbon::parse($fy->endDate);
        if ($now->between($start_date, $end_date) == true || $end_date->diffInDays($now) == 0) {
            $current_fy = \App\FinancialYear::where('idFinancialYear', '=', $fy->idFinancialYear)
                            ->pluck('financialYearName', 'idFinancialYear')->toArray();
        }
    }
    if (Auth::guard('student')->check()) {
        $student = \App\AdmEntry::where('father_mobile', '=', Auth::guard('student')->user()->mobile)
                ->orWhere('mother_mobile', '=', Auth::guard('student')->user()->mobile)
                ->first();
        $all_fys = $current_fy + \App\FinancialYear::where('idSchool', '=', $student->idSchool)
                        ->whereNotIn('idFinancialYear', $current_fy)->pluck('financialYearName', 'idFinancialYear')
                ->toArray();
    } else if (Auth::guard('teacher')->check()) {
        $teacher = \App\Employee::where('idEmployee', '=', Auth::guard('teacher')->user()->idEmployee)->first();
        $all_fys = $current_fy + \App\FinancialYear::where('idSchool', '=', $teacher->idSchool)
                        ->whereNotIn('idFinancialYear', $current_fy)->pluck('financialYearName', 'idFinancialYear')
                ->toArray();
    } else {
        $all_fys = $current_fy + \App\FinancialYear::where('idSchool', '=', Auth::guard('school')->user()->idSchool)
                        ->whereNotIn('idFinancialYear', $current_fy)->pluck('financialYearName', 'idFinancialYear')
                ->toArray();
    }


    return $all_fys;
}

function getLeaveStatus() {
    $status = ['' => '--Select--', 'Approve with PL(Paid Leave)' => 'Approve with PL(Paid Leave)', 'Approve Without PL' => 'Approve Without PL', 'Rejected' => 'Reject'];
    return $status;
}

function getProductTaxes() {
    $taxes = ['0' => '0%', '5' => '5%', '8' => '8%', '12' => '12%', '18' => '18%', '28' => '28%'];
    return $taxes;
}

function fetchSchoolUser($id){
    return DB::table('school_users')->where('idSchoolUser',$id)->first()->name;
}

function getGraph($month,$year,$idSchool,$idFinancialYear){
    $main = \Carbon\Carbon::parse("01-".$month."-".$year);
    $startDate = \Carbon\Carbon::parse("01-".$month."-".$year);
    $endDate =\Carbon\Carbon::parse($main->endOfMonth()."-".$month."-".$year);
    $transaction = DB::table('student_transaction')
                    ->where('idSchool', $idSchool)
                    ->where('idFinancialYear',$idFinancialYear)
                    ->whereDate('paymentDate', '>=', $startDate)
                    ->whereDate('paymentDate', '<=', $endDate)
                    ->select(DB::raw('COUNT(*) as students'),'paymentDate')
                    ->where(function($query) {
                        $query->whereNull('status');
                        $query->orWhere('status', '=', 'Cleared');
                        $query->orWhere('status', '=', 'In-Process');
                        $query->orWhere('status', '=', 'Success');
                    })->groupBy('paymentDate')->get()->pluck('students')->toArray();
    return  $transaction; 
}

function getChequeGraph($month,$year,$idSchool,$idFinancialYear){
    $data = [];
    $main = \Carbon\Carbon::parse("01-".$month."-".$year);
    $startDate = \Carbon\Carbon::parse("01-".$month."-".$year);
    $endDate =\Carbon\Carbon::parse($main->endOfMonth()."-".$month."-".$year);
    $data['period'] =  $main->format('Y-m');
    $data['collection'] = DB::table('student_transaction')
                    ->where('idSchool', $idSchool)
                    ->where('idFinancialYear', $idFinancialYear)
                    ->whereDate('paymentDate', '>=', $startDate)
                    ->whereDate('paymentDate', '<=', $endDate)
                    ->where(function($query) {
                        $query->whereNull('status');
                        $query->orWhere('status', '=', 'Cleared');
                        $query->orWhere('status', '=', 'In-Process');
                        $query->orWhere('status', '=', 'Success');
                    })->sum('totalPaid') + DB::table('lesser_transaction')
                    ->where('idSchool', $idSchool)
                    ->where('idFinancialYear', $idFinancialYear)
                    ->whereDate('paymentDate', '>=', $startDate)
                    ->whereDate('paymentDate', '<=', $endDate)
                    ->where(function($query) {
                        $query->whereNull('status');
                        $query->orWhere('status', '=', 'Cleared');
                        $query->orWhere('status', '=', 'In-Process');
                        $query->orWhere('status', '=', 'Success');
                        $query->orWhere('status', '=', 'Bounced');
                    })->sum('totalPaid');
    $data['inprogress'] = DB::table('student_transaction')
                    ->where('idSchool',$idSchool)
                    ->where('idFinancialYear',$idFinancialYear)
                    ->whereDate('paymentDate', '>=', $startDate)
                    ->whereDate('paymentDate', '<=', $endDate)
                    ->where(function($query) {
                        $query->whereNull('status');
                        $query->orWhere('status', '=', 'Cleared');
                        $query->orWhere('status', '=', 'In-Process');
                        $query->orWhere('status', '=', 'Success');
                    })->sum('totalPaid') + DB::table('lesser_transaction')
                    ->where('idSchool',$idSchool)
                    ->where('idFinancialYear', $idFinancialYear)
                    ->whereDate('paymentDate', '>=', $startDate)
                    ->whereDate('paymentDate', '<=', $endDate)
                    ->where(function($query) {
                        $query->whereNull('status');
                        $query->orWhere('status', '=', 'Cleared');
                        $query->orWhere('status', '=', 'In-Process');
                        $query->orWhere('status', '=', 'Success');
                    })->sum('totalPaid');
    return $data;                
}

function getMonthCollection($month,$year,$idSchool,$idFinancialYear){
    $main = \Carbon\Carbon::parse("01-".$month."-".$year);
    $startDate = \Carbon\Carbon::parse("01-".$month."-".$year);
    $endDate =\Carbon\Carbon::parse($main->endOfMonth()."-".$month."-".$year);
    $transaction = DB::table('student_transaction')
                    ->where('idSchool', $idSchool)
                    ->where('idFinancialYear', $idFinancialYear)
                    ->whereDate('paymentDate', '>=', $startDate)
                    ->whereDate('paymentDate', '<=', $endDate)
                    ->where(function($query) {
                        $query->whereNull('status');
                        $query->orWhere('status', '=', 'Cleared');
                        $query->orWhere('status', '=', 'In-Process');
                        $query->orWhere('status', '=', 'Success');
                    })->sum('totalPaid') + DB::table('lesser_transaction')
                    ->where('idSchool', $idSchool)
                    ->where('idFinancialYear', $idFinancialYear)
                    ->whereDate('paymentDate', '>=', $startDate)
                    ->whereDate('paymentDate', '<=', $endDate)
                    ->where(function($query) {
                        $query->whereNull('status');
                        $query->orWhere('status', '=', 'Cleared');
                        $query->orWhere('status', '=', 'In-Process');
                        $query->orWhere('status', '=', 'Success');
                    })->sum('totalPaid');
    return  $transaction;                
    }

    function getAdvanceCollection($month,$year,$idSchool,$idFinancialYear){
        $main = \Carbon\Carbon::parse("01-".$month."-".$year);
        $startDate = \Carbon\Carbon::parse("01-".$month."-".$year);
        $endDate =\Carbon\Carbon::parse($main->endOfMonth()."-".$month."-".$year);
        $transaction = DB::table('student_transaction')
                        ->where('idSchool', $idSchool)
                        ->where('idFinancialYear', $idFinancialYear)
                        ->whereDate('paymentDate', '<=', $endDate)
                        ->where(function($query) {
                            $query->whereNull('status');
                            $query->orWhere('status', '=', 'Cleared');
                            $query->orWhere('status', '=', 'In-Process');
                            $query->orWhere('status', '=', 'Success');
                        })->sum('totalPaid') + DB::table('lesser_transaction')
                        ->where('idSchool', $idSchool)
                        ->where('idFinancialYear', $idFinancialYear)
                        ->whereDate('paymentDate', '<=', $endDate)
                        ->where(function($query) {
                            $query->whereNull('status');
                            $query->orWhere('status', '=', 'Cleared');
                            $query->orWhere('status', '=', 'In-Process');
                            $query->orWhere('status', '=', 'Success');
                        })->sum('totalPaid');
        return  $transaction;                
        }

        function getOverdue($student,$plan,$idSchool,$idFinancialYear){
            $main =  \Carbon\Carbon::now()->subMonth()->toDateString();
            $endDate = \Carbon\Carbon::parse($main);
            if($student->idSchool == 25){
                return 0;
            }else if($student->idSchool == 140 || $student->idSchool == 135 || $student->idSchool == 159 || $student->idSchool == 160 || $student->idSchool == 139){
                $class_feeheads = DB::table('feeheads')->where('idClass', '=', $student->idClass)
                        ->where('idSection', '=', $student->idSection)
                        ->where('idFinancialYear','=', $student->idFinancialYear)
                        ->where('idSchool','=', $student->idSchool)
                        ->where('studentCategory', '=', $student->studentType)
                        ->where('feeheadName', 'LIKE', $plan.'%')
                        ->whereDate('toDate', '<=', $endDate)
                        ->whereNull('idStudent');
                $allcat_feeheads = DB::table('feeheads')->where('idClass', '=', $student->idClass)
                        ->where('idSection', '=', $student->idSection)
                        ->where('idSchool','=', $student->idSchool)
                        ->where('studentCategory', '=', 'All')
                        ->where('idFinancialYear','=', $student->idFinancialYear)
                        ->where('feeheadName', 'LIKE', $plan.'%')
                        ->whereDate('toDate', '<=', $endDate)
                        ->whereNull('idStudent');
                $p_feeheads = DB::table('feeheads')->where('idClass', '=', $student->idClass)
                        ->where('idSection', '=', $student->idSection)
                        ->where('idSchool','=', $student->idSchool)
                        ->where('studentCategory', '=', 'All')
                        ->where('idFinancialYear','=', $student->idFinancialYear)
                        ->where('feeheadName', 'LIKE', 'P%')
                        ->whereDate('toDate', '<=', $endDate)
                        ->whereNull('idStudent');   
                $admission_feeheads = DB::table('feeheads')->where('idClass', '=', $student->idClass)
                        ->where('idSection', '=', $student->idSection)
                        ->where('studentCategory', '=', $student->studentType)
                        ->where('idSchool','=', $student->idSchool)
                        ->where('idFinancialYear','=', $student->idFinancialYear)
                        ->where('feeheadName', 'LIKE', 'Admission%')
                        ->whereDate('toDate', '<=', $endDate)
                        ->whereNull('idStudent');       
                $feeheads = DB::table('feeheads')->where('idStudent', '=', $student->idStudent)
                        ->where('idFinancialYear','=', $student->idFinancialYear)
                        ->where('idSchool','=', $student->idSchool)
                        ->where('feeheadName', 'LIKE', $plan.'%')
                        ->whereDate('toDate', '<=', $endDate)
                        ->union($class_feeheads)
                        ->union($p_feeheads)
                        ->union($admission_feeheads)
                        ->union($allcat_feeheads)
                        ->orderBy('idFeehead','ASC')
                        ->orderBy('toDate')
                        ->get();               
                $total = $feeheads->sum('amount');
                $transaction = DB::table('student_transaction')
                            ->where('idSchool', $idSchool)
                            ->where('idFinancialYear', $idFinancialYear)
                            ->where('idStudent', '=', $student->idStudent)
                            ->where(function($query) {
                                $query->whereNull('status');
                                $query->orWhere('status', '=', 'Cleared');
                                $query->orWhere('status', '=', 'In-Process');
                                $query->orWhere('status', '=', 'Success');
                            })->sum('totalPaid') + DB::table('lesser_transaction')
                            ->where('idSchool', $idSchool)
                            ->where('idFinancialYear', $idFinancialYear)
                            ->where('idStudent', '=', $student->idStudent)
                            ->where(function($query) {
                                $query->whereNull('status');
                                $query->orWhere('status', '=', 'Cleared');
                                $query->orWhere('status', '=', 'In-Process');
                                $query->orWhere('status', '=', 'Success');
                            })->sum('totalPaid');
                return $total - $transaction;
            }else{
                $class_feeheads = \DB::table('feeheads')->where('idClass', '=', $student->idClass)
                ->where('idSection', '=', $student->idSection)
                ->where('idFinancialYear','=', $student->idFinancialYear)
                ->where('studentCategory', '=', $student->studentType)
                ->whereDate('toDate', '<=', $endDate)
                ->whereNull('idStudent');
                $allcat_feeheads = \DB::table('feeheads')->where('idClass', '=', $student->idClass)
                        ->where('idSection', '=', $student->idSection)
                        ->where('studentCategory', '=', 'All')
                        ->where('idFinancialYear','=',$student->idFinancialYear)
                        ->whereDate('toDate', '<=', $endDate)
                        ->whereNull('idStudent');
                $feeheads = \DB::table('feeheads')->where('idStudent', '=', $student->idStudent)
                        ->where('idFinancialYear','=', $student->idFinancialYear)
                        ->whereDate('toDate', '<=', $endDate)
                        ->union($class_feeheads)
                        ->union($allcat_feeheads)
                        ->orderBy('toDate')
                        ->get(); 

                        $total = $feeheads->sum('amount');
                        $transaction = DB::table('student_transaction')
                            ->where('idSchool', $idSchool)
                            ->where('idFinancialYear', $idFinancialYear)
                            ->where('idStudent', '=', $student->idStudent)
                            ->where(function($query) {
                                $query->whereNull('status');
                                $query->orWhere('status', '=', 'Cleared');
                                $query->orWhere('status', '=', 'In-Process');
                                $query->orWhere('status', '=', 'Success');
                            })->sum('totalPaid') + DB::table('lesser_transaction')
                            ->where('idSchool', $idSchool)
                            ->where('idFinancialYear', $idFinancialYear)
                            ->where('idStudent', '=', $student->idStudent)
                            ->where(function($query) {
                                $query->whereNull('status');
                                $query->orWhere('status', '=', 'Cleared');
                                $query->orWhere('status', '=', 'In-Process');
                                $query->orWhere('status', '=', 'Success');
                            })->sum('totalPaid');
                return $total - $transaction;
            }
        }
        
        function getClassCollection($idClass,$idSchool,$idFinancialYear){
            $student = DB::table('students')->select('idClass','idSection','idStudent','idFinancialYear')
            ->where('idClass',$idClass)->where('idFinancialYear',$idFinancialYear)
            ->where('idSchool',$idSchool)->get()->pluck('idStudent')->toArray();
            $transaction = DB::table('student_transaction')
                            ->where('idSchool', $idSchool)
                            ->where('idFinancialYear', $idFinancialYear)
                            ->whereIn('idStudent', $student)
                            ->where(function($query) {
                                $query->whereNull('status');
                                $query->orWhere('status', '=', 'Cleared');
                                $query->orWhere('status', '=', 'In-Process');
                                $query->orWhere('status', '=', 'Success');
                            })->sum('totalPaid') + DB::table('lesser_transaction')
                            ->where('idSchool', $idSchool)
                            ->where('idFinancialYear', $idFinancialYear)
                            ->whereIn('idStudent', $student)
                            ->where(function($query) {
                                $query->whereNull('status');
                                $query->orWhere('status', '=', 'Cleared');
                                $query->orWhere('status', '=', 'In-Process');
                                $query->orWhere('status', '=', 'Success');
                            })->sum('totalPaid');
            return  $transaction;                
        }


 // HRMS helpers
function getHoliday($emp,$jdate){
    //check if individual holiday 
    $holiday = \App\HrmsHoliday::where('idSchool', '=', $emp->idSchool)
                ->where('idEmployee', $emp->idEmployee)
                ->whereDate('fromDate', '<=', $jdate)
                ->whereDate('toDate', '>=', $jdate)
                ->first();
    if($holiday == null){
        //for all department
        $holiday = \App\HrmsHoliday::where('idSchool', '=', $emp->idSchool)
        ->where('designation',0)
        ->where('department',0)
        ->whereNull('idEmployee')
        ->whereDate('fromDate', '<=', $jdate)
        ->whereDate('toDate', '>=', $jdate)
        ->first();

        if($holiday == null){
            //for specific department 
            $holiday = \App\HrmsHoliday::where('idSchool', '=', $emp->idSchool)
                ->where('designation',$emp->idDesignation)
                ->where('department',$emp->idDepartment)
                ->whereNull('idEmployee')
                ->whereDate('fromDate', '<=', $jdate)
                ->whereDate('toDate', '>=', $jdate)
                ->first();
        }
    }            

    return $holiday;
}  

function checkArrival($emp,$jdate,$shifts,$school,$dayNight,$idFinancialYear,$allowedMinutes,$totalLateDays){
    $display = [];
    $doSpecialShiftExisits = DB::table('special_shifts')->where('idEmployee', '=', $emp->idEmployee)->where('shift_date',$jdate)->where('type','S')->first();
    $a_mat = \App\EmpAttendance::where('Enrollment_Number', '=', $emp->enrollmentNo)
            ->where('idSchool', '=', $school->idSchool)
            ->whereDate('date', '=', $jdate)
            ->where('status', '=', 'P')
            ->where('idType', '=', 'M')
            ->first();

    if($a_mat == null){
        $aintime = \App\EmpAttendance::where('Enrollment_Number', '=', $emp->enrollmentNo)
                ->where('Device_ID', '=', $school->Device_ID)
                ->whereDate('date', '=', $jdate)
                ->where('status', '=', 'IN')
                ->where('idType', '=', 'A')
                ->first();
        if($doSpecialShiftExisits != null){
            if($doSpecialShiftExisits->is_night == "Y"){
                $aintime = \App\EmpAttendance::where('Enrollment_Number', '=', $emp->enrollmentNo)
                            ->where('Device_ID', '=', $school->Device_ID)
                            ->whereDate('date', '=', $jdate)
                            ->where('status', '=', 'OUT')
                            ->where('idType', '=', 'A')
                            ->first();
            }
        }
        $display['normal_html'] = "";
        if($aintime == null){
            $display['status'] = "I";
            $display['days'] = $totalLateDays;
            $display['html'] = '<span style="color:red;font-weight:bold" id="status_in_'.$emp->idEmployee.'">Incomplete Attendance(IN)</span><br>';
            return $display;
        }else{
            $display['status'] = "P";
            $display['days'] = $totalLateDays;
            $display['time'] = $aintime->TimeStamp;
            $display['html'] = '<span style="color:green;font-weight: bold">IN: '.explode(" ",$aintime->TimeStamp)[1].'</span><br>';
            //check late arrival conditions 
            $lateMaster = \App\LateArrivalMaster::where('idEmployee', '=', $emp->idEmployee)->where('idFinancialYear', $idFinancialYear)->first();
            if($lateMaster == null){
                $lateMaster = \App\LateArrivalMaster::where('idDesignation', '=', $emp->idDesignation)->where('idFinancialYear',$idFinancialYear)->first();
            }
            if(isset($shifts->fromTime)){
                $start = \Carbon\Carbon::parse($shifts->fromTime.' '.$dayNight);
                $arrival = \Carbon\Carbon::parse($aintime->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\Carbon::parse($shifts->fromTime.' '.$dayNight)->addMinutes($addOnMinutes);
                            $allowed = $arrival->diffForHumans($sr,[]);
                            $display['time'] = $arrival->diffInSeconds($sr);
                            if(str_contains($allowed, 'after')){
                                $halfTime = explode(':',$lateMaster->halfDayAfter);
                                $halfOnMinutes = $halfTime[0]*60 + $halfTime[1]; //calculate minutes
                                $haf = \Carbon\Carbon::parse($shifts->fromTime.' '.$dayNight)->addMinutes($halfOnMinutes);
                                $halfTouch = $arrival->diffForHumans($haf,[]); //check for half day
                                if(str_contains($halfTouch, 'after')){
                                    $display['status'] = "HF";
                                    $display['days'] = $totalLateDays;
                                    $display['late_html'] = '<span style="color:red;font-weight:bold">Late : '.$lateRequired.'(Half-Day)<br>';
                                    $display['normal_html'] = 'Late : '.$lateRequired.'(Half-Day)';
                                }else{
                                    $display['status'] = "LT";
                                    $display['late_html'] = '<span style="color:red;font-weight:bold">Late : '.$lateRequired.'<br>';
                                    $display['normal_html'] = 'Late : '.$lateRequired;
                                    $totalLateDays++;
                                    if($lateMaster->maxLeave > $lateMaster->maxDays){
                                        if($totalLateDays >= $lateMaster->maxLeave && $lateMaster->maxLeave > 0){
                                            $totalLateDays = 0;
                                            $display['status'] = "A";
                                            $display['late_html'] = '<span style="color:red;font-weight:bold">A(Leave Late : '.$lateMaster->maxLeave.' Days) <br>';
                                            $display['normal_html'] = 'A(Leave Late : '.$lateMaster->maxLeave.' Days)';
                                        }
                                    }else{
                                        if($totalLateDays >= $lateMaster->maxDays && $lateMaster->maxDays > 0){
                                            $totalLateDays = 0;
                                            $display['status'] = "HF";
                                            $display['late_html'] = '<span style="color:red;font-weight:bold">Late Days : '.$lateMaster->maxDays.'(Half-Day)<br>';
                                            $display['normal_html'] = 'Late Days : '.$lateMaster->maxDays.'(Half-Day)';
                                        }
                                    }
                                    if($totalLateDays > 0){
                                        $checkIfLateExists = checkLateExists($jdate,$school,$emp,$lateMaster);
                                        if($checkIfLateExists == 0 && $totalLateDays > 0 && $lateMaster->maxLeave > 0 && $lateMaster->maxDays > 0){
                                            if($totalLateDays >= $lateMaster->maxLeave){
                                                $totalLateDays = 0;
                                                $display['status'] = "A";
                                                $display['late_html'] = '<span style="color:red;font-weight:bold">A(Leave Late : '.$lateMaster->maxLeave.' Days) <br>';
                                                $display['normal_html'] = 'A(Leave Late : '.$lateMaster->maxLeave.' Days)';
                                            }else if($totalLateDays >= $lateMaster->maxDays){
                                                $totalLateDays = 0;
                                                $display['status'] = "HF";
                                                $display['late_html'] = '<span style="color:red;font-weight:bold">Late Days : '.$lateMaster->maxDays.'(Half-Day)<br>';
                                                $display['normal_html'] = 'Late Days : '.$lateMaster->maxDays.'(Half-Day)';
                                            }
                                        }
                                    }
                                    $display['days'] = $totalLateDays;
                                }
                            }
                            return $display;
                        }else{
                            $sr = \Carbon\Carbon::parse($shifts->fromTime.' '.$dayNight)->addMinutes($addOnMinutes);
                            $allowedMinutes = $allowedMinutes + $arrival->diffInMinutes($sr);
                            $display['time'] = $arrival->diffInSeconds($sr);
                            if($allowedMinutes > $addOnMinutes){
                                //check for half Day
                                $halfTime = explode(':',$lateMaster->halfDayAfter);
                                $halfOnMinutes = $halfTime[0]*60 + $halfTime[1]; //calculate minutes
                                $haf = \Carbon\Carbon::parse($shifts->fromTime.' '.$dayNight)->addMinutes($halfOnMinutes);
                                $halfTouch = $arrival->diffForHumans($haf,[]); //check for half day
                                if(str_contains($halfTouch, 'after')){
                                    $display['status'] = "HF";
                                    $display['days'] = $totalLateDays;
                                    $display['late_html'] = '<span style="color:red;font-weight:bold">Late : '.$lateRequired.'(Half-Day)<br>';
                                }else{
                                    $display['status'] = "LT";
                                    $display['late_html'] = '<span style="color:red;font-weight:bold">Late : '.$lateRequired.'<br>';
                                    $totalLateDays++;
                                    if($lateMaster->maxLeave > $lateMaster->maxDays){
                                        if($totalLateDays >= $lateMaster->maxLeave && $lateMaster->maxLeave > 0){
                                            $totalLateDays = 0;
                                            $display['status'] = "A";
                                            $display['late_html'] = '<span style="color:red;font-weight:bold">A(Leave Late : '.$lateMaster->maxLeave.' Days) <br>';
                                        }
                                    }else{
                                        if($totalLateDays >= $lateMaster->maxDays && $lateMaster->maxDays > 0){
                                            $totalLateDays = 0;
                                            $display['status'] = "HF";
                                            $display['late_html'] = '<span style="color:red;font-weight:bold">Late Days : '.$lateMaster->maxDays.'(Half-Day)<br>';
                                        }
                                    }
                                    if($totalLateDays > 0){
                                        $checkIfLateExists = checkLateExists($jdate,$school,$emp,$lateMaster);
                                        if($checkIfLateExists == 0 && $totalLateDays > 0 && $lateMaster->maxLeave > 0 && $lateMaster->maxDays > 0){
                                            if($totalLateDays >= $lateMaster->maxLeave){
                                                $totalLateDays = 0;
                                                $display['status'] = "A";
                                                $display['late_html'] = '<span style="color:red;font-weight:bold">A(Leave Late : '.$lateMaster->maxLeave.' Days) <br>';
                                            }else if($totalLateDays >= $lateMaster->maxDays){
                                                $totalLateDays = 0;
                                                $display['status'] = "HF";
                                                $display['late_html'] = '<span style="color:red;font-weight:bold">Late Days : '.$lateMaster->maxDays.'(Half-Day)<br>';
                                            }
                                        }
                                    }
                                    $display['days'] = $totalLateDays;
                                    $display['minutes'] = $arrival->diffInMinutes($sr);
                                }
                            }
                        }
                    }
                }
                return $display;
            }
        }
    }        
    $display['status'] = "P";
    $display['days'] = $totalLateDays;
    $display['html'] = '<span style="color:green;font-weight:bold">P</span><br>';
    return $display;
}

function checkLateExists($jdate,$school,$emp,$lateMaster){
    $noOfdays = 31;
    $now = \Carbon\Carbon::parse($jdate);
    $y = $now->year;
    for ($i = intval($now->format('d')) + 1; $i <= $noOfdays; $i++) {
        $dt = $i . '-' . $now->month . '-' . $y;
        $tdate = \Carbon\Carbon::parse($dt);
        $aintime = \App\EmpAttendance::where('Enrollment_Number', '=', $emp->enrollmentNo)
        ->where('Device_ID', '=', $school->Device_ID)
        ->whereDate('date', '=', $tdate)
        ->where('status', '=', 'IN')
        ->where('idType', '=', 'A')
        ->first();
        $dayNight = "AM";
        if($aintime != null){
            $shifts = fetchShift($emp,$tdate);
            if($shifts != null){
                $dayNight = strtoupper($shifts->shift_from);
                $start = \Carbon\Carbon::parse($shifts->fromTime.' '.$dayNight);
                $arrival = \Carbon\Carbon::parse($aintime->TimeStamp->format('H:i:s'));
                $lateRequired = $arrival->diffForHumans($start,[]);
                if(str_contains($lateRequired, 'after')){
                    if($lateMaster != null){
                        $allowedTime = explode(':',$lateMaster->lateAllowed);
                        $addOnMinutes = $allowedTime[0]*60 + $allowedTime[1]; //calculate minutes
                        if($lateMaster->lateAllowedTimes == "daily"){
                            $sr = \Carbon\Carbon::parse($shifts->fromTime.' '.$dayNight)->addMinutes($addOnMinutes);
                            $allowed = $arrival->diffForHumans($sr,[]);
                            if(str_contains($allowed, 'after')){
                                return 1;
                            }
                        }
                    }
                }
            }
        }
    }

    return 0;
}

function checkEarlyExists($jdate,$school,$emp,$earlyMaster){
    $noOfdays = 31;
    $now = \Carbon\Carbon::parse($jdate);
    $y = $now->year;
    for ($i = intval($now->format('d')) + 1; $i <= $noOfdays; $i++) {
        $dt = $i . '-' . $now->month . '-' . $y;
        $tdate = \Carbon\Carbon::parse($dt);
        $outtime = \App\EmpAttendance::where('Enrollment_Number', '=', $emp->enrollmentNo)
                        ->where('Device_ID', '=', $school->Device_ID)
                        ->whereDate('date', '=', $tdate)
                        ->where('status', '=', 'OUT')
                        ->where('idType', '=', 'A')
                        ->first();
        $nightDay = "AM";
        if($outtime != null){
            $shifts = fetchShift($emp,$tdate);
            if($shifts != null){
                $nightDay = strtoupper($shifts->shift_to);
                $end = \Carbon\Carbon::parse($shifts->toTime . ' ' . $nightDay);
                $departure = \Carbon\Carbon::parse($outtime->TimeStamp->format('H:i:s'));
                $lateRequired = $departure->diffForHumans($end, []);
                if (str_contains($lateRequired, 'before')) {
                    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\Carbon::parse($shifts->toTime . ' ' . $nightDay)->subMinutes($addOnMinutes);
                            $allowed = $departure->diffForHumans($sr, []);
                            if(str_contains($allowed, 'before')){
                                return 1;
                            }
                        }
                    }
                }
            }
        }
    }

    return 0;
}

function checkDeparture($emp,$jdate,$shifts,$school,$nightDay,$idFinancialYear,$allowedMinutes,$totalEarlyDays){
    $display = [];
    $doSpecialShiftExisits = DB::table('special_shifts')->where('idEmployee', '=', $emp->idEmployee)->where('shift_date',$jdate)->where('type','S')->first();
    $a_mat = \App\EmpAttendance::where('Enrollment_Number', '=', $emp->enrollmentNo)
            ->where('idSchool', '=', $school->idSchool)
            ->whereDate('date', '=', $jdate)
            ->where('status', '=', 'P')
            ->where('idType', '=', 'M')
            ->first();

    if($a_mat == null){
        $outtime = \App\EmpAttendance::where('Enrollment_Number', '=', $emp->enrollmentNo)
                        ->where('Device_ID', '=', $school->Device_ID)
                        ->whereDate('date', '=', $jdate)
                        ->where('status', '=', 'OUT')
                        ->where('idType', '=', 'A')
                        ->first();
        if($doSpecialShiftExisits != null){
            if($doSpecialShiftExisits->is_night == "Y"){
                $nextDay = Carbon\Carbon::parse($jdate)->addDays(1)->format('Y-m-d');
                $outtime = \App\EmpAttendance::where('Enrollment_Number', '=', $emp->enrollmentNo)
                        ->where('Device_ID', '=', $school->Device_ID)
                        ->whereDate('date', '=', $nextDay)
                        ->where('status', '=', 'IN')
                        ->where('idType', '=', 'A')
                        ->first();
            }
        }
        if($outtime == null){
            $display['status'] = "I";
            $display['days'] = $totalEarlyDays;
            $display['html'] = '<span style="color:red;font-weight:bold" id="status_in_'.$emp->idEmployee.'">Incomplete Attendance(OUT)</span><br>';
            return $display;
        }else{
            $display['status'] = "P";
            $display['days'] = $totalEarlyDays;
            $display['time'] = $outtime->TimeStamp;
            $display['html'] = '<span style="color:green;font-weight: bold">OUT: '.explode(" ",$outtime->TimeStamp)[1].'</span><br>';
            //check late arrival conditions 
            $earlyMaster = \App\EarlyGoingMaster::where('idEmployee', '=', $emp->idEmployee)->where('idFinancialYear', $idFinancialYear)->first();
            if($earlyMaster == null){
                $earlyMaster = \App\EarlyGoingMaster::where('idDesignation', '=', $emp->idDesignation)->where('idFinancialYear', $idFinancialYear)->first();
            }
            $end = \Carbon\Carbon::parse($shifts->toTime . ' ' . $nightDay);
            $departure = \Carbon\Carbon::parse($outtime->TimeStamp->format('H:i:s'));
            $lateRequired = $departure->diffForHumans($end, []);
            if (str_contains($lateRequired, 'before')) {
                //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\Carbon::parse($shifts->toTime . ' ' . $nightDay)->subMinutes($addOnMinutes);
                        $allowed = $departure->diffForHumans($sr, []);
                        $display['before'] = $departure->diffInSeconds($sr);
                        if (str_contains($allowed, 'before')) {
                            $halfTime = explode(':', $earlyMaster->halfDayAfter);
                            $halfOnMinutes = $halfTime[0] * 60 + $halfTime[1]; //calculate minutes
                            $haf = \Carbon\Carbon::parse($shifts->toTime . ' ' . $nightDay)->subMinutes($halfOnMinutes);
                            $halfTouch = $departure->diffForHumans($haf, []); //check for half day
                            if (str_contains($halfTouch, 'before')) {
                                $display['status'] = "HF";
                                $display['days'] = $totalEarlyDays;
                                $display['late_html'] = '<span style="color:red;font-weight:bold">Early : '.$lateRequired.'(Half-Day)<br>';
                                $display['normal_html'] = 'Early : '.$lateRequired.'(Half-Day)';
                            } else {
                                $display['status'] = "LT";
                                $display['late_html'] = '<span style="color:red;font-weight:bold">Early : '.$lateRequired.'<br>';
                                $display['normal_html'] = 'Early : '.$lateRequired;
                                $totalEarlyDays++;
                                if($earlyMaster->maxLeave > $earlyMaster->maxDays){
                                    if($totalEarlyDays >= $earlyMaster->maxLeave && $earlyMaster->maxLeave > 0){
                                        $totalEarlyDays = 0;
                                        $display['status'] = "A";
                                        $display['late_html'] = '<span style="color:red;font-weight:bold">A (Early : '.$earlyMaster->maxLeave.' Days) <br>';
                                        $display['normal_html'] = 'A (Early : '.$earlyMaster->maxLeave.' Days)';
                                    }
                                }else{
                                    if($totalEarlyDays >= $earlyMaster->maxDays && $earlyMaster->maxDays > 0){
                                        $totalEarlyDays = 0;
                                        $display['status'] = "HF";
                                        $display['late_html'] = '<span style="color:red;font-weight:bold">Early Days : '.$earlyMaster->maxDays.'(Half-Day)<br>';
                                        $display['normal_html'] = 'Early Days : '.$earlyMaster->maxDays.'(Half-Day)';
                                    }
                                }
                                if($totalEarlyDays > 0){
                                    $checkIfLateExists = checkEarlyExists($jdate,$school,$emp,$earlyMaster);
                                    if($checkIfLateExists == 0 && $totalEarlyDays > 0 && $earlyMaster->maxLeave > 0 && $earlyMaster->maxDays > 0){
                                        if($totalEarlyDays >= $earlyMaster->maxLeave){
                                            $totalEarlyDays = 0;
                                            $display['status'] = "A";
                                            $display['late_html'] = '<span style="color:red;font-weight:bold">A (Early : '.$earlyMaster->maxLeave.' Days)<br>';
                                            $display['normal_html'] = 'A (Early : '.$earlyMaster->maxLeave.' Days)';
                                        }else if($totalEarlyDays >= $earlyMaster->maxDays){
                                            $totalEarlyDays = 0;
                                            $display['status'] = "HF";
                                            $display['late_html'] = '<span style="color:red;font-weight:bold">Early Days : '.$earlyMaster->maxDays.'(Half-Day)<br>';
                                            $display['normal_html'] = 'Early Days : '.$earlyMaster->maxDays.'(Half-Day)';
                                        }
                                    }
                                }
                                $display['days'] = $totalEarlyDays;
                            }
                        }
                    } else {
                        $sr = \Carbon\Carbon::parse($shifts->toTime . ' ' . $nightDay)->subMinutes($addOnMinutes);
                        $allowedMinutes = $allowedMinutes + $departure->diffInMinutes($sr);
                        $display['before'] = $departure->diffInSeconds($sr);
                        if ($allowedMinutes > $addOnMinutes) {
                            //check for half Day
                            $halfTime = explode(':', $earlyMaster->halfDayAfter);
                            $halfOnMinutes = $halfTime[0] * 60 + $halfTime[1]; //calculate minutes
                            $haf = \Carbon\Carbon::parse($shifts->toTime . ' ' . $nightDay)->subMinutes($halfOnMinutes);
                            $halfTouch = $departure->diffForHumans($haf, []); //check for half day
                            if (str_contains($halfTouch, 'before')) {
                                $display['status'] = "HF";
                                $display['days'] = $totalEarlyDays;
                                $display['late_html'] = '<span style="color:red;font-weight:bold">Early : '.$lateRequired.'(Half-Day)<br>';
                            } else {
                                $display['status'] = "LT";
                                $display['late_html'] = '<span style="color:red;font-weight:bold">Early : '.$lateRequired.'<br>';
                                $totalEarlyDays++;
                                if($earlyMaster->maxLeave > $earlyMaster->maxDays){
                                    if($totalEarlyDays >= $earlyMaster->maxLeave && $earlyMaster->maxLeave > 0){
                                        $totalEarlyDays = 0;
                                        $display['status'] = "A";
                                        $display['late_html'] = '<span style="color:red;font-weight:bold">A (Early : '.$earlyMaster->maxLeave.' Days)<br>';
                                    }
                                }else{
                                    if($totalEarlyDays >= $earlyMaster->maxDays && $earlyMaster->maxDays > 0){
                                        $totalEarlyDays = 0;
                                        $display['status'] = "HF";
                                        $display['late_html'] = '<span style="color:red;font-weight:bold">Early Days : '.$earlyMaster->maxDays.'(Half-Day)<br>';
                                    }
                                }
                                if($totalEarlyDays > 0){
                                    $checkIfLateExists = checkEarlyExists($jdate,$school,$emp,$earlyMaster);
                                    if($checkIfLateExists == 0 && $totalEarlyDays > 0 && $earlyMaster->maxLeave > 0 && $earlyMaster->maxDays > 0){
                                        if($totalEarlyDays >= $earlyMaster->maxLeave){
                                            $totalEarlyDays = 0;
                                            $display['status'] = "A";
                                            $display['late_html'] = '<span style="color:red;font-weight:bold">A (Early : '.$earlyMaster->maxLeave.' Days)<br>';
                                        }else if($totalEarlyDays >= $earlyMaster->maxDays){
                                            $totalEarlyDays = 0;
                                            $display['status'] = "HF";
                                            $display['late_html'] = '<span style="color:red;font-weight:bold">Early Days : '.$earlyMaster->maxDays.'(Half-Day)<br>';
                                        }
                                    }
                                }
                                
                                $display['days'] = $totalEarlyDays;
                                $display['minutes'] = $departure->diffInMinutes($sr);
                            }
                        }
                    }
                }
            }
            return $display;
        }
    }        
    $display['status'] = "P";
    $display['days'] = $totalEarlyDays;
    $display['html'] = '<span style="color:green;font-weight:bold">P</span><br>';
    return $display;
}

function fetchOvertime($emp,$shifts,$dayNight,$nightDay,$school,$jdate,$fy){
    $display['status'] = "N";
    $display['otHour'] = 0;
    $display['otEarning'] = 0;
    $ot = \App\AssignOvertime::where('idEmployee', '=', $emp->idEmployee)->first();
    if($ot == null){
        $ot = \App\AssignOvertime::where('idDepartment', '=', $emp->idDepartment)->where('idDesignation', '=', $emp->idDesignation)->first();
    }
    if($ot != null){
        $nows = \Carbon\Carbon::parse($jdate);
        $aouttime = \App\EmpAttendance::where('Enrollment_Number', '=', $emp->enrollmentNo)
                        ->where('Device_ID', '=', $school->Device_ID)
                        ->whereDate('date', '=', $jdate)
                        ->where('status', '=', 'OUT')
                        ->where('idType', '=', 'A')
                        ->first();
        if(isset($aouttime->TimeStamp)){
            $wstart = \Carbon\Carbon::parse($shifts->fromTime.' '.$dayNight);
            $warrival = \Carbon\Carbon::parse(explode(" ",$aouttime->TimeStamp)[1]);
            $serviceTotal = $warrival->diffInSeconds($wstart);
            
            if($ot != null){
                $time = explode(':', $ot->otAfter);
                if(count($time) > 1){
                    $ot_min = $time[0]*60 + $time[1];
                    $shift_start = \Carbon\Carbon::parse($shifts->fromTime.' '.$dayNight);
                    $shift_end = \Carbon\Carbon::parse($shifts->toTime.' '.$nightDay)->addMinutes($ot_min);
                    $shiftTotal = $shift_end->diffInSeconds($shift_start);

                    if($serviceTotal > $shiftTotal)
                    {
                        $ashift_start = \Carbon\Carbon::parse($shifts->fromTime.' '.$dayNight);
                        $ashift_end = \Carbon\Carbon::parse($shifts->toTime.' '.$nightDay);
                        $totalMinutes = $ashift_start->diffInMinutes($ashift_end);

                        $ashiftTotal = $ashift_end->diffInSeconds($ashift_start);
                        $overtime = gmdate('H:i', $serviceTotal - $ashiftTotal );
                        $display['otHour'] = $shift_end->diffInMinutes($warrival);
                        if($display['otHour'] > 0){
                            $breakRatio = explode($ot->otRatio,":");
                            //fetch earnings of the employee
                            $emp_salstr = \App\SalaryStructure::where('idEmployee', '=', $emp->idEmployee)->where('idFinancialYear', '=', $fy)->first();
                            if($emp_salstr != null){
                                $totalEarnings = 0;
                                $display['status'] = "Y";
                                $earnings = \App\SalaryStrAllowances::where('idSalaryStr', '=', $emp_salstr->idSalaryStr)->get();
                                foreach($earnings as $earning){
                                    $totalEarnings = $totalEarnings + $earning->amount;
                                }
                                $nofDays = DB::table('months')->where('idMonth',$nows->month)->first();
                                $salary = $totalEarnings/$nofDays;
                                $display['otEarning'] = ($salary/$totalMinutes) * $breakRatio[1];
                            }
                        }
                        
                        $display['status'] = "Y";
                        $display['html'] = '<span style="color:red;font-weight:bold">Overtime : '.$overtime.'</span><br>';
                        return $display;
                    }
                }
                
            }
            
        }
    }
    return $display;
}

function fetchShift($emp,$jdate){
    $emp_shift = \App\AssignShift::where('idEmployee', '=', $emp->idEmployee)->first();
    if($emp_shift == null){
        $emp_shift = \App\AssignShift::where('idDesignation',$emp->idDesignation)
        ->where('idDepartment',$emp->idDepartment)
        ->whereNull('idEmployee')->first();
    }

    if(isset($emp_shift->idShift)){
        $tdate = \Carbon\Carbon::parse($jdate);
        //check for special shift
        $doSpecialShiftExisits = DB::table('special_shifts')->where('idEmployee', '=', $emp->idEmployee)->where('shift_date',$jdate)->where('type','S')->first();
        if($doSpecialShiftExisits != null){
            $shifts = new \App\ShiftDetail();
            $specialShift = explode("-",$doSpecialShiftExisits->shift_time);//shift_time
            $shifts->fromTime = explode(" ",$specialShift[0])[0];
            $shifts->shift_from = explode(" ",$specialShift[0])[1];
            $shifts->toTime = explode(" ",$specialShift[1])[0];
            $shifts->shift_to = explode(" ",$specialShift[1])[1];
            $shifts->weekOff = "N";
            $shifts->is_night = "N";
            return $shifts;
        } 
        $doDesignationShiftExisits = DB::table('special_shifts')->where('idDesignation', '=', $emp->idDesignation)->where('shift_date',$jdate)->where('type','S')->first();
        if($doDesignationShiftExisits != null){
            $shifts = new \App\ShiftDetail();
            $specialShift = explode("-",$doDesignationShiftExisits->shift_time);//shift_time
            $shifts->fromTime = explode(" ",$specialShift[0])[0];
            $shifts->shift_from = explode(" ",$specialShift[0])[1];
            $shifts->toTime = explode(" ",$specialShift[1])[0];
            $shifts->shift_to = explode(" ",$specialShift[1])[1];
            $shifts->weekOff = "N";
            $shifts->is_night = "N";
            return $shifts;
        } 
        $shifts = DB::table('shift_details')
        ->select('fromTime','toTime','shift_from','shift_to','weekOff','is_night')
        ->join('weekdays', 'shift_details.idWeekday', '=', 'weekdays.idWeekday')
        ->where('idShift', '=', $emp_shift->idShift)
        ->where('dayName', '=', date('l', strtotime($tdate)))
        ->first();
        if($shifts != null) {
            if($shifts->weekOff == "Y"){
                $shifts->fromTime = "00:00";
                $shifts->toTime = "00:00";
            }
            return $shifts;
        }
    }
    else return null;
}

function fetchLeaveMaster($employee,$idFinancialYear){
    $designationYearWise = \App\LeaveMaster::where('idSchool', '=', $employee->idSchool)
                            ->where('idDesignation',$employee->idDesignation)
                            ->where('idFinancialYear',$idFinancialYear)
                            ->where('leaveType',"yearly")
                            ->whereNull('idEmployee')->first();
    if($designationYearWise == null){
        $paidYearLeaves = \App\LeaveMaster::where('idSchool', '=', $employee->idSchool)
        ->where('idDesignation',$employee->idDesignation)
        ->where('idEmployee',$employee->idEmployee)
        ->where('idFinancialYear',$idFinancialYear)
        ->where('leaveType',"yearly")->first();
        if($paidYearLeaves == null){
            $designationYearWise = \App\LeaveMaster::where('idSchool', '=', $employee->idSchool)
            ->where('idDesignation',$employee->idDesignation)
            ->where('idFinancialYear',$idFinancialYear)
            ->where('leaveType',"monthly")
            ->whereNull('idEmployee')->first();

            if($designationYearWise == null){
                $paidYearLeaves = \App\LeaveMaster::where('idSchool', '=', $employee->idSchool)
                ->where('idDesignation',$employee->idDesignation)
                ->where('idEmployee',$employee->idEmployee)
                ->where('idFinancialYear',$idFinancialYear)
                ->where('leaveType',"monthly")->first();  
                return $paidYearLeaves;
            }                        
            return $designationYearWise;

        }else return $paidYearLeaves;
    }                        
    return $designationYearWise;
}

function fetchPaidLeave($jdate,$employee){
    $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) return 1;
    else return -1;    
}

function checkForSandwich($emp,$rule,$arr,$jdate,$index,$school){
    if($rule == 1){
        //absent before and after
        if($arr[$index - 1] == "A"){
            $currentDate = $jdate->addDays(1);
            $aintime = \App\EmpAttendance::where('Enrollment_Number', '=', $emp->enrollmentNo)
            ->where('Device_ID', '=', $school->Device_ID)
            ->whereDate('date', '=', $currentDate)
            ->where('status', '=', 'OUT')
            ->where('idType', '=', 'A')
            ->first();
            $aouttime = \App\EmpAttendance::where('Enrollment_Number', '=', $emp->enrollmentNo)
            ->where('Device_ID', '=', $school->Device_ID)
            ->whereDate('date', '=', $currentDate)
            ->where('status', '=', 'IN')
            ->where('idType', '=', 'A')
            ->first();
            if(fetchPaidLeave($currentDate,$emp) == 1){
                return -1;
            }else
            if($aintime == null && $aouttime == null){
                return 1;
            }
        }
    }else{
        //absent befor or after
        $currentDate = $jdate->addDays(1);
        $aintime = \App\EmpAttendance::where('Enrollment_Number', '=', $emp->enrollmentNo)
            ->where('Device_ID', '=', $school->Device_ID)
            ->whereDate('date', '=', $currentDate)
            ->where('status', '=', 'OUT')
            ->where('idType', '=', 'A')
            ->first();
        $aouttime = \App\EmpAttendance::where('Enrollment_Number', '=', $emp->enrollmentNo)
            ->where('Device_ID', '=', $school->Device_ID)
            ->whereDate('date', '=', $currentDate)
            ->where('status', '=', 'IN')
            ->where('idType', '=', 'A')
            ->first();
        if(fetchPaidLeave($currentDate,$emp) == 1){
                return -1;
        }else    
        if( ($aintime == null && $aouttime == null) || $arr[$index - 1] == "A"){
            return 1;
        }
    }
    return -1;
}

function updateOldStock($idSchool,$fy,$oldDate){
    date_default_timezone_set("Asia/Kolkata");  
    $item = DB::table('food_stock')->join('canteen_food_items', 'food_stock.idFood', '=', 'canteen_food_items.id')->where('food_stock.idSchool', '=', $idSchool)
    ->where('food_stock.idFinancialYear',$fy)->whereDate('food_date',\Carbon\Carbon::now()->format('Y-m-d'))->get()->pluck('idFood')->toArray();
    if(count($item) == 0){
        $fetchOldItem = DB::table('food_stock')->join('canteen_food_items', 'food_stock.idFood', '=', 'canteen_food_items.id')->where('food_stock.idSchool', '=', $idSchool)
        ->where('food_stock.idFinancialYear',$fy)->whereDate('food_date',$oldDate->format('Y-m-d'))->get();
        foreach($fetchOldItem as $var){
            $stock = DB::table('food_stock')->join('canteen_food_items', 'food_stock.idFood', '=', 'canteen_food_items.id')->where('food_stock.idSchool', '=',$idSchool)
            ->where('food_stock.idFinancialYear', '=', $fy)
            ->where('food_stock.idFood', '=', $var->idFood)
            ->whereDate('food_date',\Carbon\Carbon::now()->format('Y-m-d'))->first();
            if($stock == null){
                DB::table('food_stock')->insert([
                    'idSchool' => $idSchool,
                    'idFinancialYear' => $fy,
                    'idFood' => $var->idFood,
                    'food_date' => \Carbon\Carbon::now()->format('Y-m-d')
                ]);
            }
        }
    }
}


function fetchDynamic($idSchool){
    return DB::table('allowances')->where('idSchool',$idSchool)->get()->pluck('allowanceName','allowanceName')->toArray();
}

function fetchPt($fy,$emp_salstr,$employee,$rawSal,$perSal){
    $ptTotal = 0;
    $pt = \App\PtMaster::where('idFinancialYear',$fy)->where('idSchool',$employee->idSchool)->where('idEmployee', $employee->idEmployee)->first();
    if($pt != null){
        $details = \App\PtMasterDetails::where('idPt',$pt->idPt)->get();
        if ($pt->gender == "A") {
            if ($pt->allowance == "D") {
                $earnings = \App\SalaryStrAllowances::where('idSalaryStr', '=', $emp_salstr->idSalaryStr)->get();
                foreach ($earnings as $earning) {
                    $name = DB::table('allowances')->where('idAllowance', $earning->idAllowance)->first();
                    if ($name != null) {
                        if ($name->allowanceName == $pt->allowance_type) {
                            foreach($details as $var){
                                if($earning->amount > $var->from_amount && $var->to_amount >= $earning->amount){
                                    $ptTotal = $var->amount;
                                    break;
                                }
                            }
                            break;
                        }
                    }
                }
            }else{
                foreach($details as $var){
                    if($var->type == "F"){
                        if($perSal > $var->from_amount && $var->to_amount >= $perSal){
                            $ptTotal = $var->amount;
                            break;
                        }
                    }else{
                        if($rawSal > $var->from_amount && $var->to_amount >= $rawSal){
                            $ptTotal = $var->amount;
                            break;
                        }
                    }
                }
            }
        }else if($pt->gender == "M" && $employee->gender == "Male"){
            if ($pt->allowance == "D") {
                $earnings = \App\SalaryStrAllowances::where('idSalaryStr', '=', $emp_salstr->idSalaryStr)->get();
                foreach ($earnings as $earning) {
                    $name = DB::table('allowances')->where('idAllowance', $earning->idAllowance)->first();
                    if ($name != null) {
                        if ($name->allowanceName == $pt->allowance_type) {
                            foreach($details as $var){
                                if($earning->amount > $var->from_amount && $var->to_amount >= $earning->amount){
                                    $ptTotal = $var->amount;
                                    break;
                                }
                            }
                            break;
                        }
                    }
                }
            }else{
                foreach($details as $var){
                    if($var->type == "F"){
                        if($perSal > intval($var->from_amount) && intval($var->to_amount) >= $perSal){
                            $ptTotal = intval($var->amount);
                            break;
                        }
                    }else{
                        if($rawSal > intval($var->from_amount) && intval($var->to_amount) >= $rawSal){
                            $ptTotal = $var->amount;
                            break;
                        }
                    }
                }
            }
        }else{
            if ($pt->allowance == "D") {
                $earnings = \App\SalaryStrAllowances::where('idSalaryStr', '=', $emp_salstr->idSalaryStr)->get();
                foreach ($earnings as $earning) {
                    $name = DB::table('allowances')->where('idAllowance', $earning->idAllowance)->first();
                    if ($name != null) {
                        if ($name->allowanceName == $pt->allowance_type) {
                            foreach($details as $var){
                                if($earning->amount > $var->from_amount && $var->to_amount >= $earning->amount){
                                    $ptTotal = $var->amount;
                                    break;
                                }
                            }
                            break;
                        }
                    }
                }
            }else{
                foreach($details as $var){
                    if($var->type == "F"){
                        if($perSal > $var->from_amount && $var->to_amount >= $perSal){
                            $ptTotal = $var->amount;
                            break;
                        }
                    }else{
                        if($rawSal > $var->from_amount && $var->to_amount >= $rawSal){
                            $ptTotal = $var->amount;
                            break;
                        }
                    }
                }
            }
        }
    }else{
        if($employee->gender == "Male"){
            $pt = \App\PtMaster::where('idFinancialYear', $fy)->where('idSchool', $employee->idSchool)
            ->where('idDepartment', $employee->idDepartment)
            ->where('idDesignation', $employee->idDesignation)->where('gender', "M")->first();
            if($pt != null){
                $details = \App\PtMasterDetails::where('idPt',$pt->idPt)->get();
                if ($pt->allowance == "D") {
                    $earnings = \App\SalaryStrAllowances::where('idSalaryStr', '=', $emp_salstr->idSalaryStr)->get();
                    foreach ($earnings as $earning) {
                        $name = DB::table('allowances')->where('idAllowance', $earning->idAllowance)->first();
                        if ($name != null) {
                            if ($name->allowanceName == $pt->allowance_type) {
                                foreach($details as $var){
                                    if($earning->amount > $var->from_amount && $var->to_amount >= $earning->amount){
                                        $ptTotal = $var->amount;
                                        break;
                                    }
                                }
                                break;
                            }
                        }
                    }
                }else{
                    foreach($details as $var){
                        if($var->type == "F"){
                            if($perSal > $var->from_amount && $var->to_amount >= $perSal){
                                $ptTotal = $var->amount;
                                break;
                            }
                        }else{
                            if($rawSal > $var->from_amount && $var->to_amount >= $rawSal){
                                $ptTotal = $var->amount;
                                break;
                            }
                        }
                    }
                }
            }
        }else if($employee->gender == "Female"){
            $pt = \App\PtMaster::where('idFinancialYear', $fy)->where('idSchool', $employee->idSchool)
            ->where('idDepartment', $employee->idDepartment)
            ->where('idDesignation', $employee->idDesignation)->where('gender', "F")->first();
            if($pt != null){
                $details = \App\PtMasterDetails::where('idPt',$pt->idPt)->get();
                if ($pt->allowance == "D") {
                    $earnings = \App\SalaryStrAllowances::where('idSalaryStr', '=', $emp_salstr->idSalaryStr)->get();
                    foreach ($earnings as $earning) {
                        $name = DB::table('allowances')->where('idAllowance', $earning->idAllowance)->first();
                        if ($name != null) {
                            if ($name->allowanceName == $pt->allowance_type) {
                                foreach($details as $var){
                                    if($earning->amount > $var->from_amount && $var->to_amount >= $earning->amount){
                                        $ptTotal = $var->amount;
                                        break;
                                    }
                                }
                                break;
                            }
                        }
                    }
                }else{
                    foreach($details as $var){
                        if($var->type == "F"){
                            if($perSal > $var->from_amount && $var->to_amount >= $perSal){
                                $ptTotal = $var->amount;
                                break;
                            }
                        }else{
                            if($rawSal > $var->from_amount && $var->to_amount >= $rawSal){
                                $ptTotal = $var->amount;
                                break;
                            }
                        }
                    }
                }
            }
        }else{
            $pt = \App\PtMaster::where('idFinancialYear', $fy)->where('idSchool', $employee->idSchool)
            ->where('idDepartment', $employee->idDepartment)
            ->where('idDesignation', $employee->idDesignation)->whereNull('idEmployee')->where('gender', "A")->first();
            if($pt != null){
                $details = \App\PtMasterDetails::where('idPt',$pt->idPt)->get();
                if ($pt->allowance == "D") {
                    $earnings = \App\SalaryStrAllowances::where('idSalaryStr', '=', $emp_salstr->idSalaryStr)->get();
                    foreach ($earnings as $earning) {
                        $name = DB::table('allowances')->where('idAllowance', $earning->idAllowance)->first();
                        if ($name != null) {
                            if ($name->allowanceName == $pt->allowance_type) {
                                foreach($details as $var){
                                    if($earning->amount > $var->from_amount && $var->to_amount >= $earning->amount){
                                        $ptTotal = $var->amount;
                                        break;
                                    }
                                }
                                break;
                            }
                        }
                    }
                }else{
                    foreach($details as $var){
                        if($var->type == "F"){
                            if($perSal > $var->from_amount && $var->to_amount >= $perSal){
                                $ptTotal = $var->amount;
                                break;
                            }
                        }else{
                            if($rawSal > $var->from_amount && $var->to_amount >= $rawSal){
                                $ptTotal = $var->amount;
                                break;
                            }
                        }
                    }
                }
            }
        }
        
    }
    return $ptTotal; 
}

function fetchEpf($fy,$emp_salstr,$employee,$rawSal,$deduction){
    $epfTotal = 0;
    $epf = \App\EpfMaster::where('idFinancialYear', $fy)->where('idSchool', $employee->idSchool)->where('idEmployee', $employee->idEmployee)->first();
    if ($epf != null) {
        if ($epf->gender == "A") {
            if ($epf->allowance == "D") {
                $earnings = \App\SalaryStrAllowances::where('idSalaryStr', '=', $emp_salstr->idSalaryStr)->get();
                foreach ($earnings as $earning) {
                    $name = DB::table('allowances')->where('idAllowance', $earning->idAllowance)->first();
                    if ($name != null) {
                        if ($name->allowanceName == $epf->allowance_type) {
                            $epfTotal = ( abs($earning->amount - $deduction) * $epf->deduction) / 100;
                            break;
                        }
                    }
                }
            } else {
                $epfTotal = ($rawSal * $epf->deduction) / 100;
            }
        }else if($epf->gender == "M" && $employee->gender == "Male"){
            if ($epf->allowance == "D") {
                $earnings = \App\SalaryStrAllowances::where('idSalaryStr', '=', $emp_salstr->idSalaryStr)->get();
                foreach ($earnings as $earning) {
                    $name = DB::table('allowances')->where('idAllowance', $earning->idAllowance)->first();
                    if ($name != null) {
                        if ($name->allowanceName == $epf->allowance_type) {
                            $epfTotal = (abs($earning->amount - $deduction) * $epf->deduction) / 100;
                            break;
                        }
                    }
                }
            } else {
                $epfTotal = ($rawSal * $epf->deduction) / 100;
            }
        }else{
            if ($epf->allowance == "D") {
                $earnings = \App\SalaryStrAllowances::where('idSalaryStr', '=', $emp_salstr->idSalaryStr)->get();
                foreach ($earnings as $earning) {
                    $name = DB::table('allowances')->where('idAllowance', $earning->idAllowance)->first();
                    if ($name != null) {
                        if ($name->allowanceName == $epf->allowance_type) {
                            $epfTotal = (abs($earning->amount - $deduction) * $epf->deduction) / 100;
                            break;
                        }
                    }
                }
            } else {
                $epfTotal = ($rawSal * $epf->deduction) / 100;
            }
        }
        if ($epfTotal > $epf->maxAllowed) {
            $epfTotal = $epf->maxAllowed;
        }
    } else {
        $epf = \App\EpfMaster::where('idFinancialYear', $fy)->where('idSchool', $employee->idSchool)
            ->where('idDepartment', $employee->idDepartment)->where('idDesignation', $employee->idDesignation)->whereNull('idEmployee')->first();
        if ($epf != null) {
            if ($epf->gender == "A") {
                if ($epf->allowance == "D") {
                    $earnings = \App\SalaryStrAllowances::where('idSalaryStr', '=', $emp_salstr->idSalaryStr)->get();
                    foreach ($earnings as $earning) {
                        $name = DB::table('allowances')->where('idAllowance', $earning->idAllowance)->first();
                        if ($name != null) {
                            if ($name->allowanceName == $epf->allowance_type) {
                                $epfTotal = (abs($earning->amount - $deduction) * $epf->deduction) / 100;
                                break;
                            }
                        }
                    }
                } else {
                    $epfTotal = ($rawSal * $epf->deduction) / 100;
                }
            }else if($epf->gender == "M" && $employee->gender == "Male"){
                if ($epf->allowance == "D") {
                    $earnings = \App\SalaryStrAllowances::where('idSalaryStr', '=', $emp_salstr->idSalaryStr)->get();
                    foreach ($earnings as $earning) {
                        $name = DB::table('allowances')->where('idAllowance', $earning->idAllowance)->first();
                        if ($name != null) {
                            if ($name->allowanceName == $epf->allowance_type) {
                                $epfTotal = (abs($earning->amount - $deduction) * $epf->deduction) / 100;
                                break;
                            }
                        }
                    }
                } else {
                    $epfTotal = ($rawSal * $epf->deduction) / 100;
                }
            }else{
                if ($epf->allowance == "D") {
                    $earnings = \App\SalaryStrAllowances::where('idSalaryStr', '=', $emp_salstr->idSalaryStr)->get();
                    foreach ($earnings as $earning) {
                        $name = DB::table('allowances')->where('idAllowance', $earning->idAllowance)->first();
                        if ($name != null) {
                            if ($name->allowanceName == $epf->allowance_type) {
                                $epfTotal = (abs($earning->amount - $deduction) * $epf->deduction) / 100;
                                break;
                            }
                        }
                    }
                } else {
                    $epfTotal =($rawSal * $epf->deduction) / 100;
                }
            }
            if ($epfTotal > $epf->maxAllowed) {
                $epfTotal = $epf->maxAllowed;
            }
        }
    }
    return round($epfTotal);
}

function formatAmountInIndianCurrency($amount) {
    if (!is_numeric($amount)) {
        return "Invalid Amount"; // Or throw an exception
    }

    $amount = round($amount, 2); // Round to 2 decimal places
    if($amount < 100000){
        return number_format($amount, 2);
    }else if($amount < 1000000){
        return round($amount / 100000, 2) . " L";
    }else if($amount < 10000000){
        return round($amount / 100000, 2) . " L";
    }else if($amount < 100000000){
        return round($amount / 10000000, 2) . " Cr";
    }
    return number_format($amount, 2);
}

Copyright © 2021 - 2025 IMMREX7