<?php

namespace App\Modules\Clients\Events;

use App\Modules\Clients\Client;
use App\Modules\Clients\Site;
use App\Modules\Clients\SiteUser;
use GuzzleHttp\Exception\ClientException;
use Illuminate\Support\Facades\Log;

class DynamicsSiteSync
{
    /**
    * Subscribe to events.
    *
    * @param  mixed $events
    *
    * @return null
    */
    public function subscribe($events)
    {
        $events->listen('SiteUpdated', 'App\Modules\Clients\Events\DynamicsSiteSync@sendToDynamicsCrm');
    }

    /**
    * Creates a new client or updates an existing one
    * in DynamicsCRM with the existing details from the
    * currently updated client in Seraph.
    *
    * @param  \App\Modules\Clients\Site $site
    *
    * @return array
    */
    public function sendToDynamicsCrm($site)
    {
        Log::info('DynamicsSiteSync sendToDynamicsCrm hit');
        Log::info($site);
        if (! config('services.dynamics.username')) {
            return;
        }
        $crmDynamics = app('MicrosoftDynamics');

        $client = Client::find($site->client_id);
        Log::info('DynamicsSiteSync loggiing client');
        Log::info($client);

        $users = SiteUser::where('site_id', $site->id)->get();
        Log::info('DynamicsSiteSync - found ' . $users->count() .' site users to sync at '. $client->name);

        $typeOverrides = array('new_seraph_id' => 'int', 'parentcustomerid' => 'lookup');

        $accountData = [
            'accountid'           => $client->dynamics_id,
            'address1_line1'      => $site->address,
            'address1_city'       => $site->address2,
            'address1_postalcode' => $site->postcode,
            'address1_telephone1' => $site->primary_phone,
            'telephone1'          => $site->primary_phone,
        ];
        Log::info('logging site data that will be sent to dynamics');
        Log::info($accountData);

        $success = $crmDynamics->accounts->updateAccount($accountData, $typeOverrides);

        foreach ($users as $user) {
            Log::info('logging each site user');
            Log::info($user);


            $contactData = [
                'parentcustomerid'      => $client->dynamics_id,
                'address1_line1'        => $site->address,
                'address1_city'         => $site->address2,
                'address1_postalcode'   => $site->postcode,
                'contactid'             => $user->dynamics_id,
            ];


            $success = $crmDynamics->contacts->updateContact($contactData, $typeOverrides);

            Log::info('logging success');
            Log::info($success);
        }


        return $site;
    }
}
