<?php
error_reporting(E_ALL);
ini_set('display_errors', 1);

if (session_status() === PHP_SESSION_NONE) {
    session_start();
}

require_once dirname(__DIR__) . '/db.php';

// Check teacher session
if (!isset($_SESSION['user_type']) || $_SESSION['user_type'] !== 'teacher') {
    header('Location: ../index.php');
    exit;
}

$forumId = isset($_GET['id']) ? (int) $_GET['id'] : 0;

if ($forumId <= 0) {
    die("<h1>Topik tidak dijumpai.</h1><a href='index-v2.php'>Kembali ke Dashboard</a>");
}

// Fetch Forum Details
$stmt = $pdo->prepare("SELECT f.*, t.full_name as author_name, t.profile_emoji 
                       FROM forums f 
                       JOIN teachers t ON f.teacher_id = t.id 
                       WHERE f.id = ?");
$stmt->execute([$forumId]);
$forum = $stmt->fetch();

if (!$forum) {
    die("<h1>Topik tidak wujud.</h1><a href='index-v2.php'>Kembali ke Dashboard</a>");
}

// Fetch Replies
$stmtReply = $pdo->prepare("
    SELECT r.*, 
    CASE 
        WHEN r.user_type = 'driver' THEN 'Pemandu' -- Adjust if needed
        WHEN r.user_type = 'teacher' THEN t.full_name
        WHEN r.user_type = 'student' THEN s.full_name
        ELSE 'Pengguna'
    END as reply_author,
    CASE 
        WHEN r.user_type = 'teacher' THEN t.profile_emoji
        WHEN r.user_type = 'student' THEN s.profile_emoji
        ELSE '👤'
    END as reply_emoji
    FROM forum_replies r 
    LEFT JOIN teachers t ON r.user_id = t.id AND r.user_type = 'teacher'
    LEFT JOIN students s ON r.user_id = s.id AND r.user_type = 'student'
    WHERE r.forum_id = ? 
    ORDER BY r.created_at ASC
");
$stmtReply->execute([$forumId]);
$replies = $stmtReply->fetchAll();
?>

<!DOCTYPE html>
<html lang="ms">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>
        <?php echo htmlspecialchars($forum['title']); ?> - TutorKita
    </title>
    <!-- CSS -->
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.2/dist/css/bootstrap.min.css" rel="stylesheet">
    <link href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css" rel="stylesheet">
    <link
        href="https://fonts.googleapis.com/css2?family=Outfit:wght@300;400;500;600;700;800&family=Plus+Jakarta+Sans:wght@300;400;500;600;700&display=swap"
        rel="stylesheet">
    <link href="../css/style.css" rel="stylesheet">
    <script src="https://cdn.jsdelivr.net/npm/sweetalert2@11"></script>
    <style>
        body {
            background: #f0f2f5;
            font-family: 'Plus Jakarta Sans', sans-serif;
        }

        .forum-header {
            background: linear-gradient(135deg, #667eea, #764ba2);
            padding: 40px 0;
            color: white;
            margin-bottom: 30px;
            border-radius: 0 0 30px 30px;
            box-shadow: 0 10px 30px rgba(102, 126, 234, 0.2);
        }

        .reply-card {
            border: none;
            border-radius: 20px;
            box-shadow: 0 5px 15px rgba(0, 0, 0, 0.05);
            margin-bottom: 20px;
            transition: transform 0.2s;
        }

        .reply-card:hover {
            transform: translateY(-3px);
        }

        .author-avatar {
            width: 50px;
            height: 50px;
            background: #eef2ff;
            border-radius: 50%;
            display: flex;
            align-items: center;
            justify-content: center;
            font-size: 24px;
            margin-right: 15px;
        }

        .teacher-badge {
            background: #e0e7ff;
            color: #4338ca;
            padding: 3px 8px;
            border-radius: 6px;
            font-size: 12px;
            font-weight: 700;
        }

        .reply-box {
            position: fixed;
            bottom: 0;
            left: 0;
            right: 0;
            background: white;
            padding: 20px;
            box-shadow: 0 -5px 20px rgba(0, 0, 0, 0.05);
            z-index: 100;
        }

        .content-container {
            padding-bottom: 100px;
        }

        .back-btn {
            background: rgba(255, 255, 255, 0.2);
            color: white;
            padding: 10px 20px;
            border-radius: 12px;
            text-decoration: none;
            backdrop-filter: blur(5px);
            transition: all 0.3s;
        }

        .back-btn:hover {
            background: rgba(255, 255, 255, 0.3);
            color: white;
        }
    </style>
</head>

<body>

    <!-- Header -->
    <div class="forum-header">
        <div class="container">
            <div class="d-flex align-items-center mb-4">
                <a href="index-v2.php" class="back-btn me-3">
                    <i class="fas fa-arrow-left me-2"></i> Kembali
                </a>
                <span class="badge bg-white text-primary rounded-pill px-3 py-2 fw-bold">
                    <?php echo htmlspecialchars($forum['subject']); ?>
                </span>
            </div>
            <h1 class="fw-bold mb-2">
                <?php echo htmlspecialchars($forum['title']); ?>
            </h1>
            <div class="d-flex align-items-center mt-3">
                <div class="d-flex align-items-center me-4">
                    <div class="author-avatar" style="width: 30px; height: 30px; font-size: 16px;">
                        <?php echo $forum['profile_emoji']; ?>
                    </div>
                    <span class="ms-2 opacity-75">Oleh Cikgu
                        <?php echo htmlspecialchars($forum['author_name']); ?>
                    </span>
                </div>
                <div class="opacity-75">
                    <i class="far fa-clock me-1"></i>
                    <?php echo date('d M Y, h:i A', strtotime($forum['created_at'])); ?>
                </div>
            </div>
        </div>
    </div>

    <div class="container content-container">
        <!-- Main Post -->
        <div class="card reply-card border-primary border-2">
            <div class="card-body p-4">
                <div class="d-flex mb-3">
                    <div class="author-avatar">
                        <?php echo $forum['profile_emoji']; ?>
                    </div>
                    <div>
                        <h5 class="fw-bold mb-0">Cikgu
                            <?php echo htmlspecialchars($forum['author_name']); ?>
                        </h5>
                        <span class="teacher-badge">PENTADBIR</span>
                    </div>
                </div>
                <div class="fs-5 text-dark" style="line-height: 1.7; white-space: pre-wrap;">
                    <?php echo htmlspecialchars($forum['content']); ?>
                </div>
                <?php if ($forum['link']): ?>
                    <div class="mt-3 p-3 bg-light rounded-3 border">
                        <i class="fas fa-link me-2 text-primary"></i>
                        <a href="<?php echo htmlspecialchars($forum['link']); ?>" target="_blank"
                            class="text-decoration-none fw-bold">Pautan Lampiran</a>
                    </div>
                <?php endif; ?>
            </div>
        </div>

        <h5 class="mt-5 mb-3 fw-bold text-secondary">Balasan (
            <?php echo count($replies); ?>)
        </h5>

        <!-- Replies List -->
        <div id="replyList">
            <?php foreach ($replies as $reply): ?>
                <div class="card reply-card">
                    <div class="card-body p-4">
                        <div class="d-flex mb-3">
                            <div class="author-avatar bg-light text-dark">
                                <?php echo $reply['reply_emoji']; ?>
                            </div>
                            <div>
                                <h6 class="fw-bold mb-0">
                                    <?php echo htmlspecialchars($reply['reply_author']); ?>
                                </h6>
                                <small class="text-muted">
                                    <?php echo strtolower($reply['user_type']) == 'teacher' ? 'GURU' : 'PELAJAR'; ?> •
                                    <?php echo date('d M, h:i A', strtotime($reply['created_at'])); ?>
                                </small>
                            </div>
                        </div>
                        <p class="mb-0 text-secondary">
                            <?php echo htmlspecialchars($reply['content']); ?>
                        </p>
                    </div>
                </div>
            <?php endforeach; ?>

            <?php if (empty($replies)): ?>
                <div class="text-center py-5 text-muted">
                    <i class="far fa-comments fa-3x mb-3 opacity-50"></i>
                    <p>Belum ada balasan. Jadilah yang pertama!</p>
                </div>
            <?php endif; ?>
        </div>
    </div>

    <!-- Reply Box -->
    <div class="reply-box">
        <div class="container">
            <form id="replyForm" onsubmit="submitReply(event)">
                <input type="hidden" name="forum_id" value="<?php echo $forumId; ?>">
                <div class="input-group">
                    <input type="text" class="form-control form-control-lg border-0 bg-light" name="reply_content"
                        id="replyContent" placeholder="Tulis balasan anda..." required
                        style="border-radius: 12px 0 0 12px; padding-left: 20px;">
                    <button class="btn btn-primary px-4 fw-bold" type="submit"
                        style="border-radius: 0 12px 12px 0; background: linear-gradient(135deg, #667eea, #764ba2); border: none;">
                        <i class="fas fa-paper-plane me-2"></i> Hantar
                    </button>
                </div>
            </form>
        </div>
    </div>

    <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
    <script>
        function submitReply(e) {
            e.preventDefault();
            const content = document.getElementById('replyContent').value;
            if (!content.trim()) return;

            const btn = e.target.querySelector('button');
            const originalText = btn.innerHTML;
            btn.innerHTML = '<i class="fas fa-spinner fa-spin"></i>';
            btn.disabled = true;

            const formData = new FormData(e.target);
            formData.append('action', 'add_forum_reply');
            // Assuming user_id and type are handled by session in API
            formData.append('user_id', '<?php echo $_SESSION['user_id']; ?>');
            formData.append('user_type', 'teacher');
            formData.append('content', content);

            fetch('../api.php', {
                method: 'POST',
                body: formData
            })
                .then(res => res.json())
                .then(data => {
                    if (data.success) {
                        location.reload();
                    } else {
                        Swal.fire('Ralat', data.message || 'Gagal menghantar balasan', 'error');
                    }
                })
                .catch(err => Swal.fire('Ralat', 'Ralat sambungan', 'error'))
                .finally(() => {
                    btn.innerHTML = originalText;
                    btn.disabled = false;
                });
        }
    </script>
</body>

</html>