<?php
#	SonicCampGuard
#
#	Copyright (c) 2024 Bundeswehr
#	Diese Anwendung wurde von Cedric Prietz entwickelt.
#	E-Mail: CedricPrietz@bundeswehr.org
#	App: 90-8303-54618
#
#	Letzte Änderung: 11.10.2024

require_once $_SERVER['DOCUMENT_ROOT'] . '/function.inc.php';
pageName('Terminal');
requireLogin();
requireRole(['Bediener', 'Bearbeiter', 'Administrator']);
showSessionAlert();

if ($_GET['console'] == 'logout') {
    $_SESSION['currentTerminal'] = NULL;
}

if ($_SESSION['currentTerminal']) {
    header('Location: /terminal/console?id=' . $_SESSION['currentTerminal']);
}

include($_SERVER['DOCUMENT_ROOT'] . '/header.inc.php');
?>

<div class="d-flex justify-content-between align-items-center flex-wrap grid-margin">
    <div>
        <h4 class="mb-md-0">Terminal</h4>
        <span class="text-secondary">Login</span>
    </div>
</div>

<?php

try {

    initializeDatabaseConnection();

    $sql = "
            SELECT Zones.*
            FROM Zones
            INNER JOIN ZonePermissions 
                ON Zones.ZoneID = ZonePermissions.ZoneID
            WHERE ZonePermissions.AccountID = :session_id

            UNION

            SELECT Zones.*
            FROM Zones
            WHERE EXISTS (
                SELECT 1
                FROM Accounts
                WHERE Accounts.ID = :session_id
                AND Accounts.Role IN ('Administrator', 'Bearbeiter')
            )
        ";

    $stmt = $pdo->prepare($sql);
    $stmt->bindParam(':session_id', $_SESSION['ID'], PDO::PARAM_INT);
    $stmt->execute();

    $zones = $stmt->fetchAll(PDO::FETCH_ASSOC);

    if ($zones) {

        echo '<div class="row">';

        foreach ($zones as $zone) {

            echo '
                    <div class="col-12 col-md-4 col-xl-3 grid-margin stretch-card">
                        <div class="card">
                            <div class="card-body">
                                <h6 class="card-title"><span class="mdi mdi-texture-box me-2"></span>' . htmlspecialchars($zone['ZoneName']) . '</h6>
                                <div class="d-grid mt-4">
                                    <a href="/terminal/console?id=' . htmlspecialchars($zone['ZoneID']) . '" class="btn btn-primary btn-icon-text">
                                        Terminal
                                        <i class="btn-icon-append mdi mdi-login"></i>
                                    </a>
                                </div>
                            </div>
                        </div>
                    </div>';


        }

        echo '</div>';

    } else {
        echo '<div class="alert alert-warning" role="alert">
                    <i class="mdi mdi-information-box-outline"></i>
                    Ihr Account verfügt über keine Berechtigung für eine Zone.
                </div>';
    }

} catch (PDOException $e) {
    echo 'Datenbankfehler: ' . $e->getMessage();
}

?>


<?php include($_SERVER['DOCUMENT_ROOT'] . '/footer.inc.php'); ?>