<?php

namespace App\Modules\Clients;

use Illuminate\Support\Facades\App;

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

    /**
     * Creates a new customer or updates an existing one
     * in SugarCRM with the existing details from the
     * currently updated customer in Seraph.
     *
     * @param  \App\Modules\Clients\Customer $customer
     *
     * @return array
     */
    public function sendToSugarCrm($customer)
    {
        $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 = [
            'first_name'                 => $customer->first_name,
            'last_name'                  => $customer->last_name,
            'email1'                     => $customer->email,
            'phone_work'                 => $customer->phone,
            'phone_mobile'               => $customer->mobile,
            'phone_other'                => $customer->phone2,
            'primary_address_street'     => $customer->address,
            'primary_address_city'       => $customer->town,
            'primary_address_postalcode' => $customer->postcode,
            'seraph_id_c'                => $customer->id,
        ];

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

        $contact = $sugar->set('Contacts', $data);

        if (! $customer->sugarcrm_id) {
            $customer->sugarcrm_id = $contact['id'];
            $customer->save();
        }

        return $contact;
    }
}
