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' => [], ]; } }