<?php

namespace App\Modules\Clients\Events;

use App\Modules\Clients\Customer;
use App\Jobs\sendCustomerToDynamicsContact;
use GuzzleHttp\Exception\ClientException;
use Illuminate\Foundation\Bus\DispatchesJobs;
use Illuminate\Support\Facades\Log;

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

    /**
     * Creates a new customer or updates an existing one
     * in DynamicsCRM with the existing details from the
     * currently updated customer in Seraph.
     *
     * @param  \App\Modules\Clients\Customer $customer
     *
     * @return array
     */
    public function sendToDynamicsCrm(Customer $customer)
    {
        Log::info('Customer sendToDynamicsCrm hit');
        
        try {
            if (! config('services.dynamics.username')) {
                Log::info('Dynamics CRM not configured - skipping sync');
                return;
            }
            Log::info('Dispatching customer to sendCustomerToDynamicsContact');
            $this->dispatch(new sendCustomerToDynamicsContact($customer));
        } catch (\Exception $e) {
            Log::error('Dynamics CRM sync failed but customer creation continues', [
                'customer_id' => $customer->id,
                'error' => $e->getMessage()
            ]);
        }
        
        return $customer;
    }
}
