<?php

namespace App\Http\Controllers\Api\Finance;

use App\Http\Controllers\Api\BaseApiController;
use App\Http\Resources\Fees\FeeRefundResource;
use App\Http\Resources\Fees\FeeTuitionTotalResource;
use App\Services\Fees\FeeRefundCalculatorService;
use App\Services\Fees\FeeStudentFeeService;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Validator;

class FeeCalculationController extends BaseApiController
{
    public function __construct(
        private FeeRefundCalculatorService $refunds,
        private FeeStudentFeeService $tuition
    ) {
        parent::__construct();
    }

    public function refund(Request $request): JsonResponse
    {
        $validator = Validator::make($request->all(), [
            'parent_id' => ['required', 'integer', 'min:1'],
            'students' => ['required', 'array'],
            'students.*.student_id' => ['nullable', 'integer'],
            'students.*.class_section_id' => ['required', 'integer', 'min:1'],
            'students.*.enrollment_status' => ['required', 'string', 'max:50'],
            'students.*.admission_status' => ['required', 'string', 'max:50'],
            'students.*.withdrawal_date' => ['nullable', 'date'],
        ]);

        if ($validator->fails()) {
            return response()->json([
                'message' => 'Validation failed.',
                'errors' => $validator->errors(),
            ], 422);
        }

        $payload = $validator->validated();
        $result = $this->refunds->calculateRefund($payload['students'], (int) $payload['parent_id']);

        return response()->json([
            'ok' => true,
            'refund' => new FeeRefundResource($result),
        ]);
    }

    public function tuitionTotal(Request $request): JsonResponse
    {
        $validator = Validator::make($request->all(), [
            'students' => ['required', 'array'],
            'students.*.class_section_id' => ['required', 'integer', 'min:1'],
            'students.*.grade' => ['nullable', 'string', 'max:20'],
        ]);

        if ($validator->fails()) {
            return response()->json([
                'message' => 'Validation failed.',
                'errors' => $validator->errors(),
            ], 422);
        }

        $payload = $validator->validated();
        $total = $this->tuition->totalTuitionFee($payload['students']);

        return response()->json([
            'ok' => true,
            'tuition' => new FeeTuitionTotalResource([
                'total_tuition' => $total,
            ]),
        ]);
    }
}
