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

    require_once $_SERVER['DOCUMENT_ROOT'] . '/function.inc.php';
    pageName('Neue Identität');
    requireLogin();
    requireRole(['Bearbeiter', 'Administrator']);
    showSessionAlert();
    initializeDatabaseConnection();

    // Neue Identität
    if(isset($_POST['createIdentity']))
    {
            // Bild eine Eindeutige ID zuweisen und hochladen
            $identityImage = $_FILES['identityImage'];

            if (isset($identityImage) && $identityImage['error'] == UPLOAD_ERR_OK) {
                // Überprüfen, ob die Datei ein Bild ist
                $check = getimagesize($identityImage['tmp_name']);
                if ($check !== false) {
                    // Generiere eine einmalige ID als Dateiname
                    $uniqueId = uniqid('', true);
                    
                    // Dateiendung des Originalbildes ermitteln
                    $fileExtension = pathinfo($identityImage['name'], PATHINFO_EXTENSION);

                    // Vollständiger Pfad für die Speicherung des Bildes
                    $targetFile = "../uploads/identities/" . $uniqueId . "." . $fileExtension;

                    // Verschiebe die hochgeladene Datei in das Zielverzeichnis
                    if (move_uploaded_file($identityImage['tmp_name'], $targetFile)) {
                        $identityImageFile = $uniqueId . "." . $fileExtension;
                    }
                }
            }
            
            // Identität in Datenbank eintragen
            $stmt = $pdo->prepare("INSERT INTO Identities (Type, Givenname, Surname, Image, Notes, IdentityIN, IdentityOUT, MilitarySecurityClearance, CurrentZone) VALUES ('Civil', :Givenname, :Surname, :Image, :Notes, :IN, :OUT, :SecurityClearance, :entryZone)");
            $stmt->bindParam(':Givenname', $_POST['identityGivenname']);
            $stmt->bindParam(':Surname', $_POST['identitySurname']);
            $stmt->bindParam(':Image', $identityImageFile);
            $stmt->bindParam(':Notes', $_POST['identityNotes']);
            $stmt->bindParam(':IN', $_POST['identityIN']);
            $stmt->bindParam(':OUT', $_POST['identityOUT']);
            $stmt->bindParam(':SecurityClearance', $_POST['identitySecurityClearance']);
            $stmt->bindParam(':entryZone', $_POST['identityEntryZone']);
            $stmt->execute();

            // Die automatisch vergebene ID des neu eingefügten Datensatzes abrufen
            $identityID = $pdo->lastInsertId();

            // Update : Dienstposten -> Nachfolger
            if ( $_POST['identitySuccessor'] ) {
                updatePosition($_POST['identitySuccessor'], 'Successor', $identityID);
                updateIdenty($identityID, 'AccessCard', getPositionDetails('ID', $_POST['identitySuccessor'], 'SuccessorAccessCard'));
            }

            // AuditLog: Eintrag erstellen
            addAuditLog($_SESSION['Username'], 'Identitäten', 'Militärische Identität "' . $_POST['identityGivenname'] . ' ' . $_POST['identitySurname'] . '" erstellt');

            // Erstellt einen Session-Alert 
            createSessionAlert("","Die Identität " . $_POST['identityGivenname'] . " " . $_POST['identitySurname'] . " wurde erstellt.","success", "false", "2000");

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

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

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

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

            <a href="/identities/identities" 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-6 grid-margin stretch-card">
        <div class="card">
            <div class="card-header bg-primary text-white">
                Stammdaten
            </div>
            <div class="card-body">
                <div class="row">
                    <div class="col-6">
                        <div class="mb-3">
                            <label for="identitySurname" class="form-label">Nachname</label>
                            <input id="identitySurname" name="identitySurname" class="form-control" type="text" autofocus>
                        </div>
                        <div class="mb-3">
                            <label for="identityGivenname" class="form-label">Vorname</label>
                            <input id="identityGivenname" name="identityGivenname" class="form-control" type="text">
                        </div>
                    </div>
                    <div class="col-6">
                        <div class="mb-3">
                            <label class="form-label">Sicherheitsüberprüfung</label>
                            <select class="js-example-basic-single form-select form-control" name="identitySecurityClearance" data-width="100%">
                                <option value="0" selected>Keine</option>
                                <option value="1">Ü1</option>
                                <option value="2">Ü2</option>
                                <option value="3">Ü3</option>
                            </select>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>

    <div class="col-lg-12 col-xl-3 grid-margin stretch-card">
        <div class="card">
            <div class="card-header">
                Kommandierung
            </div>
            <div class="card-body">
                <div class="mb-3">
                    <label for="identityIN" class="form-label">IN</label>
                    <div class="input-group flatpickr" id="flatpickr-date">
                        <input type="text" class="form-control" name="identityIN" data-input>
                        <span class="input-group-text input-group-addon" data-toggle><i data-feather="calendar"></i></span>
                    </div>
                </div>
                <div class="mb-3">
                    <label for="identityOUT" class="form-label">OUT</label>
                    <div class="input-group flatpickr" id="flatpickr-date">
                        <input type="text" class="form-control" name="identityOUT" data-input>
                        <span class="input-group-text input-group-addon" data-toggle><i data-feather="calendar"></i></span>
                    </div>
                </div>
                <div class="mb-3">
                    <label for="identityEntryZone" class="form-label">Eingangszone</label>
                    <i class="text-secondary ms-1 mdi mdi-information-slab-box" data-bs-toggle="tooltip" data-bs-placement="right" title="Erste Zone an, in die der Benutzer automatisch eingebucht wird."></i> 
                    <select class="js-example-basic-single form-select form-control" name="identityEntryZone" data-width="100%">
                        <option value="" selected>Keine Auswahl</option>
                        <?php

                            // Datenbankabfrage
                            $sql = "SELECT * FROM Zones";
                            $stmt = $pdo->query($sql);
                            $Zones = $stmt->fetchAll();

                            if ($Zones) {
                                foreach ($Zones as $Zone) {
                                    echo '<option value="' . htmlspecialchars($Zone['ZoneID']) . '">' . htmlspecialchars($Zone['ZoneName']) . '</option>';
                                }
                            }
                            
                        ?>
                    </select>
                </div>
            </div>
        </div>
    </div>

    <div class="col-lg-12 col-xl-3 grid-margin stretch-card">
        <div class="card">
            <div class="card-header">
                Foto
            </div>
            <div class="card-body">
                <div class="mb-3 text-center">
                    <img class="w-175px h-200px rounded object-fit-cover" id="imagePreview" src="../assets/images/identityPreviewPlaceholder.png" alt="Passfoto">
                </div>
                <div>
                    <input class="form-control" type="file" id="imageUpload" name="identityImage" accept="image/*">
                </div>
            </div>
        </div>
    </div>


    <div class="col-lg-12 col-xl-4 grid-margin">
        <div class="card">
            <div class="card-header" style="line-height: 20px;">
                <div class="d-flex justify-content-between align-items-baseline">
                    Identitäten
                    <a type="button" class="btn-icon" data-bs-toggle="tooltip" data-bs-placement="top" title="Die Identität wird für den Dienstposten automatisch als Nachfolger eingetragen.">
                      <i class="text-secondary mdi mdi-information-box"></i>
                    </a>
                </div>
            </div>
            <div class="card-body">
                <div class="mb-3">
                    <label class="form-label">Dienstposten</label>
                    <select class="js-example-basic-single form-select form-control" name="identitySuccessor" data-width="100%">
                        <option value="" selected>Keine Auswahl</option>
                        <?php

                            // Datenbankverbindung
                            initializeDatabaseConnection();

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

                            if ($Positions) {
                                foreach ($Positions as $Position) {
                                    echo '<option value="' . htmlspecialchars($Position['ID']) . '">' . htmlspecialchars($Position['ID']) . ' - ' . htmlspecialchars($Position['Department']) . ' - ' . htmlspecialchars($Position['PositionName']) . '</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="identityNotes" id="easyMdeExample" rows="10"></textarea>
            </div>
        </div>
    </div>

    </div>

</form>

    <script>
        document.getElementById('imageUpload').addEventListener('change', function(event) {
        const file = event.target.files[0];
        const imagePreview = document.getElementById('imagePreview');
        
        if (file) {
            const reader = new FileReader();
            reader.onload = function(e) {
            imagePreview.src = e.target.result;
            }
            reader.readAsDataURL(file);
        } else {
            imagePreview.src = "../assets/images/identityPreviewPlaceholder.png";
        }
        });
  </script>

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