#!/usr/bin/perl
# Player Registration Check Module
# To be included in index.cgi files

sub check_player_registration {
    my ($dbh, $account_id) = @_;
    
    return { needsRegistration => JSON::false, error => 'No account ID' } unless $account_id;
    
    # Check if player exists for this account
    my $player = $dbh->selectrow_hashref(
        "SELECT id, username FROM players WHERE account_id = ? ORDER BY id DESC LIMIT 1",
        undef, $account_id
    );
    
    if ($player) {
        return { 
            needsRegistration => JSON::false, 
            hasPlayer => JSON::true,
            username => $player->{username}
        };
    } else {
        return { 
            needsRegistration => JSON::true, 
            hasPlayer => JSON::false
        };
    }
}

# Handle the AJAX action in index.cgi
sub handle_check_registration {
    my ($cgi, $dbh, $account_id) = @_;
    
    if ($cgi->param('action') eq 'checkPlayerRegistration') {
        print $cgi->header('application/json');
        my $result = check_player_registration($dbh, $account_id);
        print encode_json($result);
        exit;
    }
}

1; # Return true