<?php

namespace App\Http\Requests\Frontend;

use Illuminate\Foundation\Http\FormRequest;
use Illuminate\Validation\Rule;

class StoreExamSubmissionRequest extends FormRequest
{
    public function authorize(): bool
    {
        return true;
    }

    protected function prepareForValidation(): void
    {
        $userOption = $this->input('useroption', []);

        if (is_array($userOption)) {
            $normalizedAnswers = [];

            foreach ($userOption as $questionKey => $answer) {
                $normalizedAnswers[$questionKey] = strtoupper(trim((string) $answer));
            }

            $this->merge([
                'useroption' => $normalizedAnswers,
            ]);
        }

        $this->merge([
            'usertime' => trim((string) $this->input('usertime', '')),
        ]);
    }

    public function rules(): array
    {
        return [
            'competitionassignid' => ['required', 'integer', Rule::exists('compitetionassignment', 'id')],
            'usertime' => ['nullable', 'regex:/^\d{1,2}:\d{2}(?::\d{2})?$/'],
            'useroption' => ['nullable', 'array'],
            'useroption.*' => ['nullable', 'string', Rule::in(['A', 'B', 'C', 'D'])],
        ];
    }
}
