<?php
// views/chat.php - Live Chat room management and view
require_once __DIR__ . '/../auth.php';
require_login();

$user = current_user();
$join_error = '';
$join_success = '';

// 1. Initialize Default Rooms if table is empty
$rooms_count = intval($pdo->query("SELECT COUNT(*) FROM chat_rooms")->fetchColumn());
if ($rooms_count === 0) {
    try {
        $pdo->beginTransaction();
        $pdo->exec("INSERT INTO chat_rooms (id, name, created_by) VALUES (1, '📣 Allgemein', 1)");
        $pdo->exec("INSERT INTO chat_rooms (id, name, created_by) VALUES (2, '⚽ Kader & Trainer', 1)");
        $pdo->exec("INSERT INTO chat_rooms (id, name, created_by) VALUES (3, '💼 Vorstand & Leitung', 1)");
        $pdo->commit();
    } catch (PDOException $e) {
        $pdo->rollBack();
    }
}

// 1b. Handle new channel creation (for admin, vorstand, trainer)
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['action']) && $_POST['action'] === 'create_channel') {
    if (has_role(['admin', 'vorstand', 'trainer'])) {
        $channel_name = trim($_POST['channel_name'] ?? '');
        if (!empty($channel_name)) {
            try {
                $stmt = $pdo->prepare("INSERT INTO chat_rooms (name, created_by) VALUES (:name, :created_by)");
                $stmt->execute([
                    ':name' => $channel_name,
                    ':created_by' => $user['id']
                ]);
                $new_room_id = $pdo->lastInsertId();
                
                // Add creator as member
                $stmt = $pdo->prepare("INSERT OR IGNORE INTO chat_room_members (room_id, user_id) VALUES (:room_id, :user_id)");
                $stmt->execute([
                    ':room_id' => $new_room_id,
                    ':user_id' => $user['id']
                ]);
                
                header("Location: index.php?view=chat&room_id=" . $new_room_id . "&channel_created=1");
                exit;
            } catch (PDOException $e) {
                $join_error = "Fehler beim Erstellen des Kanals: " . $e->getMessage();
            }
        } else {
            $join_error = "Bitte geben Sie einen Namen für den Kanal ein.";
        }
    } else {
        $join_error = "Keine Berechtigung zum Erstellen von Kanälen.";
    }
}

if (isset($_GET['channel_created'])) {
    $join_success = "Neuer Chat-Kanal wurde erfolgreich erstellt!";
}


// 2. Handle joining via invitation token
if (isset($_GET['join'])) {
    $token = trim($_GET['join']);
    try {
        $stmt = $pdo->prepare("SELECT * FROM chat_invites WHERE token = :token");
        $stmt->execute([':token' => $token]);
        $invite = $stmt->fetch(PDO::FETCH_ASSOC);

        if ($invite) {
            // Check expiry
            $expires = strtotime($invite['expires_at']);
            if ($expires && $expires < time()) {
                $join_error = "Dieser Einladungslink ist leider bereits abgelaufen.";
            } else {
                // Add user as member of the room
                $stmt = $pdo->prepare("INSERT OR IGNORE INTO chat_room_members (room_id, user_id) VALUES (:room_id, :user_id)");
                $stmt->execute([
                    ':room_id' => $invite['room_id'],
                    ':user_id' => $user['id']
                ]);

                // Fetch room name
                $stmt = $pdo->prepare("SELECT name FROM chat_rooms WHERE id = :id");
                $stmt->execute([':id' => $invite['room_id']]);
                $room_name = $stmt->fetchColumn();

                $join_success = "Erfolgreich beigetreten: '" . htmlspecialchars($room_name) . "'!";
                
                // Add system notification for feedback
                $stmt = $pdo->prepare("INSERT INTO notifications (user_id, title, message) VALUES (:uid, 'Chatraum beigetreten', 'Du bist dem neuen Chatraum erfolgreich beigetreten.')");
                $stmt->execute([':uid' => $user['id']]);

                // Redirect to room
                header("Location: index.php?view=chat&room_id=" . intval($invite['room_id']) . "&success_join=1");
                exit;
            }
        } else {
            $join_error = "Ungültiger Einladungslink. Bitte fragen Sie den Trainer oder Vorstand nach einem neuen Link.";
        }
    } catch (PDOException $e) {
        $join_error = "Fehler beim Beitreten: " . $e->getMessage();
    }
}

if (isset($_GET['success_join'])) {
    $join_success = "Erfolgreich dem privaten Chatraum beigetreten!";
}

// 3. Fetch list of visible rooms for the current user
// Rules:
// - Room 1 & 2 are public
// - Room 3 is Vorstand-only (requires role admin or vorstand)
// - Custom rooms: visible if created_by = user OR user is in chat_room_members OR user is admin
$rooms_query = "
    SELECT DISTINCT r.* 
    FROM chat_rooms r
    LEFT JOIN chat_room_members m ON r.id = m.room_id
    WHERE r.id IN (1, 2)
       OR (r.id = 3 AND :is_board = 1)
       OR r.created_by = :uid
       OR m.user_id = :uid
       OR :is_admin = 1
    ORDER BY r.id ASC
";

$is_board = has_role(['admin', 'vorstand']) ? 1 : 0;
$is_admin = has_role('admin') ? 1 : 0;

$stmt = $pdo->prepare($rooms_query);
$stmt->execute([
    ':uid' => $user['id'],
    ':is_board' => $is_board,
    ':is_admin' => $is_admin
]);
$visible_rooms = $stmt->fetchAll(PDO::FETCH_ASSOC);

// 4. Select active room
$active_room_id = intval($_GET['room_id'] ?? 0);
if ($active_room_id <= 0 && !empty($visible_rooms)) {
    $active_room_id = intval($visible_rooms[0]['id']);
}

// Verify user can access the active room
$room_allowed = false;
$active_room_name = '';
foreach ($visible_rooms as $vr) {
    if (intval($vr['id']) === $active_room_id) {
        $room_allowed = true;
        $active_room_name = $vr['name'];
        break;
    }
}

if (!$room_allowed && !empty($visible_rooms)) {
    $active_room_id = intval($visible_rooms[0]['id']);
    $active_room_name = $visible_rooms[0]['name'];
}
?>

<div style="margin-bottom: 24px;">
    <h1 style="font-size: 28px; font-weight: 800; color: var(--secondary);">Live-Chat</h1>
    <p style="color: var(--text-muted); font-size: 14px;">Echtzeit-Austausch zwischen Mitgliedern, Trainern und Vorstand</p>
</div>

<?php if (!empty($join_error)): ?>
    <div class="alert alert-danger"><?= htmlspecialchars($join_error) ?></div>
<?php endif; ?>

<?php if (!empty($join_success)): ?>
    <div class="alert alert-success"><?= htmlspecialchars($join_success) ?></div>
<?php endif; ?>

<div class="chat-container">
    <!-- Chat Rooms Sidebar -->
    <div class="chat-rooms-list">
        <h3 style="font-size: 15px; font-weight: 700; color: var(--secondary); margin-bottom: 10px;">💬 Chaträume</h3>
        <div style="display: flex; flex-direction: column; gap: 8px; overflow-y: auto;">
            <?php foreach ($visible_rooms as $r): ?>
                <a href="index.php?view=chat&room_id=<?= $r['id'] ?>" class="chat-room-item <?= intval($r['id']) === $active_room_id ? 'active' : '' ?>">
                    <span><?= htmlspecialchars($r['name']) ?></span>
                    <?php if (intval($r['id']) > 3): ?>
                        <span style="font-size: 10px; background: var(--primary); color: #fff; padding: 1px 4px; border-radius: 3px;">Privat</span>
                    <?php endif; ?>
                </a>
            <?php endforeach; ?>
        </div>
        
        <?php if (has_role(['admin', 'vorstand', 'trainer'])): ?>
            <div style="margin-top: 20px; border-top: 1px solid var(--border-color); padding-top: 15px;">
                <h4 style="font-size: 13px; font-weight: 700; color: var(--secondary); margin-bottom: 8px;">Kanal erstellen</h4>
                <form method="POST" action="">
                    <input type="hidden" name="action" value="create_channel">
                    <input type="text" name="channel_name" placeholder="z. B. #jugend" required style="width: 100%; padding: 8px; font-size: 12px; border: 1px solid var(--border-color); border-radius: var(--radius); margin-bottom: 8px; background: #fff; color: #334155;">
                    <button type="submit" class="btn btn-primary btn-sm" style="width: 100%; font-size: 12px; padding: 6px;">Erstellen</button>
                </form>
            </div>
        <?php endif; ?>
    </div>

    <!-- Active Chat Room Content -->
    <div class="chat-messages-area">
        <?php if ($active_room_id > 0): ?>
            <div class="chat-header">
                <div>
                    <span style="font-size: 16px; font-weight: 700; color: var(--secondary);"><?= htmlspecialchars($active_room_name) ?></span>
                </div>
                <div style="font-size: 12px; color: var(--text-muted);">
                    Echtzeit-Verbindung aktiv &bull; Polling aktiv
                </div>
            </div>

            <!-- Messages history wrapper loaded dynamically by JS -->
            <div class="chat-history" id="chat-history" data-room-id="<?= $active_room_id ?>">
                <!-- Messages will load here via AJAX in app.js -->
            </div>

            <!-- Form to send message -->
            <form class="chat-input-area" id="chat-form">
                <input type="text" id="chat-input" placeholder="Schreibe eine Nachricht in <?= htmlspecialchars($active_room_name) ?>..." required autocomplete="off">
                <button type="submit" class="btn btn-primary" style="padding: 10px 24px;">Senden</button>
            </form>
        <?php else: ?>
            <div style="display: flex; align-items: center; justify-content: center; height: 100%; color: var(--text-muted); font-size: 14px;">
                Keine Chaträume verfügbar.
            </div>
        <?php endif; ?>
    </div>
</div>
