<?php

namespace App\Http\Controllers\Api\Finance;

use App\Http\Controllers\Api\BaseApiController;
use App\Http\Requests\Payments\PaymentEventChargesListRequest;
use App\Services\Payments\PaymentEventChargesService;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Validator;

class PaymentEventChargesController extends BaseApiController
{
    public function __construct(private PaymentEventChargesService $service)
    {
        parent::__construct();
    }

    public function index(PaymentEventChargesListRequest $request): JsonResponse
    {
        $payload = $request->validated();
        $data = $this->service->listCharges($payload['school_year'] ?? null, $payload['semester'] ?? null);

        return response()->json(['ok' => true] + $data);
    }

    public function store(Request $request): JsonResponse
    {
        $data = array_merge($request->query->all(), $request->all(), $request->json()->all());
        $validator = Validator::make($data, [
            'parent_id' => ['required', 'integer', 'min:1'],
            'event_name' => ['required', 'string', 'max:255'],
            'description' => ['nullable', 'string', 'max:1000'],
            'amount' => ['required', 'numeric', 'min:0'],
            'semester' => ['required', 'string', 'max:50'],
            'school_year' => ['required', 'string', 'max:50'],
            'student_ids' => ['nullable', 'array'],
            'student_ids.*' => ['integer', 'min:1'],
            'student_id' => ['nullable', 'integer', 'min:1'],
        ]);

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

        $payload = $validator->validated();
        $userId = (int) (auth()->id() ?? 0);

        $count = $this->service->addCharges($payload, $userId);
        if ($count === 0) {
            return response()->json(['ok' => false, 'message' => 'No student selected.'], 422);
        }

        return response()->json(['ok' => true, 'inserted' => $count]);
    }

    public function enrolledStudents(PaymentEventChargesListRequest $request, int $parentId): JsonResponse
    {
        $payload = $request->validated();
        $students = $this->service->getEnrolledStudents($parentId, $payload['school_year'] ?? null);

        return response()->json(['ok' => true, 'students' => $students]);
    }
}
