<?php
header('Content-Type: application/json');

require_once __DIR__ . '/../includes/config.php';
require_once __DIR__ . '/../includes/auth_helper.php';

function jsonResponse(int $code, array $data): void
{
    http_response_code($code);
    echo json_encode($data);
    exit;
}

function getInputValue(string $key, $default = null)
{
    if (isset($_GET[$key])) {
        return $_GET[$key];
    }

    if (isset($_POST[$key])) {
        return $_POST[$key];
    }

    $raw = file_get_contents('php://input');
    if ($raw !== '') {
        $json = json_decode($raw, true);
        if (is_array($json) && array_key_exists($key, $json)) {
            return $json[$key];
        }
    }

    return $default;
}

function formatMoney($amount): string
{
    return number_format((float)$amount, 2, '.', '');
}

try {
    $pdo->beginTransaction();

    $authUser = require_authenticated_user($pdo);
    $userId = (int)$authUser['user_id'];

    $entryFeeId = (int)(getInputValue('entry_fee_id', 0) ?? 0);

    if ($entryFeeId <= 0) {
        $pdo->rollBack();
        jsonResponse(400, [
            'success' => false,
            'message' => 'entry_fee_id is required',
            'code' => 'ENTRY_FEE_ID_REQUIRED'
        ]);
    }

    $stmt = $pdo->prepare("
        SELECT
            id,
            country_code
        FROM users
        WHERE id = ?
        LIMIT 1
    ");
    $stmt->execute([$userId]);
    $user = $stmt->fetch(PDO::FETCH_ASSOC);

    if (!$user) {
        $pdo->rollBack();
        jsonResponse(404, [
            'success' => false,
            'message' => 'User not found',
            'code' => 'USER_NOT_FOUND'
        ]);
    }

    $userCountryCode = strtoupper(trim((string)($user['country_code'] ?? '')));

    if ($userCountryCode === '') {
        $pdo->rollBack();
        jsonResponse(400, [
            'success' => false,
            'message' => 'Country not set',
            'code' => 'COUNTRY_NOT_SET'
        ]);
    }

 
    $row = $stmt->fetch(PDO::FETCH_ASSOC);

    if (!$row) {
        $pdo->rollBack();
        jsonResponse(404, [
            'success' => false,
            'message' => 'Entry fee rules not found',
            'code' => 'ENTRY_FEE_RULES_NOT_FOUND'
        ]);
    }

    $rulesJson = null;
    if (!empty($row['rules_json'])) {
        $decoded = json_decode((string)$row['rules_json'], true);
        if (is_array($decoded)) {
            $rulesJson = $decoded;
        }
    }

    if ($rulesJson === null) {
        $normalPrizes = [];
        $winnerCount = max(1, (int)($row['winner_count'] ?? 1));

        $prizePercents = [
            $row['first_prize_percent'] !== null ? (float)$row['first_prize_percent'] : 0,
            $row['second_prize_percent'] !== null ? (float)$row['second_prize_percent'] : 0,
            $row['third_prize_percent'] !== null ? (float)$row['third_prize_percent'] : 0
        ];

        $totalPool = round((float)$row['entry_amount'] * (int)$row['max_players'], 2);
        $platformFeePercent = round((float)($row['platform_fee_percent'] ?? 0), 2);
        $poolAfterFee = round($totalPool - (($totalPool * $platformFeePercent) / 100), 2);

        for ($i = 0; $i < (int)$row['max_players']; $i++) {
            $amount = 0.00;

            if ($i < $winnerCount) {
                $percent = $prizePercents[$i] ?? 0;
                if ($percent > 0) {
                    $amount = round(($poolAfterFee * $percent) / 100, 2);
                }
            }

            $normalPrizes[] = [
                'position' => $i + 1,
                'amount' => formatMoney($amount)
            ];
        }

        $rulesJson = [
            'entry_fee' => formatMoney($row['entry_amount']),
            'currency_symbol' => $row['cash_currency_code'] !== null ? strtoupper((string)$row['cash_currency_code']) : '',
            'player_count' => (int)$row['max_players'],
            'total_pool' => formatMoney($totalPool),
            'platform_fee_percent' => formatMoney($platformFeePercent),
            'normal_prizes' => $normalPrizes,
            'refund_policy' => [
                'title' => 'Applies when an opponent does not play any turn and quits the game',
                'cases' => []
            ]
        ];
    }

    $pdo->commit();

    jsonResponse(200, [
        'success' => true,
        'entry_fee_id' => (int)$row['entry_fee_id'],
        'title' => !empty($row['rules_title'])
            ? (string)$row['rules_title']
            : ((string)$row['entry_fee_title'] . ' Rules'),
        'game_mode' => [
            'game_mode_id' => (int)$row['game_mode_id'],
            'mode_key' => (string)$row['mode_key'],
            'game_mode_title' => (string)$row['game_mode_title'],
            'max_players' => (int)$row['max_players'],
            'entry_wallet_type' => (string)$row['entry_wallet_type'],
            'reward_wallet_type' => (string)$row['reward_wallet_type'],
            'is_country_locked' => (int)$row['is_country_locked'] === 1,
            'match_duration_seconds' => (int)$row['match_duration_seconds'],
            'turn_duration_seconds' => (int)$row['turn_duration_seconds'],
            'max_skips' => (int)$row['max_skips']
        ],
        'entry_fee' => [
            'entry_fee_id' => (int)$row['entry_fee_id'],
            'entry_fee_title' => (string)$row['entry_fee_title'],
            'country_code' => $row['entry_fee_country_code'] !== null
                ? strtoupper((string)$row['entry_fee_country_code'])
                : null,
            'entry_amount' => formatMoney($row['entry_amount']),
            'entry_currency_type' => (string)$row['entry_currency_type'],
            'cash_currency_code' => $row['cash_currency_code'] !== null
                ? strtoupper((string)$row['cash_currency_code'])
                : null,
            'reward_pool_amount' => formatMoney($row['reward_pool_amount']),
            'reward_pool_currency_code' => $row['reward_pool_currency_code'] !== null
                ? strtoupper((string)$row['reward_pool_currency_code'])
                : null
        ],
        'prize_rule' => [
            'prize_rule_id' => $row['prize_rule_id'] !== null ? (int)$row['prize_rule_id'] : null,
            'platform_fee_percent' => $row['platform_fee_percent'] !== null
                ? formatMoney($row['platform_fee_percent'])
                : formatMoney(0),
            'winner_count' => $row['winner_count'] !== null ? (int)$row['winner_count'] : 1,
            'first_prize_percent' => $row['first_prize_percent'] !== null
                ? formatMoney($row['first_prize_percent'])
                : null,
            'second_prize_percent' => $row['second_prize_percent'] !== null
                ? formatMoney($row['second_prize_percent'])
                : null,
            'third_prize_percent' => $row['third_prize_percent'] !== null
                ? formatMoney($row['third_prize_percent'])
                : null,
            'tie_rule_type' => $row['tie_rule_type'] !== null
                ? (string)$row['tie_rule_type']
                : null
        ],
        'rules' => $rulesJson
    ]);
} catch (Throwable $e) {
    if (isset($pdo) && $pdo->inTransaction()) {
        $pdo->rollBack();
    }

    error_log('game/get-entry-fee-rules.php error: ' . $e->getMessage());

    jsonResponse(500, [
        'success' => false,
        'message' => 'Server error',
        'code' => 'SERVER_ERROR',
        'error' => $e->getMessage()
    ]);
}
