<?php

namespace App\Http\Requests;

use Illuminate\Foundation\Http\FormRequest;
use Illuminate\Support\Facades\Auth;
use Illuminate\Validation\Rule;
use Mtc\MercuryDataModels\Country;
use Mtc\MercuryDataModels\Invoice;

class UpdateBillingDetailsRequest extends FormRequest
{
    /**
     * @var bool
     */
    private bool $requires_postcode = true;

    /**
     * Determine if the user is authorized to make this request.
     *
     * @return bool
     */
    public function authorize()
    {
        return Auth::check();
    }

    /**
     * Get the validation rules that apply to the request.
     *
     * @return array
     */
    public function rules()
    {
        return [
            'vat_rate' => [
                'required',
                Rule::in([Invoice::REGULAR_VAT, Invoice::NO_VAT])
            ],
            'contact_no' => 'required',
            'billing_email' => [
                'required',
                'email',
            ],
            'first_name' => 'required',
            'last_name' => 'required',
            'address1' => 'required',
            'city' => 'required',
            'postcode' => $this->requires_postcode ? 'sometimes' : 'required',
            'country' => 'required',
        ];
    }

    /**
     * Prepare request for validation`
     *
     * @return void
     */
    protected function prepareForValidation()
    {
        $this->requires_postcode = Country::query()
            ->where('code', $this->input('country'))
            ->where('has_postcodes', 1)
            ->exists();
    }
}
