<?php

namespace App\Http\Controllers\Api;

use App\Http\Controllers\Controller;
use App\Models\Game;
use App\Models\PlatformSetting;
use App\Models\TarneebGame;
use App\Models\TrixGame;
use Illuminate\Http\Request;

class AdminController extends Controller
{
    /**
     * 🎮 سجل الألعاب المسجَّلة بالمنصة — إضافة لعبة جديدة مستقبلاً = سطر واحد هون بس.
     * كل لعبة لازم يكون عندها: uuid, bet_amount (أو bet_amount_per_player), status,
     * commission_amount, و علاقة لجدولها. الحقول تُقرأ ديناميكياً تحت.
     */
    protected function gamesRegistry(): array
    {
        return [
            [
                'type' => 'rps',
                'label' => 'حجر ورقة مقص',
                'model' => Game::class,
                'bet_column' => 'bet_amount',
                'players_per_game' => 2,
            ],
            [
                'type' => 'tarneeb',
                'label' => 'طرنيب سوري 41',
                'model' => TarneebGame::class,
                'bet_column' => 'bet_amount_per_player',
                'players_per_game' => 4,
            ],
            [
                'type' => 'trix',
                'label' => 'تريكس',
                'model' => TrixGame::class,
                'bet_column' => 'bet_amount_per_player',
                'players_per_game' => 4,
            ],
            // 🆕 لعبة جديدة؟ ضيف سطر هون بنفس الشكل، وبتظهر تلقائياً بلوحة التحكم
        ];
    }

    /**
     * GET /api/admin/stats
     */
    public function stats(Request $request)
    {
        $perGame = [];
        $totalBetsOverall = 0;
        $totalCommissionOverall = 0;
        $totalGamesOverall = 0;
        $activeGamesOverall = 0;

        foreach ($this->gamesRegistry() as $entry) {
            /** @var \Illuminate\Database\Eloquent\Model $model */
            $model = $entry['model'];
            $betColumn = $entry['bet_column'];
            $playersPerGame = $entry['players_per_game'];

            $completedQuery = $model::where('status', 'completed');
            $totalCommission = (float) $completedQuery->sum('commission_amount');

            // مجموع الرهانات = مجموع الرهان الواحد × عدد اللاعبين، لكل الألعاب (كل الحالات، مو بس المكتملة)
            $totalBets = (float) $model::sum($betColumn) * $playersPerGame;

            $gamesCount = $model::count();
            $completedCount = (clone $completedQuery)->count();
            $activeCount = $model::whereIn('status', ['waiting', 'in_progress'])->count();

            $perGame[] = [
                'type' => $entry['type'],
                'label' => $entry['label'],
                'total_games' => $gamesCount,
                'completed_games' => $completedCount,
                'active_games' => $activeCount,
                'total_bets' => $totalBets,
                'total_commission' => $totalCommission,
            ];

            $totalBetsOverall += $totalBets;
            $totalCommissionOverall += $totalCommission;
            $totalGamesOverall += $gamesCount;
            $activeGamesOverall += $activeCount;
        }

        return response()->json([
            'commission_percent' => (float) PlatformSetting::get('commission_percent', 10),
            'summary' => [
                'total_bets' => $totalBetsOverall,
                'total_commission' => $totalCommissionOverall,
                'total_games' => $totalGamesOverall,
                'active_games' => $activeGamesOverall,
            ],
            'per_game' => $perGame,
        ]);
    }

    /**
     * POST /api/admin/settings
     */
    public function updateSettings(Request $request)
    {
        $data = $request->validate([
            'commission_percent' => 'required|numeric|min:0|max:50',
        ]);

        PlatformSetting::set('commission_percent', $data['commission_percent']);

        return response()->json([
            'message' => 'تم تحديث نسبة العمولة بنجاح',
            'commission_percent' => (float) $data['commission_percent'],
        ]);
    }
}
