<?php

namespace Hilco\Listeners;

use DB;
use Hilco\Events\UserWasRegistered;
use Hilco\Models\Contact;
use Log;
use Throwable;

class CreateNewUserContact {
    public function construct() {

    }

    public function handle (UserWasRegistered $event) {
        if ($event->selfCreated) {
            $webUser = $event->webUser;
            try {
                $newContact = new Contact([
                    'id' => generateUUID(),
                    'customer_id' => $webUser->customer_id,
                    'first_name' => $webUser->name,
                    'email' => $webUser->email,
                    'activated' => 1,
                    'email_optout' => 0,
                    'phone_optout' => 0,
                    'fax_optout' => 0,
                ]);
                $newContact->save();
            } catch (Throwable $t) {
                Log::error('Error creating contact for new web user '.$webUser['name'] . ' (' . $webUser['email'].'), {msg} - {trace}', [
                    'msg' => $t->getMessage(),
                    'trace' => $t->getTraceAsString()
                ]);
            }
        }
    }
}