<?php
declare(strict_types=1);

const BJ_MIN_BET = 1;
const BJ_MAX_BET = 1000;

const BJ_RANKS = ['A', '2', '3', '4', '5', '6', '7', '8', '9', 'T', 'J', 'Q', 'K'];
const BJ_SUITS = ['c', 'd', 'h', 's'];

function bj_new_shoe(): array
{
    $deck = [];
    for ($d = 0; $d < 6; $d++) {
        foreach (BJ_SUITS as $s) {
            foreach (BJ_RANKS as $r) {
                $deck[] = $r . $s;
            }
        }
    }
    return $deck;
}

function bj_shuffle(array &$deck): void
{
    $n = count($deck);
    for ($i = $n - 1; $i > 0; $i--) {
        $j = random_int(0, $i);
        $t = $deck[$i];
        $deck[$i] = $deck[$j];
        $deck[$j] = $t;
    }
}

function bj_draw(array &$deck): string
{
    $c = array_pop($deck);
    if ($c === null) {
        throw new RuntimeException('Deste boş');
    }

    return $c;
}

function bj_rank(string $card): string
{
    return $card[0];
}

function bj_hand_value(array $cards): array
{
    $total = 0;
    $aces = 0;
    foreach ($cards as $c) {
        $r = bj_rank($c);
        if ($r === 'A') {
            $aces++;
            $total += 11;
        } elseif ($r === 'T' || $r === 'J' || $r === 'Q' || $r === 'K') {
            $total += 10;
        } else {
            $total += (int) $r;
        }
    }
    while ($total > 21 && $aces > 0) {
        $total -= 10;
        $aces--;
    }

    return [
        'total' => $total,
        'soft' => $aces > 0,
    ];
}

function bj_is_blackjack(array $cards): bool
{
    if (count($cards) !== 2) {
        return false;
    }
    $v = bj_hand_value($cards);

    return $v['total'] === 21;
}

function bj_dealer_shows_peek(string $upCard): bool
{
    $r = bj_rank($upCard);

    return $r === 'A' || $r === 'T' || $r === 'J' || $r === 'Q' || $r === 'K';
}

function bj_dealer_should_hit(array $dealer): bool
{
    $v = bj_hand_value($dealer);

    return $v['total'] < 17;
}
