<?php
// share_packing_list.php - Seite zum Verwalten von Packlisten-Freigaben
// KORREKTUR: Neue Sektion zur Freigabe für den gesamten Haushalt hinzugefügt.

if (session_status() == PHP_SESSION_NONE) {
    session_start();
}
if (!isset($_SESSION['user_id'])) {
    header("Location: login.php");
    exit;
}

require_once 'db_connect.php';

$current_user_id = $_SESSION['user_id'];
$packing_list_id = isset($_GET['id']) ? intval($_GET['id']) : 0;
$packing_list = null;
$message = '';

if ($packing_list_id <= 0) {
    header("Location: packing_lists.php");
    exit;
}

// Lade Haushalts-ID des aktuellen Nutzers
$stmt_household_check = $conn->prepare("SELECT household_id FROM users WHERE id = ?");
$stmt_household_check->bind_param("i", $current_user_id);
$stmt_household_check->execute();
$current_user_household_id = $stmt_household_check->get_result()->fetch_assoc()['household_id'];
$stmt_household_check->close();


// Prüfe, ob der Nutzer der Besitzer der Liste ist
$stmt_owner_check = $conn->prepare("SELECT id, name, user_id, share_token, household_id FROM packing_lists WHERE id = ? AND user_id = ?");
$stmt_owner_check->bind_param("ii", $packing_list_id, $current_user_id);
$stmt_owner_check->execute();
$result = $stmt_owner_check->get_result();
if ($result->num_rows !== 1) {
    // Wenn nicht Besitzer, Weiterleitung, da man Freigaben nicht verwalten kann
    header("Location: packing_lists.php");
    exit;
}
$packing_list = $result->fetch_assoc();
$stmt_owner_check->close();

// VERARBEITE FORMULAR-AKTIONEN
if ($_SERVER["REQUEST_METHOD"] == "POST") {
    $action = $_POST['action'] ?? '';

    // Aktionen für Haushaltsfreigabe
    if ($action == 'share_with_household' && $current_user_household_id) {
        $stmt_share = $conn->prepare("UPDATE packing_lists SET household_id = ? WHERE id = ? AND user_id = ?");
        $stmt_share->bind_param("iii", $current_user_household_id, $packing_list_id, $current_user_id);
        $stmt_share->execute();
        $stmt_share->close();
        header("Location: share_packing_list.php?id=" . $packing_list_id . "&msg=household_shared");
        exit;
    }
    elseif ($action == 'unshare_from_household') {
        $stmt_unshare = $conn->prepare("UPDATE packing_lists SET household_id = NULL WHERE id = ? AND user_id = ?");
        $stmt_unshare->bind_param("ii", $packing_list_id, $current_user_id);
        $stmt_unshare->execute();
        $stmt_unshare->close();
        header("Location: share_packing_list.php?id=" . $packing_list_id . "&msg=household_unshared");
        exit;
    }
    // AKTION: NEUEN ANONYMEN LINK ERSTELLEN
    elseif ($action == 'generate_token') {
        $token = bin2hex(random_bytes(16));
        $stmt_token = $conn->prepare("UPDATE packing_lists SET share_token = ? WHERE id = ?");
        $stmt_token->bind_param("si", $token, $packing_list_id);
        $stmt_token->execute();
        $stmt_token->close();
        header("Location: share_packing_list.php?id=" . $packing_list_id . "&msg=token_generated");
        exit;
    }
    // AKTION: ANONYMEN LINK LÖSCHEN
    elseif ($action == 'delete_token') {
        $stmt_token = $conn->prepare("UPDATE packing_lists SET share_token = NULL WHERE id = ?");
        $stmt_token->bind_param("i", $packing_list_id);
        $stmt_token->execute();
        $stmt_token->close();
        header("Location: share_packing_list.php?id=" . $packing_list_id . "&msg=token_deleted");
        exit;
    }
    // AKTION: NEUE FREIGABE FÜR BENUTZER HINZUFÜGEN
    elseif ($action == 'add_share') {
        $shared_with_user_id = intval($_POST['shared_with_user_id']);
        $permission_level = $_POST['permission_level'];

        if ($shared_with_user_id > 0 && in_array($permission_level, ['read', 'edit'])) {
            $stmt_check = $conn->prepare("SELECT id FROM packing_list_shares WHERE packing_list_id = ? AND shared_with_user_id = ?");
            $stmt_check->bind_param("ii", $packing_list_id, $shared_with_user_id);
            $stmt_check->execute();
            if ($stmt_check->get_result()->num_rows > 0) {
                header("Location: share_packing_list.php?id=" . $packing_list_id . "&msg=share_exists");
                exit;
            }
            $stmt_check->close();

            $stmt_add = $conn->prepare("INSERT INTO packing_list_shares (packing_list_id, shared_with_user_id, permission_level) VALUES (?, ?, ?)");
            $stmt_add->bind_param("iis", $packing_list_id, $shared_with_user_id, $permission_level);
            if ($stmt_add->execute()) {
                header("Location: share_packing_list.php?id=" . $packing_list_id . "&msg=shared");
            } else {
                header("Location: share_packing_list.php?id=" . $packing_list_id . "&msg=dberror");
            }
            $stmt_add->close();
            exit;
        }
    }
    // AKTION: FREIGABE AKTUALISIEREN
    elseif ($action == 'update_share') {
        $share_id = intval($_POST['share_id']);
        $permission_level = $_POST['permission_level'];
        if ($share_id > 0 && in_array($permission_level, ['read', 'edit'])) {
            $stmt_update = $conn->prepare("UPDATE packing_list_shares SET permission_level = ? WHERE id = ? AND packing_list_id = ?");
            $stmt_update->bind_param("sii", $permission_level, $share_id, $packing_list_id);
            if($stmt_update->execute()){
                header("Location: share_packing_list.php?id=" . $packing_list_id . "&msg=updated");
            } else {
                 header("Location: share_packing_list.php?id=" . $packing_list_id . "&msg=dberror");
            }
            $stmt_update->close();
            exit;
        }
    }
    // AKTION: FREIGABE LÖSCHEN
    elseif ($action == 'delete_share') {
        $share_id = intval($_POST['share_id']);
        if ($share_id > 0) {
            $stmt_delete = $conn->prepare("DELETE FROM packing_list_shares WHERE id = ? AND packing_list_id = ?");
            $stmt_delete->bind_param("ii", $share_id, $packing_list_id);
            if($stmt_delete->execute()){
                header("Location: share_packing_list.php?id=" . $packing_list_id . "&msg=deleted");
            } else {
                header("Location: share_packing_list.php?id=" . $packing_list_id . "&msg=dberror");
            }
            $stmt_delete->close();
            exit;
        }
    }
}

// DATENLADEN FÜR DIE SEITENANZEIGE
$stmt_users = $conn->prepare("SELECT id, username FROM users WHERE id != ? ORDER BY username ASC");
$stmt_users->bind_param("i", $current_user_id);
$stmt_users->execute();
$result_users = $stmt_users->get_result();
$all_other_users = $result_users->fetch_all(MYSQLI_ASSOC);
$stmt_users->close();

$stmt_shares = $conn->prepare("SELECT pls.id AS share_id, pls.permission_level, u.username AS shared_username FROM packing_list_shares pls JOIN users u ON pls.shared_with_user_id = u.id WHERE pls.packing_list_id = ? ORDER BY u.username ASC");
$stmt_shares->bind_param("i", $packing_list_id);
$stmt_shares->execute();
$result_shares = $stmt_shares->get_result();
$existing_shares = $result_shares->fetch_all(MYSQLI_ASSOC);
$stmt_shares->close();
$conn->close();

if (isset($_GET['msg'])) {
    $alert_type = 'info'; $alert_msg = '';
    switch ($_GET['msg']) {
        case 'household_shared': $alert_type = 'success'; $alert_msg = 'Packliste erfolgreich für den Haushalt freigegeben!'; break;
        case 'household_unshared': $alert_type = 'success'; $alert_msg = 'Freigabe für den Haushalt wurde aufgehoben.'; break;
        case 'shared': $alert_type = 'success'; $alert_msg = 'Packliste erfolgreich freigegeben!'; break;
        case 'updated': $alert_type = 'success'; $alert_msg = 'Freigabe erfolgreich aktualisiert!'; break;
        case 'deleted': $alert_type = 'success'; $alert_msg = 'Freigabe erfolgreich entfernt!'; break;
        case 'token_generated': $alert_type = 'success'; $alert_msg = 'Anonymer Freigabe-Link wurde erstellt.'; break;
        case 'token_deleted': $alert_type = 'success'; $alert_msg = 'Anonymer Freigabe-Link wurde deaktiviert.'; break;
        case 'share_exists': $alert_type = 'warning'; $alert_msg = 'Diese Packliste ist für diesen Benutzer bereits freigegeben.'; break;
        default: $alert_type = 'danger'; $alert_msg = 'Ein unbekannter Fehler ist aufgetreten.'; break;
    }
    $message = '<div class="alert alert-'.$alert_type.'" role="alert">'.$alert_msg.'</div>';
}

$page_title = "Freigaben für: " . htmlspecialchars($packing_list['name']);
require_once 'header.php';
?>

<div class="card">
    <div class="card-header d-flex justify-content-between align-items-center">
        <h2 class="h4 mb-0">Freigaben für "<?php echo htmlspecialchars($packing_list['name']); ?>" verwalten</h2>
        <a href="packing_lists.php" class="btn btn-sm btn-outline-light"><i class="fas fa-arrow-left me-2"></i>Zur Übersicht</a>
    </div>
    <div class="card-body p-4">
        <?php if(!empty($message)) echo $message; ?>
        
        <?php if ($current_user_household_id): ?>
        <div class="card bg-light mb-5">
            <div class="card-body">
                <h5 class="card-title mb-3"><i class="fas fa-users me-2"></i>Freigabe für den Haushalt</h5>
                <?php if (empty($packing_list['household_id'])): ?>
                    <p class="text-muted small">Gib diese Packliste für alle Mitglieder deines Haushalts frei. Jedes Mitglied kann sie dann ansehen und bearbeiten.</p>
                    <form action="share_packing_list.php?id=<?php echo $packing_list_id; ?>" method="post">
                        <input type="hidden" name="action" value="share_with_household">
                        <button type="submit" class="btn btn-success"><i class="fas fa-check-circle me-2"></i>Für meinen Haushalt freigeben</button>
                    </form>
                <?php else: ?>
                    <p class="text-success"><i class="fas fa-check-circle me-2"></i>Diese Packliste ist für deinen Haushalt freigegeben.</p>
                    <form action="share_packing_list.php?id=<?php echo $packing_list_id; ?>" method="post">
                        <input type="hidden" name="action" value="unshare_from_household">
                        <button type="submit" class="btn btn-sm btn-outline-danger" onclick="return confirm('Möchten Sie die Freigabe für den Haushalt wirklich aufheben? Die Liste wird dann wieder privat.');"><i class="fas fa-times-circle me-2"></i>Freigabe aufheben</button>
                    </form>
                <?php endif; ?>
            </div>
        </div>
        <hr class="my-5">
        <?php endif; ?>

        <div class="card bg-light mb-5">
            <div class="card-body">
                <h5 class="card-title mb-3"><i class="fas fa-link me-2"></i>Anonymer Freigabe-Link (schreibgeschützt)</h5>
                <p class="text-muted small">Erstelle einen geheimen Link, um die Packliste mit Personen zu teilen, die keinen Account haben. Dieser Link gewährt nur Lesezugriff.</p>
                <?php if (empty($packing_list['share_token'])): ?>
                    <form action="share_packing_list.php?id=<?php echo $packing_list_id; ?>" method="post">
                        <input type="hidden" name="action" value="generate_token">
                        <button type="submit" class="btn btn-secondary"><i class="fas fa-plus-circle me-2"></i>Geheimen Link erstellen</button>
                    </form>
                <?php else: ?>
                    <label for="share_url" class="form-label">Ihr geheimer Link:</label>
                    <div class="input-group">
                        <?php
                            $protocol = (!empty($_SERVER['HTTPS']) && $_SERVER['HTTPS'] !== 'off' || $_SERVER['SERVER_PORT'] == 443) ? "https://" : "http://";
                            $host = $_SERVER['HTTP_HOST'];
                            $path = rtrim(dirname($_SERVER['PHP_SELF']), '/\\');
                            $share_url = $protocol . $host . $path . '/public_list.php?token=' . $packing_list['share_token'];
                        ?>
                        <input type="text" id="share_url" class="form-control" value="<?php echo htmlspecialchars($share_url); ?>" readonly>
                        <button id="copy-btn" class="btn btn-outline-secondary" onclick="copyShareLink(this)" data-bs-toggle="tooltip" title="Link kopieren"><i class="fas fa-copy"></i></button>
                    </div>
                    <form action="share_packing_list.php?id=<?php echo $packing_list_id; ?>" method="post" class="mt-2">
                        <input type="hidden" name="action" value="delete_token">
                        <button type="submit" class="btn btn-sm btn-outline-danger" onclick="return confirm('Möchten Sie den geheimen Link wirklich dauerhaft deaktivieren?');"><i class="fas fa-trash-alt me-2"></i>Link deaktivieren</button>
                    </form>
                <?php endif; ?>
            </div>
        </div>

        <hr class="my-5">

        <h5 class="mb-3">Für einzelne Benutzer freigeben</h5>
        <div class="card bg-light mb-5">
            <div class="card-body">
                <form action="share_packing_list.php?id=<?php echo htmlspecialchars($packing_list_id); ?>" method="post" class="row g-3 align-items-end">
                    <input type="hidden" name="action" value="add_share">
                    <div class="col-md-5"><label for="shared_with_user_id" class="form-label">Benutzer</label><select class="form-select" id="shared_with_user_id" name="shared_with_user_id" required><option value="" disabled selected>-- Bitte wählen --</option><?php foreach ($all_other_users as $user): ?><option value="<?php echo htmlspecialchars($user['id']); ?>"><?php echo htmlspecialchars($user['username']); ?></option><?php endforeach; ?></select></div>
                    <div class="col-md-4"><label for="permission_level" class="form-label">Berechtigung</label><select class="form-select" id="permission_level" name="permission_level" required><option value="read">Lesen</option><option value="edit">Bearbeiten</option></select></div>
                    <div class="col-md-3"><button type="submit" class="btn btn-primary w-100"><i class="fas fa-user-plus me-2"></i>Freigeben</button></div>
                </form>
            </div>
        </div>

        <?php if (!empty($existing_shares)): ?>
        <h5 class="mb-3 mt-5">Bestehende Einzel-Freigaben</h5>
            <ul class="list-group">
                <?php foreach ($existing_shares as $share): ?>
                    <li class="list-group-item d-flex flex-wrap justify-content-between align-items-center">
                        <div class="fw-bold"><i class="fas fa-user me-2 text-muted"></i><?php echo htmlspecialchars($share['shared_username']); ?></div>
                        <div class="d-flex align-items-center mt-2 mt-md-0">
                            <form action="share_packing_list.php?id=<?php echo htmlspecialchars($packing_list_id); ?>" method="post" class="d-inline-flex me-2">
                                <input type="hidden" name="action" value="update_share">
                                <input type="hidden" name="share_id" value="<?php echo htmlspecialchars($share['share_id']); ?>">
                                <div class="btn-group" role="group">
                                    <input type="radio" class="btn-check" name="permission_level" id="read_<?php echo $share['share_id']; ?>" value="read" <?php echo ($share['permission_level'] == 'read') ? 'checked' : ''; ?> onchange="this.form.submit()">
                                    <label class="btn btn-sm btn-outline-secondary" for="read_<?php echo $share['share_id']; ?>">Lesen</label>
                                    <input type="radio" class="btn-check" name="permission_level" id="edit_<?php echo $share['share_id']; ?>" value="edit" <?php echo ($share['permission_level'] == 'edit') ? 'checked' : ''; ?> onchange="this.form.submit()">
                                    <label class="btn btn-sm btn-outline-primary" for="edit_<?php echo $share['share_id']; ?>">Bearbeiten</label>
                                </div>
                            </form>
                            <form action="share_packing_list.php?id=<?php echo htmlspecialchars($packing_list_id); ?>" method="post" class="d-inline">
                                <input type="hidden" name="action" value="delete_share">
                                <input type="hidden" name="share_id" value="<?php echo htmlspecialchars($share['share_id']); ?>">
                                <button type="submit" class="btn btn-danger btn-sm" title="Freigabe entfernen" onclick="return confirm('Sind Sie sicher, dass Sie diese Freigabe entfernen möchten?');"><i class="fas fa-trash-alt"></i></button>
                            </form>
                        </div>
                    </li>
                <?php endforeach; ?>
            </ul>
        <?php endif; ?>
    </div>
</div>

<script>
    function copyShareLink(button) {
        const urlInput = document.getElementById('share_url');
        if (!navigator.clipboard) {
            urlInput.select();
            document.execCommand('copy');
            alert('Link in die Zwischenablage kopiert!');
            return;
        }
        navigator.clipboard.writeText(urlInput.value).then(function() {
            const originalIconHTML = button.innerHTML;
            const originalTitle = button.getAttribute('data-bs-original-title');
            
            button.innerHTML = '<i class="fas fa-check text-success"></i>';
            const tooltip = bootstrap.Tooltip.getInstance(button);
            if (tooltip) {
                tooltip.setContent({ '.tooltip-inner': 'Kopiert!' });
                tooltip.show();
            }
            
            setTimeout(() => {
                button.innerHTML = originalIconHTML;
                if (tooltip) {
                    tooltip.hide();
                    tooltip.setContent({ '.tooltip-inner': originalTitle });
                }
            }, 2000);
        }, function(err) {
            alert('Fehler: Der Link konnte nicht kopiert werden.');
        });
    }
</script>

<?php require_once 'footer.php'; ?>
