<?php

namespace App\Modules\Clients;

use Illuminate\Support\Facades\App;

class SugarClientSync
{
    /**
     * Subscribe to events.
     *
     * @param  mixed $events
     *
     * @return null
     */
    public function subscribe($events)
    {
        $events->listen('ClientCreated', 'App\Modules\Clients\SugarClientSync@sendToSugarCrm');
        $events->listen('ClientUpdated', 'App\Modules\Clients\SugarClientSync@sendToSugarCrm');
    }

    /**
     * Creates a new client or updates an existing one
     * in SugarCRM with the existing details from the
     * currently updated client in Seraph.
     *
     * @param  \App\Modules\Clients\Client $client
     *
     * @return array
     */
    public function sendToSugarCrm($client)
    {
        $sugar = App::make('SugarRest');

        if ( ! $sugar ) {
            return; // sugar CRM not configured
        }

        // Prevent infinite loops. Stop the request
        // if this is an update triggered by SugarCRM
        if (request()->has('sugarcrm_id')) {
            return;
        }

        $data = [
            'name'                       => $client->name,
            'seraph_id_c'                => $client->id,
        ];

        if ($site = $client->sites()->first()) {
            $data = array_merge($data, [
                'billing_address_street'     => $site->address,
                'billing_address_city'       => $site->address2,
                'billing_address_postalcode' => $site->postcode,
                'phone_office'               => $site->primary_phone,
            ]);
        }

        if ($site && $siteUser = $site->users()->first()) {
            $data = array_merge($data, [
                'email1' => $siteUser->email,
            ]);
        }

        if ($client->sugarcrm_id) {
            $data['id'] = $client->sugarcrm_id;
        }

        // Ready to submit the data
        $account = $sugar->set('Accounts', $data);

        // If this is a new customer, then store
        // the sugarcrm_id locally
        if (! $client->sugarcrm_id) {
            $client->sugarcrm_id = $account['id'];
            $client->save();
        }

        return $account;
    }
}
