<?php
// Fehlerberichterstattung aktivieren
error_reporting(E_ALL);
ini_set('display_errors', 1);

// Datei definieren
$json_file = __DIR__ . '/daten.json';
$upload_dir = __DIR__ . '/uploads/';

// JSON-Daten laden
$entries = [];
if (file_exists($json_file)) {
    $json_content = file_get_contents($json_file);
    $entries = json_decode($json_content, true);
    if (!is_array($entries)) {
        $entries = []; // Falls die Datei leer oder ungültig ist, leeres Array verwenden
    }
}

// Eintrag löschen
if (isset($_GET['delete'])) {
    $id_to_delete = intval($_GET['delete']);
    if (isset($entries[$id_to_delete])) {
        // Foto löschen, wenn vorhanden
        $photo_path = $upload_dir . $entries[$id_to_delete]['photo'];
        if (file_exists($photo_path)) {
            unlink($photo_path);
        }

        unset($entries[$id_to_delete]);
        file_put_contents($json_file, json_encode(array_values($entries), JSON_PRETTY_PRINT));
        header("Location: index.php"); // Zurück zur Liste nach dem Löschen
        exit();
    }
}

// Neuer Kontakt hinzufügen
if ($_SERVER["REQUEST_METHOD"] == "POST" && isset($_POST['add_contact'])) {
    $name = htmlspecialchars($_POST['name']);
    $rufzeichen = htmlspecialchars($_POST['rufzeichen']);
    $wohnort = htmlspecialchars($_POST['wohnort']);
    $photo_name = basename($_FILES['photo']['name']);
    $upload_file = $upload_dir . $photo_name;

    if (!empty($name) && !empty($rufzeichen) && !empty($wohnort)) {
        $new_entry = [
            'name' => $name,
            'rufzeichen' => $rufzeichen,
            'wohnort' => $wohnort,
            'photo' => $photo_name
        ];

        // Foto hochladen
        if (isset($_FILES['photo']) && $_FILES['photo']['error'] === UPLOAD_ERR_OK) {
            if (!is_dir($upload_dir)) {
                mkdir($upload_dir, 0777, true);
            }
            if (move_uploaded_file($_FILES['photo']['tmp_name'], $upload_file)) {
                echo "<p>Das Foto wurde erfolgreich hochgeladen.</p>";
            } else {
                echo "<p>Beim Speichern des Fotos ist ein Fehler aufgetreten.</p>";
            }
        }

        // Neuen Eintrag hinzufügen
        $entries[] = $new_entry;
        file_put_contents($json_file, json_encode($entries, JSON_PRETTY_PRINT));
        header("Location: index.php"); // Zurück zur Liste nach dem Hinzufügen
        exit();
    } else {
        echo "<p>Bitte füllen Sie alle Eingabefelder aus, um den Kontakt hinzuzufügen.</p>";
    }
}
?>

<!DOCTYPE html>
<html lang="de">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Kontakte</title>
    <style>
        body {
            font-family: Arial, sans-serif;
            display: flex;
            flex-direction: column;
            align-items: center;
            margin: 0;
            background-color: #f4f4f9;
        }

        .container {
            background-color: #fff;
            padding: 20px;
            border-radius: 10px;
            box-shadow: 0 0 10px rgba(0, 0, 0, 0.1);
            text-align: center;
            width: 90%;
            max-width: 800px;
            margin-top: 20px;
        }

        .form-container {
            margin-top: 20px;
            text-align: left;
        }

        .form-container input[type="text"],
        .form-container input[type="file"] {
            padding: 10px;
            border: 1px solid #ccc;
            border-radius: 5px;
            width: calc(100% - 22px);
            /* Platz für Padding und Border */
            margin-bottom: 10px;
        }

        .form-container input[type="submit"] {
            padding: 10px 20px;
            border: none;
            border-radius: 5px;
            background-color: #007bff;
            color: white;
            cursor: pointer;
        }

        .form-container input[type="submit"]:hover {
            background-color: #0056b3;
        }

        .entry-list {
            margin-top: 20px;
            width: 100%;
            max-width: 800px;
        }

        .entry {
            display: flex;
            align-items: center;
            justify-content: space-between;
            margin-bottom: 10px;
            padding: 10px;
            border: 1px solid #ddd;
            border-radius: 5px;
        }

        .entry div {
            display: flex;
            align-items: center;
        }

        .entry img {
            max-width: 50px;
            max-height: 50px;
            margin-right: 20px;
            border-radius: 5px;
        }

        .entry-info {
            display: flex;
            flex-direction: column;
            align-items: flex-start;
        }

        .entry-info p {
            margin: 2px 0;
        }

        a,
        button {
            margin: 5px;
            text-decoration: none;
            color: #007bff;
            border: none;
            background: none;
            cursor: pointer;
        }

        a:hover,
        button:hover {
            color: #0056b3;
        }

        button {
            background-color: #f44336;
            color: white;
            padding: 5px 10px;
            border-radius: 5px;
        }
    </style>
</head>

<body>
    <!-- Audio Element zum Abspielen der MP3-Datei im Hintergrund -->
    <audio autoplay loop style="display: none;">
        <source src="../public/1.mp3" type="audio/mpeg">
        Ihr Browser unterstützt das Abspielen von Audio nicht.
    </audio>

    <div class="container">
        <h1>Kontakte</h1>

        <!-- Formular zum Hinzufügen eines neuen Kontakts -->
        <div class="form-container">
            <h2>Neuen Kontakt hinzufügen</h2>
            <form action="" method="post" enctype="multipart/form-data">
                <label for="name">Name:</label>
                <input type="text" id="name" name="name" required>

                <label for="rufzeichen">Rufzeichen:</label>
                <input type="text" id="rufzeichen" name="rufzeichen" required>

                <label for="wohnort">Wohnort:</label>
                <input type="text" id="wohnort" name="wohnort" required>

                <label for="photo">Foto:</label>
                <input type="file" id="photo" name="photo">

                <input type="submit" name="add_contact" value="Kontakt hinzufügen">
            </form>
        </div>

        <!-- Liste der Einträge -->
        <div class="entry-list">
            <?php foreach ($entries as $id => $entry): ?>
                <div class="entry">
                    <div>
                        <?php if (!empty($entry['photo']) && file_exists($upload_dir . $entry['photo'])): ?>
                            <img src="<?php echo 'uploads/' . htmlspecialchars($entry['photo']); ?>" alt="Vorschaubild">
                        <?php else: ?>
                            <img src="uploads/default.jpg" alt="Kein Bild verfügbar">
                        <?php endif; ?>
                        <div class="entry-info">
                            <p><strong>Name:</strong> <?php echo htmlspecialchars($entry['name']); ?></p>
                            <p><strong>Rufzeichen:</strong> <?php echo htmlspecialchars($entry['rufzeichen']); ?></p>
                            <p><strong>Wohnort:</strong> <?php echo htmlspecialchars($entry['wohnort']); ?></p>
                        </div>
                    </div>
                    <div>

                        <form action="" method="get"
                            onsubmit="return confirm('Möchten Sie diesen Eintrag wirklich löschen?');"
                            style="display: inline;">
                            <input type="hidden" name="delete" value="<?php echo $id; ?>">

                    </div>
                </div>
            <?php endforeach; ?>
        </div>
    </div>
</body>

</html>