<?php
// household_actions.php - Serverseitige Logik für alle Haushalts-Aktionen
// KORREKTUR: Leitet jetzt zur household.php weiter

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'];
$message = '';

function log_household_action($conn, $household_id, $user_id, $message) {
    if (empty($household_id)) return;
    $stmt = $conn->prepare("INSERT INTO household_logs (household_id, user_id, message) VALUES (?, ?, ?)");
    $stmt->bind_param("iis", $household_id, $user_id, $message);
    $stmt->execute();
    $stmt->close();
}

if ($_SERVER["REQUEST_METHOD"] == "POST" && isset($_POST['action'])) {
    $action = $_POST['action'];
    $current_username = $_SESSION['username'];

    $conn->begin_transaction();
    try {
        switch ($action) {
            case 'create_household':
                $household_name = trim($_POST['household_name']);
                if (empty($household_name)) throw new Exception("Der Haushaltsname darf nicht leer sein.");

                $stmt_check = $conn->prepare("SELECT household_id FROM users WHERE id = ?");
                $stmt_check->bind_param("i", $current_user_id);
                $stmt_check->execute();
                $user_data = $stmt_check->get_result()->fetch_assoc();
                if (!empty($user_data['household_id'])) throw new Exception("Du bist bereits Mitglied in einem Haushalt.");
                $stmt_check->close();

                $stmt_create = $conn->prepare("INSERT INTO households (name, admin_user_id) VALUES (?, ?)");
                $stmt_create->bind_param("si", $household_name, $current_user_id);
                $stmt_create->execute();
                $new_household_id = $conn->insert_id;
                $stmt_create->close();

                $stmt_update_user = $conn->prepare("UPDATE users SET household_id = ? WHERE id = ?");
                $stmt_update_user->bind_param("ii", $new_household_id, $current_user_id);
                $stmt_update_user->execute();
                $stmt_update_user->close();

                $log_message = htmlspecialchars($current_username) . " hat den Haushalt '" . htmlspecialchars($household_name) . "' erstellt.";
                log_household_action($conn, $new_household_id, $current_user_id, $log_message);

                $message = "Haushalt erfolgreich erstellt!";
                $_SESSION['message_type'] = 'success';
                break;

            case 'invite_member':
                $invited_username = trim($_POST['username']);
                if (empty($invited_username)) throw new Exception("Der Benutzername darf nicht leer sein.");

                $stmt_find = $conn->prepare("SELECT id, household_id FROM users WHERE username = ?");
                $stmt_find->bind_param("s", $invited_username);
                $stmt_find->execute();
                $invited_user = $stmt_find->get_result()->fetch_assoc();
                $stmt_find->close();

                if (!$invited_user) throw new Exception("Benutzer '" . htmlspecialchars($invited_username) . "' nicht gefunden.");
                if ($invited_user['id'] == $current_user_id) throw new Exception("Du kannst dich nicht selbst einladen.");
                if (!empty($invited_user['household_id'])) throw new Exception("Dieser Benutzer ist bereits in einem anderen Haushalt.");
                
                $stmt_household = $conn->prepare("SELECT id FROM households WHERE admin_user_id = ?");
                $stmt_household->bind_param("i", $current_user_id);
                $stmt_household->execute();
                $household = $stmt_household->get_result()->fetch_assoc();
                if (!$household) throw new Exception("Nur der Admin kann Mitglieder einladen.");
                $stmt_household->close();
                
                $stmt_invite = $conn->prepare("INSERT INTO household_invitations (household_id, inviter_user_id, invited_user_id) VALUES (?, ?, ?)");
                $stmt_invite->bind_param("iii", $household['id'], $current_user_id, $invited_user['id']);
                $stmt_invite->execute();
                $stmt_invite->close();

                $log_message = htmlspecialchars($current_username) . " hat " . htmlspecialchars($invited_username) . " in den Haushalt eingeladen.";
                log_household_action($conn, $household['id'], $current_user_id, $log_message);

                $message = "Einladung an " . htmlspecialchars($invited_username) . " wurde versendet.";
                $_SESSION['message_type'] = 'success';
                break;
            
            case 'respond_invitation':
                $invitation_id = intval($_POST['invitation_id']);
                $response = $_POST['response'];
                if (!in_array($response, ['accept', 'decline'])) throw new Exception("Ungültige Antwort.");
                
                $stmt_get_invite = $conn->prepare("SELECT id, household_id, status FROM household_invitations WHERE id = ? AND invited_user_id = ?");
                $stmt_get_invite->bind_param("ii", $invitation_id, $current_user_id);
                $stmt_get_invite->execute();
                $invite = $stmt_get_invite->get_result()->fetch_assoc();
                $stmt_get_invite->close();
                if (!$invite || $invite['status'] !== 'pending') throw new Exception("Einladung ist ungültig oder wurde bereits beantwortet.");

                if ($response === 'accept') {
                    $stmt_accept = $conn->prepare("UPDATE users SET household_id = ? WHERE id = ?");
                    $stmt_accept->bind_param("ii", $invite['household_id'], $current_user_id);
                    $stmt_accept->execute();
                    $stmt_accept->close();

                    $stmt_update_invite = $conn->prepare("UPDATE household_invitations SET status = 'accepted', responded_at = NOW() WHERE id = ?");
                    $stmt_update_invite->bind_param("i", $invitation_id);
                    $stmt_update_invite->execute();
                    $stmt_update_invite->close();
                    
                    $log_message = htmlspecialchars($current_username) . " ist dem Haushalt beigetreten.";
                    log_household_action($conn, $invite['household_id'], $current_user_id, $log_message);
                    
                    $message = "Du bist dem Haushalt beigetreten!";
                    $_SESSION['message_type'] = 'success';
                } else {
                    $stmt_update_invite = $conn->prepare("UPDATE household_invitations SET status = 'declined', responded_at = NOW() WHERE id = ?");
                    $stmt_update_invite->bind_param("i", $invitation_id);
                    $stmt_update_invite->execute();
                    $stmt_update_invite->close();
                    $message = "Du hast die Einladung abgelehnt.";
                    $_SESSION['message_type'] = 'info';
                }
                break;
        }
        $conn->commit();
    } catch (Exception $e) {
        $conn->rollback();
        $message = $e->getMessage();
        $_SESSION['message_type'] = 'danger';
    }

    $_SESSION['message'] = $message;
    header("Location: household.php");
    exit;
}
?>
