<?php
ob_start();
?>

<main class="container-fluid p-0">

    <!-- Add Question Modal -->
    <div class="modal fade" id="addQuestionModal" tabindex="-1" aria-labelledby="addQuestionModalLabel" aria-hidden="true">
        <div class="modal-dialog modal-xl">
            <div class="modal-content">
                <div class="modal-header">
                    <h3 class="modal-title" id="addQuestionModalLabel">Add Question</h3>
                    <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
                </div>
                <div class="modal-body">

                 <div class="d-flex flex-row flex-wrap">
                     <div class="mb-3 me-1">
                        <label for="parentCategory" class="form-label">Select Category</label>
                        <select class="form-select" id="parentCategory">
                            <option value="" selected>Select Category</option>
                            <!-- Options will be loaded dynamically -->
                        </select>
                    </div>

                    <!-- Category -->
                    <div class="mb-3 ms-1">
                        <label for="category" class="form-label">Select Week</label>
                        <select class="form-select" id="category">
                            <option value="" selected>Select Week</option>
                        </select>
                    </div>
                   </div>

                    <!-- Question Title -->
                    <div class="mb-3">
                        <label for="questionTitle" class="form-label">Question</label>
                        <input type="text" class="form-control" id="questionTitle" placeholder="Add a question">
                    </div>

                    <!-- Answer Type -->
                    <div class="mb-3">
                        <label for="answerType" class="form-label">Answer Type</label>
                        <select class="form-select" id="answerType">
                            <option value="" selected>Select Answer Type</option>
                            <option value="text">Text</option>
                            <option value="multiplechoice">Multiple Choice</option>
                            <option value="radio">Radio</option>
                        </select>
                    </div>

                    <!-- Answers Container -->
                    <div class="mb-3" id="answersContainer" style="display:none;">
                        <label class="form-label">Answers</label>
                        <div id="answersFields">
                            <div class="input-group mb-2 answer-field">
                                <input type="text" class="form-control answer-input" placeholder="Enter answer">
                                <button class="btn btn-danger remove-answer" type="button">Remove</button>
                            </div>
                        </div>
                        <button type="button" class="btn btn-secondary btn-sm" id="addMoreAnswer">Add More</button>
                    </div>

                    <!-- Textarea for text type -->
                    <div class="mb-3" id="textAnswerContainer" style="display:none;">
                        <label for="textAnswer" class="form-label">Answer</label>
                        <textarea class="form-control" id="textAnswer" rows="3" placeholder="Enter answer"></textarea>
                    </div>
                    
                     <div class="mb-3" >
                        <label for="textAnswer" class="form-label">Points</label>
                      <input type="text" name="" class="form-control" id="">
                    </div>

                  

                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Close</button>
                    <button type="button" class="btn btn-primary" id="saveQuestion">Save Question</button>
                </div>
            </div>
        </div>
    </div>

    <!-- View Question Modal -->
    <div class="modal fade" id="viewQuestionModal" tabindex="-1" aria-labelledby="viewQuestionModalLabel" aria-hidden="true">
        <div class="modal-dialog modal-xl">
            <div class="modal-content">
                <div class="modal-header">
                    <h4 class="modal-title" id="viewQuestionModalLabel">Question Details</h4>
                    <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
                </div>
                <div class="modal-body" id="viewQuestionBody">
                    <!-- Filled dynamically -->
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Close</button>
                </div>
            </div>
        </div>
    </div>

    <!-- Questions Table -->
    <div class="px-6 px-lg-7 pt-8 border-bottom mb-4">
        <div class="row mb-5">
            <div class="col-12 col-md-6">
                <h2>Questions</h2>
            </div>
            <div class="col-12 col-md-6 d-flex justify-content-end">
                <button class="btn btn-primary" data-bs-toggle="modal" data-bs-target="#addQuestionModal">+ Add</button>
            </div>
        </div>
    </div>

    <div class="container">
        <table class="table table-striped" id="questionsTable">
            <thead>
                <tr>
                    <th>#</th>
                    <th>Question</th>
                    <th>Answer Type</th>
                    <th>Week Name</th>
                    <th>Week Number</th>

                    <th>Action</th>
                </tr>
            </thead>
            <tbody id="questionsTableBody">
                <tr>
                    <td colspan="7">Loading...</td>
                </tr>
            </tbody>
        </table>
    </div>

</main>

<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>

<script>
    $(document).ready(function() {

        // Load categories for Add Question Modal
        function loadCategories() {
            $.ajax({
                url: 'https://projects.funtashtechnologies.com/gomeetapi/getallweekcategories.php',
                type: 'GET',
                dataType: 'json',
                success: function(res) {
                    if (res.Result === 'true' && res.Data.length > 0) {
                        var categorySelect = $('#category');
                        categorySelect.empty().append('<option value="" selected>Select Category</option>');
                        res.Data.reverse().forEach(function(item) {
                            categorySelect.append('<option value="' + item.weeknumber + '">' + item.weekname + '</option>');
                        });
                    }
                },
                error: function(err) {
                    console.log('Error fetching categories:', err);
                }
            });
        }

        loadCategories();

        function loadParentCategories() {
            $.ajax({
                url: 'https://projects.funtashtechnologies.com/gomeetapi/adminpanel/getassesmentcategories.php',
                type: 'GET',
                dataType: 'json',
                success: function(res) {
                    if (res.Result === 'true' && res.Data.length > 0) {
                        var parentSelect = $('#parentCategory');
                        parentSelect.empty().append('<option value="" selected>Select Parent Category</option>');

                        res.Data.forEach(function(item) {
                            parentSelect.append('<option value="' + item.id + '">' + item.title + '</option>');
                        });
                    }
                },
                error: function(err) {
                    console.log('Error fetching parent categories:', err);
                    alert('Unable to load parent categories.');
                }
            });
        }

        loadParentCategories(); // Call it on page load


        // Show/hide answer fields based on type
        $('#answerType').on('change', function() {
            var type = $(this).val();
            if (type === 'text') {
                $('#textAnswerContainer').show();
                $('#answersContainer').hide();
            } else if (type === 'multiplechoice' || type === 'radio') {
                $('#answersContainer').show();
                $('#textAnswerContainer').hide();
            } else {
                $('#textAnswerContainer, #answersContainer').hide();
            }
        });

        // Add more answer fields
        $('#addMoreAnswer').on('click', function() {
            var newField = `<div class="input-group mb-2 answer-field">
            <input type="text" class="form-control answer-input" placeholder="Enter answer">
            <button class="btn btn-danger remove-answer" type="button">Remove</button>
        </div>`;
            $('#answersFields').append(newField);
        });

        // Remove answer field
        $(document).on('click', '.remove-answer', function() {
            $(this).closest('.answer-field').remove();
        });

        // Save Question
        $('#saveQuestion').on('click', function() {
            var title = $('#questionTitle').val().trim();
            var answertype = $('#answerType').val();
            var parentCategory = $('#parentCategory').val(); // NEW
            var category = $('#category').val();
            var answers = [];

            if (!title || !answertype || !parentCategory || !category) {
                alert('Please fill all required fields');
                return;
            }

            if (answertype === 'multiplechoice' || answertype === 'radio') {
                $('.answer-input').each(function() {
                    var val = $(this).val().trim();
                    if (val) answers.push(val);
                });
                if (answers.length === 0) {
                    alert('Please add at least one answer');
                    return;
                }
            }

            var data = {
                title,
                answertype,
                parentCategory, // NEW
                category
            };

            if (answers.length > 0) data.answers = answers;
            if (answertype === 'text') data.answers = [];

            $.ajax({
                url: 'https://projects.funtashtechnologies.com/gomeetapi/addquestions.php',
                type: 'POST',
                contentType: 'application/json',
                data: JSON.stringify(data),
                success: function(res) {
                    if (res.Result === 'true') {
                        alert('Question added successfully!');
                        $('#addQuestionModal').modal('hide');
                        loadQuestions();
                        $('#questionTitle,#answerType,#category,#parentCategory').val('');
                        $('#answersFields').html(`<div class="input-group mb-2 answer-field">
                    <input type="text" class="form-control answer-input" placeholder="Enter answer">
                    <button class="btn btn-danger remove-answer" type="button">Remove</button>
                </div>`);
                        $('#answersContainer,#textAnswerContainer').hide();
                    } else {
                        alert('Error: ' + res.ResponseMsg);
                    }
                },
                error: function(err) {
                    console.log(err);
                    alert('Error adding question');
                }
            });
        });



        // Load Questions and show in table
        function loadQuestions() {
            $.ajax({
                url: 'https://projects.funtashtechnologies.com/gomeetapi/getallquestions.php',
                type: 'GET',
                dataType: 'json',
                success: function(res) {
                    var tbody = $('#questionsTableBody');
                    tbody.empty();
                    if (res.Result === 'true' && res.Data.length > 0) {
                        res.Data.forEach(function(q, i) {
                            var row = `<tr>
                            <td>${i+1}</td>
                            <td>${q.title}</td>
                            <td>${q.answertype}</td>
                            <td>${q.weekname || ''}</td>
                            <td>${q.weeknumber || ''}</td>
                           
                            <td><button class="btn btn-sm btn-primary viewQuestionBtn" data-id="${q.id}">View</button></td>
                        </tr>`;
                            tbody.append(row);
                        });
                    } else {
                        tbody.html('<tr><td colspan="7">No questions found</td></tr>');
                    }
                },
                error: function(err) {
                    console.log(err);
                }
            });
        }

        loadQuestions();

        // View Question Details
        $(document).on('click', '.viewQuestionBtn', function() {
            var qid = $(this).data('id');
            $.ajax({
                url: 'https://projects.funtashtechnologies.com/gomeetapi/getallquestions.php',
                type: 'GET',
                dataType: 'json',
                success: function(res) {
                    if (res.Result === 'true' && res.Data.length > 0) {
                        var question = res.Data.find(q => q.id == qid);
                        if (question) {
                            var html = `<div class="mb-3">
                                        <label class="form-label">Question</label>
                                        <input type="text" class="form-control" value="${question.title}" readonly>
                                    </div>
                                  `;
                            if (question.answertype === 'text') {
                                html += `<div class="mb-3">
                                        <label class="form-label">Answer</label>
                                        <textarea class="form-control" rows="3" readonly>${question.answers.join(', ')}</textarea>
                                    </div>`;
                            } else {
                                html += `<div class="mb-3 d-flex flex-row flex-wrap">
                                        <label class="form-label">Answers</label>`;
                                question.answers.forEach(a => {
                                    html += `<input type="text" class="form-control mb-2" value="${a}" readonly>`;
                                });
                                html += `</div>`;
                            }
                            html += `<div class="mb-3 d-flex flex-row flex-wrap">
                                    <label class="form-label">Week Name</label>
                                    <input type="text" class="form-control" value="${question.weekname}" readonly>
                                </div>
                                <div class="mb-3">
                                    <label class="form-label">Week Title</label>
                                    <input type="text" class="form-control" value="${question.weektitle}" readonly>
                                </div>
                                <div class="mb-3">
                                    <label class="form-label">Week Image</label><br>
                                    <img src="https://projects.funtashtechnologies.com/gomeetapi/${question.image}" class="img-fluid" style="max-height:150px;">
                                </div>`;
                            $('#viewQuestionBody').html(html);
                            $('#viewQuestionModal').modal('show');
                        }
                    }
                }
            });
        });

    });
</script>

<?php
$content = ob_get_clean();
include '../layouts/master.php';
?>