<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2018/8/16
 * Time: 10:00
 */
namespace Modules\Project\Services;

use Modules\Project\Entities\UserInvitation;

class UserObserve
{
    public function created($user)
    {
        $inviter = $this->getInviter();
        if (!$inviter) {
            return;
        }

        if (optional($inviter->distributor)->status != 1) {
            return false;
        }

        $parent = UserInvitation::firstOrCreate(['user_id' => $inviter->id]);
        $parent->children()->create(['user_id' => $user->id]);
    }

    public function getInviter()
    {
        $user = null;
        $userClass = config('auth.providers.users.model', 'App\\User');
        if ($user_id = request('parent_id', false)) {
            $user_id = intval(str_replace('from_', '', $user_id));
            $user = $userClass::find($user_id);
        }

        return $user;
    }
}
