<?php


namespace App\Http\Controllers\V1;

use App\Core\Service\EnwContactFormService;
use App\Http\Controllers\Controller;

use Illuminate\Http\Request;
use Illuminate\Support\Facades\Log;
use Exception;
use App\Exceptions\ApiErrorException;


class EnwContactFormController extends Controller
{

    private $enwContactFormService;

    public function __construct(
        EnwContactFormService $enwContactFormService
    )
    {
        $this->enwContactFormService = $enwContactFormService;
    }

    public function sendEmail(Request $request)
    {
        $response = ['status' => false, 'message' => '', 'data' => null, 'statusCode' => 500];
        try {

            if (is_null($request->getContent())) {
                throw new ApiErrorException(lang('Parameter Error.'));
            }

            $language = "en";
            if($request->headers->get('language')){
                $language = $request->headers->get('language');
                app('translator')->setLocale($language);
            }

            $params = $request->params;

            $requestParams = [
                'language' => $language,
                'name' => fillOnUndefined($params, 'name'),
                'surname' => fillOnUndefined($params, 'surname'),
                'email' => fillOnUndefined($params, 'email'),
                'subject' => fillOnUndefined($params, 'subject')
            ];

            $contactForm = $this->enwContactFormService->sendEmail($requestParams);

            if ($contactForm['status'] != 'success') {
                throw new ApiErrorException($contactForm['message']);
            }


            $response = ['status' => 1, 'statusCode' => 200, 'message' => null, 'data' => $contactForm['data']];

        } catch (ApiErrorException $e) {
            $response['message'] = implode(', ', $e->getMessageArr());
            $response['statusCode'] = 400;
        } catch (Exception $e) {
            $message = $e->getFile() . " " . $e->getLine() . " " . $e->getMessage();
            Log::error($message);
            $response['message'] = $e->getMessage();
            $response['statusCode'] = 500;
        }
        return apiResponse($response['status'], $response['message'], $response['data'], $response['statusCode']);
    }


}
