auditionadmin/app/Http/Requests/EntryStoreRequest.php

112 lines
3.1 KiB
PHP

<?php
namespace App\Http\Requests;
use App\Models\Audition;
use App\Models\Entry;
use App\Models\Student;
use Auth;
use Carbon\Carbon;
use Illuminate\Foundation\Http\FormRequest;
class EntryStoreRequest extends FormRequest
{
public function authorize(): bool
{
if (auth()->user()->is_admin) {
return true;
}
if (auth()->user()->school_id) {
return true;
}
return false;
}
public function rules(): array
{
$rules = [
'student_id' => ['required', 'exists:students,id'],
'audition_id' => ['required', 'exists:auditions,id'],
'for_seating' => ['sometimes', 'boolean'],
'for_advancement' => ['sometimes', 'boolean'],
];
// Add late_fee_waived validation only for admin users
if (auth()->user()->is_admin) {
$rules['late_fee_waived'] = ['sometimes', 'boolean'];
}
return $rules;
}
public function withValidator($validator): void
{
$validator->after(function ($validator) {
$auditionId = $this->input('audition_id');
$audition = Audition::find($auditionId);
$student = Student::find($this->input('student_id'));
if (! $audition) {
$validator->errors()->add('audition_id', 'The selected audition does not exist.');
return;
}
if (Entry::where('student_id', $this->input('student_id'))->where('audition_id', $auditionId)->exists()) {
$validator->errors()->add('student_id',
$student->full_name().' is already entered in the '.$audition->name.' audition.');
}
if (! Auth::user()->is_admin) { //Admins don't care about deadlines
$currentDate = Carbon::now('America/Chicago')->format('Y-m-d');
if ($audition->entry_deadline < $currentDate) {
$validator->errors()->add('entry_deadline', 'The entry deadline for that audition has passed.');
}
}
});
}
/**
* Prepare the data for validation.
*/
protected function prepareForValidation(): void
{
// Normalize the boolean inputs to 1 or 0
$data = [
'for_seating' => $this->boolean('for_seating'),
'for_advancement' => $this->boolean('for_advancement'),
];
// Only include late_fee_waived in the data if the user is admin
if (auth()->user()->is_admin) {
$data['late_fee_waived'] = $this->boolean('late_fee_waived');
}
$this->merge($data);
}
/**
* Get the data after validation and add the "enter_for" array.
*/
public function validatedWithEnterFor()
{
$validated = $this->validated();
$enter_for = [];
if (! empty($validated['for_seating'])) {
$enter_for[] = 'seating';
}
if (! empty($validated['for_advancement'])) {
$enter_for[] = 'advancement';
}
$validated['enter_for'] = $enter_for;
return $validated;
}
}