<?php

namespace Modules\Base\Http\Requests;

use Carbon\Carbon;
use Illuminate\Validation\Rule;
use Modules\Base\Entities\Activity;
use SMG\Support\Rules\Mobile;

class EnrollmentRequest extends BaseRequest
{
    /**
     * Get the validation rules that apply to the request.
     *
     * @return array
     */
    public function rules()
    {
        $user_id = $this->user() ? $this->user()->id : 0;

        return [
            'activity_id' => ['bail', 'required',
                Rule::exists('activities', 'id')->where(function ($query) {
                    $query->where('enroll_end', '>', Carbon::now());
                }),
                Rule::unique('enrollments')->where(function ($query) use ($user_id) {
                    $query->where('user_id', $user_id);
                }),
                function ($attribute, $value, $fail) {
                    $active = Activity::where('id', $value)->withCount('enrollments')->first();
                    if ($active && $active->limit > 0 && $active->enrollments_count >= $active->limit) {
                        return $fail('报名人数已满，不可以再报名!');
                    }
                },
                ],
            'name' => 'required',
            'mobile' => ['required', new Mobile()],
            'company' => 'required',
        ];
    }

    /**
     * @return array
     */
    public function messages()
    {
        return [
            'activity_id.unique' => '已报过名，不能再次报名',
        ];
    }
}
