<?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('Neuer Dienstposten');
requireLogin();
requireRole(['Bearbeiter', 'Administrator']);
showSessionAlert();

// Datenbankverbindung
initializeDatabaseConnection();

// Neuer Dienstposten
if (isset($_POST['createPosition'])) {

    // Dienstposten: Prüfen ob Dienstposten-ID bereits vorhanden
    $sql = "SELECT COUNT(*) FROM Positions WHERE ID = :positionID";
    $stmt = $pdo->prepare($sql);
    $stmt->bindParam(':positionID', $_POST['positionID']);
    $stmt->execute();

    $isIDNumberAvailable = $stmt->fetchColumn();

    if (!$isIDNumberAvailable) {

        // Updaten von Dienstposteninhaber
        if ($_POST['positionOwner'] == "") {
            $positionOwner = NULL;
        } else {
            $positionOwner = $_POST['positionOwner'];
            updateIdenty($_POST['positionOwner'], "AccessCard", $_POST['positionAccessCard']);
        }

        // Dienstposten in Datenbank eintragen
        $stmt = $pdo->prepare("INSERT INTO Positions (ID, Type, PositionName, Department, Phone, Mobil, Radio, OwnerAccessCard, Owner, Notes, RequiredSecurityClearance, RestrictedZoneAuthorisation) VALUES (:ID, 'Guest', :Name, :Department, :Phone, :Mobil, :Radio, :OwnerAccessCard, :Owner, :Notes, :RequiredSecurityClearance, :RestrictedZoneAuthorisation)");
        $stmt->bindParam(':ID', $_POST['positionID']);
        $stmt->bindParam(':Name', $_POST['positionName']);
        $stmt->bindParam(':Department', $_POST['positionDepartment']);
        $stmt->bindParam(':Phone', $_POST['positionPhone']);
        $stmt->bindParam(':Mobil', $_POST['positionMobil']);
        $stmt->bindParam(':Radio', $_POST['positionRadio']);
        $stmt->bindParam(':OwnerAccessCard', $_POST['positionAccessCard']);
        $stmt->bindParam(':Owner', $positionOwner);
        $stmt->bindParam(':RequiredSecurityClearance', $_POST['requiredSecurityClearance']);
        $stmt->bindParam(':RestrictedZoneAuthorisation', $_POST['restrictedZoneAuthorisation']);
        $stmt->bindParam(':Notes', $_POST['positionNotes']);
        $stmt->execute();


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

        // Alert: Hinzufügen Erfolgreich
        createSessionAlert("", "Dienstposten <h5 class='pt-2 pb-2'>" . $_POST['positionID'] . " - " . $_POST['positionDepartment'] . " - " . $_POST['positionName'] . "</h5> wurde erfolgreich hinzugefügt", "success", "false", "2000");

        // Verhindert das erneute Absenden des Formulars
        header('Location: ' . $_SERVER['PHP_SELF']);
        exit();

    } else {
        // Alert: Fehlermeldung (Dienstposten bereits vorhanden)
        sweetAlert('', 'Der Dienstposten existiert bereits!', 'error');
    }
}

// Datenbankabfrage: Nächste Freie PIC-Nr feststellen
$sql = "
        SELECT 
            CASE 
                -- Wenn es keine Einträge gibt, wird 'G001' zurückgegeben
                WHEN COUNT(a.OwnerAccessCard) = 0 THEN 'G001'
                -- Wenn 'G001' fehlt, wird es zurückgegeben
                WHEN NOT EXISTS (SELECT 1 FROM Positions WHERE OwnerAccessCard = 'G001') THEN 'G001'
                -- Sonst wird die nächste freie Nummer berechnet
                ELSE CONCAT('G', LPAD(MIN(CAST(SUBSTRING(a.OwnerAccessCard, 2) AS UNSIGNED) + 1), 3, '0'))
            END AS next_available
        FROM Positions a
        LEFT JOIN Positions b 
            ON CAST(SUBSTRING(a.OwnerAccessCard, 2) AS UNSIGNED) + 1 = CAST(SUBSTRING(b.OwnerAccessCard, 2) AS UNSIGNED)
        WHERE b.OwnerAccessCard IS NULL
        AND a.OwnerAccessCard LIKE 'G%'  -- Nur OwnerAccessCards mit einem 'L' berücksichtigen
        AND CAST(SUBSTRING(a.OwnerAccessCard, 2) AS UNSIGNED) < 9999";

$stmt = $pdo->query($sql);

$result = $stmt->fetch(PDO::FETCH_ASSOC);
if ($result) {
    $next_available = $result['next_available'];
}

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

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

    <div class="d-flex justify-content-between align-items-center flex-wrap grid-margin">
        <div>
            <h4 class="mb-md-0">Dienstposten <span class="badge bg-secondary">Gäste</span></h4>
            <span class="text-secondary">Hinzufügen</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="createPosition">
                <i class="btn-icon-prepend mdi mdi-plus"></i>
                Hinzufügen
            </button>

            <a href="/identities/positions" class="btn btn-secondary btn-icon 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" autofocus>
                    </div>
                    <div class="mb-3">
                        <label for="positionName" class="form-label">Bezeichnung</label>
                        <input id="positionName" name="positionName" class="form-control" type="text">
                    </div>
                    <div class="mb-3">
                        <label for="positionDepartment" class="form-label">Arbeitsbereich</label>
                        <input id="positionDepartment" name="positionDepartment" class="form-control" type="text">
                    </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">
                    </div>
                    <div class="mb-3">
                        <label for="positionMobil" class="form-label">Mobilfunk</label>
                        <input id="positionMobil" name="positionMobil" class="form-control" type="text">
                    </div>
                    <div class="mb-3">
                        <label for="positionRadio" class="form-label">Funk</label>
                        <input id="positionRadio" name="positionRadio" class="form-control" type="text">
                    </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 fw-bold">Zutrittskarte</label>
                        <input id="positionAccessCard" name="positionAccessCard" class="form-control" type="text"
                            placeholder="<?php echo $next_available; ?>" value="<?php echo $next_available; ?>">
                    </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="" selected>Keine Auswahl</option>
                            <?php

                            // Datenbankabfrage
                            $sql = "SELECT * FROM Identities WHERE AccessCard IS NULL AND Type = 'Guest'";
                            $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>
            </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" selected>Ohne</option>
                            <option value="1">Ü1</option>
                            <option value="2">Ü2</option>
                            <option value="3">Ü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" selected>Nein</option>
                            <option value="1">Ja</option>
                            <option value="2">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"></textarea>
                </div>
            </div>
        </div>

    </div>

</form>

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