<?php
/**
 * 777POS.com - Forum Topic View
 */

require_once __DIR__ . '/../config.php';

$db = getDB();

// Get topic slug/id from URL
$path = parse_url($_SERVER['REQUEST_URI'], PHP_URL_PATH);
$parts = explode('/', trim($path, '/'));
$topic_slug = end($parts);

// Try to find topic by slug or id
$stmt = $db->prepare("SELECT * FROM forum_topics WHERE slug = ? OR id = ?");
$stmt->execute([$topic_slug, intval($topic_slug)]);
$topic = $stmt->fetch(PDO::FETCH_ASSOC);

if (!$topic) {
    header('HTTP/1.0 404 Not Found');
    $page_title = "Topic Not Found";
    include __DIR__ . '/../includes/header.php';
    echo '<div style="text-align:center;padding:80px 20px;"><h1>Topic Not Found</h1><p>This topic may have been removed or does not exist.</p><a href="/forum/" class="btn btn-primary">Back to Forum</a></div>';
    include __DIR__ . '/../includes/footer.php';
    exit;
}

// Increment view count
$db->exec("UPDATE forum_topics SET view_count = view_count + 1 WHERE id = {$topic['id']}");

// Get topic author
$stmt = $db->prepare("SELECT * FROM users WHERE id = ?");
$stmt->execute([$topic['user_id']]);
$author = $stmt->fetch(PDO::FETCH_ASSOC);

// Get replies with pagination
$page = max(1, intval($_GET['page'] ?? 1));
$per_page = 20;
$offset = ($page - 1) * $per_page;

$total_replies = $db->query("SELECT COUNT(*) FROM forum_replies WHERE topic_id = {$topic['id']} AND status = 'active'")->fetchColumn();
$total_pages = ceil($total_replies / $per_page);

$replies = $db->query("
    SELECT r.*, u.name as author_name, u.avatar as author_avatar, u.rank_level, u.badges, u.points,
           (SELECT COUNT(*) FROM forum_replies WHERE user_id = u.id) as author_posts
    FROM forum_replies r
    LEFT JOIN users u ON r.user_id = u.id
    WHERE r.topic_id = {$topic['id']} AND r.status = 'active'
    ORDER BY r.created_at ASC
    LIMIT $per_page OFFSET $offset
")->fetchAll(PDO::FETCH_ASSOC);

// Handle new reply
$error = '';
$success = '';
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isLoggedIn()) {
    if (!verifyCSRF($_POST['csrf'] ?? '')) {
        $error = 'Invalid form submission';
    } elseif ($topic['is_locked']) {
        $error = 'This topic is locked';
    } else {
        $content = trim($_POST['content'] ?? '');
        if (strlen($content) < 10) {
            $error = 'Reply must be at least 10 characters';
        } else {
            $current_user = getCurrentUser();
            $stmt = $db->prepare("INSERT INTO forum_replies (topic_id, user_id, content) VALUES (?, ?, ?)");
            $stmt->execute([$topic['id'], $current_user['id'], $content]);

            // Update topic
            $db->exec("UPDATE forum_topics SET reply_count = reply_count + 1, last_reply_at = datetime('now'), last_reply_by = {$current_user['id']} WHERE id = {$topic['id']}");

            // Award points
            addPoints($current_user['id'], 5, 'forum_reply', "Reply to: {$topic['title']}");

            $success = 'Reply posted successfully!';
            header("Location: /forum/topic/{$topic['slug']}/?page=" . ceil(($total_replies + 1) / $per_page) . "#reply-" . $db->lastInsertId());
            exit;
        }
    }
}

global $FORUM_CATEGORIES, $USER_RANKS;
$category = $FORUM_CATEGORIES[$topic['category']] ?? ['name' => 'General', 'icon' => '💬'];

$page_title = $topic['title'] . " - Forum";
include __DIR__ . '/../includes/header.php';
?>

<style>
.topic-page { padding: 40px 20px; max-width: 900px; margin: 0 auto; }
.breadcrumb { display: flex; gap: 8px; align-items: center; margin-bottom: 24px; font-size: 0.9rem; }
.breadcrumb a { color: var(--primary); }
.breadcrumb span { color: var(--gray); }

.topic-header { background: white; border-radius: 16px; padding: 32px; margin-bottom: 24px; box-shadow: 0 2px 10px rgba(0,0,0,0.05); }
.topic-title { font-size: 1.5rem; font-weight: 700; margin-bottom: 16px; display: flex; align-items: flex-start; gap: 12px; }
.topic-badge { padding: 4px 10px; border-radius: 20px; font-size: 0.75rem; font-weight: 600; flex-shrink: 0; }
.badge-pinned { background: #fef3c7; color: #92400e; }
.badge-locked { background: #fee2e2; color: #991b1b; }
.topic-meta { display: flex; flex-wrap: wrap; gap: 16px; color: var(--gray); font-size: 0.9rem; margin-bottom: 20px; }
.topic-content { line-height: 1.8; font-size: 1rem; }
.topic-content p { margin-bottom: 16px; }

.topic-author { display: flex; gap: 16px; padding-top: 20px; border-top: 1px solid var(--gray-light); margin-top: 20px; }
.author-avatar { width: 60px; height: 60px; border-radius: 50%; object-fit: cover; }
.author-info { flex: 1; }
.author-name { font-weight: 600; display: flex; align-items: center; gap: 8px; }
.author-rank { font-size: 0.8rem; padding: 2px 8px; border-radius: 10px; }
.author-stats { font-size: 0.85rem; color: var(--gray); margin-top: 4px; }

.replies-section { margin-top: 32px; }
.replies-header { display: flex; justify-content: space-between; align-items: center; margin-bottom: 20px; }
.replies-title { font-size: 1.2rem; font-weight: 700; }

.reply-card { background: white; border-radius: 12px; padding: 24px; margin-bottom: 16px; box-shadow: 0 2px 10px rgba(0,0,0,0.05); display: flex; gap: 16px; }
.reply-author { width: 120px; text-align: center; flex-shrink: 0; }
.reply-author-avatar { width: 64px; height: 64px; border-radius: 50%; object-fit: cover; margin: 0 auto 8px; }
.reply-author-name { font-weight: 600; font-size: 0.9rem; margin-bottom: 4px; }
.reply-author-rank { font-size: 0.75rem; padding: 2px 8px; border-radius: 10px; display: inline-block; }
.reply-author-posts { font-size: 0.75rem; color: var(--gray); margin-top: 8px; }
.reply-content { flex: 1; min-width: 0; }
.reply-header { display: flex; justify-content: space-between; align-items: center; margin-bottom: 12px; padding-bottom: 12px; border-bottom: 1px solid var(--gray-light); }
.reply-date { font-size: 0.85rem; color: var(--gray); }
.reply-body { line-height: 1.7; }
.reply-body p { margin-bottom: 12px; }
.reply-footer { display: flex; gap: 12px; margin-top: 16px; padding-top: 16px; border-top: 1px solid var(--gray-light); }
.reply-action { font-size: 0.85rem; color: var(--gray); cursor: pointer; }
.reply-action:hover { color: var(--primary); }
.solution-badge { background: #dcfce7; color: #166534; padding: 4px 10px; border-radius: 20px; font-size: 0.75rem; font-weight: 600; }

.reply-form { background: white; border-radius: 16px; padding: 32px; margin-top: 32px; box-shadow: 0 2px 10px rgba(0,0,0,0.05); }
.reply-form h3 { margin-bottom: 20px; font-size: 1.2rem; }
.login-prompt { text-align: center; padding: 40px; color: var(--gray); }

.pagination { display: flex; justify-content: center; gap: 8px; margin-top: 24px; }
.pagination a, .pagination span { padding: 8px 14px; border-radius: 8px; text-decoration: none; }
.pagination a { background: white; color: var(--dark); box-shadow: 0 2px 5px rgba(0,0,0,0.1); }
.pagination a:hover { background: var(--primary); color: white; }
.pagination .current { background: var(--primary); color: white; }

@media (max-width: 768px) {
    .reply-card { flex-direction: column; }
    .reply-author { width: 100%; display: flex; align-items: center; gap: 12px; text-align: left; }
    .reply-author-avatar { margin: 0; width: 48px; height: 48px; }
}
</style>

<div class="topic-page">
    <div class="breadcrumb">
        <a href="/forum/">Forum</a>
        <span>›</span>
        <a href="/forum/?category=<?= e($topic['category']) ?>"><?= $category['icon'] ?> <?= e($category['name']) ?></a>
        <span>›</span>
        <span><?= e(substr($topic['title'], 0, 30)) ?>...</span>
    </div>

    <div class="topic-header">
        <h1 class="topic-title">
            <?= e($topic['title']) ?>
            <?php if ($topic['is_pinned']): ?>
                <span class="topic-badge badge-pinned">📌 Pinned</span>
            <?php endif; ?>
            <?php if ($topic['is_locked']): ?>
                <span class="topic-badge badge-locked">🔒 Locked</span>
            <?php endif; ?>
        </h1>

        <div class="topic-meta">
            <span><?= $category['icon'] ?> <?= e($category['name']) ?></span>
            <span>👁️ <?= number_format($topic['view_count']) ?> views</span>
            <span>💬 <?= number_format($topic['reply_count']) ?> replies</span>
            <span>📅 <?= timeAgo($topic['created_at']) ?></span>
        </div>

        <div class="topic-content">
            <?= nl2br(e($topic['content'])) ?>
        </div>

        <?php if ($author):
            $author_rank = getUserRank($author['rank_level']);
        ?>
        <div class="topic-author">
            <img src="<?= e($author['avatar'] ?: '/assets/default-avatar.php') ?>" alt="" class="author-avatar">
            <div class="author-info">
                <div class="author-name">
                    <?= e($author['name']) ?>
                    <span class="author-rank" style="background: <?= $author_rank['color'] ?>20; color: <?= $author_rank['color'] ?>;">
                        <?= $author_rank['icon'] ?> <?= $author_rank['name'] ?>
                    </span>
                </div>
                <div class="author-stats">
                    <?= number_format($author['points']) ?> points • Member since <?= date('M Y', strtotime($author['created_at'] ?? 'now')) ?>
                </div>
            </div>
        </div>
        <?php endif; ?>
    </div>

    <?php if ($total_replies > 0): ?>
    <div class="replies-section">
        <div class="replies-header">
            <h2 class="replies-title">💬 <?= number_format($total_replies) ?> Replies</h2>
        </div>

        <?php foreach ($replies as $reply):
            $reply_rank = getUserRank($reply['rank_level'] ?? 0);
        ?>
        <div class="reply-card" id="reply-<?= $reply['id'] ?>">
            <div class="reply-author">
                <img src="<?= e($reply['author_avatar'] ?: '/assets/default-avatar.php') ?>" alt="" class="reply-author-avatar">
                <div>
                    <div class="reply-author-name"><?= e($reply['author_name'] ?? 'Anonymous') ?></div>
                    <span class="reply-author-rank" style="background: <?= $reply_rank['color'] ?>20; color: <?= $reply_rank['color'] ?>;">
                        <?= $reply_rank['icon'] ?> <?= $reply_rank['name'] ?>
                    </span>
                    <div class="reply-author-posts"><?= number_format($reply['author_posts'] ?? 0) ?> posts</div>
                </div>
            </div>
            <div class="reply-content">
                <div class="reply-header">
                    <span class="reply-date"><?= timeAgo($reply['created_at']) ?></span>
                    <?php if ($reply['is_solution']): ?>
                        <span class="solution-badge">✅ Solution</span>
                    <?php endif; ?>
                </div>
                <div class="reply-body">
                    <?= nl2br(e($reply['content'])) ?>
                </div>
                <div class="reply-footer">
                    <span class="reply-action">👍 Helpful (<?= $reply['helpful_count'] ?>)</span>
                    <span class="reply-action">🔗 Share</span>
                    <?php if (isLoggedIn() && getCurrentUser()['id'] == $topic['user_id'] && !$reply['is_solution']): ?>
                        <span class="reply-action">✅ Mark as Solution</span>
                    <?php endif; ?>
                </div>
            </div>
        </div>
        <?php endforeach; ?>

        <?php if ($total_pages > 1): ?>
        <div class="pagination">
            <?php if ($page > 1): ?>
                <a href="?page=<?= $page - 1 ?>">← Prev</a>
            <?php endif; ?>

            <?php for ($i = max(1, $page - 2); $i <= min($total_pages, $page + 2); $i++): ?>
                <?php if ($i == $page): ?>
                    <span class="current"><?= $i ?></span>
                <?php else: ?>
                    <a href="?page=<?= $i ?>"><?= $i ?></a>
                <?php endif; ?>
            <?php endfor; ?>

            <?php if ($page < $total_pages): ?>
                <a href="?page=<?= $page + 1 ?>">Next →</a>
            <?php endif; ?>
        </div>
        <?php endif; ?>
    </div>
    <?php endif; ?>

    <!-- Reply Form -->
    <div class="reply-form">
        <h3>💬 Post a Reply</h3>

        <?php if ($topic['is_locked']): ?>
            <div class="login-prompt">
                <p>🔒 This topic is locked and no longer accepting replies.</p>
            </div>
        <?php elseif (!isLoggedIn()): ?>
            <div class="login-prompt">
                <p>You must be logged in to reply.</p>
                <a href="/auth/login.php?redirect=<?= urlencode($_SERVER['REQUEST_URI']) ?>" class="btn btn-primary" style="margin-top: 12px;">Sign In to Reply</a>
            </div>
        <?php else: ?>
            <?php if ($error): ?>
                <div class="error-msg" style="background:#fee2e2;border:1px solid #ef4444;color:#991b1b;padding:12px;border-radius:8px;margin-bottom:16px;"><?= e($error) ?></div>
            <?php endif; ?>

            <form method="POST">
                <input type="hidden" name="csrf" value="<?= generateCSRF() ?>">
                <div class="form-group">
                    <textarea name="content" rows="5" placeholder="Write your reply..." required minlength="10"></textarea>
                </div>
                <button type="submit" class="btn btn-primary">
                    <span>📤</span> Post Reply
                </button>
            </form>
        <?php endif; ?>
    </div>
</div>

<?php include __DIR__ . '/../includes/footer.php'; ?>
