<?php

namespace App\Http\Controllers\Api;

use App\Model\Setting;
use App\Notifications\ContactUsEnquiry;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Notification;
use Illuminate\Support\Facades\Validator;
use Symfony\Component\HttpFoundation\Response;

class SubmitEnquiryController extends ApiController
{
    /**
     * Handle the incoming request.
     */
    public function __invoke(Request $request)
    {
        $validator = Validator::make($request->all(), [
            'name' => ['required', 'string', 'max:100'],
            'email' => ['required', 'email'],
            'phone' => ['required', 'string', 'max:20',],
            'enquiry' => ['required', 'string', 'max:300'],
        ], $this->addValidationErrorCode(), ['phone' => 'contact no']);

        if ($validator->fails()) {
            return $this->handleValidationResponse($validator->errors()->toArray());
        }

        try {
            $admins = Setting::getAdminNotifyEmails();

            if (count($admins)) {
                Notification::route('mail', $admins)->notify(new ContactUsEnquiry($request));
            }

            return $this->json([], Response::HTTP_OK);
        } catch (\Exception $e) {
            // report($e);

            return $this->jsonError(Response::HTTP_UNPROCESSABLE_ENTITY, $e->getMessage());
        }
    }
}
