<?php

namespace Fivable\Buildable\Controllers;

use Fivable\Scaffolding\Controllers\ApiController;
use GuzzleHttp\Client;
use GuzzleHttp\Exception\BadResponseException;
use GuzzleHttp\Promise\AggregateException;
use Illuminate\Http\Request;
use Illuminate\Http\JsonResponse;
use Mail;

class BuildableUtilityController extends ApiController
{

    /**
     * Send an email for the General Inquiry form
     * @param Request $request
     * @return JsonResponse
     */
    public function contactFormGeneral(Request $request) : JsonResponse
    {
        Mail::send('buildable::email.contact-general', ['data' => $request->all()], function ($message) {
            $message->from(env('BUILDABLE_FROM_EMAIL', 'engineering@fivable.com'));
            $message->to(env('BUILDABLE_TO_EMAIL', 'engineering@fivable.com'));
            $message->subject("New General Contact Form Submitted");
        });

        return response()->json([
            'success' => 'email sent successfully',
        ]);
    }

    /**
     * Sends Salesforce form via Contact - Sales form
     * @param Request $request
     * @return JsonResponse
     * @throws \GuzzleHttp\Exception\GuzzleException
     */
    public function contactFormSales(Request $request) : JsonResponse
    {
        $data = $request->all();

        try {
            $client = new Client(['verify' => false]);
            $response = $client->request('POST', config('buildable.barnacleSalesforce'), ['form_params' => $data]);
        } catch (\GuzzleHttp\Exception\GuzzleException $e) {
            return response()->json([
                'failure' => 'an error occurred sending form params to Salesforce'
            ]);
        }

        return response()->json([
            'success' => 'salesforce form sent'
        ]);
    }
}
