<?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('Identität Bearbeiten');
    requireLogin();
    requireRole(['Bearbeiter', 'Administrator']);
    showSessionAlert();
    initializeDatabaseConnection();

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

    $identity = $stmt->fetch();

    if (!$identity) {

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

    // Update : Identität
    if(isset($_POST['updateIdentity']))
    {

        // Update : Bild
        $identityImage = $_FILES['identityImage'];
        if (isset($identityImage) && $identityImage['error'] == UPLOAD_ERR_OK) {
            $check = getimagesize($identityImage['tmp_name']);
            if ($check !== false) {
                $uniqueId = uniqid('', true);
                $fileExtension = pathinfo($identityImage['name'], PATHINFO_EXTENSION);
                $targetFile = "../uploads/identities/" . $uniqueId . "." . $fileExtension;
                if (move_uploaded_file($identityImage['tmp_name'], $targetFile)) {
                    $identityImageFile = $uniqueId . "." . $fileExtension;
                    unlink("../uploads/identities/" . $identity['Image']);
                }
            }
        } else {
            $identityImageFile = $identity['Image'];
        }

        updateIdenty($identity['ID'], 'Givenname', $_POST['identityGivenname']);
        updateIdenty($identity['ID'], 'Surname', $_POST['identitySurname']);
        updateIdenty($identity['ID'], 'Image', $identityImageFile);
        updateIdenty($identity['ID'], 'Notes', $_POST['identityNotes']);
        updateIdenty($identity['ID'], 'IdentityIN', $_POST['identityIN']);
        updateIdenty($identity['ID'], 'IdentityOUT', $_POST['identityOUT']);
        updateIdenty($identity['ID'], 'MilitarySecurityClearance', $_POST['identitySecurityClearance']);

        // AuditLog: Eintrag erstellen
        addAuditLog($_SESSION['Username'], 'Identität', 'Identität "' . $identity['Surname'] . ', ' . $identity['Givenname'] . '" bearbeitet');

        // Alert: Speichern Erfolgreich
        createSessionAlert("","Identität <h5 class='pt-2 pb-2'>" . $identity['Surname'] . ", " . $identity['Givenname'] . "</h5> wurde erfolgreich aktualisiert","success", "false", "2000");
        
        // Weiterleitung zur Übersicht
        header("Location: /identities/identities");
        exit(); 
            
    }

    // IDENTITÄT LÖSCHEN
    if(isset($_POST['deleteIdentity'])) {

        // WENN BILD VORHANDEN, DANN LÖSCHEN
        if ( $identity['Image'] != NULL ) {
            unlink("../uploads/identities/" . $identity['Image']);
        }

        // Update : Dienstposten von Identität befreien
        updatePosition(getPositionDetails('OwnerAccessCard', $identity['AccessCard'], 'ID'), 'Owner', NULL);
        updatePosition(getPositionDetails('SuccessorAccessCard', $identity['AccessCard'], 'ID'), 'Successor', NULL);

        // AuditLog: Eintrag erstellen
        addAuditLog($_SESSION['Username'], 'Identität', 'Identität "' . $identity['Surname'] . ', ' . $identity['Givenname'] . '" gelöscht');

        // Alert: Löschen Erfolgreich
        createSessionAlert("","Identität <h4 class='pt-2 pb-2'>" . $identity['Surname'] . ", " . $identity['Givenname'] . "</h4> wurde erfolgreich gelöscht","success", "false", "3000");

        // SQL-Befehl zum Löschen der Identität
        $sql = "DELETE FROM Identities WHERE ID = :ID";

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

        // Weiterleitung zur Übersicht
        header("Location: /identities/identities");
        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"><?php echo $identity['Surname'] . ", " . $identity['Givenname'];?></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="updateIdentity">
                <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="#modalDeleteIdentity">
                <i class="btn-icon-prepend mdi mdi-delete"></i>
                Löschen
            </button>

            <a href="/identities/identities" 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-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" value="<?php echo $identity['Surname']; ?>">
                        </div>
                        <div class="mb-3">
                            <label for="identityGivenname" class="form-label">Vorname</label>
                            <input id="identityGivenname" name="identityGivenname" class="form-control" type="text" value="<?php echo $identity['Givenname']; ?>">
                        </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="">Keine</option>
                                <option value="1" <?php if ($identity['MilitarySecurityClearance'] == '1') { echo 'selected'; } ?>>Ü1</option>
                                <option value="2" <?php if ($identity['MilitarySecurityClearance'] == '2') { echo 'selected'; } ?>>Ü2</option>
                                <option value="3" <?php if ($identity['MilitarySecurityClearance'] == '3') { echo 'selected'; } ?>>Ü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" value="<?php echo $identity['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" value="<?php echo $identity['IdentityOUT']; ?>" data-input>
                        <span class="input-group-text input-group-addon" data-toggle><i data-feather="calendar"></i></span>
                    </div>
                </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="<?php if ( $identity['Image'] == NULL ) { echo '../assets/images/identityPreviewPlaceholder.png'; } else { echo '../uploads/identities/' . $identity['Image']; } ?>" 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-12 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"><?php echo $identity['Notes']; ?></textarea>
            </div>
        </div>
    </div>

    </div>

</form>

    <!-- Modal : Identität Löschen -->
    <div class="modal fade" id="modalDeleteIdentity" tabindex="-1" aria-labelledby="deleteIdentityModalLabel" 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="deleteIdentityModalLabel">Identität 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 "<?php echo $identity['Surname'] . ", " . $identity['Givenname']?>" löschen möchtest?</p>
                    <p class="mb-2">Durch das Löschen der Identität wird der zugeordnete Dienstposten automatisch entfernt. Der Dienstposten kann anschließend einer neuen Identität 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="deleteIdentity">
                        <i class="btn-icon-prepend mdi mdi-delete"></i>
                        Löschen
                    </button>
                </div>
            </form>
        </div>
    </div>
    </div>

    <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'); ?>