<?php

namespace App\Http\Requests\Administrator;

use App\Http\Requests\ApiFormRequest;
use Illuminate\Validation\Rule;

class UpdateEnrollmentStatusesRequest extends ApiFormRequest
{
    public function validationData(): array
    {
        $data = $this->all();

        if (array_key_exists('enrollment_status', $data)) {
            return $data;
        }

        $raw = $this->getContent() ?: '';
        if ($raw !== '') {
            $json = json_decode($raw, true);
            if (is_array($json)) {
                return array_merge($data, $json);
            }

            parse_str($raw, $parsed);
            if (is_array($parsed)) {
                return array_merge($data, $parsed);
            }
        }

        $queryString = (string) $this->server->get('QUERY_STRING', '');
        if ($queryString !== '') {
            $parsedQuery = [];
            parse_str($queryString, $parsedQuery);
            if (is_array($parsedQuery)) {
                return array_merge($data, $parsedQuery);
            }
        }

        return $data;
    }

    public function authorize(): bool
    {
        return auth()->check();
    }

    public function rules(): array
    {
        $allowedStatuses = [
            'admission under review',
            'payment pending',
            'enrolled',
            'withdraw under review',
            'refund pending',
            'withdrawn',
            'denied',
            'waitlist',
        ];

        return [
            'enrollment_status' => ['required', 'array', 'min:1'],
            'enrollment_status.*' => ['required', 'string', Rule::in($allowedStatuses)],
        ];
    }

    public function messages(): array
    {
        return [
            '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.',
        ];
    }
}
