<?php

namespace App\Http\Requests\Admin;

use GuzzleHttp\Psr7\Request;
use Illuminate\Foundation\Http\FormRequest;
use Illuminate\Validation\Rules;

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

    /**
     * Get the validation rules that apply to the request.
     *
     * @return array<string, mixed>
     */
    public function rules()
    {
        return [
            'title' => 'nullable|string|max:50',
            'type'  => 'nullable|string|max:20',
            'status' => 'nullable|integer|in:0,1',
            'start_date' => 'nullable|date',
            'end_date' => 'nullable|date|after_or_equal:start_date',
            'banner' => 'nullable|file|mimes:jpg,jpeg,png,mp4|max:20480',
            'video_link' => 'nullable|url|max:191',
            'redirect_url'      => 'nullable|max:191',
            'total_views' => 'nullable|integer|min:0',
            'ad_duration' => 'nullable|integer|min:1',
            'skip_after' => 'nullable|integer|min:0',
            'frequency_capping' => 'nullable|integer|min:1',
            'content' => 'nullable|string|max:191',
            'position' => 'nullable|string|max:50',
            'size' => 'nullable|string|max:20',
        ];
    }

    public function withValidator($validator)
    {
        $validator->after(function ($validator) {
            $type = $this->input('type');

            if ($type === 'local') {
                if (!$this->filled('start_date')) {
                    $validator->errors()->add('start_date', 'The start date is nullable when type is local.');
                }
                if (!$this->filled('end_date')) {
                    $validator->errors()->add('end_date', 'The end date is nullable when type is local.');
                }
                if (!$this->file('banner') && !$this->has('id')) {
                    $validator->errors()->add('banner', 'The banner is nullable when type is local.');
                }
                if (!$this->filled('redirect_url')) {
                    $validator->errors()->add('redirect_url', 'The redirect url is nullable when type is local.');
                }
            }

            if ($type === 'google') {
                if (!$this->filled('content')) {
                    $validator->errors()->add('content', 'The content is nullable when type is google.');
                }
            }
        });
    }
}