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

require_once $_SERVER['DOCUMENT_ROOT'] . '/function.inc.php';
pageName('Schutzbauten');
requireLogin();
requireRole(['Auswerter', 'Bearbeiter', 'Administrator']);
showSessionAlert();
initializeDatabaseConnection();

if (isset($_POST['resetShelters'])) {

    updateDBEntry('Identities', '', '', 'CurrentShelter', NULL);
    updateDBEntry('Shelters', '', '', 'QuickQty', NULL);
    createSessionAlert("Schutzbauten", "Erfolgreich Zurückgesetzt", "success", "false", "2000");

    // Weiterleitung zur Übersicht
    header("Location: /reports/report-shelters");
    exit();
}

// MPDF-Bibliothek
require_once '../assets/vendor/autoload.php';

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

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

    // MPDF-Instanz erstellen
    $mpdf = new \Mpdf\Mpdf([
        'margin_left' => 20,
        'margin_right' => 20,
        'margin_top' => 20,
        'margin_bottom' => 25,
        'margin_header' => 10,
        'margin_footer' => 10
    ]);

    $mpdf->SetTitle('Schutzbautenbericht');

    $mpdf->SetHTMLHeader('
        <table class="table-col">
            <tr>
                <td width="30%" style="text-align: left; font-size: 10px;"><span style="font-weight:bold;color: #004971;">SONIC</span><span style="color: #9e9264;">CG</span></td>
                <td style="text-align: center; font-size: 10px;">VS-NfD</td>
                <td width="30%" style="text-align: right; font-size: 10px;">Schutzbautenbericht</td>
            </tr>
        </table>
    ');

    $mpdf->SetHTMLFooter('
        <table class="table-col">
            <tr>
                <td style="text-align: left; font-size: 10px;">Dieses Dokument wurde am <b>' . date('Y-m-d H:i') . '</b> von <b>' . $_SESSION['DisplayName'] . '</b> elektronisch erstellt.</td>
                <td style="text-align: right; font-size: 10px;">Seite {PAGENO} von {nbpg}</td>
            </tr>
        </table>
    ');

    $html = '
    <style>
        body {
            font-family: Roboto, Helvetica, sans-serif;
            font-size: 12px;
        }
        h3 {
            text-align: center;
            text-transform: uppercase;
            color: #333;
            margin-bottom: 30px;
        }
        .table-col {
            width: 100%;
            border: 0;
        }
        .table-col td {
            border: 0;
            padding: 0;
        }
        .table-bordered {
            width: 100%;
            border-collapse: collapse;
            font-size: 12px;
        }
        .table-bordered thead th {
            border-top: 0;
            font-weight: 700;
            text-transform: uppercase;
            color: #7987a1;
            padding: .65rem .65rem;
            border: 1px solid #e9ecef;
            text-align: left;
        }
        .table-bordered tbody td {
            padding: .65rem .65rem;
            border: 1px solid #e9ecef;
        }
        .text-center {
            text-align: center;
        }
        .text-right {
            text-align: right;
        }
        .card-header {
            margin-bottom: 5px; 
            margin-top: 20px; 
            color: #ffffff; 
            padding: .65rem .65rem;
        }
        .alert-warning {
            margin: 20px 0 20px 0;
            padding: .65rem .65rem;
            background: #f79524;
            color: #ffffff;
        }
        .bg-primary {
            background: #004971;
        }
        .bg-secondary {
            background: #7987a1;
        }
        .bg-warning {
            background: #f79524;
        }
        .bg-danger {
            background: #bc2524;
        }
    </style>
    ';

    $html .= '<h3>Schutzbautenbericht</h3>';

    $html .= '<div class="card-header bg-primary">Schutzbauten</div>';

    $sql = "SELECT * FROM Shelters ORDER BY Name";
    $stmt = $pdo->prepare($sql);
    $stmt->execute();
    $results = $stmt->fetchAll(PDO::FETCH_ASSOC);

    $totalPersons = 0;

    if ($results) {

        $html .= '
        <table class="table-bordered">
            <thead>
                <tr>
                    <th width="40%">Bezeichnung</th>
                    <th width="20%" style="text-align: center;">Telefon</th>
                    <th width="20%" style="text-align: center;">Funk</th>
                    <th width="15%" style="text-align: center;">Personen</th>
                </tr>
            </thead>
            <tbody>';

        foreach ($results as $row) {
            $personCount = countDBEntries('Identities', 'CurrentShelter', $row['ID']);
            $totalPersons += $personCount;
            $html .= '
            <tr>
                <td style="font-weight:bold;">' . htmlspecialchars($row['Name']) . '</td>
                <td class="text-center">' . htmlspecialchars($row['Phone']) . '</td>
                <td class="text-center">' . htmlspecialchars($row['Radio']) . '</td>
                <td class="text-center">' . $personCount . '</td>
            </tr>';
        }

        $html .= '
            <tr><td colspan="3" class="text-right" style="border: 0;">Gesamt</td><td class="text-center"><b>' . $totalPersons . '</b></td></tr>
            </tbody>
        </table>';
    } else {
        $html .= '<p style="color:red; text-align:center;"><strong>Es sind keine Schutzbauten vorhanden.</strong></p>';
    }

    $sql = "
        SELECT 
            i.*,
            s.Name AS ShelterGroup
        FROM Identities i
        INNER JOIN Shelters s ON i.CurrentShelter = s.ID
        WHERE
            i.AccessCard IS NOT NULL
            AND i.AccessCard <> ''
            AND i.CurrentShelter IS NOT NULL
            AND i.CurrentShelter <> ''
            AND i.Type <> 'Local'
            AND (
                CURDATE() BETWEEN DATE(i.IdentityIN) AND DATE(i.IdentityOUT)
                OR CURDATE() = DATE(i.IdentityIN)
                OR CURDATE() = DATE(i.IdentityOUT)
            )
        ORDER BY ShelterGroup, i.ID
    ";

    $stmt = $pdo->query($sql);
    $rows = $stmt->fetchAll(PDO::FETCH_ASSOC);

    if (count($rows) === 0) {

    } else {

        $groupedData = [];
        foreach ($rows as $row) {
            $groupedData[$row['ShelterGroup']][] = $row;
        }

        foreach ($groupedData as $shelterGroup => $groupRows) {

            $html .= '<div style="page-break-before: always;"></div>';
            $html .= '<div class="card-header bg-secondary">' . htmlspecialchars($shelterGroup) . '</div>';

            $html .= '
            <table class="table-bordered">
                <thead>
                    <tr>
                        <th width="10%">Karte</th>
                        <th>Identität</th>
                    </tr>
                </thead>
                <tbody>';

            foreach ($groupRows as $row) {
                $html .= '
                <tr>
                    <td>' . htmlspecialchars($row['AccessCard']) . '</td>
                    <td>' . htmlspecialchars($row['Rank']) . ' ' . htmlspecialchars($row['Surname']) . ', ' . htmlspecialchars($row['Givenname']) . '</td>
                </tr>';
            }

            $html .= '</tbody></table>';
        }
    }

    $sql_unassigned = "
        SELECT 
            i.AccessCard,
            i.Rank,
            i.Surname,
            i.Givenname,
            z.ZoneName AS Zone,
            COALESCE(p1.Radio, p2.Radio, 'Kein Funk') AS Funk
        FROM Identities i
        LEFT JOIN Zones z ON i.CurrentZone = z.ZoneID
        LEFT JOIN Positions p1 ON i.ID = p1.Owner
        LEFT JOIN Positions p2 ON i.ID = p2.Successor
        WHERE
            i.AccessCard IS NOT NULL
            AND i.AccessCard <> ''
            AND (i.CurrentShelter IS NULL OR i.CurrentShelter = '')
            AND i.Type <> 'Local'
            AND (
                CURDATE() BETWEEN DATE(i.IdentityIN) AND DATE(i.IdentityOUT)
                OR CURDATE() = DATE(i.IdentityIN)
                OR CURDATE() = DATE(i.IdentityOUT)
            )
        ORDER BY i.ID
    ";

    $stmt_unassigned = $pdo->query($sql_unassigned);
    $unassigned_rows = $stmt_unassigned->fetchAll(PDO::FETCH_ASSOC);

    if (count($unassigned_rows) === 0) {

    } else {

        $html .= '<div style="page-break-before: always;"></div>';
        $html .= '<div class="card-header bg-danger">Keine Schutzraumzuordnung</div>';

        $html .= '
        <table class="table-bordered">
            <thead>
                <tr>
                    <th width="10%">Karte</th>
                    <th>Identität</th>
                    <th>Funk</th>
                    <th>Zone</th>
                </tr>
            </thead>
            <tbody>';

        foreach ($unassigned_rows as $row) {
            $html .= '
            <tr>
                <td>' . htmlspecialchars($row['AccessCard']) . '</td>
                <td>' . htmlspecialchars($row['Rank']) . ' ' . htmlspecialchars($row['Surname']) . ', ' . htmlspecialchars($row['Givenname']) . '</td>
                <td>' . htmlspecialchars($row['Funk']) . '</td>
                <td>' . (!empty($row['Zone']) ? htmlspecialchars($row['Zone']) : 'Keine Zone') . '</td>
            </tr>';
        }

        $html .= '</tbody></table>';
    }

    $mpdf->WriteHTML($html);
    $mpdf->Output('Schutzbautenbericht_' . date('Y-m-d_H-i') . '.pdf', 'D');
}

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

<div class="d-flex justify-content-between align-items-center flex-wrap grid-margin">
    <div>
        <h4 class="mb-md-0">Schutzbauten</h4>
        <span class="text-secondary">Bericht</span>
    </div>
    <div class="d-flex align-items-center flex-wrap text-nowrap">

        <a href="/reports/report-shelters-quick" class="btn btn-primary btn-icon-text mb-2 me-2 mb-md-0">
            <i class="mdi mdi-run-fast"></i> Schnellerfassung
        </a>

        <button type="button" class="btn btn-danger btn-icon mb-2 mb-md-0 me-2" data-bs-toggle="modal"
            data-bs-target="#modalResetShelters">
            <i class="mdi mdi-restore"></i>
        </button>

        <div class="dropdown" data-bs-toggle="tooltip" data-bs-placement="left" title="Exportieren">
            <button class="btn btn-success btn-icon me-2" type="button" id="dropdownMenuButton"
                data-bs-toggle="dropdown" aria-haspopup="true" aria-expanded="false">
                <i class="mdi mdi-download"></i>
            </button>
            <div class="dropdown-menu" aria-labelledby="dropdownMenuButton">
                <form action="" method="post">
                    <button class="dropdown-item" name="pdfDownload">PDF</button>
                </form>
            </div>
        </div>

        <a href="/reports/reportboard" 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-12 col-md-9 order-2 order-xl-1 grid-margin">

        <div class="card">
            <div class="card-header bg-primary text-white">
                Schutzbauten
            </div>
            <div class="card-body">
                <?php
                try {
                    $sql = "SELECT * FROM 
                                    Shelters
                                ORDER BY 
                                    Name
                            ";

                    $stmt = $pdo->prepare($sql);
                    $stmt->execute();
                    $results = $stmt->fetchAll(PDO::FETCH_ASSOC);

                    if ($results) {
                        echo '<div class="table-responsive">';
                        echo "<table id='dTableAdminZones' class='table table-bordered'>";
                        echo '<thead>
                                <tr>
                                    <th>Bezeichnung</th>
                                    <th width="15%" class="text-center">Telefon</th>
                                    <th width="15%" class="text-center">Funk</th>
                                    <th width="15%" class="text-center">Personen</th>
                                    <th style="white-space: nowrap; width: 1%;">Optionen</th>
                                </tr>
                            </thead>';

                        foreach ($results as $row) {
                            echo "<tr>";
                            echo "<td class='fw-bold'>{$row['Name']}</td>";
                            echo "<td class='text-center'>{$row['Phone']}</td>";
                            echo "<td class='text-center'>{$row['Radio']}</td>";
                            echo "<td class='text-center'>" . countDBEntries('Identities', 'CurrentShelter', $row['ID']);
                            if (!is_null($row['QuickQty'])) {
                                echo " ( " . htmlspecialchars($row['QuickQty']) . " )";
                            }
                            echo "</td>";
                            echo '<td style="padding: .60rem .85rem;"><a href="/reports/report-shelter?id=' . $row['ID'] . '" class="btn btn-sm btn-inverse-light btn-icon-text" style="margin: 0px;"><i class="mdi mdi-account-group"></i> Verwalten</a></td>';
                            echo "</tr>";
                        }
                        echo "</table>";
                        echo '</div>';
                    } else {
                        echo '<div class="alert alert-warning mb-0" role="alert">
                                <i class="mdi mdi-alert-box-outline"></i>
                                Es sind keine Schutzbauten vorhanden.
                            </div>
                            ';
                    }
                } catch (PDOException $e) {
                    echo "Datenbankfehler: " . $e->getMessage();
                }
                ?>
            </div>
        </div>

    </div>

    <div class="col-12 col-md-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">Im <strong>Alarmfall</strong> können hier alle Personen den entsprechenden
                    <strong>Schutzbauten</strong> zugewiesen werden. Dadurch lässt sich ein
                    Lagebericht erstellen, der aufzeigt, welche Personen noch keinem
                    <strong>Schutzbau</strong> zugeordnet sind und wie sie im <strong>Ernstfall</strong>
                    erreicht werden können.
                </li>
            </ul>
        </div>
    </div>


</div>


<!-- Modal : Schutzbauten Zurücksetzen -->
<div class="modal fade" id="modalResetShelters" tabindex="-1" 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">Zurücksetzen</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">
                        Durch diesen Vorgang werden alle bereits erfassten Personen wieder
                        ausgetragen.
                    </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="resetShelters">
                        <i class="btn-icon-prepend mdi mdi-restore"></i>
                        Zurücksetzen
                    </button>
                </div>
            </form>
        </div>
    </div>
</div>

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