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

require_once $_SERVER['DOCUMENT_ROOT'] . '/function.inc.php';
pageName('Dienstposten: ' . $_GET['id']);
requireLogin();
requireRole(['Bearbeiter', 'Administrator']);

// Dienstpostendaten aus der Datenbank holen
initializeDatabaseConnection();

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

$position = $stmt->fetch();

if (!$position) {

    header("Location: /identities/positions");
    exit();

} else {

    $currentPosition = $position['ID'];
    $currentName = $position['PositionName'];
    $currentDepartment = $position['Department'];

    $currentOwner = $position['Owner'];
    $currentOwnerAccessCard = $position['OwnerAccessCard'];
    $currentSuccessor = $position['Successor'];

}

// Dienstposten Updaten
if (isset($_POST['updatePosition'])) {

    // Update : Dienstposten-ID
    if ($_POST['positionID']) {
        updatePosition($_GET['id'], 'ID', $_POST['positionID']);
        $currentPosition = $_POST['positionID'];
    }
    // Update : Zutrittskarte
    if ($_POST['positionAccessCard']) {
        updatePosition($currentPosition, 'OwnerAccessCard', $_POST['positionAccessCard']);
        updatePosition($currentPosition, 'SuccessorAccessCard', "N" . $_POST['positionAccessCard']);
        $currentOwnerAccessCard = $_POST['positionAccessCard'];
    }

    // Update : Inhaber des Dienstposten
    if ($_POST['positionOwner'] == "") {
        $positionOwner = NULL;
    } else {
        $positionOwner = $_POST['positionOwner'];
    }
    updateIdenty($currentOwner, 'AccessCard', NULL);
    updateIdenty($positionOwner, 'AccessCard', $currentOwnerAccessCard);
    updatePosition($currentPosition, 'Owner', $positionOwner);

    // Update : Nachfolger des Dienstposten
    if ($_POST['positionSuccessor'] == "") {
        $positionSuccessor = NULL;
    } else {
        $positionSuccessor = $_POST['positionSuccessor'];
    }
    updateIdenty($currentSuccessor, 'AccessCard', NULL);
    updateIdenty($positionSuccessor, 'AccessCard', "N" . $currentOwnerAccessCard);
    updatePosition($currentPosition, 'Successor', $positionSuccessor);

    // Update : Daten
    updatePosition($currentPosition, 'PositionName', $_POST['positionName']);
    updatePosition($currentPosition, 'Department', $_POST['positionDepartment']);
    updatePosition($currentPosition, 'Phone', $_POST['positionPhone']);
    updatePosition($currentPosition, 'Mobil', $_POST['positionMobil']);
    updatePosition($currentPosition, 'Radio', $_POST['positionRadio']);
    updatePosition($currentPosition, 'Notes', $_POST['positionNotes']);
    updatePosition($currentPosition, 'RequiredSecurityClearance', $_POST['requiredSecurityClearance']);
    updatePosition($currentPosition, 'RestrictedZoneAuthorisation', $_POST['restrictedZoneAuthorisation']);

    // AuditLog: Eintrag erstellen
    addAuditLog($_SESSION['Username'], 'Dienstposten', 'Dienstposten "' . $positionID . ' - ' . $_POST['positionName'] . ' - ' . $_POST['positionDepartment'] . '" bearbeitet');

    // Alert: Speichern Erfolgreich
    createSessionAlert("", "Dienstposten <h5 class='pt-2 pb-2'>" . $currentDepartment . " - " . $currentName . "</h5> wurde erfolgreich aktualisiert", "success", "false", "2000");

    // Weiterleitung zur Übersicht
    header("Location: /identities/positions");
    exit();
}


// Dienstposten Löschen
if (isset($_POST['deletePosition'])) {

    // Identität : Dienstposten von dem Dienstposteninhber entfernen
    updateIdenty($currentOwner, 'AccessCard', NULL);
    // Identität : Dienstposten von dem Nachfolger entfernen
    updateIdenty($currentSuccessor, 'AccessCard', NULL);

    // SQL-Befehl zum Löschen des Dienstposten
    $sql = "DELETE FROM Positions WHERE ID = :ID";

    $stmt = $pdo->prepare($sql);
    $stmt->bindParam(':ID', $_GET['id']);
    $stmt->execute();

    // AuditLog: Eintrag erstellen
    addAuditLog($_SESSION['Username'], 'Dienstposten', 'Dienstposten "' . $currentPosition . ' - ' . $currentName . ' - ' . $currentDepartment . '" gelöscht');

    // Alert: Löschen Erfolgreich
    createSessionAlert("", "Dienstposten <h4 class='pt-2 pb-2'>" . $currentPosition . " - " . $currentDepartment . " - " . $currentName . "</h4> wurde erfolgreich gelöscht", "success", "false", "3000");

    // Weiterleitung zur Übersicht
    header("Location: /identities/positions");
    exit();
}


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

<form action="" method="post" id="editPositionCivil">

    <div class="d-flex justify-content-between align-items-center flex-wrap grid-margin">
        <div>
            <h4 class="mb-3 mb-md-0">Dienstposten <span class="badge bg-secondary"><?php echo $position['ID']; ?></span>
            </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="updatePosition">
                <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="#modalDeletePosition">
                <i class="btn-icon-prepend mdi mdi-delete"></i>
                Löschen
            </button>

            <a href="/identities/positions" 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">
                    Stammdaten
                </div>
                <div class="card-body">
                    <div class="mb-3">
                        <label for="positionID" class="form-label fw-bold">Dienstposten-ID</label>
                        <input id="positionID" name="positionID" class="form-control" type="text"
                            data-bs-toggle="tooltip" data-bs-placement="left"
                            title="Durch Eingabe einer neuen Dienstposten-ID wird die bestehende automatisch ersetzt."
                            placeholder="<?php echo $position['ID']; ?>">
                    </div>
                    <div class="mb-3">
                        <label for="positionName" class="form-label">Bezeichnung</label>
                        <input id="positionName" name="positionName" class="form-control" type="text"
                            value="<?php echo $position['PositionName']; ?>">
                    </div>
                    <div class="mb-3">
                        <label for="positionDepartment" class="form-label">Dienststelle</label>
                        <input id="positionDepartment" name="positionDepartment" class="form-control" type="text"
                            value="<?php echo $position['Department']; ?>">
                    </div>
                </div>
            </div>
        </div>

        <div class="col-lg-12 col-xl-4 grid-margin stretch-card">
            <div class="card">
                <div class="card-header">
                    Kontakt
                </div>
                <div class="card-body">
                    <div class="mb-3">
                        <label for="positionPhone" class="form-label">Telefon</label>
                        <input id="positionPhone" name="positionPhone" class="form-control" type="text"
                            value="<?php echo $position['Phone']; ?>">
                    </div>
                    <div class="mb-3">
                        <label for="positionMobil" class="form-label">Mobilfunk</label>
                        <input id="positionMobil" name="positionMobil" class="form-control" type="text"
                            value="<?php echo $position['Mobil']; ?>">
                    </div>
                    <div class="mb-3">
                        <label for="positionRadio" class="form-label">Funk</label>
                        <input id="positionRadio" name="positionRadio" class="form-control" type="text"
                            value="<?php echo $position['Radio']; ?>">
                    </div>
                </div>
            </div>
        </div>

        <div class="col-lg-12 col-xl-4 grid-margin stretch-card">
            <div class="card">
                <div class="card-header">
                    Identitäten
                </div>
                <div class="card-body">
                    <div class="mb-3">
                        <label for="positionAccessCard" class="form-label">Zutrittskarte</label>
                        <input id="positionAccessCard" name="positionAccessCard" class="form-control" type="text"
                            data-bs-toggle="tooltip" data-bs-placement="left"
                            title="Durch Eingabe einer neuen Karten-ID wird die bestehende automatisch ersetzt."
                            placeholder="<?php echo $position['OwnerAccessCard']; ?>">
                    </div>
                    <div class="mb-3">
                        <label class="form-label">Dienstposteninhaber</label>
                        <select class="js-example-basic-single form-select form-control" name="positionOwner"
                            data-width="100%">
                            <option value="">Keine Auswahl</option>
                            <?php

                            // Wenn Dienstposteninhaber existiert, diesen Anzeigen
                            if ($position['Owner']) {
                                echo '<option value="' . $position['Owner'] . '" selected>' . getIdentityDetails($position['Owner'], 'Rank') . ' ' . getIdentityDetails($position['Owner'], 'Surname') . ', ' . getIdentityDetails($position['Owner'], 'Givenname') . '</option>';
                            }

                            // Datenbankverbindung
                            initializeDatabaseConnection();

                            // Datenbankabfrage
                            $sql = "SELECT * FROM Identities WHERE AccessCard IS NULL AND Type = 'Civil'";
                            $stmt = $pdo->query($sql);
                            $Identities = $stmt->fetchAll();

                            if ($Identities) {
                                foreach ($Identities as $Identity) {
                                    echo '<option value="' . htmlspecialchars($Identity['ID']) . '">' . htmlspecialchars($Identity['Rank']) . ' ' . htmlspecialchars($Identity['Surname']) . ', ' . htmlspecialchars($Identity['Givenname']) . '</option>';
                                }
                            }

                            ?>
                        </select>
                    </div>
                    <div class="mb-3">
                        <label class="form-label">Nachfolger</label>
                        <select class="js-example-basic-single form-select form-control" name="positionSuccessor"
                            data-width="100%">
                            <option value="">Keine Auswahl</option>
                            <?php

                            // Wenn Nachfolger existiert, diesen Anzeigen
                            if ($position['Successor']) {
                                echo '<option value="' . $position['Successor'] . '" selected>' . getIdentityDetails($position['Successor'], 'Rank') . ' ' . getIdentityDetails($position['Successor'], 'Surname') . ', ' . getIdentityDetails($position['Successor'], 'Givenname') . '</option>';
                            }

                            if ($Identities) {
                                foreach ($Identities as $Identity) {
                                    echo '<option value="' . htmlspecialchars($Identity['ID']) . '">' . htmlspecialchars($Identity['Rank']) . ' ' . htmlspecialchars($Identity['Surname']) . ', ' . htmlspecialchars($Identity['Givenname']) . '</option>';
                                }
                            }

                            ?>
                        </select>
                    </div>
                </div>
            </div>
        </div>

        <div class="col-lg-12 col-xl-4 grid-margin">
            <div class="card">
                <div class="card-header bg-warning text-white">
                    Sicherheit
                </div>
                <div class="card-body">
                    <div class="mb-3">
                        <label class="form-label">Erforderliche Sicherheitsüberprüfung</label>
                        <select class="js-example-basic-single form-select form-control"
                            name="requiredSecurityClearance" data-width="100%">
                            <option value="0" <?php if ($position['RequiredSecurityClearance'] == '0') {
                                echo 'selected';
                            } ?>>Ohne</option>
                            <option value="1" <?php if ($position['RequiredSecurityClearance'] == '1') {
                                echo 'selected';
                            } ?>>Ü1</option>
                            <option value="2" <?php if ($position['RequiredSecurityClearance'] == '2') {
                                echo 'selected';
                            } ?>>Ü2</option>
                            <option value="3" <?php if ($position['RequiredSecurityClearance'] == '3') {
                                echo 'selected';
                            } ?>>Ü3</option>
                        </select>
                    </div>
                    <div class="mb-3">
                        <label class="form-label">Sperrzonenberechtigung</label>
                        <select class="js-example-basic-single form-select form-control"
                            name="restrictedZoneAuthorisation" data-width="100%">
                            <option value="0" <?php if ($position['RestrictedZoneAuthorisation'] == '0') {
                                echo 'selected';
                            } ?>>Nein</option>
                            <option value="1" <?php if ($position['RestrictedZoneAuthorisation'] == '1') {
                                echo 'selected';
                            } ?>>Ja</option>
                            <option value="2" <?php if ($position['RestrictedZoneAuthorisation'] == '2') {
                                echo 'selected';
                            } ?>>Begleitet</option>
                        </select>
                    </div>
                </div>
            </div>
        </div>

        <div class="col-lg-12 col-xl-8 grid-margin">
            <div class="card">
                <div class="card-header">
                    Notizen
                </div>
                <div class="card-body">
                    <textarea class="form-control" name="positionNotes" id="easyMdeExample"
                        rows="10"><?php echo $position['Notes']; ?></textarea>
                </div>
            </div>
        </div>

    </div>

</form>

<!-- Modal : Dienstposten Löschen -->
<div class="modal fade" id="modalDeletePosition" tabindex="-1" aria-labelledby="deletePositionModalLabel"
    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" id="deletePositionModalLabel">Dienstposten 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">Bist du sicher, dass du den Dienstposten löschen möchtest?</p>
                    <p class="mb-2">Durch das Löschen des Dienstpostens werden alle zugeordneten Identitäten automatisch
                        entfernt. Diese Identitäten können anschließend einem neuen Dienstposten zugewiesen werden.</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="deletePosition">
                        <i class="btn-icon-prepend" data-feather="trash-2"></i>
                        Löschen
                    </button>
                </div>
            </form>
        </div>
    </div>
</div>

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