<?php

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

require_once '../function.inc.php';
pageName("Protokolle");
requireLogin();
requireRole(['Auditor', 'Administrator']);

// TCPDF-Bibliothek Laden
require_once '../assets/vendors/tcpdf/tcpdf.php';

// Erstellen und Herunterladen des Protokolls
if (isset($_POST['pdfDownload'])) {

    // AuditLog: Eintrag erstellen
    addAuditLog($_SESSION['Username'], 'Auditing', 'Protokoll Heruntergeladen');

    class AuditLogPDF extends TCPDF
    {

        public function Header()
        {
            $this->SetY(5);
            $this->SetFont('helvetica', '', 8);
            $this->Cell(90, 10, 'SONICCG', 0, 0, 'L');
            $this->Cell(0, 10, 'Audit-Protokoll', 0, 0, 'R');
            $this->Ln(10);
        }

        public function Footer()
        {
            $this->SetY(-15);
            $this->SetFont('helvetica', '', 8);
            $this->Cell(90, 10, 'Dieses Dokument wurde am ' . date('Y-m-d H:i:s') . ' von ' . $_SESSION['DisplayName'] . ' elektronisch erstellt.', 0, 0, 'L');
            $this->Cell(90, 10, 'Seite ' . $this->getAliasNumPage() . ' von ' . $this->getAliasNbPages(), 0, 0, 'R');
            $this->Ln(20);
        }
    }

    $pdf = new AuditLogPDF();

    $pdf->SetMargins(20, 20, 20);
    $pdf->SetAutoPageBreak(true, 25);

    $pdf->SetCreator(PDF_CREATOR);
    $pdf->SetAuthor('SONICCG');
    $pdf->SetTitle('Protokoll');
    $pdf->SetSubject('AuditLog');

    $pdf->AddPage();

    $pdf->SetFont('helvetica', '', 10);

    $period_from = isset($_POST['period_from']) ? $_POST['period_from'] : null;
    $period_until = isset($_POST['period_until']) ? $_POST['period_until'] : null;

    if (!$period_until) {
        $period_until = date('Y-m-d');
    }

    if ($period_until) {
        $period_until .= ' 23:59:59';
    }

    $html = '<h1>Audit-Protokoll</h1>';

    if ($period_from && $period_until) {
        $html .= '<h4>Zeitraum von ' . $period_from . ' bis ' . $period_until . '</h4><br><br>';
    } elseif ($period_from) {
        $html .= '<h4>Zeitraum von ' . $period_from . ' bis ' . $period_until . '</h4><br><br>';
    } elseif ($period_until) {
        $html .= '<h4>Gesamter Zeitraum bis zum ' . $period_until . '</h4><br><br>';
    }

    $html .= '    
        <table border="1" cellpadding="2" style="font-size: 7px;">
            <tr style="font-weight: bold;">
                <th width="13%">Type</th>
                <th width="45%">Beschreibung</th>
                <th width="15%">Benutzer</th>
                <th width="13%">IP-Adresse</th>
                <th width="15%">Datum</th>
            </tr>';

    // Datenbankverbindung
    initializeDatabaseConnection();

    $sql = "SELECT Type, Username, Description, IPAddress, Timestamp FROM AuditLogs";

    if ($period_from && $period_until) {
        $sql .= " WHERE Timestamp BETWEEN :period_from AND :period_until";
    } elseif ($period_from) {
        $sql .= " WHERE Timestamp >= :period_from";
    } elseif ($period_until) {
        $sql .= " WHERE Timestamp <= :period_until";
    }

    $sql .= " ORDER BY ID DESC";

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

    if ($period_from) {
        $stmt->bindParam(':period_from', $period_from);
    }
    if ($period_until) {
        $stmt->bindParam(':period_until', $period_until);
    }

    $stmt->execute();

    $AuditLogs = $stmt->fetchAll(PDO::FETCH_ASSOC);

    if ($AuditLogs) {
        foreach ($AuditLogs as $AuditLog) {
            $html .= "<tr>";
            $html .= "<td>" . htmlspecialchars($AuditLog['Type']) . "</td>";
            $html .= "<td>" . htmlspecialchars($AuditLog['Description']) . "</td>";
            $html .= "<td>" . htmlspecialchars($AuditLog['Username']) . "</td>";
            $html .= "<td>" . htmlspecialchars($AuditLog['IPAddress']) . "</td>";
            $html .= "<td>" . htmlspecialchars($AuditLog['Timestamp']) . "</td>";
            $html .= "</tr>";
        }
    }

    $html .= '</table>';

    $pdf->writeHTML($html, true, false, true, false, '');

    $pdf->Output('AuditLog_' . date('Y-m-d_H-i-s') . '.pdf', 'D');
}

include('../header.inc.php');
?>
<div class="d-flex justify-content-between align-items-center flex-wrap grid-margin">
    <div>
        <h4 class="mb-3 mb-md-0">Protokolle</h4>
        <span class="text-secondary">Auditing</span>
    </div>
    <div class="d-flex align-items-center flex-wrap text-nowrap">
        <button type="button" name="pdfDownload" class="btn btn-primary btn-icon-text mb-2 mb-md-0"
            data-bs-toggle="modal" data-bs-target="#modalDownload">
            <svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none"
                stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"
                class="feather feather-download-cloud btn-icon-prepend">
                <polyline points="8 17 12 21 16 17"></polyline>
                <line x1="12" y1="12" x2="12" y2="21"></line>
                <path d="M20.88 18.09A5 5 0 0 0 18 9h-1.26A8 8 0 1 0 3 16.29"></path>
            </svg>
            Download
        </button>
    </div>
</div>

<div class="row">

    <div class="col-lg-12 col-xl-9 order-2 order-xl-1 grid-margin">
        <div class="card">
            <div class="card-header bg-primary text-white">
                Einträge
            </div>
            <div class="card-body">
                <div class="table-responsive">
                    <table id="dataTableAuditLogs" class="table table-bordered dataTable">
                        <thead>
                            <tr>
                                <th>Type</th>
                                <th>Beschreibung</th>
                                <th>Benutzer</th>
                                <th>IP-Adresse</th>
                                <th>Datum</th>
                            </tr>
                        </thead>
                        <tbody>

                            <?php

                            // Datenbankverbindung
                            initializeDatabaseConnection();

                            // Datenbankabfrage
                            $sql = "SELECT Type, Username, Description, IPAddress, Timestamp FROM AuditLogs ORDER BY ID DESC";

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

                            $AuditLogs = $stmt->fetchAll();

                            if ($AuditLogs) {
                                foreach ($AuditLogs as $AuditLog) {
                                    echo "<tr>";
                                    echo "<td>" . htmlspecialchars($AuditLog['Type']) . "</td>";
                                    echo "<td>" . htmlspecialchars($AuditLog['Description']) . "</td>";
                                    echo "<td>" . htmlspecialchars($AuditLog['Username']) . "</td>";
                                    echo "<td>" . htmlspecialchars($AuditLog['IPAddress']) . "</td>";
                                    echo "<td>" . htmlspecialchars($AuditLog['Timestamp']) . "</td>";
                                    echo "</tr>";
                                }
                            }

                            ?>

                        </tbody>
                    </table>
                </div>
            </div>
        </div>
    </div>

    <div class="col-lg-12 col-xl-3 order-1 order-xl-2 grid-margin">
        <div class="card">
            <div class="card-header bg-warning text-white">
                Information
            </div>
            <ul class="list-group list-group-flush">
                <li class="list-group-item">Einträge werden <b>automatisch gelöscht</b>, sobald sie älter als
                    <b>90 Tage</b> sind. Dies trägt zur Optimierung unserer Datenverwaltung als auch zur Einhaltung der
                    Datenschutzstandards bei.
                </li>
            </ul>
        </div>
    </div>

</div>


<!-- Modal: Download -->
<div class="modal fade" id="modalDownload" tabindex="-1" aria-labelledby="exampleModalLabel" 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="modalDownloadLabel">Protokoll Exportieren</h5>
                    <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="btn-close"></button>
                </div>
                <div class="modal-body">
                    <p>Beim Export von Protokollen können Sie optional einen gewünschten Zeitraum festlegen. Wird kein
                        Zeitraum ausgewählt, erfolgt der Export für den gesamten verfügbaren Zeitraum. Der Exportvorgang
                        wird ebenfalls protokolliert.</p>
                    <div class="row">
                        <div class="col-6">
                            <div class="mb-3 mt-4">
                                <div class="input-group flatpickr" id="flatpickr-date">
                                    <input type="text" class="form-control" placeholder="Von" name="period_from"
                                        data-input>
                                    <span class="input-group-text input-group-addon" data-toggle><i
                                            data-feather="calendar"></i></span>
                                </div>
                            </div>
                        </div>
                        <div class="col-6">
                            <div class="mb-3 mt-4">
                                <div class="input-group flatpickr" id="flatpickr-date">
                                    <input type="text" class="form-control" placeholder="Bis" name="period_until"
                                        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="modal-footer">
                    <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Abbrechen</button>
                    <button type="submit" name="pdfDownload" class="btn btn-primary"
                        data-bs-dismiss="modal">Download</button>
                </div>
            </form>
        </div>
    </div>
</div>

<?php include('../footer.inc.php'); ?>