<?php

namespace App;

use Illuminate\Database\Eloquent\Model;
use Mtc\Modules\Members\Models\Member;
use MtcPharmacy\Multisite\Classes\MultisiteSite;

class MemberInfo extends Model
{
    protected $table = 'members_info';

    protected function site()
    {
        return $this->belongsTo(MultisiteSite::class, 'multisite__site_id');
    }

    public static function registerSiteOfOrigin(Member $member, int $site_id)
    {
        $member_info = MemberInfo::query()
            ->where('member_id', $member->id)
            ->where('multisite__site_id', $site_id)
            ->first();

        if (! $member_info) {
            $member_info = new MemberInfo;
            $member_info->member_id = $member->id;
            $member_info->multisite__site_id = $site_id;
            $member_info->save();
        }

        return $member_info->id;
    }

    public static function getSiteOfOrigin(Member $member): string
    {
        $site_name = '-';

        $member_info = self::query()
            ->where('member_id', $member->id)
            ->first();

        if ($member_info) {
            $site_name = $member_info->site->name ?? config('app.name');
        }

        return $site_name;
    }
}
