| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105 |
- <?php
- namespace App\Services\WorldCup;
- use App\Services\WorldCup\Repositories\SqlWorldCupSettlementRepository;
- use App\Services\WorldCup\Repositories\WorldCupSettlementRepositoryInterface;
- class WorldCupSettlementService
- {
- private $repository;
- public function __construct(WorldCupSettlementRepositoryInterface $repository = null)
- {
- $this->repository = $repository ?: new SqlWorldCupSettlementRepository();
- }
- public function settleMatch(int $matchId, string $result, string $actor): array
- {
- if (!in_array($result, ['home', 'draw', 'away'], true)) {
- return $this->fail('Invalid match result');
- }
- $match = $this->repository->findMatch($matchId);
- if (!$match) {
- return $this->fail('Match not found');
- }
- if (($match['status'] ?? '') === 'finished') {
- return $this->fail('Match already settled');
- }
- if ($result === 'draw' && ($match['stage'] ?? '') !== 'group') {
- return $this->fail('Draw is only available for group stage');
- }
- $bets = $this->repository->pendingBetsForMatch($matchId);
- $summary = $this->settleBets($bets, $result);
- $this->repository->markMatchFinished($matchId, $result);
- $this->repository->writeAudit($actor, 'settle_match', [
- 'match_id' => $matchId,
- 'result' => $result,
- 'summary' => $summary,
- ]);
- return $this->success($summary);
- }
- public function settleWinner(string $selection, string $actor): array
- {
- $selection = trim($selection);
- if ($selection === '') {
- return $this->fail('Winner selection is required');
- }
- $summary = $this->settleBets($this->repository->pendingWinnerBets(), $selection);
- $this->repository->writeAudit($actor, 'settle_winner', [
- 'selection' => $selection,
- 'summary' => $summary,
- ]);
- return $this->success($summary);
- }
- private function settleBets(array $bets, string $winningSelection): array
- {
- $summary = [
- 'won_count' => 0,
- 'lost_count' => 0,
- 'paid_amount' => 0,
- ];
- foreach ($bets as $bet) {
- $status = (string)$bet['selection'] === $winningSelection ? 'won' : 'lost';
- if ($status === 'won') {
- $paidAmount = $this->repository->payBet($bet);
- $summary['won_count']++;
- $summary['paid_amount'] += $paidAmount;
- } else {
- $summary['lost_count']++;
- }
- $this->repository->markBetSettled((int)$bet['bet_id'], $status);
- }
- return $summary;
- }
- private function success(array $data): array
- {
- return [
- 'success' => true,
- 'message' => '',
- 'data' => $data,
- ];
- }
- private function fail(string $message): array
- {
- return [
- 'success' => false,
- 'message' => $message,
- 'data' => [],
- ];
- }
- }
|