<div class="container-xxl flex-grow-1 container-p-y">
              <h4 class="py-3 mb-4"><span class="text-muted fw-light">Edit Diagnostic Package</h4>
              
  <div class="row"><div class="col-md-6">
      <div class="card mb-4">
          <form method="post" action="#" id="inputform" enctype="multipart/form-data">
        <div class="card-body">
            
            <div class="mb-3">
              <label class="form-label">Main Test Name *</label>
              <input type="text" class="form-control" name="name" placeholder="Main Test Name" required value="<?=$diagnostic[0]['name']?>">
            </div>
         
          <div class="mb-3">
            <label for="exampleFormControlInput1" class="form-label">Image *</label>
            <input
              type="file"
              class="form-control"
              id="exampleFormControlInput1"
               name="image" placeholder="Image"/>
          </div>
          <p style="color:red">please upload only jpg,jpeg and png format files</p>
          <img src="<?php echo $this->config->item('bharosa_base_url').$diagnostic[0]['image'];?>" alt="banner" width="60" height="60">
    
          <div class="mb-3">
            <label for="exampleFormControlInput1" class="form-label">One Person Price *</label>
            <input
              type="number"
              class="form-control"
              id="exampleFormControlInput1"
              placeholder="One Person Price" name="one_person" required value="<?=$diagnostic[0]['one_person']?>"/>
          </div>
          
          <div class="mb-3">
            <label for="exampleFormControlInput1" class="form-label">One Person Discount Price *</label>
            <input
              type="number"
              class="form-control"
              id="exampleFormControlInput1"
              placeholder="One Person Discount price" name="one_person_discount" required value="<?=$diagnostic[0]['one_person_discount']?>"/>
          </div>
          
          <div class="mb-3">
            <label for="exampleFormControlInput1" class="form-label">Two Person Price *</label>
            <input
              type="number"
              class="form-control"
              id="exampleFormControlInput1"
              placeholder="Two Person Price" name="two_person" required value="<?=$diagnostic[0]['two_person']?>"/>
          </div>
          
          <div class="mb-3">
            <label for="exampleFormControlInput1" class="form-label">Two Person Discount Price *</label>
            <input
              type="number"
              class="form-control"
              id="exampleFormControlInput1"
              placeholder="Two Person Discount price" name="two_person_discount" required value="<?=$diagnostic[0]['two_person_discount']?>"/>
          </div>
          
          <div class="mb-3">
            <label for="exampleFormControlInput1" class="form-label">Three Person Price *</label>
            <input
              type="number"
              class="form-control"
              id="exampleFormControlInput1"
              placeholder="Three Person Price" name="three_person" required value="<?=$diagnostic[0]['three_person']?>"/>
          </div>
          
          <div class="mb-3">
            <label for="exampleFormControlInput1" class="form-label">Three Person Discount Price *</label>
            <input
              type="number"
              class="form-control"
              id="exampleFormControlInput1"
              placeholder="Three person Discount price" name="three_person_discount" required value="<?=$diagnostic[0]['three_person_discount']?>"/>
          </div>
          
          <div class="mb-3">
            <label for="exampleFormControlInput1" class="form-label">Four Person Price *</label>
            <input
              type="number"
              class="form-control"
              id="exampleFormControlInput1"
              placeholder="Four Person Price" name="four_person" required value="<?=$diagnostic[0]['four_person']?>"/>
          </div>
          
          <div class="mb-3">
            <label for="exampleFormControlInput1" class="form-label">Four Person Discount Price *</label>
            <input
              type="number"
              class="form-control"
              id="exampleFormControlInput1"
              placeholder="Four Person Discount price" name="four_person_discount" required value="<?=$diagnostic[0]['four_person_discount']?>"/>
          </div>
          
          <div class="mb-3">
            <label for="exampleFormControlInput1" class="form-label">Five Person Price *</label>
            <input
              type="number"
              class="form-control"
              id="exampleFormControlInput1"
              placeholder="Five Person Price" name="five_person" required value="<?=$diagnostic[0]['five_person']?>"/>
          </div>
          
          <div class="mb-3">
            <label for="exampleFormControlInput1" class="form-label">Five Person Discount Price *</label>
            <input
              type="number"
              class="form-control"
              id="exampleFormControlInput1"
              placeholder="Five Person Discount Price" name="five_person_discount" required value="<?=$diagnostic[0]['five_person_discount']?>"/>
          </div>
          
          <div class="mb-3">
            <label for="exampleFormControlInput1" class="form-label">Report in(hrs) *</label>
            <input
              type="number"
              class="form-control"
              id="exampleFormControlInput1"
              placeholder="Report in" name="report_in" required value="<?=$diagnostic[0]['report_in']?>"/>
          </div>
          
          <div class="mb-3">
            <label for="exampleFormControlInput1" class="form-label">Fasting *</label>
            <select class="form-select" name="fasting" required placeholder="Fasting">
                <option value="">Select Fasting</option>
                <option value="yes" <?php if($diagnostic[0]['fasting']=='yes'){echo 'selected="selected"';}?>>Yes</option>
                <option value="no" <?php if($diagnostic[0]['fasting']=='no'){echo 'selected="selected"';}?>>No</option>
            </select>
          </div>
          
          
        <div id="testsContainer">
          <?php foreach ($tests as $i => $test): ?>
            <div class="test-group mb-3">
              <div class="card p-3 mb-2 border">
                <div class="mb-2">
                  <label class="form-label">Test Name *</label>
                  <input type="text" name="tests[<?= $i ?>][name]" class="form-control" value="<?= $test['name'] ?>" required>
                  <input type="hidden" name="tests[<?= $i ?>][id]" value="<?= $test['id'] ?>">
                </div>
        
                    <?php 
                      $sub_tests = is_array($test['sub_tests']) ? $test['sub_tests'] : json_decode($test['sub_tests'], true);
                    ?>
                    <div class="sub-tests mb-2">
                      <label class="form-label">Sub Test Name(s) *</label>
                      <?php foreach ($sub_tests as $j => $sub): ?>
                        <div class="sub-test-row mb-1 d-flex gap-2">
                          <input type="text" name="tests[<?= $i ?>][sub_tests][<?= $j ?>][name]" class="form-control" value="<?= $sub['name'] ?>" required>
                          <input type="hidden" name="tests[<?= $i ?>][sub_tests][<?= $j ?>][id]" value="<?= $sub['id'] ?>">
                          <button type="button" class="btn btn-sm btn-danger removeSubTest">Remove</button>
                        </div>
                      <?php endforeach; ?>
                    </div>

        
                <button type="button" class="btn btn-sm btn-outline-primary addSubTest">+ Add Sub Test</button>
                <button type="button" class="btn btn-sm btn-outline-danger removeTest">Remove Test</button>
              </div>
            </div>
          <?php endforeach; ?>
        </div>
        
        <!-- Add Test Button -->
        <button type="button" id="addTest" class="btn btn-outline-success mb-3">+ Add Another Test</button>

            
            <!--<button type="button" id="addTest" class="btn btn-outline-success mb-3">+ Add Another Test</button>-->

          
        </div>
      </div>
      <input type="hidden" class="form-control-file" placeholder="Image" name="image" value="<?=$diagnostic[0]['image']?>">
       <button type="button" name="sub" value="sub" class="btn btn-success" id="saveBtn">Submit</button>
      </form>
      <a href="<?=base_url('admin/register/diagnostic')?>"><button type="button" class="btn btn-danger">Cancel</button></a>
    </div></div>
</div>

<script>
  let testIndex = <?= count($tests) ?>; // continue from last index

  // Add new test
  document.getElementById('addTest').addEventListener('click', function () {
    const container = document.getElementById('testsContainer');
    const html = `
      <div class="test-group mb-3">
        <div class="card p-3 mb-2 border">
          <div class="mb-2">
            <label class="form-label">Test Name *</label>
            <input type="text" name="tests[${testIndex}][name]" class="form-control" placeholder="Enter Test Name" required>
          </div>
          <div class="sub-tests mb-2">
            <label class="form-label">Sub Test Name(s) *</label>
            <div class="sub-test-row mb-1 d-flex gap-2">
              <input type="text" name="tests[${testIndex}][sub_tests][0][name]" class="form-control" placeholder="Enter Sub Test Name" required>
              <button type="button" class="btn btn-sm btn-danger removeSubTest">Remove</button>
            </div>
          </div>
          <button type="button" class="btn btn-sm btn-outline-primary addSubTest">+ Add Sub Test</button>
          <button type="button" class="btn btn-sm btn-outline-danger removeTest">Remove Test</button>
        </div>
      </div>`;
    container.insertAdjacentHTML('beforeend', html);
    testIndex++;
  });

  // Delegate add/remove buttons
  document.addEventListener('click', function (e) {
    // Add sub-test
    if (e.target.classList.contains('addSubTest')) {
      const testGroup = e.target.closest('.test-group');
      const subTests = testGroup.querySelector('.sub-tests');
      const inputs = subTests.querySelectorAll('.sub-test-row');
      const testNameInput = testGroup.querySelector('input[name^="tests["]');
      const match = testNameInput.name.match(/tests\[(\d+)]/);
      const i = match ? match[1] : 0;
      const j = inputs.length;

      const newInput = `
        <div class="sub-test-row mb-1 d-flex gap-2">
          <input type="text" name="tests[${i}][sub_tests][${j}][name]" class="form-control" placeholder="Enter Sub Test Name" required>
          <button type="button" class="btn btn-sm btn-danger removeSubTest">Remove</button>
        </div>`;
      subTests.insertAdjacentHTML('beforeend', newInput);
    }

    // Remove sub-test
    if (e.target.classList.contains('removeSubTest')) {
      e.target.closest('.sub-test-row').remove();
    }

    // Remove test group
    if (e.target.classList.contains('removeTest')) {
      e.target.closest('.test-group').remove();
    }
  });
</script>



<script>
$(document).ready(function () {
    const namePattern = /^[A-Za-z0-9][A-Za-z0-9\s'.-]{2,}$/;
    const numberFields = [
        'one_person', 'one_person_discount',
        'two_person', 'two_person_discount',
        'three_person', 'three_person_discount',
        'four_person', 'four_person_discount',
        'five_person', 'five_person_discount',
        'report_in'
    ];

    $('#saveBtn').on('click', function () {
        let isValid = true;

        $('#inputform [required]').each(function () {
            let value = $(this).val();
            if (Array.isArray(value)) {
                value = value.join('');
            }
            value = value ? value.toString().trim() : '';
            const fieldName = $(this).attr('name');

            // Check if empty
            if (value === '') {
                isValid = false;
                $(this).addClass('is-invalid');
                showToast('Error', `${$(this).attr('placeholder') || 'Field'} is required`, 'error');
                return;
            }

            // Name validations
            if (
                fieldName === 'name' ||
                /\btests\[\d+\]\[name\]$/.test(fieldName) ||
                /\btests\[\d+\]\[sub_tests\]\[\d+\]\[name\]$/.test(fieldName)
            ) {
                if (!namePattern.test(value)) {
                    isValid = false;
                    $(this).addClass('is-invalid');
                    showToast('Error', 'Name must be at least 3 characters and contain only letters, numbers, spaces, dots, hyphens or apostrophes.', 'error');
                    return;
                }
            }

            // Number validations
            if (numberFields.includes(fieldName)) {
                if (isNaN(value) || parseFloat(value) < 0) {
                    isValid = false;
                    $(this).addClass('is-invalid');
                    showToast('Error', `${$(this).attr('placeholder')} cannot be negative`, 'error');
                    return;
                }
            }

            $(this).removeClass('is-invalid').addClass('is-valid');
        });

        if (isValid) {
            const form = $('#inputform')[0];
            const formData = new FormData(form);

            $.ajax({
                url: '<?= base_url("admin/register/edit_diagnostic_data/" . $diagnostic[0]["id"]) ?>',
                type: 'POST',
                data: formData,
                contentType: false,
                processData: false,
                success: function (response) {
                    const res = JSON.parse(response);
                    if (res.success) {
                        showToast('Success', res.message, 'success');
                        // $('#inputform')[0].reset(); // Uncomment if you want to reset
                        $('.form-control').removeClass('is-valid');
                        window.location.href = '<?= base_url("admin/register/diagnostic") ?>';
                    } else {
                        showToast('Error', res.message, 'error');
                    }
                },
                error: function () {
                    showToast('Error', 'An unexpected error occurred.', 'error');
                },
            });
        } else {
            $('html, body').animate({
                scrollTop: $('.is-invalid:first').offset().top - 100,
            }, 500);
        }
    });

    // Real-time validation
    $('#inputform').on('input change', '.form-control', function () {
        const value = $(this).val().toString().trim();
        const fieldName = $(this).attr('name');
        let isFieldValid = true;

        if (value === '') {
            isFieldValid = false;
        } else {
            if (
                fieldName === 'name' ||
                /\btests\[\d+\]\[name\]$/.test(fieldName) ||
                /\btests\[\d+\]\[sub_tests\]\[\d+\]\[name\]$/.test(fieldName)
            ) {
                isFieldValid = namePattern.test(value);
            } else if (numberFields.includes(fieldName)) {
                isFieldValid = !isNaN(value) && parseFloat(value) >= 0;
            }
        }

        if (isFieldValid) {
            $(this).removeClass('is-invalid').addClass('is-valid');
        } else {
            $(this).removeClass('is-valid').addClass('is-invalid');
        }
    });
});
</script>

<!-- Toastr CSS -->
<link href="https://cdnjs.cloudflare.com/ajax/libs/toastr.js/latest/toastr.min.css" rel="stylesheet">
<!-- Toastr JS -->
<script src="https://cdnjs.cloudflare.com/ajax/libs/toastr.js/latest/toastr.min.js"></script>


<script>
// Show toast using jQuery
function showToast(title, message, type) {
    toastr.options = {
        closeButton: true,
        progressBar: true,
        positionClass: "toast-top-right",
        timeOut: "3000",
    };

    if (type === 'success') {
        toastr.success(message, title);
    } else if (type === 'error') {
        toastr.error(message, title);
    } else if (type === 'info') {
        toastr.info(message, title);
    } else if (type === 'warning') {
        toastr.warning(message, title);
    }
}


</script>
            