<?php
// household.php - Zentrale Seite für die Haushaltsübersicht und -verwaltung

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

require_once 'db_connect.php';
require_once 'header.php';

$current_user_id = $_SESSION['user_id'];
$message = '';

if (isset($_SESSION['message'])) {
    $message = '<div class="alert alert-'.$_SESSION['message_type'].'" role="alert">'.htmlspecialchars($_SESSION['message']).'</div>';
    unset($_SESSION['message']);
    unset($_SESSION['message_type']);
}

// Lade Haushalts-Informationen
$stmt_household = $conn->prepare("SELECT household_id FROM users WHERE id = ?");
$stmt_household->bind_param("i", $current_user_id);
$stmt_household->execute();
$household_id = $stmt_household->get_result()->fetch_assoc()['household_id'];
$stmt_household->close();

$household_data = null;
$household_members_stats = [];
$household_logs = [];
$is_admin = false;

if ($household_id) {
    // Haushaltsdetails laden
    $stmt_details = $conn->prepare("SELECT * FROM households WHERE id = ?");
    $stmt_details->bind_param("i", $household_id);
    $stmt_details->execute();
    $household_data = $stmt_details->get_result()->fetch_assoc();
    $is_admin = ($household_data && $household_data['admin_user_id'] == $current_user_id);
    $stmt_details->close();

    // Mitglieder und deren Statistiken laden
    $stmt_members = $conn->prepare("
        SELECT 
            u.id, u.username,
            (SELECT COUNT(*) FROM articles WHERE user_id = u.id) as article_count,
            (SELECT COUNT(*) FROM packing_lists WHERE user_id = u.id) as list_count
        FROM users u 
        WHERE u.household_id = ?
        ORDER BY u.username
    ");
    $stmt_members->bind_param("i", $household_id);
    $stmt_members->execute();
    $household_members_stats = $stmt_members->get_result()->fetch_all(MYSQLI_ASSOC);
    $stmt_members->close();
    
    // Eingeladene Mitglieder laden
    $stmt_pending = $conn->prepare("SELECT u.username FROM household_invitations hi JOIN users u ON hi.invited_user_id = u.id WHERE hi.household_id = ? AND hi.status = 'pending'");
    $stmt_pending->bind_param("i", $household_id);
    $stmt_pending->execute();
    $pending_invitations = $stmt_pending->get_result()->fetch_all(MYSQLI_ASSOC);
    $stmt_pending->close();


    // Haushalts-Log laden
    $stmt_logs = $conn->prepare("SELECT message, created_at FROM household_logs WHERE household_id = ? ORDER BY created_at DESC LIMIT 20");
    $stmt_logs->bind_param("i", $household_id);
    $stmt_logs->execute();
    $household_logs = $stmt_logs->get_result()->fetch_all(MYSQLI_ASSOC);
    $stmt_logs->close();
}

$conn->close();
?>

<div class="row g-4">
    <div class="col-lg-5">
        <div class="card">
            <div class="card-header"><h2 class="h4 mb-0"><i class="fas fa-home me-2"></i>Mein Haushalt</h2></div>
            <div class="card-body p-4">
                <?php if(!empty($message)) echo $message; ?>

                <?php if (!$household_id): ?>
                    <p>Du bist derzeit in keinem Haushalt. Erstelle einen neuen Haushalt, um Packlisten und Artikel mit anderen zu teilen.</p>
                    <form action="household_actions.php" method="post">
                        <input type="hidden" name="action" value="create_household">
                        <div class="row g-3 align-items-end">
                            <div class="col-sm-8"><label for="household_name" class="form-label">Name deines Haushalts</label><input type="text" class="form-control" name="household_name" id="household_name" placeholder="z.B. Familie Mustermann" required></div>
                            <div class="col-sm-4"><button type="submit" class="btn btn-primary w-100">Erstellen</button></div>
                        </div>
                    </form>
                <?php else: ?>
                    <h4><?php echo htmlspecialchars($household_data['name']); ?></h4>
                    <?php if ($is_admin) echo '<span class="badge bg-success mb-3">Du bist Administrator dieses Haushalts</span>'; ?>

                    <h5 class="mt-4">Mitglieder</h5>
                    <ul class="list-group">
                        <?php foreach ($household_members_stats as $member): ?>
                            <li class="list-group-item d-flex justify-content-between align-items-center">
                                <span><i class="fas fa-user me-2"></i><?php echo htmlspecialchars($member['username']); ?></span>
                                <div>
                                    <span class="badge bg-secondary rounded-pill" data-bs-toggle="tooltip" title="Erstellte Artikel"><i class="fas fa-box fa-xs me-1"></i> <?php echo $member['article_count']; ?></span>
                                    <span class="badge bg-secondary rounded-pill" data-bs-toggle="tooltip" title="Erstellte Packlisten"><i class="fas fa-clipboard-list fa-xs me-1"></i> <?php echo $member['list_count']; ?></span>
                                </div>
                            </li>
                        <?php endforeach; ?>
                        <?php foreach ($pending_invitations as $pending): ?>
                             <li class="list-group-item d-flex justify-content-between align-items-center">
                                <span><i class="fas fa-user-clock me-2 text-muted"></i><?php echo htmlspecialchars($pending['username']); ?></span>
                                <span class="badge bg-warning text-dark rounded-pill">Eingeladen</span>
                            </li>
                        <?php endforeach; ?>
                    </ul>

                    <?php if ($is_admin): ?>
                        <hr class="my-4">
                        <h5>Neues Mitglied einladen</h5>
                        <form action="household_actions.php" method="post">
                            <input type="hidden" name="action" value="invite_member">
                            <div class="row g-3 align-items-end">
                                <div class="col-sm-8"><label for="username" class="form-label">Benutzername des Mitglieds</label><input type="text" class="form-control" id="username" name="username" required></div>
                                <div class="col-sm-4"><button type="submit" class="btn btn-primary w-100"><i class="fas fa-paper-plane me-2"></i>Einladen</button></div>
                            </div>
                        </form>
                    <?php endif; ?>
                <?php endif; ?>
            </div>
        </div>
    </div>
    
    <div class="col-lg-7">
        <div class="card h-100">
            <div class="card-header"><h2 class="h4 mb-0"><i class="fas fa-stream me-2"></i>Aktivitäten im Haushalt</h2></div>
            <div class="card-body p-2">
                <?php if (empty($household_logs)): ?>
                    <div class="p-4 text-center text-muted">Noch keine Aktivitäten vorhanden.</div>
                <?php else: ?>
                    <ul class="list-group list-group-flush">
                        <?php foreach ($household_logs as $log): ?>
                            <li class="list-group-item">
                                <div class="d-flex w-100 justify-content-between">
                                    <p class="mb-1"><?php echo htmlspecialchars($log['message']); ?></p>
                                    <small class="text-muted"><?php echo date('d.m.Y H:i', strtotime($log['created_at'])); ?></small>
                                </div>
                            </li>
                        <?php endforeach; ?>
                    </ul>
                <?php endif; ?>
            </div>
        </div>
    </div>
</div>

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