<?php

namespace App\Services\Bonus;

use App\Enums\BonusStatusEnum;
use App\Enums\CoinMatterEnum;
use App\Enums\NotificationType;
use App\Enums\NotifyEventType;
use App\Events\CoinLogEvent;
use App\Events\NotificationEvent;
use App\Models\Bonus;
use App\Models\User;
use App\Notifications\UserAutoNotification;

class ReferralBonus
{
    /**
     * Give referral bonus to parent user when a new user joins under him/her.
     *
     * @return void
     */
    public function giveReferralBonus(User $sponsor, User $user)
    {
        // generation loop
        $coins = config('application_info.referral.joining');
        // bonus
        Bonus::create([
            'receiver_id' => $sponsor->id,
            'sender_id' => $user->id,
            'coins' => $coins,
            'status' => BonusStatusEnum::SUCCESS,
            'remark' => 'Referral Bonus',
        ]);

        $sponsor->increment('coins', $coins);

        event(new NotificationEvent($sponsor, NotifyEventType::BONUS, 'Referral Bonus', 'You have received a Referral Bonus of '.$coins.'Coins.'));

        $sponsor->notify(new UserAutoNotification(
            NotificationType::REFERRAL_BONUS,
            ['coins' => $coins]
        ));

        event(new CoinLogEvent($sponsor, CoinMatterEnum::REFERRAL_BONUS, $coins, '+'));
    }
}
