<?php
ob_start();
?>
<main class="container-fluid px-6 pb-10">
  <header class="py-4 border-bottom">
    <div class="row align-items-center">
      <div class="col">
        <div class="d-flex align-items-center gap-4">
          <h1 class="h4 ls-tight">Create Assessment Question</h1>
        </div>
      </div>
    </div>
  </header>
  <div id="responseMessage" class="mt-3"></div>

  <form id="createAssessmentForm">
    <div class="row g-3 mt-6">
      <div class="col-12 col-md-6">
        <label class="form-label">Category</label>
        <select name="categoryid" class="form-control" required id="categorySelect">
          <option value="">Select Category</option>
        </select>
      </div>
      <div class="col-md-6 col-12">
        <label class="form-label">Question</label>
        <input type="text" name="question" class="form-control" required>
      </div>

      <div class="col-md-5 col-12">
        <label class="form-label">Option</label>
        <input type="text" id="optionInput" class="form-control">
      </div>
      <div class="col-md-5 col-12">
        <label class="form-label">Rating</label>
        <input type="number" id="ratingInput" class="form-control" min="0" max="5">
      </div>
      <div class="col-md-2 col-12 d-flex align-items-end">
        <button type="button" id="addOptionBtn" class="btn btn-sm btn-secondary">Add Option</button>
      </div>

      <div class="col-md-4">
        <label class="form-label">Added Options:</label>
        <ul id="optionsList" class="list-group"></ul>
      </div>
    </div>

    <input type="hidden" name="options" id="finalOptions">
    <input type="hidden" name="ratings" id="finalRatings">

    <div class="d-flex justify-content-end gap-2 mt-5">
      <button type="reset" class="btn btn-sm btn-neutral">Cancel</button>
      <button type="submit" class="btn btn-sm btn-primary">Save</button>
    </div>
  </form>
</main>

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

<script>
  let optionsArray = [];
  let ratingsArray = [];

  $(document).ready(function () {
    // Fetch categories
    $.getJSON("https://projects.funtashtechnologies.com/gomeetapi/adminpanel/getassesmentcategories.php", function (res) {
      if (res.Result === "true" && Array.isArray(res.Data)) {
        const select = $('#categorySelect');
        res.Data.forEach(cat => {
          select.append(`<option value="${cat.id}">${cat.title}</option>`);
        });
      }
    });

    // Add option button click
    $('#addOptionBtn').click(function () {
      const option = $('#optionInput').val().trim();
      const rating = $('#ratingInput').val().trim();

      if (!option || rating === '') {
        alert("Please enter both option and rating.");
        return;
      }

      optionsArray.push(option);
      ratingsArray.push(rating);

      $('#optionsList').append(
        `<li class="list-group-item d-flex justify-content-between align-items-center py-2 mb-1">
        Option :   ${option} <span class="badge bg-primary rounded-pill"> Rating :  ${rating}</span>
        </li>`
      );

      $('#optionInput').val('');
      $('#ratingInput').val('');
    });

    // Form submit
    $('#createAssessmentForm').on('submit', function (e) {
      e.preventDefault();

      if (optionsArray.length === 0) {
        alert("Please add at least one option.");
        return;
      }

      $('#finalOptions').val(optionsArray.join(','));
      $('#finalRatings').val(ratingsArray.join(','));

      const form = this;
      const formData = new FormData(form);
      formData.append("createdby", "superadmin");

      $.ajax({
        url: 'https://projects.funtashtechnologies.com/gomeetapi/adminpanel/assessmentquestions.php',
        method: 'POST',
        processData: false,
        contentType: false,
        data: formData,
        success: function (response) {
          let alertClass = response.Result === "true" ? 'alert-success' : 'alert-danger';
          $('#responseMessage').html(`<div class="alert ${alertClass}">${response.ResponseMsg}</div>`);
          if (response.Result === "true") {
            optionsArray = [];
            ratingsArray = [];
            $('#optionsList').html('');
            $('#createAssessmentForm')[0].reset();
            setTimeout(() => window.location.href = 'assesmentquestions.php', 1000);
           
          }
        },
        error: function () {
          $('#responseMessage').html('<div class="alert alert-danger">Something went wrong. Please try again.</div>');
        }
      });
    });
  });
</script>

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