<?php

namespace App\Services\Accounting;

use DateTime;
use Illuminate\Http\Request;
use App\Constants\Accounting;
use App\Models\Accounting\FeeType;
use Illuminate\Support\Facades\DB;
use App\Models\Accounting\ClassFee;
use App\Models\Academic\AcademicYear;
use App\Models\Academic\StudentClass;

class ClassFeesService
{   
    public function getClassFees()
    {
        return ClassFee::selectRaw('
                SUM(amount) as amount,
                sc.class_name,
                ay.year,
                class_fees.student_class_id,
                class_fees.academic_year_id
            ')
            ->leftJoin('student_classes as sc', 'sc.id', '=', 'class_fees.student_class_id')
            ->leftJoin('academic_years as ay', 'ay.id', '=', 'class_fees.academic_year_id')
            ->groupBy(
                'class_fees.student_class_id',
                'class_fees.academic_year_id',
                'sc.class_name',
                'ay.year'
            )
            ->orderBy('sc.id', 'asc')
            ->orderBy('ay.year', 'desc')
            ->get();
    }



    public function getFeeDetails($classId, $academic_year_id)
    {
        return ClassFee::select([
                'student_classes.class_name',
                'academic_years.year',
                'class_fees.student_class_id',
                'class_fees.academic_year_id',
                'class_fees.fee_type_id',
                'class_fees.amount',
                'class_fees.month',
                'fee_types.title as fee_type_title',
            ])
            ->leftJoin('student_classes', 'student_classes.id', '=', 'class_fees.student_class_id')
            ->leftJoin('academic_years', 'academic_years.id', '=', 'class_fees.academic_year_id')
            ->leftJoin('fee_types', 'fee_types.id', '=', 'class_fees.fee_type_id')
            ->where('class_fees.student_class_id', $classId)
            ->where('class_fees.academic_year_id', $academic_year_id)
            ->get();
    }


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

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

        $student_class_id = $request->input('student_class_id');
        $academic_year_id = $request->input('academic_year_id');
        $classFee = $this->checkClassFees($student_class_id, $academic_year_id);

        if ($classFee->count() > 0) {
            return collect([]);
        }

        $months = ['Jan','Feb','Mar','Apr','May','Jun','Jul','Aug','Sep','Oct','Nov','Dec'];

        foreach ($request->except(['_token', 'student_class_id', 'academic_year_id']) as $key => $value) {
            if ($value === null || $value === '') {
                continue; // skip empty fields
            }

            // Split key into fee type and month
            if (preg_match('/^(.+)_('.implode('|', $months).')$/', $key, $matches)) {
                $feeTypeCode = $matches[1]; // e.g., Tuition
                $monthName = $matches[2]; // 'Jan', 'Feb', etc.
                $month = DateTime::createFromFormat('M', $monthName)->format('n'); 
                // Get fee_type_id from the code
                $feeType = FeeType::where('code', $feeTypeCode)->first();
                if (!$feeType) continue; // skip if fee_type not found

                if(!empty($value)){
                    ClassFee::create([
                        'student_class_id' => $student_class_id,
                        'academic_year_id' => $academic_year_id,
                        'branch_id' => auth()->user()->branch_id,
                        'fee_type_id' => $feeType->id,
                        'month' => $month,
                        'amount' => $value,
                    ]);
                }
            }
        }

        $classFeesdata = [];

        return collect($classFeesdata);
    }

    public function update(Request $request)
    {
        $this->validateRequest($request);
        $academic_year_id = $request->input('academic_year_id');
        $student_class_id = $request->input('student_class_id');
        
        // Delete existing fees for the class
        $this->delete($student_class_id, $academic_year_id);
        $this->store($request);
    }

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


    public function validateRequest(Request $request)
    {
        $request->validate([
            'student_class_id' => 'required',
            'academic_year_id' => 'required',

            // 'fee_type_id' => 'array|required',
            // 'fee_type_id.*' => 'exists:fee_types,id',
            // 'amount' => 'array|required',
            // 'amount.*' => 'numeric',
        ]);
    }

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

    public function getRelatedData()
    {
        return [
            'classes' => StudentClass::pluck('class_name', 'id'),
            // 'feeTypes' => FeeType::whereNotIn('code', [Accounting::TRANSPORT, Accounting::HOSTEL])->get(),
            'feeTypes' => FeeType::where('status', 1)->select('id','title','code')->get()->unique('code'),
            'years' => AcademicYear::orderBy('year', 'desc')->pluck('year', 'id'),
        ];
    }
}
