<commit_before><?php
echo '<title>HP Monopoly</title>';
require 'sql_connect.php';
require 'bertiebotts.php';

session_start();

const GALLEONS = 493;
const SICKLES = 29;
const KNUTS = 1;

function formatError($str){
    return '<strong>'.$str.'</strong><br>';
}
function showMainMenu(){
    session_destroy();
    echo "Usernames are limited to 16 alphanumeric characters, Game IDs are limited to 6.";
    echo "<form action='index.php' method='POST'>
                Username: <input type='text' name='username' maxlength=16> 
                Game ID: <input type='text' name='gameid' maxlength=6>
                <input type='submit' name='join' value='Join Game'>
                <br>
                Max Players:
                    <select name='maxplayers'>
                        <option disabled selected value=1> </option>
                        <option value=2>2</option>
                        <option value=3>3</option>
                        <option value=4>4</option>
                        <option value=5>5</option>
                        <option value=6>6</option>
                        <option value=7>7</option>
                        <option value=8>8</option>
                    </select>
                <input type='submit' name='create' value='Create New Game'>
            </form><br>";
    listGames();
}
function debugQuery($statement){
    global $db;
    if($result=$db->query($statement)){
        return $result;
    } else {
        logError($db->error);
        die('Fatal error');
    }
}
function logError($data){
    $file=fopen('HPLOG.log','a');
    fwrite($file,PHP_EOL .$data);
    fwrite($file,PHP_EOL .'POST Dump: '.var_export($_POST,true).''.PHP_EOL .'| SESSION Dump: '.var_export($_SESSION,true).PHP_EOL);
    fclose($file);
}
function listGames(){
    $results=debugQuery('SELECT * FROM myPHPgames');
    while($row=$results->fetch_object()){
        echo '<span style="background-color:white">'.$row->id.' has '.$row->currentplayers.'/'.$row->maxplayers.' people playing.</span><br>';
        $gameresults=debugQuery('SELECT `username`,`color` FROM myPHPusers WHERE `gameid`="'.$row->id.'"');
        while($gamerow=$gameresults->fetch_object()){
            echo '<span style="margin-left:35px;background-color:'.$gamerow->color.'">    '.$gamerow->username.'</span><br>';
        }
    }
}
function printHPMoney($input){
    $results = array();
    $money=abs($input);
    $results[0]= floor($money/GALLEONS);
    $results[1]= floor(($money-($results[0]*GALLEONS))/SICKLES);
    $results[2]= $money-($results[0]*GALLEONS)-($results[1]*SICKLES);
    return $results[0].' Galleon'.($results[0]==1?'':'s').', '
                                .$results[1].' Sickle'.($results[1]==1?'':'s').', and '
                                .$results[2].' Knut'.($results[2]==1?'':'s').'';
}
function toNormalMoney($galleon,$sickle,$knut){
    return ($galleon*GALLEONS)+($sickle*SICKLES)+($knut*KNUTS);
}
function createGame($username,$gameid,$maxplayers){
    $result=debugQuery('SELECT `id` from `myPHPgames` WHERE `id`="'.$gameid.'"');
    if($result->num_rows){
        echo formatError('Game already exists! Try to Join instead!');
        showMainMenu();
    } else {
        $userResult=debugQuery('SELECT `gameid` FROM `myPHPusers` WHERE `username`="'.$username.'"');
        if($userResult->num_rows){
            $container=$userResult->fetch_object();
            $oldresult=debugQuery('SELECT `creator` FROM `myPHPgames` WHERE `id`="'.$container->gameid.'"');
            if($oldresult->num_rows){
                $creatorObject=$oldresult->fetch_object();
                if($username==$creatorObject->creator){
                    deleteGame($container->gameid);
                } else {
                    removeUser($username,$gameid);
                }
            }
        } else {
            debugQuery('INSERT INTO `myPHPusers` (`id` ,`username` ,`money` ,`gameid`, `created`) VALUES (NULL , "'.$username.'", "7500", "", NULL)');
        }
        //create gameMaster for new game
        debugQuery('INSERT INTO `myPHPgames` (`id` ,`creator` ,`currentplayers` ,`maxplayers`, `created`) VALUES ("'.$gameid.'" , "'.$username.'", 1, "'.$maxplayers.'", NULL)');
        //create beans for new game
        debugQuery('CREATE TABLE `'.$gameid.'Beans` LIKE `myPHPbeans`');
        debugQuery('INSERT `'.$gameid.'Beans` SELECT * FROM `myPHPbeans`');
        debugQuery('ALTER TABLE `'.$gameid.'Beans` ADD `owner` VARCHAR( 16 ) NOT NULL');
        //create wizard cards for new game
        /*
        debugQuery('CREATE TABLE `'.$gameid.'Wizards` LIKE `myPHPwizards`');
        debugQuery('INSERT `'.$gameid.'Wizards` SELECT * FROM `myPHPwizards`');
        debugQuery('ALTER TABLE `'.$gameid.'Wizards` ADD `owner` VARCHAR( 16 ) NOT NULL');
        */
        //create properties for new game
        /*
        debugQuery('CREATE TABLE `'.$gameid.'Properties` LIKE `myPHPproperties`');
        debugQuery('INSERT `'.$gameid.'Properties` SELECT * FROM `myPHPproperties`');
        debugQuery('ALTER TABLE `'.$gameid.'Properties` ADD `owner` VARCHAR( 16 ) NOT NULL');
        */
        
        //join player into game
        debugQuery('UPDATE `myPHPusers` SET `money`=7500,`gameid`="'.$gameid.'" WHERE `username`="'.$username.'"');
        $_SESSION['gameid']=$gameid;
        $_SESSION['username']=$username;
        echo formatError('Created Game!');
        doGame($username,$gameid);
    }
}
function joinGame($username,$gameid){
    $result=debugQuery('SELECT `currentplayers`,`maxplayers` from `myPHPgames` WHERE `id`="'.$gameid.'"');
    if($result->num_rows){
        $countObject=$result->fetch_object();
        $userResult=debugQuery('SELECT `gameid` FROM `myPHPusers` WHERE `username`="'.$username.'"');
        if($userResult->num_rows){
            $userData=$userResult->fetch_object();
            if($gameid==$userData->gameid){
                $_SESSION['gameid'] = $_POST['gameid'];
                $_SESSION['username'] = $_POST['username'];
                echo formatError('Joined Game!');
                doGame($username,$gameid);
            } else if($countObject->currentplayers<$countObject->maxplayers){
                $newCount=$countObject->currentplayers+1;
                debugQuery('UPDATE `myPHPgames` SET `currentplayers`='.$newCount.' WHERE `id`="'.$gameid.'"');
                debugQuery('UPDATE `myPHPusers` SET `money`=7500,`gameid`="'.$gameid.'" WHERE `username`="'.$username.'"');
                $_SESSION['gameid'] = $_POST['gameid'];
                $_SESSION['username'] = $_POST['username'];
                echo formatError('Joined Game!');
                doGame($username,$gameid);
            } else {
                echo formatError('Game is full!');
                showMainMenu();
            }
        } else if($countObject->currentplayers<$countObject->maxplayers){
            debugQuery('INSERT INTO `myPHPusers` (`id` ,`username` ,`money` ,`gameid`, `created`) VALUES (NULL , "'.$username.'", "7500", "'.$gameid.'", NULL)');
            $newCount=$countObject->currentplayers+1;
            debugQuery('UPDATE `myPHPgames` SET `currentplayers`='.$newCount.' WHERE `id`="'.$gameid.'"');
            $_SESSION['gameid'] = $_POST['gameid'];
            $_SESSION['username'] = $_POST['username'];
            echo formatError('Joined Game!');
            doGame($username,$gameid);
        } else {
            echo formatError('Game is full!');
            showMainMenu();
        }
    } else {
        echo formatError("Game doesn't exist! Try to Create it instead!");
        showMainMenu();
    }
}
function deleteGame($gameid){
    //assume the game exists
    
    //delete all beans
    debugQuery('DROP TABLE '.$gameid.'Beans');
    //delete all wizard cards
    /*debugQuery('DROP TABLE '.$gameid.'Wizards');*/
    //delete all properties
    /*debugQuery('DROP TABLE '.$gameid.'Properties');*/
    //erase the gameMaster
    debugQuery('DELETE FROM `myPHPgames` WHERE `id`="'.$gameid.'"');
    //update all users with that gameid to no gameid and 7500 money
    debugQuery('UPDATE `myPHPusers` SET `money`=7500,`gameid`="" WHERE `gameid`="'.$gameid.'"');
}
function removeUser($username,$gameid){
    //assume the user exists
    //assume the game exists
    
    //get amount of current players
    $result=debugQuery('SELECT `currentplayers`,`creator` FROM `myPHPgames` WHERE `id`="'.$gameid.'"');
    $gameData=$result->fetch_object();
    //if there are still players after this operation
    if($gameData->currentplayers > 1 and $username!=$gamedata->creator){
        //decrement gameMaster's currentplayer count
        $newplayers=$gameData-1;
        debugQuery('UPDATE `myPHPgames` SET `currentplayers`='.$newplayers.' WHERE `id`="'.$gameid.'"');
        //remove their name from every bean
        debugQuery('UPDATE `'.$gameid.'Beans` SET `owner`="" WHERE `owner`="'.$username.'"');
        //remove their name from every wizard
        /*debugQuery('UPDATE `'.$gameid.'Wizards` SET `owner`="" WHERE `owner`="'.$username.'"');*/
        //remove every upgrade from their properties
        /*TO BE FIGURED OUT AFTER PROPERTIES EXIST*/
        //remove their name from every property
        /*debugQuery('UPDATE `'.$gameid.'Properties` SET `owner`="" WHERE `owner`="'.$username.'"');*/
    } else {
        //otherwise delete the entire game
        deleteGame($gameid);
    }
}
function doGame($username,$gameid){<commit_msg>Began property support: create and delete games<commit_after><?php
echo '<title>HP Monopoly</title>';
require 'sql_connect.php';
require 'bertiebotts.php';
require 'properties.php';

session_start();

const GALLEONS = 493;
const SICKLES = 29;
const KNUTS = 1;

function formatError($str){
    return '<strong>'.$str.'</strong><br>';
}
function showMainMenu(){
    session_destroy();
    echo "Usernames are limited to 16 alphanumeric characters, Game IDs are limited to 6.";
    echo "<form action='index.php' method='POST'>
                Username: <input type='text' name='username' maxlength=16> 
                Game ID: <input type='text' name='gameid' maxlength=6>
                <input type='submit' name='join' value='Join Game'>
                <br>
                Max Players:
                    <select name='maxplayers'>
                        <option disabled selected value=1> </option>
                        <option value=2>2</option>
                        <option value=3>3</option>
                        <option value=4>4</option>
                        <option value=5>5</option>
                        <option value=6>6</option>
                        <option value=7>7</option>
                        <option value=8>8</option>
                    </select>
                <input type='submit' name='create' value='Create New Game'>
            </form><br>";
    listGames();
}
function debugQuery($statement){
    global $db;
    if($result=$db->query($statement)){
        return $result;
    } else {
        logError($db->error);
        die('Fatal error');
    }
}
function logError($data){
    $file=fopen('HPLOG.log','a');
    fwrite($file,PHP_EOL .$data);
    fwrite($file,PHP_EOL .'POST Dump: '.var_export($_POST,true).''.PHP_EOL .'| SESSION Dump: '.var_export($_SESSION,true).PHP_EOL);
    fclose($file);
}
function listGames(){
    $results=debugQuery('SELECT * FROM myPHPgames');
    while($row=$results->fetch_object()){
        echo '<span style="background-color:white">'.$row->id.' has '.$row->currentplayers.'/'.$row->maxplayers.' people playing.</span><br>';
        $gameresults=debugQuery('SELECT `username`,`color` FROM myPHPusers WHERE `gameid`="'.$row->id.'"');
        while($gamerow=$gameresults->fetch_object()){
            echo '<span style="margin-left:35px;background-color:'.$gamerow->color.'">    '.$gamerow->username.'</span><br>';
        }
    }
}
function printHPMoney($input){
    $results = array();
    $money=abs($input);
    $results[0]= floor($money/GALLEONS);
    $results[1]= floor(($money-($results[0]*GALLEONS))/SICKLES);
    $results[2]= $money-($results[0]*GALLEONS)-($results[1]*SICKLES);
    return $results[0].' Galleon'.($results[0]==1?'':'s').', '
                                .$results[1].' Sickle'.($results[1]==1?'':'s').', and '
                                .$results[2].' Knut'.($results[2]==1?'':'s').'';
}
function toNormalMoney($galleon,$sickle,$knut){
    return ($galleon*GALLEONS)+($sickle*SICKLES)+($knut*KNUTS);
}
function createGame($username,$gameid,$maxplayers){
    $result=debugQuery('SELECT `id` from `myPHPgames` WHERE `id`="'.$gameid.'"');
    if($result->num_rows){
        echo formatError('Game already exists! Try to Join instead!');
        showMainMenu();
    } else {
        $userResult=debugQuery('SELECT `gameid` FROM `myPHPusers` WHERE `username`="'.$username.'"');
        if($userResult->num_rows){
            $container=$userResult->fetch_object();
            $oldresult=debugQuery('SELECT `creator` FROM `myPHPgames` WHERE `id`="'.$container->gameid.'"');
            if($oldresult->num_rows){
                $creatorObject=$oldresult->fetch_object();
                if($username==$creatorObject->creator){
                    deleteGame($container->gameid);
                } else {
                    removeUser($username,$gameid);
                }
            }
        } else {
            debugQuery('INSERT INTO `myPHPusers` (`id` ,`username` ,`money` ,`gameid`, `created`) VALUES (NULL , "'.$username.'", "7500", "", NULL)');
        }
        //create gameMaster for new game
        debugQuery('INSERT INTO `myPHPgames` (`id` ,`creator` ,`currentplayers` ,`maxplayers`, `created`) VALUES ("'.$gameid.'" , "'.$username.'", 1, "'.$maxplayers.'", NULL)');
        //create beans for new game
        debugQuery('CREATE TABLE `'.$gameid.'Beans` LIKE `myPHPbeans`');
        debugQuery('INSERT `'.$gameid.'Beans` SELECT * FROM `myPHPbeans`');
        debugQuery('ALTER TABLE `'.$gameid.'Beans` ADD `owner` VARCHAR( 16 ) NOT NULL');
        //create wizard cards for new game
        /*
        debugQuery('CREATE TABLE `'.$gameid.'Wizards` LIKE `myPHPwizards`');
        debugQuery('INSERT `'.$gameid.'Wizards` SELECT * FROM `myPHPwizards`');
        debugQuery('ALTER TABLE `'.$gameid.'Wizards` ADD `owner` VARCHAR( 16 ) NOT NULL');
        */
        //create properties for new game
        debugQuery('CREATE TABLE `'.$gameid.'Properties` LIKE `myPHPproperties`');
        debugQuery('INSERT `'.$gameid.'Properties` SELECT * FROM `myPHPproperties`');
        
        //join player into game
        debugQuery('UPDATE `myPHPusers` SET `money`=7500,`gameid`="'.$gameid.'" WHERE `username`="'.$username.'"');
        $_SESSION['gameid']=$gameid;
        $_SESSION['username']=$username;
        echo formatError('Created Game!');
        doGame($username,$gameid);
    }
}
function joinGame($username,$gameid){
    $result=debugQuery('SELECT `currentplayers`,`maxplayers` from `myPHPgames` WHERE `id`="'.$gameid.'"');
    if($result->num_rows){
        $countObject=$result->fetch_object();
        $userResult=debugQuery('SELECT `gameid` FROM `myPHPusers` WHERE `username`="'.$username.'"');
        if($userResult->num_rows){
            $userData=$userResult->fetch_object();
            if($gameid==$userData->gameid){
                $_SESSION['gameid'] = $_POST['gameid'];
                $_SESSION['username'] = $_POST['username'];
                echo formatError('Joined Game!');
                doGame($username,$gameid);
            } else if($countObject->currentplayers<$countObject->maxplayers){
                $newCount=$countObject->currentplayers+1;
                debugQuery('UPDATE `myPHPgames` SET `currentplayers`='.$newCount.' WHERE `id`="'.$gameid.'"');
                debugQuery('UPDATE `myPHPusers` SET `money`=7500,`gameid`="'.$gameid.'" WHERE `username`="'.$username.'"');
                $_SESSION['gameid'] = $_POST['gameid'];
                $_SESSION['username'] = $_POST['username'];
                echo formatError('Joined Game!');
                doGame($username,$gameid);
            } else {
                echo formatError('Game is full!');
                showMainMenu();
            }
        } else if($countObject->currentplayers<$countObject->maxplayers){
            debugQuery('INSERT INTO `myPHPusers` (`id` ,`username` ,`money` ,`gameid`, `created`) VALUES (NULL , "'.$username.'", "7500", "'.$gameid.'", NULL)');
            $newCount=$countObject->currentplayers+1;
            debugQuery('UPDATE `myPHPgames` SET `currentplayers`='.$newCount.' WHERE `id`="'.$gameid.'"');
            $_SESSION['gameid'] = $_POST['gameid'];
            $_SESSION['username'] = $_POST['username'];
            echo formatError('Joined Game!');
            doGame($username,$gameid);
        } else {
            echo formatError('Game is full!');
            showMainMenu();
        }
    } else {
        echo formatError("Game doesn't exist! Try to Create it instead!");
        showMainMenu();
    }
}
function deleteGame($gameid){
    //assume the game exists
    
    //delete all beans
    debugQuery('DROP TABLE '.$gameid.'Beans');
    //delete all wizard cards
    /*debugQuery('DROP TABLE '.$gameid.'Wizards');*/
    //delete all properties
    debugQuery('DROP TABLE '.$gameid.'Properties');
    //erase the gameMaster
    debugQuery('DELETE FROM `myPHPgames` WHERE `id`="'.$gameid.'"');
    //update all users with that gameid to no gameid and 7500 money
    debugQuery('UPDATE `myPHPusers` SET `money`=7500,`gameid`="" WHERE `gameid`="'.$gameid.'"');
}
function removeUser($username,$gameid){
    //assume the user exists
    //assume the game exists
    
    //get amount of current players
    $result=debugQuery('SELECT `currentplayers`,`creator` FROM `myPHPgames` WHERE `id`="'.$gameid.'"');
    $gameData=$result->fetch_object();
    //if there are still players after this operation
    if($gameData->currentplayers > 1 and $username!=$gamedata->creator){
        //decrement gameMaster's currentplayer count
        $newplayers=$gameData-1;
        debugQuery('UPDATE `myPHPgames` SET `currentplayers`='.$newplayers.' WHERE `id`="'.$gameid.'"');
        //remove their name from every bean
        debugQuery('UPDATE `'.$gameid.'Beans` SET `owner`="" WHERE `owner`="'.$username.'"');
        //remove their name from every wizard
        /*debugQuery('UPDATE `'.$gameid.'Wizards` SET `owner`="" WHERE `owner`="'.$username.'"');*/
        //remove every upgrade from their properties
        /*TO BE FIGURED OUT AFTER PROPERTIES EXIST*/
        //remove their name from every property
        /*debugQuery('UPDATE `'.$gameid.'Properties` SET `owner`="" WHERE `owner`="'.$username.'"');*/
    } else {
        //otherwise delete the entire game
        deleteGame($gameid);
    }
}
function doGame($username,$gameid){
{'fraction_non_alphanumeric': 0.18078348332451033, 'fraction_numerical': 0.008258337744838539, 'mean_word_length': 2.7497022628026997, 'pattern_counts': {'":': 0, '<': 83, '<?xml version=': 0, '>': 143, 'https://': 0, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '5953194', 'n_tokens_mistral': 5716, 'n_tokens_neox': 5504, 'n_words': 1162}