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

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

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

$shelterEntry = $stmt->fetch();

if (!$shelterEntry) {

    header("Location: /administration/shelters");
    exit();

}

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

    // Daten Updaten
    updateDBEntry('Shelters', 'ID', $_GET['id'], 'Name', $_POST['shelterName']);
    updateDBEntry('Shelters', 'ID', $_GET['id'], 'Coordinates', $_POST['shelterCoordinates']);
    updateDBEntry('Shelters', 'ID', $_GET['id'], 'Phone', $_POST['shelterPhone']);
    updateDBEntry('Shelters', 'ID', $_GET['id'], 'Radio', $_POST['shelterRadio']);

    // AuditLog: Eintrag erstellen
    addAuditLog($_SESSION['Username'], 'Schutzbauten', 'Schutzbau "' . $shelterEntry['Name'] . '" bearbeitet');

    // Alert: Speichern Erfolgreich
    createSessionAlert("", "Schutzbau <h5 class='pt-2 pb-2'>" . $shelterEntry['Name'] . "</h5> wurde aktualisiert", "success", "false", "2000");

    // Weiterleitung zur Übersicht
    header("Location: /administration/shelters");
    exit();

}

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

    // AuditLog: Eintrag erstellen
    addAuditLog($_SESSION['Username'], 'Schutzbauten', 'Schutzbau "' . $shelterEntry['Name'] . '" aus dem System entfernt');

    // Alert: Löschen Erfolgreich
    createSessionAlert("", "Schutzbau <h4 class='pt-2 pb-2'>" . $shelterEntry['Name'] . "</h4> wurde erfolgreich gelöscht", "success", "false", "3000");

    // Löschen der Daten in der Datenbank
    deleteDBEntry('Shelters', 'ID', $_GET['id']);

    // Weiterleitung zur Übersicht
    header("Location: /administration/shelters");
    exit();
}

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">Bearbeiten</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-text mb-2 mb-md-0 me-2" data-bs-toggle="modal"
                data-bs-target="#modalDeleteShelter">
                <i class="btn-icon-prepend mdi mdi-delete"></i>
                Löschen
            </button>

            <a href="/administration/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-4 grid-margin">
            <div class="card">
                <div class="card-header bg-primary text-white">
                    Allgemein
                </div>
                <div class="card-body">

                    <div class="mb-3">
                        <label for="shelterName" class="form-label">Bezeichnung</label>
                        <input id="shelterName" name="shelterName" class="form-control" type="text"
                            value="<?php echo $shelterEntry['Name']; ?>" autofocus>
                    </div>
                    <div class="mb-3">
                        <label for="shelterCoordinates" class="form-label">Koordinaten</label>
                        <input id="shelterCoordinates" name="shelterCoordinates" class="form-control" type="text"
                            value="<?php echo $shelterEntry['Coordinates']; ?>" readonly>
                    </div>

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

        <div class="col-lg-12 col-xl-3 grid-margin">
            <div class="card">
                <div class="card-header bg-primary text-white">
                    Kommunikation
                </div>
                <div class="card-body">

                    <div class="mb-3">
                        <label for="shelterPhone" class="form-label">Telefon</label>
                        <input id="shelterPhone" name="shelterPhone" class="form-control" type="text"
                            value="<?php echo $shelterEntry['Phone']; ?>">
                    </div>
                    <div class="mb-3">
                        <label for="shelterRadio" class="form-label">Funk</label>
                        <input id="shelterRadio" name="shelterRadio" class="form-control" type="text"
                            value="<?php echo $shelterEntry['Radio']; ?>">
                    </div>

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

        <div class="col-lg-12 col-xl-5 grid-margin">
            <div class="card">
                <div class="card-header bg-secondary text-white">
                    Position
                </div>
                <div id="map" style="height: 350px;"></div>
                <div class="card-body">Klicken Sie auf die Karte, um Koordinaten automatisch zu generieren und die
                    gewünschte Position zu markieren.</div>
            </div>
        </div>

    </div>

</form>

<!-- Modal : Schutzbau Löschen -->
<div class="modal fade" id="modalDeleteShelter" 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">Löschen</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">Schutzbau
                        "<?php echo $shelterEntry['Name']; ?>" wirklich
                        löschen?</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="deleteShelter">
                        <i class="btn-icon-prepend mdi mdi-delete"></i>
                        Löschen
                    </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').setView([<?php echo $app_config['map_position']; ?>], 15);
    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);
        document.getElementById('shelterCoordinates').value = initialCoordinates;
    }

    map.on('click', function (e) {
        var coords = e.latlng;
        document.getElementById('shelterCoordinates').value = coords.lat + ', ' + coords.lng;

        if (currentMarker) {
            map.removeLayer(currentMarker);
        }

        currentMarker = L.marker([coords.lat, coords.lng], { icon: shelterIcon }).addTo(map);

    });
</script>