diff --git a/app/Http/Controllers/api/PvPQuizController.php b/app/Http/Controllers/api/PvPQuizController.php index 4f0e7e3..97741e0 100644 --- a/app/Http/Controllers/api/PvPQuizController.php +++ b/app/Http/Controllers/api/PvPQuizController.php @@ -81,6 +81,16 @@ class PvPQuizController extends Controller 'time_taken_seconds' => 'required|numeric|min:0.1|max:15', // Max 15 seconds to answer ]); + // Prevent answering the same question twice! + $alreadyAnswered = $match->answers() + ->where('user_id', auth()->id()) + ->where('question_id', $request->question_id) + ->exists(); + + if ($alreadyAnswered) { + return $this->failed(null, 'خطا', 'شما قبلا به این سوال پاسخ داده‌اید.'); + } + $player = $match->players()->where('user_id', auth()->id())->firstOrFail(); $question = Question::with('options')->find($request->question_id); @@ -144,30 +154,43 @@ class PvPQuizController extends Controller */ private function finalizeMatch(PvpMatch $match) { - // Get both players, ordered by the highest score first $players = $match->players()->orderByDesc('score')->get(); - - $player1 = $players->first(); // The one with the higher score - $player2 = $players->last(); // The one with the lower score + $player1 = $players->first(); + $player2 = $players->last(); $winnerId = null; - - // Check if it's a draw, or if someone actually won if ($player1->score > $player2->score) { $winnerId = $player1->user_id; } - // If scores are exactly equal, winnerId stays null (Draw/Tie) - // Close the room $match->update([ 'status' => 'completed', 'ended_at' => now(), 'winner_id' => $winnerId ]); - // TODO (Next Step): Fire a WebSocket Event here to push the "Game Over" screen! - } + // --- NEW: UPDATE GAMIFICATION STATS --- + $user1 = \App\Models\User::find($player1->user_id); + $user2 = \App\Models\User::find($player2->user_id); + $user1->increment('duels_played'); + $user2->increment('duels_played'); + + // Give XP and Wins + if ($winnerId) { + $winner = \App\Models\User::find($winnerId); + $winner->increment('duels_won'); + $winner->increment('xp', 50); // Winner gets 50 XP + + // NOTE: Here we will later trigger the "duel_win" Daily Quest progress! + } + + // Loser/Draw gets participation XP + $loserId = $winnerId === $user1->id ? $user2->id : $user1->id; + \App\Models\User::find($loserId)->increment('xp', 10); + + // TODO: Fire a WebSocket Event to push "Game Over" screen! + } /** * STEP 4: Get Final Match Results */