<?php

namespace App\Services\Accounting;

use App\Models\Academic\AcademicYear;
use App\Models\Academic\StudentClass;
use App\Models\Accounting\ClassFee;
use App\Models\Accounting\FeeType;
use Illuminate\Http\Request;

class StudentFeeService
{
    public function getClassFees()
    {
        return ClassFee::selectRaw('sum(amount) as amount, sc.class_name, ay.year, 
                class_fees.class_id, class_fees.year_id')
                ->leftJoin('student_classes as sc', 'sc.id', '=', 'class_fees.class_id')
                ->leftJoin('academic_years as ay', 'ay.id', '=', 'class_fees.year_id')
                ->groupBy('class_fees.class_id', 'class_fees.year_id', 'sc.class_name', 'ay.year', 'dp.name')
                ->get();
    }

    public function getFeeDetails($classId, $yearId)
    {
        $query = ClassFee::select([
            'student_classes.class_name',
            'academic_years.year',
            'class_fees.class_id',
            'class_fees.year_id',
        ])
        ->leftJoin('student_classes', 'student_classes.id', '=', 'class_fees.class_id')
        ->leftJoin('academic_years', 'academic_years.id', '=', 'class_fees.year_id')
        ->where('class_id', $classId)
        ->where('year_id', $yearId);


        return $query->first();
    }

    public function getSelectedFeeTypes($classId, $year_id)
    {
        $query = ClassFee::where('class_id', $classId)->where('year_id', $year_id);
        return $query->pluck('amount', 'fee_type_id')->toArray();
    }

    public function store(Request $request)
    {
        $this->validateRequest($request);

        $classFee = $this->checkClassFees($request->class_id, $request->year_id);

        if ($classFee->count() > 0) {
            return redirect()->route('class_fees.index')->with('warning', 'Class Fee already created for this class\year. You can update it from the list.');
        }

        $class_id = $request->input('class_id');
        $year_id = $request->input('year_id');
        $fee_type_ids = $request->input('fee_type_id');
        $amounts = $request->input('amount');
        $months = $request->input('month');
        $classFeesdata = [];

        foreach ($fee_type_ids as $key => $fee_type_id) {
            if (!empty($amounts[$fee_type_id])) {
                $classFeesdata[] = [
                    'class_id' => $class_id,
                    'year_id' => $year_id,
                    'fee_type_id' => $fee_type_id,
                    'amount' => $amounts[$fee_type_id],
                    'month' => $months[$fee_type_id],
                    'created_at' => now(),
                    'updated_at' => now(),
                ];
            }
        }

        $transportHostel = FeeType::where('code', 'TRANSPORT')->orWhere('code', 'HOSTEL')->get();

        foreach ($transportHostel as $fee_type) {

            $classFeesdata[] = [
                'class_id' => $class_id,
                'year_id' => $year_id,
                'fee_type_id' => $fee_type->id,
                'amount' => 0,
                'month' => $fee_type->month,
                'created_at' => now(),
                'updated_at' => now(),
            ];

        }

        ClassFee::insert($classFeesdata);
    }

    public function update(Request $request)
    {
        $this->validateRequest($request);
        $year_id = $request->input('year_id');
        $class_id = $request->input('class_id');

        // Delete existing fees for the class
        $this->delete($class_id, $year_id);

        $this->store($request);

    }

    public function delete($class_id, $year_id)
    {
        $classFees = ClassFee::where('class_id', $class_id)->where('year_id', $year_id);
        $classFees->delete();
    }


    public function validateRequest(Request $request)
    {
        $request->validate([
            'fee_type_id' => 'array|required',
            'fee_type_id.*' => 'exists:fee_types,id',
            'amount' => 'array|required',
            'amount.*' => 'numeric',
        ]);
    }

    public function checkClassFees($class_id, $year_id)
    {
        $classFees =ClassFee::where('class_id', $class_id)->where('year_id', $year_id);
        $classFees->get();
        return $classFees;
    }

    public function getRelatedData()
    {
        return [
            'classes' => StudentClass::pluck('class_name', 'id'),
            'classFees' => ClassFee::all(),
            'feeTypes' => FeeType::all(),
            'years' => AcademicYear::pluck('year','id'),
        ];
    }
}
