<commit_before><?php

namespace App\Services;

use App\Events\NewContactWasRegistered;
use App\Models\Business;
use App\Models\Contact;
use App\Models\User;

/*******************************************************************************
 * Contact Service Layer
 ******************************************************************************/
class ContactService
{
    /**
     * Register a new Contact.
     *
     * @param Business $business
     * @param array    $data
     *
     * @return App\Models\Contact
     */
    public function register(Business $business, $data)
    {
        if (false === $contact = self::getExisting($business, $data['nin'])) {
            $contact = Contact::create($data);

            $business->contacts()->attach($contact);
            $business->save();

            logger()->info("Contact created contactId:{$contact->id}");

            if (array_key_exists('notes', $data)) {
                self::updateNotes($business, $contact, $data['notes']);
            }
        }

        event(new NewContactWasRegistered($contact));

        return $contact;
    }

    /**
     * Copy Contact from provided exiting.
     *
     * @param User     $user
     * @param Business $business
     * @param Contact  $existingContact
     *
     * @return App\Models\Contact
     */
    public function copyFrom(User $user, Business $business, Contact $existingContact)
    {
        $contact = Contact::create($existingContact->toArray());
        $contact->user()->associate($user->id);
        $contact->businesses()->detach();
        $contact->save();

        $business->contacts()->attach($contact);
        $business->save();

        return $contact;
    }

    /**
     * Associate Contact with User.
     *
     * @param Contact $contact
     * @param User    $user
     *
     * @return App\Models\Contact
     */
    public function linkToUser(Contact $contact, User $user)
    {
        $contact->user()->associate($user->id);
        $contact->save();

        return $contact->fresh();
    }

    /**
     * Find an existing contact with the same NIN.
     *
     * @param Business $business
     * @param string   $nin
     *
     * @return App\Models\Contact
     */
    public function getExisting(Business $business, $nin)
    {
        if (trim($nin) == '') {
            return false;
        }

        $existingContacts = $business->contacts()->whereNotNull('nin')->where(['nin' => $nin])->get();

        foreach ($existingContacts as $existingContact) {
            logger()->info("[ADVICE] Found existing contactId:{$existingContact->id}");

            if ($existingContact->isSubscribedTo($business->id)) {
                logger()->info('[ADVICE] Existing contact is already linked to business');

                return $existingContact;
            }
        }

        return false;
    }

    /**
     * Find an existing Contact By UserId.
     *
     * @param int $userId
     *
     * @return Collection|Builder
     */
    public function findExistingContactsByUserId($userId)
    {
        return Contact::where('user_id', '=', $userId)->get();
    }

    /**
     * Find an existing Contact By Email.
     *
     * @param string $email
     *
     * @return Collection|Builder
     */
    public function findExistingContactsByEmail($email)
    {
        return Contact::whereNull('user_id')
            ->whereNotNull('email')
            ->where('email', '<>', '')
            ->where(['email' => $email])
            ->get();
    }

    /**
     * Find a contact within a Business addressbok.
     *
     * @param Business $business
     * @param Contact  $contact
     *
     * @return App\Models\Contact
     */
    public function find(Business $business, Contact $contact)
    {
        return $business->contacts()->find($contact->id);
    }

    /**
     * Update Contact attributes.
     *
     * @param Business $business
     * @param Contact  $contact
     * @param array    $data
     * @param string   $notes
     *
     * @return void
     */
    public function update(Business $business, Contact $contact, $data = [], $notes = null)
    {
        $contact->firstname = $data['firstname'];
        $contact->lastname = $data['lastname'];
        $contact->email = $data['email'];
        $contact->nin = $data['nin'];
        $contact->gender = $data['gender'];
        $contact->birthdate = $data['birthdate'];
        $contact->mobile = $data['mobile'];
        $contact->mobile_country = $data['mobile_country'];
        $contact->postal_address = $data['postal_address'];

        $contact->save();

        self::updateNotes($business, $contact, $notes);

        return $contact;
    }

    /**
     * Detach a Contact froma Business addressbok.
     *
     * @param Business $business
     * @param Contact  $contact
     *
     * @return int
     */
    public function detach(Business $business, Contact $contact)
    {
        return $contact->businesses()->detach($business->id);<commit_msg>Use optional field value retrieval<commit_after><?php

namespace App\Services;

use App\Events\NewContactWasRegistered;
use App\Models\Business;
use App\Models\Contact;
use App\Models\User;

/*******************************************************************************
 * Contact Service Layer
 ******************************************************************************/
class ContactService
{
    /**
     * Register a new Contact.
     *
     * @param Business $business
     * @param array    $data
     *
     * @return App\Models\Contact
     */
    public function register(Business $business, $data)
    {
        if (false === $contact = self::getExisting($business, $data['nin'])) {
            $contact = Contact::create($data);

            $business->contacts()->attach($contact);
            $business->save();

            logger()->info("Contact created contactId:{$contact->id}");

            if (array_key_exists('notes', $data)) {
                self::updateNotes($business, $contact, $data['notes']);
            }
        }

        event(new NewContactWasRegistered($contact));

        return $contact;
    }

    /**
     * Copy Contact from provided exiting.
     *
     * @param User     $user
     * @param Business $business
     * @param Contact  $existingContact
     *
     * @return App\Models\Contact
     */
    public function copyFrom(User $user, Business $business, Contact $existingContact)
    {
        $contact = Contact::create($existingContact->toArray());
        $contact->user()->associate($user->id);
        $contact->businesses()->detach();
        $contact->save();

        $business->contacts()->attach($contact);
        $business->save();

        return $contact;
    }

    /**
     * Associate Contact with User.
     *
     * @param Contact $contact
     * @param User    $user
     *
     * @return App\Models\Contact
     */
    public function linkToUser(Contact $contact, User $user)
    {
        $contact->user()->associate($user->id);
        $contact->save();

        return $contact->fresh();
    }

    /**
     * Find an existing contact with the same NIN.
     *
     * @param Business $business
     * @param string   $nin
     *
     * @return App\Models\Contact
     */
    public function getExisting(Business $business, $nin)
    {
        if (trim($nin) == '') {
            return false;
        }

        $existingContacts = $business->contacts()->whereNotNull('nin')->where(['nin' => $nin])->get();

        foreach ($existingContacts as $existingContact) {
            logger()->info("[ADVICE] Found existing contactId:{$existingContact->id}");

            if ($existingContact->isSubscribedTo($business->id)) {
                logger()->info('[ADVICE] Existing contact is already linked to business');

                return $existingContact;
            }
        }

        return false;
    }

    /**
     * Find an existing Contact By UserId.
     *
     * @param int $userId
     *
     * @return Collection|Builder
     */
    public function findExistingContactsByUserId($userId)
    {
        return Contact::where('user_id', '=', $userId)->get();
    }

    /**
     * Find an existing Contact By Email.
     *
     * @param string $email
     *
     * @return Collection|Builder
     */
    public function findExistingContactsByEmail($email)
    {
        return Contact::whereNull('user_id')
            ->whereNotNull('email')
            ->where('email', '<>', '')
            ->where(['email' => $email])
            ->get();
    }

    /**
     * Find a contact within a Business addressbok.
     *
     * @param Business $business
     * @param Contact  $contact
     *
     * @return App\Models\Contact
     */
    public function find(Business $business, Contact $contact)
    {
        return $business->contacts()->find($contact->id);
    }

    /**
     * Update Contact attributes.
     *
     * @param Business $business
     * @param Contact  $contact
     * @param array    $data
     * @param string   $notes
     *
     * @return void
     */
    public function update(Business $business, Contact $contact, $data = [], $notes = null)
    {
        $contact->firstname = array_get($data, 'firstname');
        $contact->lastname = array_get($data, 'lastname');
        $contact->email = array_get($data, 'email');
        $contact->nin = array_get($data, 'nin');
        $contact->gender = array_get($data, 'gender');
        $contact->birthdate = array_get($data, 'birthdate');
        $contact->mobile = array_get($data, 'mobile');
        $contact->mobile_country = array_get($data, 'mobile_country');
        $contact->postal_address = array_get($data, 'postal_address');

        $contact->save();

        self::updateNotes($business, $contact, $notes);

        return $contact;
    }

    /**
     * Detach a Contact froma Business addressbok.
     *
     * @param Business $business
     * @param Contact  $contact
     *
     * @return int
     */
    public function detach(Business $business, Contact $contact)
    {
        return $contact->businesses()->detach($business->id);
{'fraction_non_alphanumeric': 0.1742874109263658, 'fraction_numerical': 0.0, 'mean_word_length': 2.282975958414555, 'pattern_counts': {'":': 0, '<': 7, '<?xml version=': 0, '>': 109, 'https://': 0, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '7565139', 'n_tokens_mistral': 2804, 'n_tokens_neox': 2722, 'n_words': 598}