IMMREX7

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

<?php

namespace App\Http\Controllers\School;

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

class NorthTransactionController extends SchoolController {

    public $total_amount = 0;

    /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function index(Request $request) {
        if (!request()->ajax()) {
            return view('schools.north.transaction.studentlist');
        }
        $columns = array(
            //   0 =>'sNo',
            0 => 'photo',
            1 => 'ecNo',
            2 => 'name',
            3 => 'father_name',
            4 => 'className',
            5 => 'sectionName',
            6 => 'mobile',
            7 => 'action',
        );
         $totalData = \App\AdmEntry::where('idSchool', '=', Auth::guard('school')->user()->idSchool)
                ->where('isActive', '=', 'Y');
        if ($request->idFinancialYear != null) {
            $totalData = $totalData->where('idFinancialYear', '=', $request->idFinancialYear)
                    ->count();
        } else {
            $totalData = $totalData->where('idFinancialYear', '=', Session::get('idFinancialYear'))
                    ->count();
        }
        $totalFiltered = $totalData;
        $limit = $request->input('length');
        $start = $request->input('start');
        $order = $columns[$request->input('order.0.column')];
        $dir = $request->input('order.0.dir');


        // Get Data according to search value    
        if (empty($request->input('search.value'))) {
            if ($limit == '-1') {
                $students = DB::table('students')
                        ->join('classes', 'students.idClass', '=', 'classes.idClass')
                        ->join('sections', 'students.idSection', '=', 'sections.idSection')
                        ->orderBy($order, $dir)
                        ->where('isActive', '=', 'Y')
                        ->where('students.idSchool', '=', Auth::guard('school')->user()->idSchool);
            } else {
                $students = DB::table('students')
                        ->join('classes', 'students.idClass', '=', 'classes.idClass')
                        ->join('sections', 'students.idSection', '=', 'sections.idSection')
                        ->offset($start)
                        ->limit($limit)
                        ->orderBy($order, $dir)
                        ->where('isActive', '=', 'Y')
                        ->where('students.idSchool', '=', Auth::guard('school')->user()->idSchool);
            }
            if ($request->idFinancialYear != null) {
                $students = $students->where('students.idFinancialYear', '=', $request->idFinancialYear)->get();
            } else {
                $students = $students->where('students.idFinancialYear', '=', Session::get('idFinancialYear'))->get();
            }
        } else {
            $search = $request->input('search.value');
            if ($limit == '-1') {
                $students = DB::table('students')
                        ->join('classes', 'students.idClass', '=', 'classes.idClass')
                        ->join('sections', 'students.idSection', '=', 'sections.idSection')
                        ->orderBy($order, $dir)
                        ->where('isActive', '=', 'Y')
                        ->where('students.idSchool', '=', Auth::guard('school')->user()->idSchool)
                        ->where(function ($query) use ($search) {
                    $query->where(DB::raw('CONCAT(firstName, " ",lastName)'), 'LIKE', "%{$search}%")
                    ->orWhere('ecNo', 'LIKE', "%{$search}%")
                    ->orWhere('className', 'LIKE', "%{$search}%")
                    ->orWhere('sectionName', 'LIKE', "%{$search}%")
                    ->orWhere('father_fname', 'LIKE', "%{$search}%")
                    ->orWhere('studentDob', 'LIKE', "%{$search}%")
                    ->orWhere('father_mobile', 'LIKE', "%{$search}%");
                });
            } else {
                $students = DB::table('students')
                        ->join('classes', 'students.idClass', '=', 'classes.idClass')
                        ->join('sections', 'students.idSection', '=', 'sections.idSection')
                        ->offset($start)
                        ->limit($limit)
                        ->orderBy($order, $dir)
                        ->where('isActive', '=', 'Y')
                        ->where('students.idSchool', '=', Auth::guard('school')->user()->idSchool)
                        ->where(function ($query) use ($search) {
                    $query->where(DB::raw('CONCAT(firstName, " ",lastName)'), 'LIKE', "%{$search}%")
                    ->orWhere('ecNo', 'LIKE', "%{$search}%")
                    ->orWhere('className', 'LIKE', "%{$search}%")
                    ->orWhere('sectionName', 'LIKE', "%{$search}%")
                    ->orWhere('father_fname', 'LIKE', "%{$search}%")
                    ->orWhere('studentDob', 'LIKE', "%{$search}%")
                    ->orWhere('father_mobile', 'LIKE', "%{$search}%");
                });
            }
            $totalFiltered = DB::table('students')
                    ->join('classes', 'students.idClass', '=', 'classes.idClass')
                    ->join('sections', 'students.idSection', '=', 'sections.idSection')
                    ->where('isActive', '=', 'Y')
                    ->where('students.idSchool', '=', Auth::guard('school')->user()->idSchool)
                    ->where(function ($query) use ($search) {
                $query->where(DB::raw('CONCAT(firstName, " ",lastName)'), 'LIKE', "%{$search}%")
                ->orWhere('ecNo', 'LIKE', "%{$search}%")
                ->orWhere('className', 'LIKE', "%{$search}%")
                ->orWhere('sectionName', 'LIKE', "%{$search}%")
                ->orWhere('father_fname', 'LIKE', "%{$search}%")
                ->orWhere('studentDob', 'LIKE', "%{$search}%")
                ->orWhere('father_mobile', 'LIKE', "%{$search}%");
            });
            if ($request->idFinancialYear != null) {
                $students = $students->where('students.idFinancialYear', '=', $request->idFinancialYear)->get();
                $totalFiltered = $totalFiltered->where('students.idFinancialYear', '=', $request->idFinancialYear)->get()->count();
            } else {
                $students = $students->where('students.idFinancialYear', '=', Session::get('idFinancialYear'))->get();
                $totalFiltered = $totalFiltered->where('students.idFinancialYear', '=', Session::get('idFinancialYear'))->get()->count();
            }
        }
        $data = array();
        if (!empty($students)) {
            $count = 1;
            foreach ($students as $var) {
//                $nestedData['sNo'] = $count;
                $nestedData['photo'] = '<img src="https://online-login.online/storage/schools/' . $var->idSchool . '/students/' . $var->photo . '" height="60">';
                $nestedData['ecNo'] = $var->ecNo;
                $nestedData['name'] = $var->firstName . " " . $var->middleName . " " . $var->lastName;
                $nestedData['father_name'] = $var->father_fname . " " . $var->father_lname;
                $nestedData['className'] = $var->className;
                $nestedData['sectionName'] = $var->sectionName;
                $nestedData['father_mobile'] = $var->father_mobile;
                $nestedData['action'] = '<a class="btn btn-warning btn-sm" href="https://online-login.online/school/north/stdtransaction/' . $var->idStudent . '/details" target="_blank">Select</a>';
                $data[] = $nestedData;
//                $count++;
            }
        }
        $json_data = array(
            "draw" => intval($request->input('draw')),
            "recordsTotal" => intval($totalData),
            "recordsFiltered" => intval($totalFiltered),
            "data" => $data
        );

        $students = json_encode($json_data);
        return $students;

//        $students = \App\AdmEntry::where('idSchool', '=', Auth::guard('school')->user()->idSchool)
//                ->get();
//        return view('schools.transaction.studentlist', compact('students'));
    }

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

    /**
     * Store a newly created resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return \Illuminate\Http\Response
    */ 
    public function store(Request $request) {
        $rules = [];
        if ($request->paymentMode == 'Cash') {
            $rules += ['payable' => 'required'];
        } else if ($request->paymentMode == 'Card') {
            $rules += ['cardNo' => 'required', 'payable' => 'required'];
        } else {
            $rules += [
                'idBank' => 'required',
                'chequeDate' => 'required',
                'chequeNo' => 'required',
                'amount' => 'required'
            ];
        }
        $messages = [
            'cardNo.required' => 'Card No or Trans ID field is required',
            'totalPaid.required' => 'Enter The Amount.',
            'idBank.required' => 'Bank must be selected',
            'chequeDate.required' => 'Cheque / DD Date must be filled.',
            'chequeNo.required' => 'Cheque / DD No. must be filled.'
        ];
        $this->validate($request, $rules, $messages);
        
        $penaltyAmount = 0;
        $isSuccessful=0;
      
        $chqbounce = \App\FailedTransaction::where('idStudent', '=', $request->idStudent)
                ->where('idFinancialYear', '=', $request->idFinancialYear)
                ->where('status', '=', 'Bounced')
                ->where('chqFineStatus', '=', '0')
                ->get();
        if (isset($chqbounce)) {
            foreach ($chqbounce as $chqFine)
                $penaltyAmount = $penaltyAmount + $chqFine->chequeBounceCharge;
        }
        
        $totalFine= $request->totalFine;
        $totalPaid=0;
        $headerType=array();
        foreach($request->selectedHeaders as $demandID){
            $totalHeader = \App\NorthFeeHead::where('isParent','=',$demandID)->select(DB::raw('SUM(discount) as total_discount'),DB::raw('SUM(amount) as total_amount'))->first();
            array_push($headerType,$demandID);
            $totalPaid=$totalPaid+($totalHeader->total_amount - $totalHeader->total_discount);
        }
        
        $totalHeader = \App\NorthFeeHead::whereIn('idFeehead',$headerType)->select('idType')->distinct();
        //->count('idType') ->get()
        if($totalHeader->count('idType') > 1){
            flash('Fees cannot been submitted because one selected header belongs to different category !!');
            if ($request->ajax()) {
                    return response()->json(['success' => "SUCCESS"], 200, ['app-status' => 'success']);
            }
        }
        
       
        $finalAmount=$totalFine+$totalPaid;
        
        if((count($request->selectedHeaders) == '1') && $finalAmount > $request->payable)
        {
            if($totalHeader->first()->idType == 'bus')
            $isSuccessful=$this->isBusLesserTransaction($request,$penaltyAmount);
            elseif($totalHeader->first()->idType == 'hostel')
                $isSuccessful=$this->isHostelLesserTransaction($request,$penaltyAmount);
            else $isSuccessful=$this->isLesserTransaction($request,$penaltyAmount);
            
        }elseif((count($request->selectedHeaders) >= 1) && $finalAmount == $request->payable)
        {
           if($totalHeader->first()->idType == 'bus') 
           $isSuccessful=$this->storeBusTransaction($request,$penaltyAmount);
        elseif($totalHeader->first()->idType == 'hostel')
                $isSuccessful=$this->storeHostelTransaction($request,$penaltyAmount);
           else $isSuccessful=$this->storeTransaction($request,$penaltyAmount);
            
        }else{
            flash('Fees cannot been submitted because one selected header belongs to lesser transaction !!');
            if ($request->ajax()) {
                    return response()->json(['success' => "SUCCESS"], 200, ['app-status' => 'success']);
            }
        }
        
    
        if ($isSuccessful == 1) {

            if (isset($chqbounce)) {
                foreach ($chqbounce as $chqFine) {
                    $chqFine->chqFineStatus = 1;
                    $chqFine->update();
                }
            }

            flash('Fees has been submitted successfully!!');
            if ($request->ajax()) {
                return response()->json(['success' => "SUCCESS"], 200, ['app-status' => 'success']);
            }
            
        } else {
            flash('Fees has not been submitted successfully!!');
            if ($request->ajax()) {
                return response()->json(['success' => "SUCCESS"], 200, ['app-status' => 'success']);
            }
        }
    }
    
    
    public function isLesserTransaction(Request $request,$penaltyAmount){
        //add the amount to the lesser table
        DB::beginTransaction();
        try{
        $total_paid = 0;
         if ($request->paymentMode == 'Cash' || $request->paymentMode == 'Card'){
            $total_paid = $request->payable;
        } else {
            $total_paid = $request->payable;
        }
        
        $stdtransaction = new \App\LesserTransaction();
        $stdtransaction->fill($request->all());
        if ($request->has('paymentDate') && $request->paymentDate != null) {
            $stdtransaction->paymentDate = $request->paymentDate;
        } else {
            $stdtransaction->paymentDate = today_date();
        }
        if ($request->paymentMode == 'Cheque' || $request->paymentMode == 'DD') {
                $stdtransaction->status = 'In-Process';
            }
        $stdtransaction->totalPaid =$total_paid;
        $next_receiptno = next_receiptno();
        $stdtransaction->receiptNo = 'SFP000' . $next_receiptno;
        $stdtransaction->idSchool = Auth::guard('school')->user()->idSchool;
        $stdtransaction->penaltyAmount = $penaltyAmount;
        $stdtransaction->fine = $request->totalFine;
        $stdtransaction->discount = 0;

        $stdtransaction->save();
        $totalDiscount=0;
        foreach($request->selectedHeaders as $demandID){
            foreach($request->subhead[$demandID] as $subheaders){
            //details are stored here
            $stdtransaction_detail = new \App\LesserTransactionDetail();
                $stdtransaction_detail->idStudent = $request->idStudent;
                $stdtransaction_detail->idLesserTransaction = $stdtransaction->idLesserTransaction;
                $stdtransaction_detail->idFeehead = $subheaders['id'];
                if ($request->has('paymentDate') && $request->paymentDate != null) {
                    $stdtransaction_detail->paymentDate = $request->paymentDate;
                } else {
                    $stdtransaction_detail->paymentDate = today_date();
                }
                if ($request->paymentMode == 'Cheque' || $request->paymentMode == 'DD') {
                    $stdtransaction_detail->status = 'In-Process';
                }
    
                $stdtransaction_detail->amountPaid = $subheaders['headerPaid'];
                $stdtransaction_detail->fine = 0;
                if(DB::table('lesser_transaction_details')->where('idFeehead', $subheaders['id'])->where('idStudent', $request->idStudent)->doesntExist()){
                    $stdtransaction_detail->discount = $subheaders['headerDiscount'];
                    $totalDiscount=$totalDiscount+$subheaders['headerDiscount'];
                }else $stdtransaction_detail->discount =0;
                $stdtransaction_detail->save();
            }
        }
        if($totalDiscount>0){
            $stdtransaction->discount=$totalDiscount;
            $stdtransaction->update();
        }
        DB::commit();
        return 1;
        }catch(\Exception $e){
            DB::rollBack();
            return 0;
            
        }
        //    
    }
    
     public function isBusLesserTransaction(Request $request,$penaltyAmount){
        //add the amount to the lesser table
        DB::beginTransaction();
        try{
        $total_paid = 0;
         if ($request->paymentMode == 'Cash' || $request->paymentMode == 'Card'){
            $total_paid = $request->payable;
        } else {
            $total_paid = $request->payable;
        }
        
        $stdtransaction = new \App\BusLesserTransaction();
        $stdtransaction->fill($request->all());
        if ($request->has('paymentDate') && $request->paymentDate != null) {
            $stdtransaction->paymentDate = $request->paymentDate;
        } else {
            $stdtransaction->paymentDate = today_date();
        }
        if ($request->paymentMode == 'Cheque' || $request->paymentMode == 'DD') {
                $stdtransaction->status = 'In-Process';
            }
        $stdtransaction->totalPaid =$total_paid;
        $next_receiptno = next_receiptno();
        $stdtransaction->receiptNo = 'SFP000' . $next_receiptno;
        $stdtransaction->idSchool = Auth::guard('school')->user()->idSchool;
        $stdtransaction->penaltyAmount = $penaltyAmount;
        $stdtransaction->fine = $request->totalFine;
        $stdtransaction->discount = 0;

        $stdtransaction->save();
        $totalDiscount=0;
        foreach($request->selectedHeaders as $demandID){
            foreach($request->subhead[$demandID] as $subheaders){
            //details are stored here
            $stdtransaction_detail = new \App\BusLesserTransactionDetail();
                $stdtransaction_detail->idStudent = $request->idStudent;
                $stdtransaction_detail->idBusLesserTransaction = $stdtransaction->idBusLesserTransaction;
                $stdtransaction_detail->idBusFeehead = $subheaders['id'];
                if ($request->has('paymentDate') && $request->paymentDate != null) {
                    $stdtransaction_detail->paymentDate = $request->paymentDate;
                } else {
                    $stdtransaction_detail->paymentDate = today_date();
                }
                if ($request->paymentMode == 'Cheque' || $request->paymentMode == 'DD') {
                    $stdtransaction_detail->status = 'In-Process';
                }
    
                $stdtransaction_detail->amountPaid = $subheaders['headerPaid'];
                $stdtransaction_detail->fine = 0;
                if(DB::table('bus_lesser_transaction_details')->where('idBusFeehead', $subheaders['id'])->where('idStudent', $request->idStudent)->doesntExist()){
                    $stdtransaction_detail->discount = $subheaders['headerDiscount'];
                    $totalDiscount=$totalDiscount+$subheaders['headerDiscount'];
                }else $stdtransaction_detail->discount =0;
                $stdtransaction_detail->save();
            }
        }
        if($totalDiscount>0){
            $stdtransaction->discount=$totalDiscount;
            $stdtransaction->update();
        }
        DB::commit();
        return 1;
        }catch(\Exception $e){
            DB::rollBack();
            return 0;
            
        }
        //    
    }
    
    public function isHostelLesserTransaction(Request $request,$penaltyAmount){
        //add the amount to the lesser table
        DB::beginTransaction();
        try{
        $total_paid = 0;
         if ($request->paymentMode == 'Cash' || $request->paymentMode == 'Card'){
            $total_paid = $request->payable;
        } else {
            $total_paid = $request->payable;
        }
        
        $stdtransaction = new \App\HostelLesserTransaction();
        $stdtransaction->fill($request->all());
        if ($request->has('paymentDate') && $request->paymentDate != null) {
            $stdtransaction->paymentDate = $request->paymentDate;
        } else {
            $stdtransaction->paymentDate = today_date();
        }
        if ($request->paymentMode == 'Cheque' || $request->paymentMode == 'DD') {
                $stdtransaction->status = 'In-Process';
            }
        $stdtransaction->totalPaid =$total_paid;
        $next_receiptno = next_receiptno();
        $stdtransaction->receiptNo = 'SFP000' . $next_receiptno;
        $stdtransaction->idSchool = Auth::guard('school')->user()->idSchool;
        $stdtransaction->penaltyAmount = $penaltyAmount;
        $stdtransaction->fine = $request->totalFine;
        $stdtransaction->discount = 0;

        $stdtransaction->save();
        $totalDiscount=0;
        foreach($request->selectedHeaders as $demandID){
            foreach($request->subhead[$demandID] as $subheaders){
            //details are stored here
            $stdtransaction_detail = new \App\HostelLesserTransactionDetail();
                $stdtransaction_detail->idStudent = $request->idStudent;
                $stdtransaction_detail->idHostelLesserTransaction = $stdtransaction->idHostelLesserTransaction;
                $stdtransaction_detail->idFeehead = $subheaders['id'];
                if ($request->has('paymentDate') && $request->paymentDate != null) {
                    $stdtransaction_detail->paymentDate = $request->paymentDate;
                } else {
                    $stdtransaction_detail->paymentDate = today_date();
                }
                if ($request->paymentMode == 'Cheque' || $request->paymentMode == 'DD') {
                    $stdtransaction_detail->status = 'In-Process';
                }
    
                $stdtransaction_detail->amountPaid = $subheaders['headerPaid'];
                $stdtransaction_detail->fine = 0;
                if(DB::table('hostel_lesser_transaction_details')->where('idFeehead', $subheaders['id'])->where('idStudent', $request->idStudent)->doesntExist()){
                    $stdtransaction_detail->discount = $subheaders['headerDiscount'];
                    $totalDiscount=$totalDiscount+$subheaders['headerDiscount'];
                }else $stdtransaction_detail->discount =0;
                $stdtransaction_detail->save();
            }
        }
        if($totalDiscount>0){
            $stdtransaction->discount=$totalDiscount;
            $stdtransaction->update();
        }
        DB::commit();
        return 1;
        }catch(\Exception $e){
            DB::rollBack();
            return 0;
            
        }
        //    
    }
    
    
    public function storeTransaction(Request $request,$penaltyAmount){
         DB::beginTransaction();
        try{
        $total_paid = 0;
        if ($request->paymentMode == 'Cash' || $request->paymentMode == 'Card'){
            $total_paid = $request->payable;
        } else {
            $total_paid = $request->payable;
        }
        $stdtransaction = new \App\StudentTransaction();
        $stdtransaction->fill($request->all());
        if ($request->has('paymentDate') && $request->paymentDate != null) {
            $stdtransaction->paymentDate = $request->paymentDate;
        } else {
            $stdtransaction->paymentDate = today_date();
        }

        if ($request->paymentMode == 'Cash' || $request->paymentMode == 'Card') {
            $stdtransaction->totalPaid = $total_paid;
        } else {
            $stdtransaction->totalPaid = $total_paid;
            $stdtransaction->status = 'In-Process';
        }

        $next_receiptno = next_receiptno();
        $stdtransaction->receiptNo = 'SFP000' . $next_receiptno;
        $stdtransaction->idSchool = Auth::guard('school')->user()->idSchool;
        $stdtransaction->penaltyAmount = $penaltyAmount;
        $stdtransaction->fine = $request->totalFine;
        $stdtransaction->discount = 0;
        $stdtransaction->save();
        
        //for loop for headers
        $totalDiscount=0;
        foreach($request->selectedHeaders as $demandID){
             foreach($request->subhead[$demandID] as $subheaders){
                $stdtransaction_detail = new \App\StudentTransactionDetail();
                $stdtransaction_detail->idStudent = $request->idStudent;
                $stdtransaction_detail->idTransaction = $stdtransaction->idTransaction;
                $stdtransaction_detail->idFeehead = $subheaders['id'];
                if ($request->has('paymentDate') && $request->paymentDate != null) {
                    $stdtransaction_detail->paymentDate = $request->paymentDate;
                } else {
                    $stdtransaction_detail->paymentDate = today_date();
                }
    
                $stdtransaction_detail->amountPaid = $subheaders['headerPaid'];
                $stdtransaction_detail->fine = 0;
                $stdtransaction_detail->isNorth = 2;
                $stdtransaction_detail->discount = $subheaders['headerDiscount'];
                $totalDiscount=$totalDiscount+$subheaders['headerDiscount'];
                
                if ($request->paymentMode == 'Cheque' || $request->paymentMode == 'DD') {
                    $stdtransaction_detail->status = 'In-Process';
                }
                
                $stdtransaction_detail->save();
             }
        }
        
        if($totalDiscount >0){
            $stdtransaction->discount = $totalDiscount;
            $stdtransaction->update(); 
        }
        DB::commit();
        return 1;
        }catch(\Exception $e){
            DB::rollBack();
            return 0;
            
        }
    }

    public function storeBusTransaction(Request $request,$penaltyAmount){
         DB::beginTransaction();
        try{
        $total_paid = 0;
        if ($request->paymentMode == 'Cash' || $request->paymentMode == 'Card'){
            $total_paid = $request->payable;
        } else {
            $total_paid = $request->payable;
        }
        $stdtransaction = new \App\BusTransaction();
        $stdtransaction->fill($request->all());
        if ($request->has('paymentDate') && $request->paymentDate != null) {
            $stdtransaction->paymentDate = $request->paymentDate;
        } else {
            $stdtransaction->paymentDate = today_date();
        }

        if ($request->paymentMode == 'Cash' || $request->paymentMode == 'Card') {
            $stdtransaction->totalPaid = $total_paid;
        } else {
            $stdtransaction->totalPaid = $total_paid;
            $stdtransaction->status = 'In-Process';
        }

        $next_receiptno = next_receiptno();
        $stdtransaction->receiptNo = 'SFP000' . $next_receiptno;
        $stdtransaction->idSchool = Auth::guard('school')->user()->idSchool;
        $stdtransaction->penaltyAmount = $penaltyAmount;
        $stdtransaction->fine = $request->totalFine;
        $stdtransaction->discount = 0;
        $stdtransaction->save();
        
        //for loop for headers
        $totalDiscount=0;
        foreach($request->selectedHeaders as $demandID){
             foreach($request->subhead[$demandID] as $subheaders){
                $stdtransaction_detail = new \App\BusTransactionDetail();
                $stdtransaction_detail->idStudent = $request->idStudent;
                $stdtransaction_detail->idBusTransaction = $stdtransaction->idBusTransaction;
                $stdtransaction_detail->idBusFeehead = $subheaders['id'];
                if ($request->has('paymentDate') && $request->paymentDate != null) {
                    $stdtransaction_detail->paymentDate = $request->paymentDate;
                } else {
                    $stdtransaction_detail->paymentDate = today_date();
                }
    
                $stdtransaction_detail->amountPaid = $subheaders['headerPaid'];
                $stdtransaction_detail->fine = 0;
                $stdtransaction_detail->isNorth = 2;
                $stdtransaction_detail->discount = $subheaders['headerDiscount'];
                $totalDiscount=$totalDiscount+$subheaders['headerDiscount'];
                
                if ($request->paymentMode == 'Cheque' || $request->paymentMode == 'DD') {
                    $stdtransaction_detail->status = 'In-Process';
                }
                
                $stdtransaction_detail->save();
             }
        }
        
        if($totalDiscount >0){
            $stdtransaction->discount = $totalDiscount;
            $stdtransaction->update(); 
        }
        DB::commit();
        return 1;
        }catch(\Exception $e){
            DB::rollBack();
            return 0;
            
        }
    }

    public function storeHostelTransaction(Request $request,$penaltyAmount){
         DB::beginTransaction();
        try{
        $total_paid = 0;
        if ($request->paymentMode == 'Cash' || $request->paymentMode == 'Card'){
            $total_paid = $request->payable;
        } else {
            $total_paid = $request->payable;
        }
        $stdtransaction = new \App\HostelTransaction();
        $stdtransaction->fill($request->all());
        if ($request->has('paymentDate') && $request->paymentDate != null) {
            $stdtransaction->paymentDate = $request->paymentDate;
        } else {
            $stdtransaction->paymentDate = today_date();
        }

        if ($request->paymentMode == 'Cash' || $request->paymentMode == 'Card') {
            $stdtransaction->totalPaid = $total_paid;
        } else {
            $stdtransaction->totalPaid = $total_paid;
            $stdtransaction->status = 'In-Process';
        }

        $next_receiptno = next_receiptno();
        $stdtransaction->receiptNo = 'SFP000' . $next_receiptno;
        $stdtransaction->idSchool = Auth::guard('school')->user()->idSchool;
        $stdtransaction->penaltyAmount = $penaltyAmount;
        $stdtransaction->fine = $request->totalFine;
        $stdtransaction->discount = 0;
        $stdtransaction->save();
        
        //for loop for headers
        $totalDiscount=0;
        foreach($request->selectedHeaders as $demandID){
             foreach($request->subhead[$demandID] as $subheaders){
                $stdtransaction_detail = new \App\HostelTransactionDetail();
                $stdtransaction_detail->idStudent = $request->idStudent;
                $stdtransaction_detail->idHostelTransaction = $stdtransaction->idHostelTransaction;
                $stdtransaction_detail->idFeehead = $subheaders['id'];
                if ($request->has('paymentDate') && $request->paymentDate != null) {
                    $stdtransaction_detail->paymentDate = $request->paymentDate;
                } else {
                    $stdtransaction_detail->paymentDate = today_date();
                }
    
                $stdtransaction_detail->amountPaid = $subheaders['headerPaid'];
                $stdtransaction_detail->fine = 0;
                $stdtransaction_detail->isNorth = 2;
                $stdtransaction_detail->discount = $subheaders['headerDiscount'];
                $totalDiscount=$totalDiscount+$subheaders['headerDiscount'];
                
                if ($request->paymentMode == 'Cheque' || $request->paymentMode == 'DD') {
                    $stdtransaction_detail->status = 'In-Process';
                }
                
                $stdtransaction_detail->save();
             }
        }
        
        if($totalDiscount >0){
            $stdtransaction->discount = $totalDiscount;
            $stdtransaction->update(); 
        }
        DB::commit();
        return 1;
        }catch(\Exception $e){
            DB::rollBack();
            return 0;
            
        }
    }

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

    /**
     * Show the form for editing the specified resource.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function edit($id) {
        //
    }

    /**
     * Update the specified resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function update(Request $request, $id) {
        //
    }

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

    public function stdList(Request $request) {
        $classes = ['' => '--Select Class--'] + \App\ClassM::where('idSchool', '=', Auth::guard('school')->user()->idSchool)
                        ->orderBy('idClass')->get()->pluck('className', 'idClass')->toArray();
        $fys = ['' => '--Select Academic Year--'] + \App\FinancialYear::where('idSchool', '=', Auth::guard('school')->user()->idSchool)
                        ->orderBy('idFinancialYear')->get()->pluck('financialYearName', 'idFinancialYear')->toArray();
        $students = [];
        if ($request->idClass != null && $request->idSection != null && $request->idFinancialYear != null) {
            $students = \App\AdmEntry::where('idSchool', '=', Auth::guard('school')->user()->idSchool)
                            ->where('idClass', '=', $request->idClass)
                            ->where('idSection', '=', $request->idSection)
                            ->where('idFinancialYear', '=', $request->idFinancialYear)
                            ->orderBy('idStudent')->get();
        } else if ($request->ecNo != null) {
            $students = \App\AdmEntry::where('idSchool', '=', Auth::guard('school')->user()->idSchool)
                    ->where('ecNo', '=', $request->ecNo)
                    ->get();
        }
        return view('schools.north.transaction.studentlist', compact('classes', 'students', 'fys'));
    }

    public function getFeeDetails($id) {
        $student = \App\AdmEntry::where('idStudent', '=', $id)->first();
        $class_feeheads = \DB::table('northfeeheads')->where('idClass', '=', $student->idClass)
                ->where('idSection', '=', $student->idSection)
                ->where('studentCategory', '=', $student->studentType)
                ->where('isParent',0)
                ->where('isActive','=','Y')
                ->whereNull('idStudent');
        $feeheads = \DB::table('northfeeheads')->where('idStudent', '=', $student->idStudent)
                ->where('isActive','=','Y')
                ->where('isParent',0)
                ->union($class_feeheads)
                ->orderBy('toDate')
                ->get();
        $fineheads=\DB::table('northfines')->where('idSchool', '=', $student->idSchool)->where('idFinancialYear', '=', $student->idFinancialYear)->get();  
        $paidfees = \App\StudentTransaction::where('idStudent', '=', $student->idStudent)
                        ->where(function($query) {
                            $query->whereNull('status');
                            $query->orWhere('status', '=', 'In-Process');
                            $query->orWhere('status', '=', 'Cleared');
                            $query->orWhere('status', '=', 'Success');
                        })->get();
        $paidbusfees = \App\BusTransaction::where('idStudent', '=', $student->idStudent)
                        ->where(function($query) {
                            $query->whereNull('status');
                            $query->orWhere('status', '=', 'In-Process');
                            $query->orWhere('status', '=', 'Cleared');
                            $query->orWhere('status', '=', 'Success');
                        })->get();
        $paidhostelfees = \App\HostelTransaction::where('idStudent', '=', $student->idStudent)
                        ->where(function($query) {
                            $query->whereNull('status');
                            $query->orWhere('status', '=', 'In-Process');
                            $query->orWhere('status', '=', 'Cleared');
                            $query->orWhere('status', '=', 'Success');
                        })->get();
        $lesserfees = \App\LesserTransaction::where('idStudent', '=', $student->idStudent)
                        ->where(function($query) {
                            $query->whereNull('status');
                            $query->orWhere('status', '=', 'In-Process');
                            $query->orWhere('status', '=', 'Cleared');
                            $query->orWhere('status', '=', 'Success');
                        })->get();
        $lesserbusfees = \App\BusLesserTransaction::where('idStudent', '=', $student->idStudent)
                        ->where(function($query) {
                            $query->whereNull('status');
                            $query->orWhere('status', '=', 'In-Process');
                            $query->orWhere('status', '=', 'Cleared');
                            $query->orWhere('status', '=', 'Success');
                        })->get();
        $lesserhostelfees = \App\HostelLesserTransaction::where('idStudent', '=', $student->idStudent)
                        ->where(function($query) {
                            $query->whereNull('status');
                            $query->orWhere('status', '=', 'In-Process');
                            $query->orWhere('status', '=', 'Cleared');
                            $query->orWhere('status', '=', 'Success');
                        })->get();
        return view('schools.north.transaction.feedetails_form', compact( 'feeheads', 'fineheads','student','paidfees','paidhostelfees','lesserfees','paidbusfees','lesserbusfees','lesserhostelfees'));
    }

    public function printReceipt($id) {
        $school = \App\School::where('idSchool', '=', Auth::guard('school')->user()->idSchool)->first();
        $transaction = \App\StudentTransaction::where('idTransaction', '=', $id)->first();
        $feehead_ids = $transaction->details->pluck('idFeehead')->toArray();
        $demands = \App\NorthFeeHead::select('isParent')->where('isParent', '!=', '0')
                                ->whereIn('idFeehead', $feehead_ids)
                                ->distinct('isParent')
                                ->get();
        $student = \App\AdmEntry::where('idStudent', '=', $transaction->idStudent)->first();
        $class_feeheads = \DB::table('northfeeheads')->where('idClass', '=', $student->idClass)
                ->where('idSection', '=', $student->idSection)
                ->where('studentCategory', '=', $student->studentType)
                ->where('isParent',0)
                ->where('isActive','=','Y')
                ->whereNull('idStudent');
        $feeheads = \DB::table('northfeeheads')->where('idStudent', '=', $student->idStudent)
                ->where('isActive','=','Y')
                ->where('isParent',0)
                ->union($class_feeheads)
                ->orderBy('toDate')
                ->get();
        $feetotal = $feeheads->sum('amount');
        
        $pdf = PDF::loadView('schools.north.transaction.print_receipt', ['margin_top' => 20], compact('demands','transaction', 'school', 'student', 'feetotal'));
        return $pdf->stream('feereceipt.pdf');
    }
    
    public function printHostelReceipt($id) {
        $school = \App\School::where('idSchool', '=', Auth::guard('school')->user()->idSchool)->first();
        $transaction = \App\HostelTransaction::where('idHostelTransaction', '=', $id)->first();
        $feehead_ids = $transaction->details->pluck('idParent')->toArray();
       
        $demands = \App\NorthFeeHead::where('isParent', '=', '0')
                                ->whereIn('idFeehead', $feehead_ids)
                                ->get();
                                
        $student = \App\AdmEntry::where('idStudent', '=', $transaction->idStudent)->first();
        $class_feeheads = \DB::table('northfeeheads')->where('idClass', '=', $student->idClass)
                ->where('idSection', '=', $student->idSection)
                ->where('studentCategory', '=', $student->studentType)
                ->where('isParent',0)
                ->whereNull('idStudent');
        $feeheads = \DB::table('northfeeheads')->where('idStudent', '=', $student->idStudent)->where('isParent',0)
                ->union($class_feeheads)
                ->orderBy('toDate')
                ->get();
        $feetotal = $feeheads->sum('amount');
        
        $pdf = PDF::loadView('schools.north.transaction.print_receipt', ['margin_top' => 20], compact('demands','transaction', 'school', 'student', 'feetotal'));
        return $pdf->stream('feereceipt.pdf');
    }

     public function printBusReceipt($id) {
        $school = \App\School::where('idSchool', '=', Auth::guard('school')->user()->idSchool)->first();
        $transaction = \App\BusTransaction::where('idBusTransaction', '=', $id)->first();
        $feehead_ids = $transaction->details->pluck('idParent')->toArray();
       
        $demands = \App\NorthFeeHead::where('isParent', '=', '0')
                                ->whereIn('idFeehead', $feehead_ids)
                                ->get();
                                
        $student = \App\AdmEntry::where('idStudent', '=', $transaction->idStudent)->first();
        $class_feeheads = \DB::table('northfeeheads')->where('idClass', '=', $student->idClass)
                ->where('idSection', '=', $student->idSection)
                ->where('studentCategory', '=', $student->studentType)
                ->where('isParent',0)
                ->whereNull('idStudent');
        $feeheads = \DB::table('northfeeheads')->where('idStudent', '=', $student->idStudent)->where('isParent',0)
                ->union($class_feeheads)
                ->orderBy('toDate')
                ->get();
        $feetotal = $feeheads->sum('amount');
        
        $pdf = PDF::loadView('schools.north.transaction.print_receipt', ['margin_top' => 20], compact('demands','transaction', 'school', 'student', 'feetotal'));
        return $pdf->stream('feereceipt.pdf');
    }

    public function lesserAmtReceipt($id) {
        $school = \App\School::where('idSchool', '=', Auth::guard('school')->user()->idSchool)->first();
        $transaction = \App\LesserTransaction::where('idLesserTransaction', '=', $id)->first();
        $student = \App\AdmEntry::where('idStudent', '=', $transaction->idStudent)->first();
        $feehead_ids = $transaction->details->pluck('idFeehead')->toArray();
        $demands = \App\NorthFeeHead::where('isParent', '=', '0')
                                ->whereIn('idFeehead', $feehead_ids)
                                ->get();
        $class_feeheads = \DB::table('northfeeheads')->where('idClass', '=', $student->idClass)
                ->where('idSection', '=', $student->idSection)
                ->where('studentCategory', '=', $student->studentType)
                ->where('isParent',0)
                ->whereNull('idStudent');
        $feeheads = \DB::table('northfeeheads')->where('idStudent', '=', $student->idStudent)->where('isParent',0)
                ->union($class_feeheads)
                ->orderBy('toDate')
                ->get();
        $feetotal = $feeheads->sum('amount');

        $pdf = PDF::loadView('schools.north.transaction.print_lesseramt_receipt', ['margin_top' => 20], compact('demands','transaction', 'school', 'student', 'feetotal'));
        return $pdf->stream('feereceipt.pdf');
    }

    public function cancelReceipt($id) {
        $transaction = \App\StudentTransaction::where('idTransaction', '=', $id)->first();
        $student = \App\AdmEntry::where('idStudent', '=', $transaction->idStudent)->first();
        return view('schools.north.transaction.cancelreceipt', compact('transaction', 'student'));
    }

    public function cancelLessPaidReceipt($id) {
        $transaction = \App\LesserTransaction::where('idLesserTransaction', '=', $id)->first();
        $student = \App\AdmEntry::where('idStudent', '=', $transaction->idStudent)->first();
        return view('schools.north.transaction.cancelreceipt', compact('transaction', 'student'));
    }

    public function receiptCancellation(Request $request) {
        $rules = ['remarks' => 'required'];
        $this->validate($request, $rules);
        $acessAmount = 0;
        if ($request->type == 'Full') {
            $transaction = \App\StudentTransaction::where('idTransaction', '=', $request->idTransaction)->first();
            $acessAmount = $transaction->accessPaid;
            DB::beginTransaction();
            $transaction->status = 'Cancelled';
            $transaction->remarks = $request->remarks;
            $transaction->update();
            $stdtransaction_dets = \App\StudentTransactionDetail::where('idTransaction', '=', $request->idTransaction)->get();
            foreach ($stdtransaction_dets as $var) {
                $det = \App\StudentTransactionDetail::where('idTransactionDetail', '=', $var->idTransactionDetail)->first();
                $det->status = 'Cancelled';
                $det->update();
            }
            DB::commit();
            if ($acessAmount > 0) {
                $excess_transaction = DB::table('excess_transaction')
                                ->join('student_transaction', 'excess_transaction.idTransaction', '=', 'student_transaction.idTransaction')
                                ->where('idStudent', '=', $request->idStudent)
                                ->where('idFinancialYear', '=', $request->idFinancialYear)
                                ->where(function($query) {
                                    $query->whereNull('status');
                                    $query->orWhere('status', '=', 'Cleared');
                                    $query->orWhere('status', '=', 'In-Process');
                                    $query->orWhere('status', '=', 'Success');
                                })
                                ->where('excess_transaction.isActive', '=', 'Y')
                                ->orderBy('excess_transaction.idTransaction', 'desc')->first();
                if (isset($excess_transaction))
                    $acessAmount = $acessAmount + $excess_transaction->excessAmount;

                $excess = new \App\ExcessTransaction();
                $excess->idTransaction = $request->idTransaction;
                $excess->excessAmount = $acessAmount;
                $excess->remarks = "Access amount has been reverted to this transaction and previous access amount has been added";
                $excess->save();
            }
        } else {
            $transaction = \App\LesserTransaction::where('idLesserTransaction', '=', $request->idLesserTransaction)->first();
            $acessAmount = $transaction->accessPaid;
            DB::beginTransaction();
            $transaction->status = 'Cancelled';
            $transaction->remarks = $request->remarks;
            $transaction->update();
            $stdtransaction_dets = \App\LesserTransactionDetail::where('idLesserTransaction', '=', $request->idTransaction)->get();
            foreach ($stdtransaction_dets as $var) {
                $det = \App\LesserTransactionDetail::where('idLessTransactionDet', '=', $var->idLessTransactionDet)->first();
                $det->status = 'Cancelled';
                $det->update();
            }
            DB::commit();
//            if ($acessAmount > 0) {
//                $excess_transaction = DB::table('excess_transaction')
//                                ->join('lesser_transaction', 'excess_transaction.idLesserTransaction', '=', 'lesser_transaction.idLesserTransaction')
//                                ->where('idStudent', '=', $request->idStudent)
//                                ->where('idFinancialYear', '=', $request->idFinancialYear)
//                                ->where(function($query) {
//                                    $query->whereNull('status');
//                                    $query->orWhere('status', '=', 'Cleared');
//                                    $query->orWhere('status', '=', 'In-Process');
//                                    $query->orWhere('status', '=', 'Success');
//                                })
//                                ->where('excess_transaction.isActive', '=', 'Y')
//                                ->orderBy('excess_transaction.idLesserTransaction', 'desc')->first();
//                if (isset($excess_transaction))
//                    $acessAmount = $acessAmount + $excess_transaction->excessAmount;
//
//                $excess = new \App\ExcessTransaction();
//                $excess->idTransaction = $request->idTransaction;
//                $excess->excessAmount = $acessAmount;
//                $excess->remarks = "Access amount has been reverted to this transaction and previous access amount has been added";
//                $excess->save();
//            }
        }
        return redirect('school/cancelled-receipts');
    }
}

Copyright © 2021 - 2025 IMMREX7