<?php

namespace App\Modules\Clients\Events;

use App\Modules\Clients\Client;
use App\Modules\Clients\SiteUser;
use GuzzleHttp\Exception\ClientException;
use Illuminate\Support\Facades\Log;
use App\Jobs\sendClientToDynamicsAccount;
use Illuminate\Foundation\Bus\DispatchesJobs;



class DynamicsClientSync
{
	use DispatchesJobs;
    /**
     * Subscribe to events.
     *
     * @param  mixed $events
     *
     * @return null
     */
    public function subscribe($events)
    {
        $events->listen('ClientCreated', 'App\Modules\Clients\Events\DynamicsClientSync@sendToDynamicsCrm');
        $events->listen('ClientUpdated', 'App\Modules\Clients\Events\DynamicsClientSync@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\Client $client
     *
     * @return array
     */
    public function sendToDynamicsCrm($client)
    {
        Log::info('Client sendToDynamicsCrm hit');
        Log::info($client);
        if (! config('services.dynamics.username')) {
            return;
        }
		$this->dispatch(new sendClientToDynamicsAccount($client));
        return $client;
    }

    /**
     * Returns an array containing all the site users
     * for the given client.
     *
     * @param  \App\Modules\Clients\Client $client
     * @return array
     */
    protected function getSiteUsers($client)
    {
        return $client->sites->map(function($site) {
            return $site->users->flatMap(function($user) use ($site) {
                return [
                    'id'                  => $user->id,
                    'firstname'           => $user->first_name,
                    'lastname'            => $user->last_name,
                    'emailaddress1'       => $user->email,
                    'telephone1'          => $user->phone,
                    'mobilephone'         => $user->mobile,
                    'address1_line1'      => $site->address,
                    'address1_city'       => $site->address2,
                    'address1_postalcode' => $site->postcode,
                ];
            });
        })->reject(function($user) {
            return $user->isEmpty();
        })->toArray();
    }

    /**
     * Returns the method to use for the API,
     * either PATCH or POST.
     *
     * @param  \App\Modules\Clients\Client $client
     * @return string
     */
    protected function getMethod($client)
    {
        return $client->dynamics_id ? 'patch' : 'post';
    }

    /**
     * Returns the URL to use for the API.
     *
     * @param  \App\Modules\Clients\Client $client
     * @return string
     */
    protected function getUrl($client)
    {
        $url = 'api/data/v8.1/accounts';

        return $client->dynamics_id ? $url.'('.$client->dynamics_id.')' : $url;
    }

    protected function sendSiteusersAsContactsToDynamics($siteUsersArray, $client, $crmDynamics) {


        foreach ($siteUsersArray as $user) {

            Log::info("\n sendSiteusersAsContactsToDynamics | Syncing site users");
            Log::info("\n logging user");
            Log::info($user);
            $data = [
                'firstname'           => $user['firstname'],
                'lastname'            => $user['lastname'],
                'emailaddress1'       => $user['emailaddress1'],
                'telephone1'          => $user['telephone1'],
                'mobilephone'         => $user['mobilephone'],
                'new_seraph_id'       => $user['id'],
                'new_seraph_model'    => 'siteuser',
                'parentcustomerid'    => $client->dynamics_id,
                'telephone2'          => $client['telephone1'],
                'address1_line1'      => $user['address1_line1'],
                'address1_city'       => $user['address1_city'],
                'address1_postalcode' => $user['address1_postalcode'],
            ];

            $typeOverrides = array('new_seraph_id' => 'int', 'parentcustomerid' => 'lookup');
            $siteUserDynamicsId = $crmDynamics->contacts->createContact($data, $typeOverrides);

            $updatedSiteUser = SiteUser::find($user['id']);
            Log::info("\n logging updatedSiteUser");
            Log::info($updatedSiteUser);
            $updatedSiteUser->dynamics_id = $siteUserDynamicsId;
            $updatedSiteUser->save();
        }

    }
}
