<?php
// start session 
session_start();
    // connect to database
    include 'config/database.php';
    include_once "security/session_config.php";
    include_once "security/csrf.php";
    
    include_once 'config/properties.php';
    include_once "resources/manageusers.php";
    include_once "resources/EncryptDecrypt.php";
    include_once "resources/forum.php";

    $csrf_token=get_csrf_token();

    // initialize objects
    $users = new ManageUsers();
    $forum = new Forum();

    // set page title
    $page_no = 9;
    $user_id = $_SESSION['uid'];
    $users->user_id = $_SESSION['uid'];
    ?>
    <html>

        <head>
            <meta name="csrf-token" content="<?= htmlspecialchars($csrf_token) ?>">
            <?php include "./head.php" ?>
            <title>
                <?php echo _("FR0134"); ?>
            </title>
            <link rel="stylesheet" href="assets/css/forum/style.css">
        </head>

        <body>
            <?php include "./menu_primary.php"; ?>

            <div class="container pb-90 x-gap-50 bg-primary-opacity-1 rounded-16 mb-50">

                <div class="row px-20">
                    <div class="d-flex justify-between rounded-16 bg-white -dark-bg-dark-1 shadow-4 py-15 mt-20 action_btn">
                        <div class="col-md-7 pl-0 first_sect">
                            <!-- <button class="button h-50 px-30 -purple-1 text-white post_qus"><?php echo _("FR0105") ?></button>
                            <div class="clearfix"></div> -->
                            <div style="display: flex; gap: 10px;">

                                <button class="button h-50 px-30 -purple-1 text-white " onclick="showNormalForm()">
                                    <?php echo _("FR0105") ?>
                                </button>
                                <?php
                                $ai = $users->getUserConfig('ai_enable_forum');
                                if ($ai == "Yes") {
                                ?>
                                    <button class="button h-50 px-30 -purple-1 text-white ask_ai" onclick="showAIForm()">
                                        <?php echo _("FR0135") ?>
                                    </button>
                                <?php } ?>
                            </div>
                            <!-- <form class="contact-form col-md-12 px-0 mt-20 post-forum">
                                <label class="text-16 lh-1 fw-500 text-dark-1 mb-10"><?php echo _("FR0106") ?></label>
                                <div>
                                    <select style="padding: 10px 22px;" id="course_name">
                                        <option value=""><?php echo _("FR0115"); ?></option>
                                        <option value="General">General</option>
                                        <?php
                                        $stmt = $forum->get_topic_names($user_id);
                                        while ($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
                                            ?>
                                            <option value="<?php echo htmlentities($row['course_name']); ?>"><?php echo htmlentities($row['course_name']); ?></option>
                                        <?php } ?>
                                    </select>
                                    <div id="topic_name_empty"  class="text-red-1 ml-5 mb-5 message"><?php echo _("FR0501") ?></div>
                                </div>

                                <label class="text-16 lh-1 fw-500 text-dark-1 mb-10 mt-10"><?php echo _("FR0101"); ?></label>
                                <div>
                                    <input type="text" placeholder="<?php echo _("FR0113"); ?>" id="question_title"
                                           style="padding: 10px 22px;" maxlength="200">
                                    <div id="question_length_empty" class="text-red-1 ml-5 mb-5 message"><?php echo _("FR0502") ?></div>
                                </div>

                                <label class="text-16 lh-1 fw-500 text-dark-1 mb-10 mt-10"><?php echo _("FR0102"); ?></label>
                                <div>
                                    <textarea type="text" placeholder="<?php echo _("FR0114"); ?>" id="question_desc"
                                              style="padding: 10px 22px;" rows="4" maxLength="65535"></textarea>
                                    <div id="question_length_empty1" class="text-red-1 ml-5 mb-5 message"><?php echo _("FR0503"); ?></div>
                                </div>

                                <div class="d-flex justify-start">
                                    <button class="button h-40 px-40 bg-color-primary mt-20 text-white" id="submit"><i class="fa fa-spinner fa-spin" id="loader"></i><?php echo _("FR0104") ?></button>
                                    <button class="button h-40 px-40 bg-color-secondary mt-20 text-white ml-5 close-forum"><?php echo _("AS0156"); ?></button>
                                </div>
                            </form> -->
                            <div id="form-wrapper">
                                <form class="contact-form col-md-12 px-0 mt-20 post-forum">
                                    <label class="text-16 lh-1 fw-500 text-dark-1 mb-10"><?php echo _("FR0106") ?></label>
                                    <div>
                                        <select style="padding: 10px 22px;" id="course_name">
                                            <option value=""><?php echo _("FR0115"); ?></option>
                                            <option value="General">General</option>
                                            <?php
                                            $stmt = $forum->get_topic_names($user_id);
                                            while ($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
                                            ?>
                                                <option value="<?php echo htmlentities($row['course_name']); ?>"><?php echo htmlentities($row['course_name']); ?></option>
                                            <?php } ?>
                                        </select>
                                        <div id="topic_name_empty" class="text-red-1 ml-5 mb-5 message"><?php echo _("FR0501") ?></div>
                                    </div>

                                    <label class="text-16 lh-1 fw-500 text-dark-1 mb-10 mt-10"><?php echo _("FR0101"); ?></label>
                                    <div>
                                        <input type="text" placeholder="<?php echo _("FR0113"); ?>" id="question_title"
                                            style="padding: 10px 22px;" maxlength="200">
                                        <div id="question_length_empty" class="text-red-1 ml-5 mb-5 message"><?php echo _("FR0502") ?></div>
                                    </div>

                                    <label class="text-16 lh-1 fw-500 text-dark-1 mb-10 mt-10"><?php echo _("FR0102"); ?></label>
                                    <div>
                                        <textarea type="text" placeholder="<?php echo _("FR0114"); ?>" id="question_desc"
                                            style="padding: 10px 22px;" rows="4" maxLength="65535"></textarea>
                                        <div id="question_length_empty1" class="text-red-1 ml-5 mb-5 message"><?php echo _("FR0503"); ?></div>
                                    </div>

                                    <div class="d-flex justify-start">
                                        <button class="button h-40 px-40 bg-color-primary mt-20 text-white" id="submit"><i class="fa fa-spinner fa-spin" id="loader"></i><?php echo _("FR0104") ?></button>
                                        <button class="button h-40 px-40 bg-color-secondary mt-20 text-white ml-5 close-forum"><?php echo _("AS0156"); ?></button>
                                    </div>
                                </form>
                                <?php
                                $ai = $users->getUserConfig('ai_enable_forum');
                                if ($ai == "Yes") {
                                ?>
                                    <form class="contact-form col-md-12 px-0 mt-20 post-forum-ai" style="display: none;">
                                        <label class="text-16 lh-1 fw-500 text-dark-1 mb-10"><?php echo _("FR0106") ?></label>
                                        <div>
                                            <select style="padding: 10px 22px;" id="course_name">
                                                <option value=""><?php echo _("FR0115"); ?></option>

                                                <?php
                                                $stmt = $forum->get_course_content_grouped($user_id);
                                                $courseContentMap = [];
                                                $addedCourses = [];

                                                while ($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
                                                    $courseId = $row['course_id'];
                                                    $courseName = $row['course_name'];
                                                    $offeringId = $row['offering_id'];
                                                    $contentDtlId = $row['contentdtl_id'];

                                                    // Build JS data map
                                                    if (!isset($courseContentMap[$courseId])) {
                                                        $courseContentMap[$courseId] = [
                                                            'offering_id' => $offeringId,
                                                            'contentdtl_ids' => []
                                                        ];
                                                    }
                                                    $courseContentMap[$courseId]['contentdtl_ids'][] = $contentDtlId;

                                                    // Output <option> only if the course hasn't been added yet
                                                    if (!in_array($courseId, $addedCourses)) {
                                                        echo '<option value="' . htmlentities($courseId) . '">' . htmlentities($courseName) . '</option>';
                                                        $addedCourses[] = $courseId; // Mark this course as added
                                                    }
                                                }

                                                ?>

                                            </select>
                                            <div id="topic_name_empty" class="text-red-1 ml-5 mb-5 message"><?php echo _("FR0501"); ?></div>
                                        </div>

                                        <label class="text-16 lh-1 fw-500 text-dark-1 mb-10 mt-10"><?php echo _("FR0102"); ?></label>
                                        <div>
                                            <textarea placeholder="<?php echo _("FR0114"); ?>" id="question_desc" style="padding: 10px 22px;" rows="4" maxLength="65535"></textarea>
                                            <div id="question_length_empty1" class="text-red-1 ml-5 mb-5 message"><?php echo _("FR0503"); ?></div>
                                        </div>

                                        <div class="d-flex justify-start">
                                            <button class="button h-40 px-40 bg-color-primary mt-20 text-white" id="submit_ai">
                                                <i class="fa fa-spinner fa-spin" id="loader" style="display: none;"></i>Ask AI
                                            </button>
                                            <button class="button h-40 px-40 bg-color-secondary mt-20 text-white ml-5 close-forum">Cancel</button>
                                        </div>

                                    </form>
                                    
                                <?php } ?>
                            </div>
                        </div>
                        <div class="col-md-5 second_sect pb-10">
                            <a href="#" class="text-16 px-5 text-blue-3 forum_rules_tag py-5" style="position: absolute; right: 0;"><?php echo _("FR0120"); ?></a>
                            <div class="rules_discussion_forum mt-25">
                                <ol id="rules" class="px-5">
                                    <li><?php echo _("FR0124"); ?></li>
                                    <li><?php echo _("FR0125"); ?></li>
                                    <li><?php echo _("FR0126"); ?></li>
                                    <li><?php echo _("FR0127"); ?></li>
                                    <li><?php echo _("FR0128"); ?></li>
                                    <li><?php echo _("FR0129"); ?></li>
                                    <li><?php echo _("FR0130"); ?></li>
                                    <li><?php echo _("FR0131"); ?></li>
                                    <li><?php echo _("FR0132"); ?></li>
                                    <li><?php echo _("FR0133"); ?></li>    
                                </ol>
                            </div>
                        </div>
                    </div>

                    <div class="rounded-16 bg-white -dark-bg-dark-1 shadow-4 mt-20 px-5 py-5">

                        <div class="tabs -active-primary js-tabs rounded-8">
                            <div class="d-flex justify-end forum_main_flex">
                                <div class="tabs__controls d-flex js-tabs-controls bg-white rounded-top-8">
                                    <button class="tabs__button  text-16 py-10 px-20 is-active-tab"
                                            type="button" id="all_questions">
                                                <?php echo _("FR0108"); ?>
                                    </button>
                                    <button class="tabs__button  text-16 py-10 px-20"
                                            type="button" id="my_questions">
                                                <?php echo _("FR0109"); ?>
                                    </button>
                                </div>
                                <div class="d-flex justify-between forum_main_flex">
                                    <a href="javascript:;" class="button -icon bg-color-primary text-white" id="refresh"
                                       style="min-width: 50px;height: 44px;">
                                        <i class="fa fa fa-refresh text-13"></i>
                                    </a>
                                    <form class="contact-form mb-0 ml-5" style="width:200px;">
                                        <input type="text" placeholder="Search..." class="text-16" autocomplete='off'
                                               style="padding: 10px 22px;" id="search">
                                    </form>

                                    <select class="form-control text-16 ml-5 rounded-8" id="course_name1" name="course_name1"
                                            style="width: 200px !important;text-overflow: ellipsis;height: 45px;">
                                                <?php
                                                $stmt = $forum->get_forum_topic_name($user_id);
                                                if ($stmt->rowCount() > 0) {
                                                    ?>
                                            <option value=""><?php echo _("FR0121") ?></option>
                                        <?php }while ($row = $stmt->fetch(PDO::FETCH_ASSOC)) { ?>
                                            <option value="<?php echo htmlentities($row['topic_name']); ?>"><?php echo htmlentities($row['topic_name']); ?></option>
                                        <?php } ?>
                                    </select>
                                </div>
                            </div>

                            <div class="tabs__content js-tabs-content bg-white pt-10 col-md-12 pb-50 px-10">
                                <div class="form_view"></div>
                                <div class="d-flex justify-center pt-30 pb-10">
                                    <button class="text-purple-1 lh-12 underline fw-500 load_discussions"><?php echo _("FR0112"); ?></button>
                                </div>
                                <input type="hidden" value="<?php echo $user_id ?>" name="user_id" id="user_id">
                            </div>
                        </div>

                    </div>
                </div>
            </div>


            <?php include "./footer_primary.php"; ?>
            <script type='text/javascript' src="assets/js/jquery.highlight.js"></script>
            <script>
                // You need to extract this data from PHP to JS

                var courseContentData = <?php echo json_encode($courseContentMap); ?>;

                Object.keys(courseContentData).forEach(courseId => {
                    const entry = courseContentData[courseId];
                    entry.contentdtl_ids = [...new Set(entry.contentdtl_ids)];
                });
                // console.log(courseContentData);

                function showNormalForm() {
                    const wrapper = document.getElementById("form-wrapper");
                    const normalForm = document.querySelector(".post-forum");
                    const aiForm = document.querySelector(".post-forum-ai");

                    normalForm.style.display = "block";
                    if (aiForm) aiForm.style.display = "none";

                    wrapper.prepend(normalForm);
                }

                function showAIForm() {
                    const wrapper = document.getElementById("form-wrapper");
                    const normalForm = document.querySelector(".post-forum");
                    const aiForm = document.querySelector(".post-forum-ai");

                    if (!aiForm) return;

                    aiForm.style.display = "block";
                    normalForm.style.display = "none";

                    wrapper.prepend(aiForm);
                }

                $(".close-forum").click(function() {
                    $(".post-forum").hide();
                });

                $("#submit_ai").click(function(e) {
                    e.preventDefault();
                    page = 1;
                    var submitForm = true;
                    var input = this;
                    input.disabled = true;
                    $("#loader").show();

                    var topic_name = $('#course_name option:selected').text();
                    var topic_name_value = $('#course_name').val();
                    var question_desc = $('#question_desc').val().trim();

                    if (question_desc === "" || question_desc.length < 10 || question_desc.length > 65535) {
                        $('#question_length_empty1').show();
                        submitForm = false;
                    } else {
                        $('#question_length_empty1').hide();
                    }

                    if (topic_name === "") {
                        $('#topic_name_empty').show();
                        submitForm = false;
                    } else {
                        $('#topic_name_empty').hide();
                    }

                    if (!submitForm) {
                        $("#loader").hide();
                        input.disabled = false;
                        return;
                    }
                    const csrf_token = $('meta[name="csrf-token"]').attr('content');
                    var offering_id = "";
                    $.ajax({
                        url: 'forum/new_topic_ai.php',
                        data: {"topic_name": topic_name,"question_desc": question_desc,"csrf_token": csrf_token},
                        type: 'POST',
                        dataType: 'json',
                        success: function(response) {
                            // $('#question_desc').val('');
                            // $('#course_name').val('');
                            $('#course_name1').find('option').remove();
                            $('#course_name1').append(response.options);

                            const offering_id = courseContentData[topic_name_value]?.offering_id;
                            const contentdtl_ids = courseContentData[topic_name_value]?.contentdtl_ids;

                            if (!offering_id || !contentdtl_ids || !Array.isArray(contentdtl_ids)) {
                                alert("Invalid course content mapping.");
                                $("#loader").hide();
                                input.disabled = false;
                                return;
                            }
                            $.ajax({
                                url: 'modules/ask_ai.php',
                                method: 'POST',
                                dataType: 'json',
                                data: {
                                    mode: 'content',
                                    offer: offering_id,
                                    ids: contentdtl_ids,
                                    user_input: question_desc,
                                    csrf_token: csrf_token
                                },

                                success: function(data) {

                                    $.ajax({
                                        url: 'forum/new_reply.php',
                                        method: 'POST',
                                        data: {
                                            topic_id: response.tid, // topic_id must be available from previous AJAX response
                                            topic_res_user: data.response,
                                            mode: "ai",
                                            csrf_token: csrf_token
                                        },

                                        success: function(replyInsertStatus) {
                                            // console.log("AI reply inserted:", replyInsertStatus);
                                            $('#loader').hide();
                                            readDiscussions('', '', page, false, 1);
                                            page++;
                                            input.disabled = false;
                                            $('#all_questions').addClass('is-active-tab');
                                            $('#my_questions').removeClass('is-active-tab');
                                        },


                                        error: function(xhr, status, error) {
                                            console.error("Failed to insert AI reply:", error);
                                        }
                                    });
                                },
                            });
                        },
                        error: function() {
                            alert("<?php echo _("GN0401") ?>");
                            input.disabled = false;
                        }
                    });

                });
            </script>
            <script type="text/javascript">
                $(document).ready(function() {
                    $('.ask_ai').click(function() {
                        $(".post-forum-ai").css("display", "block");
                    });
                });
                $(".post_qus").click(function () {
                    $(".post-forum").css("display", "block");
                });

                $(".close-forum").click(function () {
                    $(".post-forum").css("display", "block");
                });

                $(".forum_rules_tag").hover(
                        function () {
                            $(".rules_discussion_forum").css("display", "block");
                        }, function () {
                    $(".rules_discussion_forum").css("display", "none");
                }
                );

                $('#course_name1>option').each(function () {
                    var text = $(this).text();
                    $(this).attr("title", text);
                    if (text.length > 20) {
                        text = text.substring(0, 19) + '...';
                        $(this).text(text);
                    }
                });


                var page = 1;
                $(document).ready(function () {
                    $('#loader').hide();
                    readDiscussions('', '', page, false, 0);
                    page++;


                    $('#search').keyup(function () {
                        var text = $(this).val();
                        $('.topic').hide();
                        $('.topic:contains("' + text + '")').closest('.topic').show();
                        $('.qus_title').each(function () {
                            $(this).unhighlight();
                            $(this).highlight(text);
                        });
                        $('.qus_desc').each(function () {
                            $(this).unhighlight();
                            $(this).highlight(text);
                        });
                        $('.reply_desc').each(function () {
                            $(this).unhighlight();
                            $(this).highlight(text);
                        });
                        $('.forumuser').each(function () {
                            $(this).unhighlight();
                            $(this).highlight(text);
                        });
                    });
                    $.expr[":"].contains = $.expr.createPseudo(function (arg) {
                        return function (elem) {
                            return $(elem).text().toUpperCase().indexOf(arg.toUpperCase()) >= 0;
                        };
                    });
                });


                $("#submit").click(function (e) {
                    e.preventDefault();
                    page = 1;
                    var submitForm = true;
                    var input = this;
                    input.disabled = true;
                    var topic_name = $('#course_name').val();
                    var question_title = $('#question_title').val();
                    var question_desc = $('#question_desc').val().trim();

                    if (question_title === "") {
                        $('#question_length_empty').show();
                        submitForm = false;
                    } else {
                        $('#question_length_empty').hide();
                    }
                    if (question_desc === "" || question_desc.length < 10 || question_desc.length > '65535') {
                        $('#question_length_empty1').show();
                        submitForm = false;
                    } else {
                        $('#question_length_empty1').hide();
                    }
                    if (topic_name === "")
                    {
                        $('#topic_name_empty').show();
                        submitForm = false;
                    } else {
                        $('#topic_name_empty').hide();
                    }
                    if (!submitForm) {
                        $('#loader').hide();
                        input.disabled = false;
                        return false;

                    }
                    const csrf_token = $('meta[name="csrf-token"]').attr('content');

                    $.ajax({
                        url: 'forum/new_topic.php',
                        data: {"topic_name": topic_name, "question_title": question_title, "question_desc": question_desc, "csrf_token": csrf_token},
                        type: 'POST',
                        success: function (data1) {
                            $('#question_title').val('');
                            $('#question_desc').val('');
                            $('#course_name').val('');
                            $('#loader').hide();
                            readDiscussions('', '', page, false, 1);
                            page++;
                            //need to check weather it works
                            $('#course_name1').find('option').remove();
                            $('#course_name1').append(data1);
                            input.disabled = false;
                            //                            $('#course_name1').val('');
                            $('#all_questions').addClass('is-active-tab');
                            $('#my_questions').removeClass('is-active-tab');
                        },
                        error: function () {
                            alert("<?php echo _("GN0401") ?>");
                            input.disabled = false;
                        }
                    });
                });

                function reply(input, value)
                {
                    var topic_id = value;
                    $('#loader' + topic_id + '').show();
                    input.disabled = true;
                    var topic_res_user = $('#topic_res_user_' + value + '').val();
                    if (topic_res_user === "")
                    {
                        $('#reply_length_empty' + value + '').fadeIn('slow', function () {
                            $('#reply_length_empty' + value + '').delay(5000).fadeOut();
                        });
                        $('#loader' + topic_id + '').hide();
                        input.disabled = false;
                        return false;
                    }
                    var replyLength = $('#topic_res_user_' + value + '').val().length;
                    if (replyLength > '65535')
                    {
                        $('#loader' + topic_id + '').hide();
                        input.disabled = false;
                        return false;
                    }
                    const csrf_token = $('meta[name="csrf-token"]').attr('content');
                    
                    $.ajax({
                        url: 'forum/new_reply.php',
                        data: {"topic_id": topic_id, "topic_res_user": topic_res_user, "csrf_token": csrf_token},
                        type: 'POST',
                        success: function () {
                            ajaxSuccess();
                        },
                        error: function () {
                            alert("<?php echo _("GN0401") ?>");
                            $('#loader' + topic_id + '').hide();
                            input.disabled = false;
                        }
                    });
                }
                $("#all_questions").click(function () {
                    page = 1;
                    $('#all_questions').addClass('is-active-tab');
                    $('#my_questions').removeClass('is-active-tab');
                    var topic_name = $('#course_name1').val();
                    readDiscussions(topic_name, '', page, false, 0);
                    page++;
                });
                $("#my_questions").click(function () {
                    page = 1;
                    var topic_name = $('#course_name1').val();
                    var user_id = $('#user_id').val();
                    $('#all_questions').removeClass('is-active-tab');
                    $('#my_questions').addClass('is-active-tab');
                    readDiscussions(topic_name, user_id, page, false, 0);
                    page++;
                });

                $('select[name=course_name1]').change(function () {
                    var topic_name = $('#course_name1').val();
                    var user_id = "";
                    if ($("#my_questions").hasClass("is-active-tab"))
                    {
                        user_id = $('#user_id').val();
                    }
                    readDiscussions(topic_name, user_id, 1, false, 0);
                    if (topic_name === "")
                    {
                        $('#course_name1').attr({"title": "All Topics"});
                    } else {
                        $('#course_name1').attr({"title": topic_name});
                    }
                });

                $('#refresh').click(function () {
                    $this = $(this);
                    $(this).addClass('fa-spin');
                    $('#search').val('');
                    var topic_name = $('#course_name1').val();
                    var user_id = "";
                    if ($("#my_questions").hasClass("is-active-tab")) {
                        user_id = $('#user_id').val();
                    }
                    $this.removeClass('fa-spin');
                    readDiscussions(topic_name, user_id, 1, false, 0);
                });

                function topicEdit(event, id) {
                    var v_title = $(event).closest(".topic").find(".qus_title");
                    var v_desc = $(event).closest(".topic").find(".qus_desc");
                   
                    var value_title = $(v_title).html();
                    var value_desc = $(v_desc).html();
                    $(v_title).replaceWith($('<input type="text" class="form-control forum_qus_title" id="topicTitle" autocomplete="off" value="' + value_title + '" maxlength="200">'));
                    $(v_desc).replaceWith($('<textarea class="form-control forum_qus_desc" id="topicDesc" autocomplete="off" rows="7"  maxlength="65535">' + value_desc + '</textarea>'));
                    var button = $(event).closest(".topic").find(".action_buttons");
                    $(button).removeClass('action_buttons');
                    $(button).addClass('action_buttons_block');
                    //                    // $(button).css({"display": "block"});
                    var v1 = $(event).closest(".topic").find(".topic_submit");
                    var v2 = $(event).closest(".topic").find(".topic_cancel");
                    $(v1).click(function () {
                        var resp = $(event).closest(".topic").find('#topicTitle').val().trim();
                        value_title = resp;
                        var resp1 = $(event).closest(".topic").find('#topicDesc').val().trim();
                        value_desc = resp1;
                        if (resp === "") {
                            $('#question_length_empty' + id + '').fadeIn('slow', function () {
                                $('#question_length_empty' + id + '').delay(5000).fadeOut();
                            });
                            return false;
                        } else if (resp1 === "") {
                            $('#question_length_empty' + id + '').fadeIn('slow', function () {
                                $('#question_length_empty' + id + '').delay(5000).fadeOut();
                            });
                            return false;
                        } else {
                            value_title = resp;
                            value_desc = resp1;
                            const csrf_token = $('meta[name="csrf-token"]').attr('content');
                            $.ajax({
                                url: 'forum/edit_topic.php',
                                data: {"question_title": resp, "question_desc": resp1, "topic_id": id, "csrf_token": csrf_token},
                                type: 'POST',
                                success: function (data) {
                                    if (data) {
                                        var v_replace = $(event).closest(".topic").find("#topicTitle");
                                        $(v_replace).replaceWith($('<pre class="qus_title"></pre>'));
                                        $(event).closest(".topic").find(".qus_title").text(resp);
                                        var v_replace1 = $(event).closest(".topic").find("#topicDesc");
                                        $(v_replace1).replaceWith($('<pre class="qus_desc"></pre>'));
                                        $(event).closest(".topic").find(".qus_desc").text(resp1);
                                        // $(button).css({"display": "none"});
                                        $(button).removeClass('action_buttons_block');
                                        $(button).addClass('action_buttons');
                                    }
                                },
                                error: function () {
                                    alert("<?php echo _("GN0401") ?>");
                                }
                            });
                        }
                    });
                    $(v2).click(function () {
                        var v_replace = $(event).closest(".topic").find("#topicTitle");
                        $(v_replace).replaceWith($('<pre class="qus_title">' + value_title + '</pre>'));
                        var v_replace1 = $(event).closest(".topic").find("#topicDesc");
                        $(v_replace1).replaceWith($('<pre class="qus_desc">' + value_desc + '</pre>'));
                        $(button).removeClass('action_buttons_block');
                        $(button).addClass('action_buttons');
                        //$(button).css({"display": "none"});
                    });
                }


                function topicDelete(event, id) {
                    if (confirm("<?php echo _("FR0301") ?>") == true) {
                        const csrf_token = $('meta[name="csrf-token"]').attr('content');
                        $.ajax({
                            url: 'forum/delete_topic.php',
                            data: {"topic_id": id, "csrf_token": csrf_token},
                            type: 'POST',
                            success: function (data) {
                                $('#course_name1').find('option').remove();
                                $('#course_name1').append(data);
                                ajaxSuccess();
                            },
                            error: function () {
                                alert("<?php echo _("GN0401") ?>");
                            }
                        });
                    }
                }

                function replyEdit(event, id) {
                    var v = $(event).closest(".replies-list").find(".reply_desc");
                    var value = $(v).html();
                    $(v).replaceWith($('<textarea class="form-control forum_qus_desc" id="replyText" autocomplete="off" rows="3" maxLength="65535">' + value + '</textarea>'));
                    var button = $(event).closest(".replies-list").find(".action_buttons");
                    //                    $(button).css({"display": "block"});
                    $(button).removeClass('action_buttons');
                    $(button).addClass('action_buttons_block');
                    var v1 = $(event).closest(".replies-list").find(".reply_submit");
                    var v2 = $(event).closest(".replies-list").find(".reply_cancel");
                    $(v1).click(function () {
                        var resp = $(event).closest(".replies-list").find('#replyText').val().trim();
                        //            value = resp;
                        if (resp === "") {
                            $('#reply_length_empty_edit' + id + '').fadeIn('slow', function () {
                                $('#reply_length_empty_edit' + id + '').delay(5000).fadeOut();
                            });
                            return false;
                        } else {
                            value = resp;
                            const csrf_token = $('meta[name="csrf-token"]').attr('content');
                            $.ajax({
                                url: 'forum/edit_reply.php',
                                data: {"response_text": resp, "response_id": id, "csrf_token": csrf_token},
                                type: 'POST',
                                success: function (data) {
                                    if (data) {
                                        var v_replace = $(event).closest(".replies-list").find("#replyText");
                                        $(v_replace).replaceWith($('<pre class="reply_desc"></pre>'));
                                        var v = $(event).closest(".replies-list").find(".reply_desc");
                                        $(v).text(resp);
                                        //  $(button).css({"display": "none"});
                                        $(button).removeClass('action_buttons_block');
                                        $(button).addClass('action_buttons');
                                    }
                                },
                                error: function () {
                                    alert("<?php echo _("GN0401") ?>");
                                }
                            });
                        }
                    });
                    $(v2).click(function () {
                        var v_replace = $(event).closest(".replies-list").find("#replyText");
                        $(v_replace).replaceWith($('<pre class="reply_desc">' + value + '</pre>'));
                        $(button).removeClass('action_buttons_block');
                        $(button).addClass('action_buttons');
                        //$(button).css({"display": "none"});
                    });
                }

                function replyDelete(event, id) {
                    if (confirm("<?php echo _("FR0302") ?>") == true) {
                         const csrf_token = $('meta[name="csrf-token"]').attr('content');
                        $.ajax({
                            url: 'forum/delete_reply.php',
                            data: {"response_id": id, "csrf_token": csrf_token},
                            type: 'POST',
                            success: function () {
                                ajaxSuccess();
                            },
                            error: function () {
                                alert("<?php echo _("GN0401") ?>");
                            }
                        });
                    }
                }

                function topicRemoveSpam(event, topic_id) {
                    if (confirm("<?php echo _("FR0303") ?>") == true) {
                        $('#loader_tra' + topic_id + '').show();
                        event.disabled = true;
                        const csrf_token = $('meta[name="csrf-token"]').attr('content');
                        $.ajax({
                            url: 'forum/remove_spam_topic.php',
                            data: {"topic_id": topic_id, "csrf_token": csrf_token},
                            type: 'POST',
                            success: function (data) {
                                ajaxSuccess();
                                $('#loader_tra' + topic_id + '').hide();
                                event.disabled = false;
                            },
                            error: function () {
                                alert("<?php echo _("GN0401") ?>");
                                $('#loader_tra' + topic_id + '').hide();
                                event.disabled = false;
                            }
                        });
                    }
                }

                function topicReportSpam(event, topic_id) {
                    if (confirm("<?php echo _("FR0306") ?>") == true) {
                        $('#loader_ta' + topic_id + '').show();
                        event.disabled = true;
                        const csrf_token = $('meta[name="csrf-token"]').attr('content');
                        $.ajax({
                            url: 'forum/report_spam_topic.php',
                            data: {"topic_id": topic_id, "csrf_token": csrf_token},
                            type: 'POST',
                            success: function (data) {
                                ajaxSuccess();
                                $('#loader_ta' + topic_id + '').hide();
                                event.disabled = false;
                            },
                            error: function () {
                                alert("<?php echo _("GN0401") ?>");
                                $('#loader_ta' + topic_id + '').hide();
                                event.disabled = false;
                            }
                        });
                    }
                    window.reload(document.location);
                }

                function replyRemoveSpam(event, response_id) {
                    if (confirm("<?php echo _("FR0304") ?>") == true) {
                        $('#loader_rra' + response_id + '').show();
                        event.disabled = true;
                        const csrf_token = $('meta[name="csrf-token"]').attr('content');
                        $.ajax({
                            url: 'forum/remove_spam_reply.php',
                            data: {"response_id": response_id, "csrf_token": csrf_token},
                            type: 'POST',
                            success: function (data) {
                                ajaxSuccess();
                                $('#loader_rra' + response_id + '').hide();
                                event.disabled = false;
                            },
                            error: function () {
                                alert("<?php echo _("GN0401") ?>");
                                $('#loader_rra' + response_id + '').hide();
                                event.disabled = false;
                            }
                        });
                    }
                }

                function replyReportSpam(event, topic_id, response_id) {
                    if (confirm("<?php echo _("FR0305") ?>") == true) {
                        $('#loader_ra' + response_id + '').show();
                        event.disabled = true;
                        const csrf_token = $('meta[name="csrf-token"]').attr('content');
                        $.ajax({
                            url: 'forum/report_spam_reply.php',
                            data: {"topic_id": topic_id, "response_id": response_id, "csrf_token": csrf_token},
                            type: 'POST',
                            success: function () {
                                ajaxSuccess();
                                $('#loader_ra' + response_id + '').hide();
                                event.disabled = false;
                            },
                            error: function () {
                                alert("<?php echo _("GN0401") ?>");
                                $('#loader_ra' + response_id + '').hide();
                                event.disabled = false;
                            }
                        });
                    }
                }

                $('.load_discussions').click(function () {
                    var load = true;
                    var topic_name = $('#course_name1').val();
                    var mode = $('.is-active-tab').attr('id');
                    if (mode == "all_questions") {
                        mode = "";
                        //            alert(page);
                        readDiscussions(topic_name, mode, page, load, 1);
                        page++;
                    } else if (mode == "my_questions") {
                        mode = $('#user_id').val();
                        readDiscussions(topic_name, mode, page, load, 1);
                        page++;
                    }
                });

                function readDiscussions(t, u, p, l, f) {
                    $.ajax({
                        url: 'forum/forum_view.php',
                        data: {"topic_name": t, "user_id": u, "page": p, "flag": f},
                        dataType: "html",
                        contentType: "application/json",
                        type: 'GET',
                        success: function (data) {
                            if (l) {
                                $('.form_view').append(data);
                            } else {
                                $('.form_view').html(data);
                            }
                            var total_disc = $('#total_disc').val();
                            var numItems = $('.topic').length;
                            if (parseInt(numItems) === 0) {
                                $('.load_discussions').hide();
                            } else {
                                if (parseInt(numItems) === parseInt(total_disc)) {
                                    $('.load_discussions').hide();
                                } else {
                                    $('.load_discussions').show();
                                }
                            }

                        }, error: function () {
                            alert("<?php echo _("GN0401") ?>");
                        }
                    });
                }

                function ajaxSuccess() {
                    var val = $('#course_name1').val();
                    var mode = $('.is-active-tab').attr('id');
                    if (mode == "all_questions") {
                        mode = "";
                    } else {
                        mode = $('#user_id').val();
                    }
                    if (val === "") {
                        readDiscussions('', mode, page - 1, false, 0);
                    } else {
                        readDiscussions(val, mode, page - 1, false, 0);
                    }
                }
            </script>
        </body>

    </html>