<?php

namespace App\Http\Requests\ScheduledTask;

use App\Models\Group;
use App\Models\Resource;
use Illuminate\Validation\Rule;
use Illuminate\Foundation\Http\FormRequest;

class StoreScheduledTaskRequest extends FormRequest
{
    /**
     * Determine if the user is authorized to make this request.
     */
    public function authorize(): bool
    {
        return true;
    }

    /**
     * Get the validation rules that apply to the request.
     *
     * @return array<string, \Illuminate\Contracts\Validation\ValidationRule|array<mixed>|string>
     */
    public function rules(): array
    {
        $groupTable     = Group::tableName();
        $resourcesTable = Resource::tableName();

        return [
            'title'               => ['required', 'max:255'],
            'begin_date'          => ['required', 'date'],
            'end_date'            => ['required', 'date', 'after:begin_date'],
            'frequency'           => ['required', 'in:hourly,daily,weekly,monthly'],
            'sending_time'        => [Rule::requiredIf($this->input('frequency') != "hourly"), function ($attribute, $value, $fail) {

                if ($this->input('frequency') == 'daily' && !in_array($value, range(0, 23))) {
                    $fail(trans('scheduled-report.validations.invalid.hour'));

                }

            }
            ],
            'sending_weekly_day'  => [Rule::requiredIf($this->input('frequency') == "weekly"), function ($attribute, $value, $fail) {

                if ($this->input('frequency') == "weekly" && !in_array($value, $this->getWeekDays())) {

                    $fail(trans('scheduled-report.validations.invalid.weekday'));
                }

            }
            ],
            'sending_monthly_day' => [Rule::requiredIf($this->input('frequency') == "monthly"), function ($attribute, $value, $fail) {

                if ($this->input('frequency') == "monthly" && (!in_array($value, range(1, 28)) && $value != "last")) {

                    $fail(trans('scheduled-report.validations.invalid.monthday'));
                }

            }
            ],
            'groups'              => ['nullable', "exists:$groupTable,group_ID"],
            'report'              => ['required', "exists:$resourcesTable,id"],
            'send_to_admins'      => ['nullable'],
            'subject'             => ['required', 'max:100'],
            'body'                => ['required']
        ];

    }

    public function messages()
    {
        return [
            'title.required'               => trans('scheduled-report.validations.required.title'),
            'begin_date.required'          => trans('scheduled-report.validations.required.dates'),
            'end_date.required'            => trans('scheduled-report.validations.required.dates'),
            'frequency.required'           => trans('scheduled-report.validations.required.frequency'),
            'groups.required'              => trans('scheduled-report.validations.required.groups'),
            'sujbect.required'             => trans('scheduled-report.validations.required.subject'),
            'body.required'                => trans('scheduled-report.validations.required.body'),
            'sending_time.required'        => trans('scheduled-report.validations.required.hour'),
            'sending_weekly_day.required'  => trans('scheduled-report.validations.required.weekday'),
            'sending_monthly_day.required' => trans('scheduled-report.validations.required.monthday'),
            'end_date.after'               => trans('scheduled-report.validations.after.end_date')
        ];
    }

    public function handleSendingTime($attribute, $value, $fail)
    {

        if ($this->input('frequency') !== 'hourly' && $this->input('frequency') == "daily" && empty($value)) {
            $fail(trans('scheduled-report.validations.required.hour'));
        } elseif ($this->input('frequency') !== 'hourly' && $this->input('frequency') == "weekly" && empty($value)) {
            $fail(trans('scheduled-report.validations.required.weekday'));
        } elseif ($this->input('frequency') !== 'hourly' && $this->input('frequency') == "monthly" && empty($value)) {
            $fail(trans('scheduled-report.validations.required.monthday'));
        }

    }

    private function getWeekDays()
    {
        return ['monday', 'tuesday', 'wednesday', 'thursday', 'friday', 'saturday', 'sunday'];
    }

}