<?php

namespace App\Crm;

use App\Facades\Settings;
use App\Services\SalesforceCrmApi;
use Illuminate\Support\Facades\App;
use Mtc\Crm\Contracts\EnquiryAction;
use Mtc\Crm\Contracts\EnquiryActionModel;
use Mtc\Crm\Contracts\EnquiryModel;

class SendToSalesforce implements EnquiryAction
{
    use CheckForExpiredAction;

    private SalesforceCrmApi $api;

    public function enabled(): bool
    {
        return Settings::get('salesforce-crm-enabled') === true;
    }

    public function formAdditionalDataFields(): array
    {
        return [];
    }

    public function formQuestionDataFields(): array
    {
        return [
            'salesforce-field' => [
                'type' => 'select',
                'label' => 'Field mapped against Salesforce',
                'choices' => [
                    'firstName' => 'First Name',
                    'lastName' => 'Last Name',
                    'email' => 'Email',
                    'mobile' => 'Phone Number',
                    'postcode' => 'Postcode',
                    'selected_dealership' => 'Dealership',
                    'formType' => 'Form Type',
                    'message' => 'Message',
                    'testDriveDate' => 'Test Drive Date',
                    'testDriveTime' => 'Test Drive Time',
                ],
            ],
        ];
    }

    public function handle(EnquiryActionModel $action, EnquiryModel $enquiry): ?bool
    {
        if ($this->expired($action)) {
            return false;
        }
        $this->api = App::make(SalesforceCrmApi::class);
        return $this->api->sendLead($enquiry, $action);
    }

    public function successDetails(): string
    {
        return $this->api->getResponseMessage();
    }

    public function failureReason(): string
    {
        return $this->api->getResponseMessage() ?? 'Unknown error';
    }

    /**
     * Data fields to add to dealership
     *
     * @return array
     */
    public function dealershipAdditionalDataFields(): array
    {
        return [
            'salesforce-dealer-id' => [
                'type' => 'text',
                'label' => 'Dealer ID in Salesforce'
            ],
        ];
    }
}
