<?php
    if($_SERVER['REQUEST_METHOD'] == 'POST')
    {
        if(isset($_POST['leave'])) {
            include 'app/FormValidator.php';
            $validator = new FormValidator(array(
                'group' => array('required' => true, 'regex' => '/^[a-f0-9]{8}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{12}$/')
            ));

            if($validator->isValid($_POST)) {
                $statementMembership = $RUNTIME['PDO']->prepare("DELETE FROM os_groups_membership WHERE GroupID = ? AND PrincipalID = ?");
                $statementMembership->execute(array($_REQUEST['group'], $_SESSION['UUID']));
            }
        }

        header('Location: index.php?page=groups');
        die();
    }

    include 'app/OpenSim.php';
    $opensim = new OpenSim();

    $HTML->setHTMLTitle("Gruppen");
    $HTML->importSeitenInhalt("deine-regionen.html");

    $table = '<table class="table"><thead><tr><th scope="col">Name</th><th scope="col">GrĂ¼nder</th><th scope="col">Aktionen</th></thead><tbody>%%ENTRY%%</tbody></table>';
    
    $statementGroups = $RUNTIME['PDO']->prepare("SELECT Name,FounderID,os_groups_membership.GroupID FROM os_groups_groups JOIN os_groups_membership ON os_groups_groups.GroupID = os_groups_membership.GroupID WHERE PrincipalID = ?");
    $statementGroups->execute(array($_SESSION['UUID']));

    while($rowGroups = $statementGroups->fetch()) 
    {
        $entry = '<tr><td>'.htmlspecialchars($rowGroups['Name']).'</td><td>'.htmlspecialchars($opensim->getUserName($rowGroups['FounderID'])).'</td><td><form action="index.php?page=groups" method="post">%%CSRF%%<input type="hidden" name="group" value="'.htmlspecialchars($rowGroups['GroupID']).'"><button type="submit" name="leave" class="btn btn-danger btn-sm">VERLASSEN</button></form></td></tr>';
        $table = str_replace("%%ENTRY%%", $entry."%%ENTRY%%", $table);
    }

    $table = str_replace("%%ENTRY%%", "", $table);
    $HTML->ReplaceSeitenInhalt("%%REGION-LIST%%", $table);

    $HTML->build();
    echo $HTML->ausgabe();
?>