<?php $section = $sections['faq_section'] ?? []; ?>

<form method="post" action="<?php echo site_url('admin/product/save_section'); ?>">
  <input type="hidden" name="prd_id" value="<?php echo $product['prd_id']; ?>">
  <input type="hidden" name="section_key" value="faq_section">


  <div class="form-group">
    <label>Section Heading</label>
    <input name="heading" class="form-control" value="<?php echo $section['heading'] ?? ''; ?>">
  </div>


  <hr>
  <h5>FAQ Items</h5>
  <div id="faq-wrapper">
    <?php
    $faqs = $section['items'] ?? [['question' => '', 'answer' => '']];
    foreach ($faqs as $index => $faq): ?>


      <div class="faq-box border p-3 mb-3">
        <div class="form-group">
          <label>Question</label>
          <input name="items[<?php echo $index; ?>][question]" class="form-control" value="<?php echo $faq['question']; ?>">
        </div>
        <div class="form-group">
          <label>Answer</label>
          <textarea name="items[<?php echo $index; ?>][answer]" class="form-control" rows="2"><?php echo $faq['answer']; ?></textarea>
        </div>
        <button type="button" class="btn btn-danger remove-faq">Remove</button>
      </div>


    <?php endforeach; ?>
  </div>


  <button type="button" id="add-faq" class="btn btn-secondary mb-3">Add FAQ</button>


  <button class="btn btn-success">Save Section</button>
</form>

<script>
  let faqIndex = <?php echo count($faqs); ?>;


  // Add new FAQ
  $('#add-faq').on('click', function() {
    let html = `
<div class="faq-box border p-3 mb-3">
<div class="form-group">
<label>Question</label>
<input name="items[` + faqIndex + `][question]" class="form-control">
</div>
<div class="form-group">
<label>Answer</label>
<textarea name="items[` + faqIndex + `][answer]" class="form-control" rows="2"></textarea>
</div>
<button type="button" class="btn btn-danger remove-faq">Remove</button>
</div>`;


    $('#faq-wrapper').append(html);
    faqIndex++;
  });


  // Remove FAQ
  $(document).on('click', '.remove-faq', function() {
    $(this).closest('.faq-box').remove();
  });
</script>