<?php
chdir('../');
session_start();
require_once('public/connection.php');

include('partials/header.php');
include('partials/navbar.php');
include('partials/sidebar.php');
include('partials/alert.php');

if (!isset($_SESSION['staff_id'])) {
    header("Location: ../index.php");
    exit;
}

// Fetch exams
$exams = $conn->query("
    SELECT 
        e.id,
        eg.class,
        s.subjects AS subject_name,
        eg.term,
        eg.session,
        e.exam_type
    FROM exams e
    JOIN exam_groups eg ON e.exam_group_id = eg.id
    LEFT JOIN school_subjects s ON eg.subject_id = s.id
    ORDER BY e.created_at DESC
");
?>

<div class="content-wrapper">
    <div class="content-header">
        <div class="container-fluid">
            <h4>Manage Questions</h4>
        </div>
    </div>

    <div class="content container-fluid">

        <!-- ADD BUTTON -->
        <div class="row mb-3">
            <div class="col-12">
                <button class="btn btn-primary w-100" type="button" data-bs-toggle="collapse" data-bs-target="#questionFormCollapse">
                    + Add New Question
                </button>
            </div>
        </div>

        <!-- COLLAPSE FORM -->
        <div class="collapse" id="questionFormCollapse">
            <div class="card card-body mt-3">

                <!-- Question Type Selector -->
                <div class="row mb-3">
                    <div class="col-12 col-md-6 mx-auto text-center">
                        <label for="questionType" class="form-label fw-bold">Select Question Type</label>
                        <select id="questionType" class="form-select text-center" onchange="toggleQuestionType()">
                            <option value="">-- Select Type --</option>
                            <option value="multiple">Multiple Choice</option>
                            <option value="theory">Theory</option>
                        </select>
                    </div>
                </div>

                <!-- MULTIPLE CHOICE CSV/EXCEL -->
                <div id="multipleSection" style="display:none;">
                    <hr><h5 class="text-primary text-center">Multiple Choice Questions</h5>
                    <div class="row mb-2">
                        <div class="col-6">
                            <a href="import_export_questions.php?export=csv" class="btn btn-success btn-sm w-100 mb-2">⬇ Export CSV</a>
                        </div>
                        <div class="col-6">
                            <a href="import_export_questions.php?export=xlsx" class="btn btn-success btn-sm w-100 mb-2">⬇ Export Excel</a>
                        </div>
                        <div class="col-6">
                            <form action="import_export_questions.php" method="POST" enctype="multipart/form-data" class="d-flex gap-2">
                                <input type="file" name="csv_file" accept=".csv" required class="form-control form-control-sm">
                                <button type="submit" name="import_csv_mcq" class="btn btn-primary btn-sm">⬆ Import CSV</button>
                            </form>
                        </div>
                        <div class="col-6">
                            <form action="import_export_questions.php" method="POST" enctype="multipart/form-data" class="d-flex gap-2">
                                <input type="file" name="xlsx_file" accept=".xlsx" required class="form-control form-control-sm">
                                <button type="submit" name="import_xlsx_mcq" class="btn btn-primary btn-sm">⬆ Import Excel</button>
                            </form>
                        </div>
                    </div>
                </div>

                <!-- THEORY CSV/EXCEL -->
                <div id="theorySection" style="display:none;">
                    <hr><h5 class="text-primary text-center">Theory Questions</h5>
                    <div class="row mb-2">
                        <div class="col-6">
                            <a href="import_export_questions_2.php?export=csv" class="btn btn-success btn-sm w-100 mb-2">⬇ Export CSV</a>
                        </div>
                        <div class="col-6">
                            <a href="import_export_questions_2.php?export=xlsx" class="btn btn-success btn-sm w-100 mb-2">⬇ Export Excel</a>
                        </div>
                        <div class="col-6">
                            <form action="import_export_questions_2.php" method="POST" enctype="multipart/form-data" class="d-flex gap-2">
                                <input type="file" name="csv_file" accept=".csv" required class="form-control form-control-sm">
                                <button type="submit" name="import_csv_theory" class="btn btn-primary btn-sm">⬆ Import CSV</button>
                            </form>
                        </div>
                        <div class="col-6">
                            <form action="import_export_questions_2.php" method="POST" enctype="multipart/form-data" class="d-flex gap-2">
                                <input type="file" name="xlsx_file" accept=".xlsx" required class="form-control form-control-sm">
                                <button type="submit" name="import_xlsx_theory" class="btn btn-primary btn-sm">⬆ Import Excel</button>
                            </form>
                        </div>
                    </div>
                </div>

                <!-- Manual question form -->
                <hr class="mt-4">
                <?php include('partials/question_form.php'); ?>
            </div>
        </div>

       <!-- FILTER -->
<div class="row mb-3 mt-4">
    <div class="col-12 col-md-4">
        <label><strong>Filter by Exam</strong></label>
        <select id="filterExam" class="form-select">
            <option value="">All Exams</option>
            <?php
            // Reset pointer to start of result set
            $exams->data_seek(0);
            while($ex = $exams->fetch_assoc()): ?>
                <option value="<?= $ex['id'] ?>">
    <?= "{$ex['class']} - {$ex['subject_name']} - {$ex['term']} - {$ex['session']} - {$ex['exam_type']}" ?>
</option>

            <?php endwhile; ?>
        </select>
    </div>
</div>


        <!-- BULK DELETE BUTTON -->
        <div class="row mb-2">
            <div class="col-12 col-md-4">
                <button id="bulkDeleteBtn" class="btn btn-danger w-100">Delete Selected Questions</button>
            </div>
        </div>

        <!-- TABLE -->
        <div class="card mt-3">
            <div class="card-header bg-dark text-white">All Questions</div>
            <div class="card-body table-responsive">
                <table id="questionsTable" class="table table-bordered table-striped text-center align-middle">
                    <thead>
                        <tr>
                            <th><input type="checkbox" id="selectAll"></th>
                            <th>Exam</th>
                            <th>Question</th>
                            <th>Type</th>
                            <th>Correct Answer</th>
                            <th>Marks</th>
                            <th>Image</th>
                            <th>Action</th>
                        </tr>
                    </thead>
                    <tbody></tbody>
                </table>
            </div>
        </div>

    </div>
</div>

<!-- VIEW Modal -->
<div class="modal fade" id="viewQuestionModal" tabindex="-1" aria-hidden="true">
  <div class="modal-dialog modal-lg modal-dialog-centered">
      <div class="modal-content">
          <div class="modal-header bg-info text-white">
              <h5 class="modal-title">View Question</h5>
              <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
          </div>
          <div class="modal-body" id="viewQuestionBody"></div>
      </div>
  </div>
</div>

<!-- EDIT Modal -->
<div class="modal fade" id="editQuestionModal" tabindex="-1" aria-hidden="true">
  <div class="modal-dialog modal-lg modal-dialog-centered">
      <div class="modal-content">
          <div class="modal-header bg-warning text-dark">
              <h5 class="modal-title">Edit Question</h5>
              <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
          </div>
          <div class="modal-body" id="editQuestionBody"></div>
      </div>
  </div>
</div>

<?php include('partials/footer.php'); ?>

<script>
// Toggle question type sections
function toggleQuestionType() {
    const type = document.getElementById('questionType').value;
    document.getElementById('multipleSection').style.display = (type === 'multiple') ? 'block' : 'none';
    document.getElementById('theorySection').style.display = (type === 'theory') ? 'block' : 'none';
}

// DataTables AJAX
$(document).ready(function() {
    var table = $('#questionsTable').DataTable({
        processing: true,
        serverSide: true,
        ajax: {
            url: "partials/ajax_questions.php",
            type: "GET",
            data: function(d){ d.exam_id = $('#filterExam').val(); }
        },
        columns: [
            { 
                data: "id",
                render: function(id){
                    return `<input type="checkbox" class="selectCheckbox" value="${id}">`;
                },
                orderable:false
            },
            { data: "exam_label" },
            { data: "question_text" },
            { data: "question_type" },
            { data: "correct_answer" },
            { data: "marks" },
            { 
                data: "question_image",
                render: img => img ? `<img src="../${img}" width="50" style="object-fit:cover;border-radius:5px">` : 'N/A'
            },
            { 
                data: "id",
                orderable: false,
                render: id => `
                    <button class="btn btn-info btn-sm view-btn" data-id="${id}"><i class="bi bi-eye"></i></button>
                    <button class="btn btn-warning btn-sm edit-btn" data-id="${id}"><i class="bi bi-pencil-square"></i></button>
                    <button class="btn btn-danger btn-sm delete-btn" data-id="${id}"><i class="bi bi-trash"></i></button>
                `
            }
        ]
    });

    // Filter change
    $('#filterExam').change(()=> table.ajax.reload());

    // SELECT ALL
    $('#selectAll').on('click', function(){
        $('.selectCheckbox').prop('checked', this.checked);
    });

    // BULK DELETE
    $('#bulkDeleteBtn').on('click', function(){
        var ids = $('.selectCheckbox:checked').map(function(){ return $(this).val(); }).get();
        if(ids.length === 0){ alert('No questions selected'); return; }
        if(!confirm('Delete selected questions?')) return;
        $.post('partials/ajax_questions.php?action=bulk_delete',{ids:ids},function(res){
            alert(res.message);
            table.ajax.reload();
        },'json');
    });

    // VIEW question
    $('#questionsTable').on('click','.view-btn', function(){
        const id = $(this).data('id');
        $.get('partials/ajax_questions.php?action=view&id='+id, data=>{
            $('#viewQuestionBody').html(data);
            $('#viewQuestionModal').modal('show');
        });
    });

    // EDIT question
    // EDIT question button click
$('#questionsTable').on('click','.edit-btn', function(){
    const id = $(this).data('id');
    $.get('partials/ajax_questions.php?action=edit&id='+id, function(data){
        $('#editQuestionBody').html(data);
        $('#editQuestionModal').modal('show');

        // Bind submit AFTER content is loaded
        $('#editQuestionForm').off('submit').on('submit', function(e){
            e.preventDefault();
            var formData = new FormData(this);
            formData.append('action','update');

            $.ajax({
                url:'partials/ajax_questions.php',
                type:'POST',
                data:formData,
                contentType:false,
                processData:false,
                dataType:'json',
                success:function(res){
                    alert(res.message);
                    $('#editQuestionModal').modal('hide');
                    $('#questionsTable').DataTable().ajax.reload();
                },
                error:function(xhr){
                    console.log(xhr.responseText);
                    alert('Update failed!');
                }
            });
        });
    });
});


    // DELETE question
    $('#questionsTable').on('click','.delete-btn', function(){
        const id = $(this).data('id');
        if(!confirm('Delete this question?')) return;
        $.post('partials/ajax_questions.php?action=delete',{id},res=>{
            alert(res.message);
            table.ajax.reload();
        },'json');
    });
});
</script>

<style>
#filterExam { width:100%; margin-top:5px; }
@media(max-width:576px){ #filterExam{ font-size:14px; } }
</style>
