<?php
namespace Lotterybit\Console\Commands;
use Illuminate\Console\Command;
use Lotterybit\Lottery;
use Lotterybit\User;
class RaffleWinners extends Command
{
protected $signature = 'lotteries:raffle';
protected $description = 'Raffles lottery winners';
protected $lottery, $user;
public function __construct(Lottery $lottery, User $user)
{
parent::__construct();
$this->lottery = $lottery;
$this->user = $user;
}
public function handle()
{
$toRaffle = $this->lottery->raffle()->get(); // Get ended lotteries
foreach ($toRaffle as $lottery)
{
$lottery->update([ 'is_ended' => true ]);
// Get lottery participants
$players = $lottery->participants; // Get lottery participants
// If no players
if( ! count($players) )
{
continue;
}
// process lottery only if 2 or more players
if( count($players) < 2 )
{
// Refund player ticket price, becouse only player
$player = $lottery->participants()->first();
$userWallet = $player->user->wallet;
$userWallet->update([
'balance' => $userWallet->balance + $lottery->ticket_price
]);
$userWallet->logs()->create([
'action' => 'add',
'value' => $lottery->ticket_price,
'comment' => 'Lottery #' . $lottery->id . ' refund (you were the only player who bought ticket)'
]);
}
else
{
// The part where we choose random winners
$playerCount = count($players);
$winnersCount = (int) floor($playerCount / 2);
$participantIDs = $lottery->participants()->lists('id', 'user_id')->toArray();
$winnersList = (array) array_rand($participantIDs, $winnersCount);
foreach($winnersList as $uid)
{
$lottery->participants()->where('user_id', $uid)->update([ 'is_winner' => true ]);
if( $user = $this->user->find($uid) )
{
$userWallet = $user->wallet;
$userWallet->update([ 'balance' => $userWallet->balance + ($lottery->ticket_price * 2) ]);
$userWallet->logs()->create([
'action' => 'add',
'value' => $lottery->ticket_price * 2,
'comment' => 'Won lottery #' . $lottery->id . ' | ticket price: ' . $lottery->ticket_price / 100000000 . ' | given ' . ($lottery->ticket_price * 2) / 100000000
]);
}
}
}
}
}
}