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

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

$shelterID = $_GET['id'];

$sql = "SELECT * FROM Shelters WHERE ID = ?";
$stmt = $pdo->prepare($sql);
$stmt->execute([$_GET['id']]);

$shelterEntry = $stmt->fetch();

if (!$shelterEntry) {

    header("Location: /reports/report-shelters");
    exit();

}

if (isset($_POST['updateShelter'])) {

    $selectedCards = $_POST['AccessCards'] ?? [];

    $pdo->beginTransaction();

    try {
        $sqlReset = "
            UPDATE Identities
            SET CurrentShelter = NULL
            WHERE CurrentShelter = :shelterID
        ";
        $stmtReset = $pdo->prepare($sqlReset);
        $stmtReset->execute(['shelterID' => $shelterID]);

        $sqlUpdate = "
            UPDATE Identities
            SET CurrentShelter = :shelterID
            WHERE AccessCard = :accessCard
        ";
        $stmtUpdate = $pdo->prepare($sqlUpdate);

        foreach ($selectedCards as $card) {
            $stmtUpdate->execute([
                'shelterID' => $shelterID,
                'accessCard' => $card
            ]);
        }
        $pdo->commit();

        createSessionAlert("{$shelterEntry['Name']}", "Erfolgreich Gespeichert", "success", "false", "2000");

        header("Location: /reports/report-shelters");
        exit();

    } catch (Exception $e) {

        $pdo->rollBack();
        echo "Fehler beim Aktualisieren der Shelter-Zuordnung: " . $e->getMessage();

    }

}

if (isset($_POST['resetShelter'])) {

    updateDBEntry('Identities', 'CurrentShelter', $shelterID, 'CurrentShelter', NULL);
    createSessionAlert("{$shelterEntry['Name']}", "Erfolgreich Zurückgesetzt", "success", "false", "2000");

    // Weiterleitung zur Übersicht
    header("Location: /reports/report-shelters");
    exit();
}

// SQL-Abfrage vorbereiten
$sql = "
    SELECT ID, AccessCard, CurrentShelter
    FROM Identities
    WHERE 
        -- Bedingung 1: AccessCard darf nicht NULL oder leer sein
        (AccessCard IS NOT NULL AND AccessCard <> '')
        
        -- Bedingung 2: CurrentShelter ist entweder leer/NULL oder entspricht der aktuellen Zone (Ausnahme/selected)
        AND (
            (CurrentShelter IS NULL OR CurrentShelter = '')
            OR (CurrentShelter = :shelterID)
        )

        -- Bedingung 3: IdentityIN & IdentityOUT müssen das heutige Datum einschließen oder gleich sein
        AND (
            CURDATE() BETWEEN DATE(IdentityIN) AND DATE(IdentityOUT)
            OR CURDATE() = DATE(IdentityIN)
            OR CURDATE() = DATE(IdentityOUT)
        )

        -- Bedingung 4: Type darf nicht 'Local' sein
        AND Type <> 'Local'
        
    ORDER BY AccessCard ASC
";

$stmt = $pdo->prepare($sql);
$stmt->execute(['shelterID' => $shelterID]);
$cards = $stmt->fetchAll(PDO::FETCH_ASSOC);

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

<form action="" method="post" id="updateZone" enctype="multipart/form-data">

    <div class="d-flex justify-content-between align-items-center flex-wrap grid-margin">
        <div>
            <h4 class="mb-md-0"><?php echo $shelterEntry['Name']; ?></h4>
            <span class="text-secondary">Schutzbau</span>
        </div>
        <div class="d-flex align-items-center flex-wrap text-nowrap">

            <button class="btn btn-primary btn-icon-text me-2" type="submit" name="updateShelter">
                <i class="btn-icon-prepend mdi mdi-check-bold"></i>
                Speichern
            </button>

            <button type="button" class="btn btn-danger btn-icon mb-2 mb-md-0 me-2" data-bs-toggle="modal"
                data-bs-target="#modalResetShelter">
                <i class="mdi mdi-restore"></i>
            </button>

            <a href="/reports/report-shelters" class="btn btn-secondary btn-icon mb-2 mb-md-0">
                <i class="mdi mdi-arrow-left-top"></i>
            </a>

        </div>
    </div>

    <div class="row">

        <div class="col-lg-12 col-xl-7 grid-margin">
            <div class="card">
                <div class="card-header bg-primary text-white">
                    Personenerfassung
                </div>
                <div class="card-body">
                    <div class="alert alert-primary mb-4" role="alert">
                        Tragen Sie alle <strong>Kartennummern</strong> ein, die in diesen
                        <strong>Schutzbau</strong> eingebucht werden sollen. Anschließend müssen Sie nur noch
                        auf <strong>„Speichern“</strong> klicken, um alle Personen in diesem
                        <strong>Schutzbau</strong> zu erfassen.

                    </div>

                    <div class="mb-3">
                        <select name="AccessCards[]" id="AccessCards" multiple="multiple"
                            class="js-example-basic-multiple form-select" autofocus>
                            <?php foreach ($cards as $card): ?>
                                <?php
                                // Falls CurrentShelter der Zone entspricht, soll die Option ausgewählt sein
                                $selected = ($card['CurrentShelter'] === $shelterID) ? 'selected' : '';
                                $cleanAccessCard = preg_replace('/\s+/', '', $card['AccessCard']);
                                ?>
                                <option value="<?= htmlspecialchars($cleanAccessCard) ?>" <?= $selected ?>>
                                    <?= htmlspecialchars($cleanAccessCard) ?>
                                </option>
                            <?php endforeach; ?>
                        </select>
                    </div>

                </div>
            </div>
        </div>

        <div class="col-lg-12 col-xl-5 grid-margin">

            <div class="card grid-margin">
                <div class="card-header bg-secondary text-white">
                    Position
                </div>
                <div id="map" style="height: 300px;"></div>
            </div>

            <div class="row">
                <div class="col-6 grid-margin">
                    <div class="card">
                        <div class="card-body text-center">
                            <span class="mdi mdi-phone-classic text-secondary"></span>
                            <h3><?php echo $shelterEntry['Phone']; ?></h3>
                        </div>
                    </div>
                </div>

                <div class="col-6 grid-margin">
                    <div class="card">
                        <div class="card-body text-center">
                            <span class="mdi mdi-radio-handheld text-secondary"></span>
                            <h3><?php echo $shelterEntry['Radio']; ?></h3>
                        </div>
                    </div>
                </div>
            </div>

        </div>

    </div>

</form>

<!-- Modal : Schutzbau Zurücksetzen -->
<div class="modal fade" id="modalResetShelter" tabindex="-1" aria-hidden="true">
    <div class="modal-dialog modal-dialog-centered">
        <div class="modal-content">
            <form action="" method="POST">
                <div class="modal-header">
                    <h5 class="modal-title">Zurücksetzen</h5>
                    <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="btn-close"></button>
                </div>
                <div class="modal-body">
                    <p class="fw-bold mb-2">
                        Durch diesen Vorgang werden alle bereits in diesem Schutzbau erfassten Personen wieder
                        ausgetragen.
                    </p>
                    <p>Der Vorgang kann nicht rückgängig gemacht werden.</p>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Abbrechen</button>
                    <button type="submit" class="btn btn-icon-text btn-danger" name="resetShelter">
                        <i class="btn-icon-prepend mdi mdi-restore"></i>
                        Zurücksetzen
                    </button>
                </div>
            </form>
        </div>
    </div>
</div>

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

<script>
    var initialCoordinates = "<?php echo $shelterEntry['Coordinates']; ?>";

    var map = L.map('map', {
        dragging: false,          // Kein Verschieben
        scrollWheelZoom: false,   // Kein Scrollrad-Zoom
        doubleClickZoom: false,   // Kein Doppelklick-Zoom
        touchZoom: false,         // Kein Touch-Zoom
        zoomControl: false        // Zoom-Buttons entfernen
    }).setView([<?php echo $shelterEntry['Coordinates']; ?>], 17);

    L.tileLayer('<?php echo $app_config['map_tile']; ?>', {
        attribution: ''
    }).addTo(map);

    var currentMarker = null;

    if (initialCoordinates) {
        var initialCoordsArray = initialCoordinates.split(',').map(parseFloat);
        currentMarker = L.marker(initialCoordsArray, { icon: shelterIcon }).addTo(map);
    }
</script>