{% extends 'dashboard/admin_dashboard/main.html' %}
{% load static %}
{% block content %}
<h4 class="fw-bold py-3 mb-4"><span class="text-muted fw-light">Safety Training /</span> Edit Safety Training</h4>
<div style="padding: 10px;">
  {% if messages %}
    {% for message in messages %}
      <div class="alert {% if 'success' in message.tags %}alert-success{% elif 'danger' in message.tags %}alert-danger{% elif 'warning' in message.tags %}alert-warning{% elif 'info' in message.tags %}alert-info{% endif %} alert-dismissible" role="alert" id="success-alert">
        {{ message }}
        <button type="button" class="btn-close" data-bs-dismiss="alert" aria-label="Close">
        </button>
      </div>
    {% endfor %}
  {% endif %}
</div>
<div class="row">
    <div class="col-md-12">
      <div class="card mb-4">
        <form role="form" method="POST" enctype="multipart/form-data" action="">
            {% csrf_token %}
          <div class="card-body">
              <div class="form-group mb-3">
                <label class="form-label">Title</label>
                <input type="text" name="title" class="form-control" value="{{ training_instance.title }}" required>
              </div>

              <div class="form-group mb-3">
                <label class="form-label">Video File</label>
                <input type="file" id="videoInput" name="video_files" class="form-control" onchange="previewVideo()" accept="video/mp4">
                  {% if training_instance.video_file %}
                        <p>Current Video: <a href="/safety_training/{{ training_instance.video_file.url }}" target="_blank">{{ training_instance.video_file.name }}</a></p>
                    {% endif %}
              </div>

              <div class="form-group mb-3">
                <label class="form-label">Status</label>
                <select name="status" class="form-control" required>
                  <option value="1" {% if training_instance.is_active == 1 %}selected{% endif %}>Active</option>
                  <option value="0" {% if training_instance.is_active == 0 %}selected{% endif %}>Inactive</option>
                </select>
              </div>

              <div class="form-group mb-3" style="display:none" id="videoPreviewWrapper">
                <label class="form-label">Preview</label>
                <video id="videoPreview" width="100%" height="300" controls>
                  <source id="videoSource" type="video/mp4">
                  Your browser does not support the video tag.
                </video>
              </div>

              <hr>
              <h3 style="margin-top: 30px; border-bottom: 2px solid #3c8dbc; padding-bottom: 5px;">Questions</h3>
             <input type="hidden" id="question_count" name="question_count" value="{{ questions|length|add:1 }}">
             <div id="questions_container">
                {% for question in questions %}
                    <div class="box box-info question-group mb-3" id="question_{{ forloop.counter }}">
                        <div class="box-header with-border">
                            <h3 class="box-title">Question {{ forloop.counter }}</h3>
                        </div>
                        <div class="box-body">
                            <input type="hidden" name="question_id_{{ forloop.counter }}" value="{{ question.id }}">
                            <div class="form-group mb-3">
                                <label class="form-label" >Question</label>
                                <input type="text" name="question_{{ forloop.counter }}" class="form-control" value="{{ question.question_text }}" placeholder="Question text" required>
                            </div>
                            <div class="row">
                                <div class="col-sm-6 form-group mb-3">
                                    <label class="form-label">Option A</label>
                                    <input type="text" name="option_a_{{ forloop.counter }}" class="form-control" value="{{ question.option_a }}" required>
                                </div>
                                <div class="col-sm-6 form-group mb-3">
                                    <label class="form-label">Option B</label>
                                    <input type="text" name="option_b_{{ forloop.counter }}" class="form-control" value="{{ question.option_b }}" required>
                                </div>
                                <div class="col-sm-6 form-group mb-3">
                                    <label class="form-label">Option C</label>
                                    <input type="text" name="option_c_{{ forloop.counter }}" class="form-control" value="{{ question.option_c }}" required>
                                </div>
                                <div class="col-sm-6 form-group mb-3">
                                    <label class="form-label">Option D</label>
                                    <input type="text" name="option_d_{{ forloop.counter }}" class="form-control" value="{{ question.option_d }}" required>
                                </div>
                            </div>
                            <div class="form-group mb-3">
                                <label class="form-label">Correct Option</label>
                                <select name="correct_option_{{ forloop.counter }}" class="form-control" required>
                                    <option value="">Select</option>
                                    <option value="A" {% if question.correct_option == 'A' %}selected{% endif %}>A</option>
                                    <option value="B" {% if question.correct_option == 'B' %}selected{% endif %}>B</option>
                                    <option value="C" {% if question.correct_option == 'C' %}selected{% endif %}>C</option>
                                    <option value="D" {% if question.correct_option == 'D' %}selected{% endif %}>D</option>
                                </select>
                            </div>
                            <button type="button" onclick="removeQuestion({{ forloop.counter }})" class="btn btn-danger btn-sm mt-3">
                                <i class="bx bx-trash"></i> Remove
                            </button>
                        </div>
                    </div>
                {% empty %}
                    <div class="box box-info question-group" id="question_1">
                        <div class="box-header with-border">
                            <h3 class="box-title">Question 1</h3>
                        </div>
                        <div class="box-body">
                            <div class="form-group mb-3">
                                <label class="form-label">Question</label>
                                <input type="text" name="question_1" class="form-control" placeholder="Question text" required>
                            </div>
                            <div class="row">
                                <div class="col-sm-6 form-group mb-3">
                                    <label class="form-label">Option A</label>
                                    <input type="text" name="option_a_1" class="form-control" required>
                                </div>
                                <div class="col-sm-6 form-group mb-3">
                                    <label class="form-label">Option B</label>
                                    <input type="text" name="option_b_1" class="form-control" required>
                                </div>
                                <div class="col-sm-6 form-group mb-3">
                                    <label class="form-label">Option C</label>
                                    <input type="text" name="option_c_1" class="form-control" required>
                                </div>
                                <div class="col-sm-6 form-group mb-3">
                                    <label class="form-label">Option D</label>
                                    <input type="text" name="option_d_1" class="form-control" required>
                                </div>
                            </div>
                            <div class="form-group">
                                <label class="form-label">Correct Option</label>
                                <select name="correct_option_1" class="form-control" required>
                                    <option value="">Select</option>
                                    <option value="A">A</option>
                                    <option value="B">B</option>
                                    <option value="C">C</option>
                                    <option value="D">D</option>
                                </select>
                            </div>
                        </div>
                    </div>
                {% endfor %}
             </div>

              <button type="button" onclick="addQuestion()" class="btn btn-success">
                <i class="bx bx-plus"></i> Add Another Question
              </button>
            </div>
          <div class="box-footer text-center mt-3 mb-3">
              <button type="submit" class="btn btn-primary">Submit</button>
            </div>
        </form>
      </div>
    </div>
  </div>
<script src="{% static 'plugins/jQuery/jQuery-2.1.3.min.js' %}" type="text/javascript"></script>
<style>
    .question-group {
        margin-bottom: 20px;
        border-radius: 5px;
    }
</style>

<script>
    function previewVideo() {
        const videoInput = document.getElementById('videoInput');
        const videoPreviewWrapper = document.getElementById('videoPreviewWrapper');
        const videoPreview = document.getElementById('videoPreview');
        const videoSource = document.getElementById('videoSource');

        videoPreviewWrapper.style.display = "none";
        const file = videoInput.files && videoInput.files[0];

        if (file && file.type === "video/mp4") {
            const fileURL = URL.createObjectURL(file);
            videoSource.src = fileURL;
            videoPreviewWrapper.style.display = "block";
            videoPreview.load();
        } else if (file) {
            alert("Please select a valid MP4 video file.");
        }
    }

    let questionIndex = {{ questions|length|default:1 }};

    function addQuestion() {
        questionIndex++;
        const container = document.getElementById('questions_container');
        const questionBlock = `
            <div class="box box-info question-group" id="question_${questionIndex}">
                <div class="box-header with-border">
                    <h3 class="box-title">Question ${questionIndex}</h3>
                </div>
                <div class="box-body">
                    <div class="form-group">
                        <label class="form-label">Question</label>
                        <input type="text" name="question_${questionIndex}" class="form-control" placeholder="Question text" required>
                    </div>
                    <div class="row">
                        <div class="col-sm-6 form-group mb-3">
                            <label class="form-label">Option A</label>
                            <input type="text" name="option_a_${questionIndex}" class="form-control" required>
                        </div>
                        <div class="col-sm-6 form-group mb-3">
                            <label class="form-label">Option B</label>
                            <input type="text" name="option_b_${questionIndex}" class="form-control" required>
                        </div>
                        <div class="col-sm-6 form-group mb-3">
                            <label class="form-label">Option C</label>
                            <input type="text" name="option_c_${questionIndex}" class="form-control" required>
                        </div>
                        <div class="col-sm-6 form-group mb-3">
                            <label class="form-label">Option D</label>
                            <input type="text" name="option_d_${questionIndex}" class="form-control" required>
                        </div>
                    </div>
                    <div class="form-group">
                        <label class="form-label">Correct Option</label>
                        <select name="correct_option_${questionIndex}" class="form-control" required>
                            <option value="">Select</option>
                            <option value="A">A</option>
                            <option value="B">B</option>
                            <option value="C">C</option>
                            <option value="D">D</option>
                        </select>
                    </div>
                    <button type="button" onclick="removeQuestion(${questionIndex})" class="btn btn-danger btn-sm mb-3">
                        <i class="bx bx-trash"></i> Remove
                    </button>
                </div>
            </div>
        `;
        container.insertAdjacentHTML('beforeend', questionBlock);
        document.getElementById('question_count').value = questionIndex;
    }

    function removeQuestion(index) {
        if (questionIndex > 1) {
            const questionBlock = document.getElementById(`question_${index}`);
            if (questionBlock) {
                questionBlock.remove();
                questionIndex--;
                document.getElementById('question_count').value = questionIndex;
                updateQuestionNumbers();
            }
        } else {
            alert("At least one question is required.");
        }
    }

    function updateQuestionNumbers() {
        const questionGroups = document.querySelectorAll('.question-group');
        questionGroups.forEach((group, index) => {
            const newIndex = index + 1;
            group.id = `question_${newIndex}`;
            group.querySelector('.box-title').textContent = `Question ${newIndex}`;
            const questionInput = group.querySelector('input[name^="question_"]');
            if (questionInput) questionInput.name = `question_${newIndex}`;
            const optionA = group.querySelector('input[name^="option_a_"]');
            if (optionA) optionA.name = `option_a_${newIndex}`;
            const optionB = group.querySelector('input[name^="option_b_"]');
            if (optionB) optionB.name = `option_b_${newIndex}`;
            const optionC = group.querySelector('input[name^="option_c_"]');
            if (optionC) optionC.name = `option_c_${newIndex}`;
            const optionD = group.querySelector('input[name^="option_d_"]');
            if (optionD) optionD.name = `option_d_${newIndex}`;
            const correctOption = group.querySelector('select[name^="correct_option_"]');
            if (correctOption) correctOption.name = `correct_option_${newIndex}`;
            const questionIdInput = group.querySelector('input[name^="question_id_"]');
            if (questionIdInput) questionIdInput.name = `question_id_${newIndex}`;
            const removeButton = group.querySelector('button');
            if (removeButton) {
                removeButton.setAttribute('onclick', `removeQuestion(${newIndex})`);
            }
        });
    }
</script>
{% endblock %}