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

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

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

// Get admin settings for theme color
$themeColor = '#667eea'; // Default color
try {
    $stmt = $pdo->prepare("SELECT theme_color FROM admin LIMIT 1");
    $stmt->execute();
    $adminSettings = $stmt->fetch();
    if ($adminSettings && $adminSettings['theme_color']) {
        $themeColor = $adminSettings['theme_color'];
    }
} catch (Exception $e) {
    // Use default
}

// 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>
    <!-- Favicon -->
    <link rel="icon" type="image/png" href="../assets/logo/favicon.png">

    <!-- 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>
        :root {
            --primary-color: <?php echo $themeColor; ?>;
        }
        body {
            background: #f0f2f5;
            font-family: 'Plus Jakarta Sans', sans-serif;
        }

        .forum-header {
            background: linear-gradient(135deg, var(--primary-color), #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>
                <?php if ($forum['teacher_id'] == $_SESSION['user_id']): ?>
    <button id="pinForumBtn" onclick="togglePinForum(<?php echo $forum['id']; ?>)"
        class="btn btn-<?php echo ($forum['is_pinned'] == 'Yes' ? 'warning' : 'info'); ?> btn-sm rounded-pill px-3 me-2 shadow-sm">
        <i class="fas fa-thumbtack me-2"></i> <?php echo ($forum['is_pinned'] == 'Yes' ? 'Unpin' : 'Pin'); ?>
    </button>
    <button onclick="deleteCurrentForum()"
        class="btn btn-danger btn-sm rounded-pill px-3 ms-auto shadow-sm">
        <i class="fas fa-trash-alt me-2"></i> Padam
    </button>
<?php endif; ?>
            </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 (!empty($forum['attachment'])): ?>
                    <div class="mt-4 mb-3">
                        <h6 class="fw-bold text-secondary mb-2"
                            style="font-size: 0.9rem; text-transform: uppercase; letter-spacing: 0.5px;">Lampiran</h6>
                        <?php if (in_array(strtolower($forum['attachment_type']), ['jpg', 'jpeg', 'png'])): ?>
                            <a href="../<?php echo $forum['attachment']; ?>" target="_blank">
                                <img src="../<?php echo $forum['attachment']; ?>" class="img-fluid rounded-4 border shadow-sm"
                                    style="max-height: 400px; width: auto;">
                            </a>
                        <?php elseif (strtolower($forum['attachment_type']) === 'pdf'): ?>
                            <div class="p-3 bg-white rounded-3 border d-flex align-items-center shadow-sm"
                                style="max-width: 350px;">
                                <div class="me-3 bg-light rounded-circle d-flex align-items-center justify-content-center"
                                    style="width: 50px; height: 50px;">
                                    <i class="fas fa-file-pdf text-danger fa-lg"></i>
                                </div>
                                <div class="flex-grow-1">
                                    <h6 class="mb-0 text-dark fw-bold">Dokumen PDF</h6>
                                    <a href="../<?php echo $forum['attachment']; ?>" target="_blank"
                                        class="text-primary text-decoration-none small">Klik untuk lihat</a>
                                </div>
                                <a href="../<?php echo $forum['attachment']; ?>" download
                                    class="btn btn-light rounded-circle text-secondary">
                                    <i class="fas fa-download"></i>
                                </a>
                            </div>
                        <?php endif; ?>
                    </div>
                <?php endif; ?>
                <?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" id="reply-content-<?php echo $reply['id']; ?>">
                            <?php echo htmlspecialchars($reply['content']); ?>
                        </p>
                        <?php if ($reply['user_type'] == 'teacher' && $reply['user_id'] == $_SESSION['user_id']): ?>
                            <div class="d-flex justify-content-end mt-2">
                                <button class="btn btn-sm btn-outline-primary me-2" onclick="editReply(<?php echo $reply['id']; ?>, '<?php echo htmlspecialchars(addslashes($reply['content'])); ?>')">
                                    <i class="fas fa-edit"></i> Edit
                                </button>
                                <button class="btn btn-sm btn-outline-danger" onclick="deleteReply(<?php echo $reply['id']; ?>)">
                                    <i class="fas fa-trash-alt"></i> Padam
                                </button>
                            </div>
                        <?php endif; ?>
                        <?php if (!empty($reply['attachment'])): ?>
                            <div class="mt-3">
                                <?php if (in_array(strtolower($reply['attachment_type']), ['jpg', 'jpeg', 'png'])): ?>
                                    <a href="../<?php echo $reply['attachment']; ?>" target="_blank">
                                        <img src="../<?php echo $reply['attachment']; ?>" class="img-fluid rounded border shadow-sm"
                                            style="max-height: 300px; object-fit: cover;">
                                    </a>
                                <?php elseif (strtolower($reply['attachment_type']) === 'pdf'): ?>
                                    <div class="p-3 bg-light rounded border d-flex align-items-center" style="max-width: 300px;">
                                        <i class="fas fa-file-pdf text-danger fa-2x me-3"></i>
                                        <div class="flex-grow-1">
                                            <h6 class="mb-0 text-dark" style="font-size: 0.9rem;">Dokumen Lampiran</h6>
                                            <small class="text-muted">PDF File</small>
                                        </div>
                                        <a href="../<?php echo $reply['attachment']; ?>" target="_blank"
                                            class="btn btn-sm btn-outline-primary rounded-pill">
                                            <i class="fas fa-download"></i>
                                        </a>
                                    </div>
                                <?php endif; ?>
                            </div>
                        <?php endif; ?>
                    </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="bg-light border mb-2 px-3 py-2 rounded" id="filePreviewArea"
                    style="display:none; margin-bottom: 0 !important;">
                    <div class="d-flex justify-content-between align-items-center">
                        <small class="text-primary fw-bold"><i class="fas fa-paperclip me-1"></i> <span
                                id="fileName">File</span></small>
                        <button type="button" class="btn btn-sm text-danger p-0" onclick="removeFile()"><i
                                class="fas fa-times"></i></button>
                    </div>
                </div>
                <div class="input-group shadow-sm" style="border-radius: 12px; overflow: hidden;">
                    <button type="button" class="btn btn-light text-secondary border-0 px-3"
                        onclick="document.getElementById('attachmentInput').click()" title="Lampirkan Gambar/PDF">
                        <i class="fas fa-paperclip"></i>
                    </button>
                    <input type="file" id="attachmentInput" name="attachment" style="display: none;"
                        accept="image/jpeg,image/png,application/pdf" onchange="previewFile()">

                    <input type="text" class="form-control form-control-lg border-0 bg-light" name="reply_content"
                        id="replyContent" placeholder="Tulis balasan anda..." required>

                    <button class="btn btn-primary px-4 fw-bold" type="submit"
                        style="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 previewFile() {
            const input = document.getElementById('attachmentInput');
            if (input.files.length > 0) {
                document.getElementById('fileName').innerText = input.files[0].name;
                document.getElementById('filePreviewArea').style.display = 'block';
            }
        }

        function removeFile() {
            document.getElementById('attachmentInput').value = '';
            document.getElementById('filePreviewArea').style.display = 'none';
        }

        function submitReply(e) {
            e.preventDefault();
            const content = document.getElementById('replyContent').value;
            if (!content.trim()) return;

            const btn = e.target.querySelector('button[type="submit"]');
            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');
            formData.append('content', content);

            // Check for file
            const fileInput = document.getElementById('attachmentInput');
            if (fileInput.files.length > 0) {
                formData.append('attachment', fileInput.files[0]);
            }

            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;
                });
        }

        function deleteCurrentForum() {
            Swal.fire({
                title: 'Adakah anda pasti?',
                text: "Forum ini akan dipadam secara kekal!",
                icon: 'warning',
                showCancelButton: true,
                confirmButtonColor: '#d33',
                cancelButtonColor: '#3085d6',
                confirmButtonText: 'Ya, padam!',
                cancelButtonText: 'Batal'
            }).then((result) => {
                if (result.isConfirmed) {
                    var formData = new FormData();
                    formData.append('action', 'delete_forum');
                    formData.append('id', '<?php echo $forumId; ?>');

                    fetch('../api.php', { method: 'POST', body: formData })
                        .then(r => r.json())
                        .then(res => {
                            if (res.success) {
                                Swal.fire('Berjaya', 'Forum berjaya dipadam', 'success').then(() => {
                                    window.location.href = 'index-v2.php';
                                });
                            } else {
                                Swal.fire('Ralat', res.message, 'error');
                            }
                        })
                        .catch(e => Swal.fire('Ralat', 'Ralat sambungan', 'error'));
                }
            });
        }

        function togglePinForum(forumId) {
            Swal.fire({
                title: 'Tukar Status Pin Forum?',
                text: "Adakah anda ingin menukar status pin forum ini?",
                icon: 'question',
                showCancelButton: true,
                confirmButtonColor: '#3085d6',
                cancelButtonColor: '#d33',
                confirmButtonText: 'Ya',
                cancelButtonText: 'Batal'
            }).then((result) => {
                if (result.isConfirmed) {
                    var formData = new FormData();
                    formData.append('action', 'toggle_forum_pin');
                    formData.append('forum_id', forumId);

                    fetch('../api.php', { method: 'POST', body: formData })
                        .then(r => r.json())
                        .then(res => {
                            if (res.success) {
                                Swal.fire('Berjaya', res.message, 'success').then(() => {
                                    location.reload();
                                });
                            } else {
                                Swal.fire('Ralat', res.message, 'error');
                            }
                        })
                        .catch(e => Swal.fire('Ralat', 'Ralat sambungan', 'error'));
                }
            });
        }

        function editReply(replyId, currentContent) {
            Swal.fire({
                title: 'Edit Balasan',
                input: 'textarea',
                inputLabel: 'Kandungan Balasan',
                inputValue: currentContent,
                showCancelButton: true,
                confirmButtonText: 'Simpan',
                cancelButtonText: 'Batal',
                inputValidator: (value) => {
                    if (!value) {
                        return 'Kandungan balasan tidak boleh kosong!';
                    }
                }
            }).then((result) => {
                if (result.isConfirmed) {
                    const newContent = result.value;
                    const formData = new FormData();
                    formData.append('action', 'update_forum_reply');
                    formData.append('reply_id', replyId);
                    formData.append('content', newContent);

                    fetch('../api.php', {
                        method: 'POST',
                        body: formData
                    })
                    .then(res => res.json())
                    .then(data => {
                        if (data.success) {
                            Swal.fire('Berjaya', 'Balasan berjaya dikemas kini', 'success');
                            document.getElementById(`reply-content-${replyId}`).innerText = newContent;
                        } else {
                            Swal.fire('Ralat', data.message || 'Gagal mengemas kini balasan', 'error');
                        }
                    })
                    .catch(err => Swal.fire('Ralat', 'Ralat sambungan', 'error'));
                }
            });
        }

        function deleteReply(replyId) {
            Swal.fire({
                title: 'Adakah anda pasti?',
                text: "Balasan ini akan dipadam secara kekal!",
                icon: 'warning',
                showCancelButton: true,
                confirmButtonColor: '#d33',
                cancelButtonColor: '#3085d6',
                confirmButtonText: 'Ya, padam!',
                cancelButtonText: 'Batal'
            }).then((result) => {
                if (result.isConfirmed) {
                    const formData = new FormData();
                    formData.append('action', 'delete_forum_reply');
                    formData.append('reply_id', replyId);

                    fetch('../api.php', {
                        method: 'POST',
                        body: formData
                    })
                    .then(res => res.json())
                    .then(data => {
                        if (data.success) {
                            Swal.fire('Berjaya', 'Balasan berjaya dipadam', 'success').then(() => {
                                location.reload();
                            });
                        } else {
                            Swal.fire('Ralat', data.message || 'Gagal memadam balasan', 'error');
                        }
                    })
                    .catch(err => Swal.fire('Ralat', 'Ralat sambungan', 'error'));
                }
            });
        }
    </script>
</body>

</html>