<?php

namespace App\Http\Controllers\Api\Administrator;

use App\Http\Controllers\Controller;
use App\Services\Administrator\AdministratorEnrollmentService;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Validator;
use Illuminate\Validation\Rule;

class AdministratorEnrollmentController extends Controller
{
    public function __construct(
        protected AdministratorEnrollmentService $service
    ) {
    }

    public function index(Request $request): JsonResponse
    {
        return response()->json(
            $this->service->enrollmentWithdrawalData(
                (string) $request->query('schoolYear', '')
            )
        );
    }

    public function newStudents(): JsonResponse
    {
        return response()->json($this->service->showNewStudentsData());
    }

    public function updateStatuses(Request $request): JsonResponse
    {
        $editorUserId = (int) Auth::id();
        if ($editorUserId <= 0) {
            return response()->json(['message' => 'Please log in first.'], 401);
        }

        $payload = $request->all();
        if (!array_key_exists('enrollment_status', $payload)) {
            $json = json_decode($request->getContent() ?: '', true);
            if (is_array($json) && array_key_exists('enrollment_status', $json)) {
                $payload['enrollment_status'] = $json['enrollment_status'];
            }
        }
        if (!array_key_exists('enrollment_status', $payload)) {
            $payload['enrollment_status'] = $request->query('enrollment_status');
        }

        $allowedStatuses = [
            'admission under review',
            'payment pending',
            'enrolled',
            'withdraw under review',
            'refund pending',
            'withdrawn',
            'denied',
            'waitlist',
        ];

        $validator = Validator::make($payload, [
            'enrollment_status' => ['required', 'array', 'min:1'],
            'enrollment_status.*' => ['required', 'string', Rule::in($allowedStatuses)],
        ], [
            'enrollment_status.required' => 'Enrollment statuses are required.',
            'enrollment_status.array' => 'Enrollment statuses must be an array.',
            'enrollment_status.min' => 'At least one enrollment status is required.',
            'enrollment_status.*.in' => 'One or more enrollment statuses are invalid.',
        ]);

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

        $data = $validator->validated();
        $result = $this->service->updateStatuses(
            (array) ($data['enrollment_status'] ?? []),
            $editorUserId
        );

        return response()->json(['message' => $result['message']], $result['status']);
    }
}
