<div class="container-xxl flex-grow-1 container-p-y">
              <h4 class="py-3 mb-4"><span class="text-muted fw-light">Add 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>
            </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" required/>
          </div>
          <p style="color:red">please upload only jpg,jpeg and png format files</p>
          
    
          <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" min="0" required/>
          </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" min="0" required/>
          </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" min="0" required/>
          </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" min="0" required/>
          </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" min="0" required/>
          </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" min="0" required/>
          </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" min="0" required/>
          </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" min="0" required/>
          </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" min="0" required/>
          </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" min="0" required/>
          </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" min="0" required/>
          </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">Yes</option>
                <option value="no">No</option>
            </select>
          </div>
          
          
          <div id="testsContainer">
              <div class="test-group mb-3">
                <div class="card p-3 mb-2 border position-relative">
                  <button type="button" class="btn-close position-absolute top-0 end-0 m-2 removeTest" aria-label="Remove Test"></button>
                  <div class="mb-2">
                    <label class="form-label">Test Name *</label>
                    <input type="text" name="tests[0][test_name]" class="form-control" placeholder="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">
                      <input type="text" name="tests[0][sub_tests][]" class="form-control me-2" placeholder="Sub Test Name" required>
                      <button type="button" class="btn btn-danger btn-sm removeSubTest">Remove</button>
                    </div>
                  </div>
                  <button type="button" class="btn btn-sm btn-outline-primary addSubTest">+ Add Sub Test</button>
                </div>
              </div>
            </div>
            
            <button type="button" id="addTest" class="btn btn-outline-success mb-3">+ Add Another Test</button>

          
        </div>
      </div>
       <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 = 1;

  // 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 position-relative">
          <button type="button" class="btn-close position-absolute top-0 end-0 m-2 removeTest" aria-label="Remove Test"></button>
          <div class="mb-2">
            <label class="form-label">Test Name *</label>
            <input type="text" name="tests[${testIndex}][test_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">
              <input type="text" name="tests[${testIndex}][sub_tests][]" class="form-control me-2" placeholder="Enter Sub Test Name" required>
              <button type="button" class="btn btn-danger btn-sm removeSubTest">Remove</button>
            </div>
          </div>
          <button type="button" class="btn btn-sm btn-outline-primary addSubTest">+ Add Sub Test</button>
        </div>
      </div>`;
    container.insertAdjacentHTML('beforeend', html);
    testIndex++;
  });

  // Delegate Sub Test and Remove actions
  document.addEventListener('click', function (e) {
    if (e.target.classList.contains('addSubTest')) {
      const subTestSection = e.target.closest('.test-group').querySelector('.sub-tests');
      const testNameInput = subTestSection.querySelector('input');
      const nameAttr = testNameInput.getAttribute('name');
      const newSubTest = `
        <div class="sub-test-row mb-1 d-flex">
          <input type="text" name="${nameAttr}" class="form-control me-2" placeholder="Enter Sub Test Name" required>
          <button type="button" class="btn btn-danger btn-sm removeSubTest">Remove</button>
        </div>`;
      subTestSection.insertAdjacentHTML('beforeend', newSubTest);
    }

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

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


<script>
$(document).ready(function () {
    $('#saveBtn').on('click', function () {
        let isValid = true;

        const namePattern = /^[A-Za-z][A-Za-z0-9\s'.-]{2,}$/;

        // Validate all required fields
        $('#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');

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

            // Name validation
            if (fieldName === 'name' && !namePattern.test(value)) {
                isValid = false;
                $(this).addClass('is-invalid');
                showToast('Error', 'Name must start with a letter and be at least 3 characters long.', 'error');
                return;
            }

            // Non-negative number validation
            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'
            ];
            
            if (numberFields.includes(fieldName)) {
                // Only allow digits and ensure value > 0
                if (!/^[1-9][0-9]*$/.test(value)) {
                    isValid = false;
                    $(this).addClass('is-invalid');
                    showToast('Error', `${$(this).attr('placeholder')} must be a whole number greater than 0.`, 'error');
                    return;
                }
            }


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

        // Validate dynamic test and sub-tests
        $('#testsContainer .test-group').each(function () {
            const testName = $(this).find('input[name*="[test_name]"]');
            const testValue = testName.val().trim();

            if (!namePattern.test(testValue)) {
                isValid = false;
                testName.addClass('is-invalid');
                showToast('Error', 'Test Name must start with a letter and be at least 3 characters.', 'error');
            } else {
                testName.removeClass('is-invalid').addClass('is-valid');
            }

            $(this).find('input[name*="[sub_tests]"]').each(function () {
                const subTestValue = $(this).val().trim();
                if (!namePattern.test(subTestValue)) {
                    isValid = false;
                    $(this).addClass('is-invalid');
                    showToast('Error', 'Sub Test Name must start with a letter and be at least 3 characters.', 'error');
                } else {
                    $(this).removeClass('is-invalid').addClass('is-valid');
                }
            });
        });

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

            $.ajax({
                url: '<?= base_url("admin/register/insert_diagnostic"); ?>',
                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();
                        $('.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().trim();
        const fieldName = $(this).attr('name');
        const namePattern = /^[A-Za-z][A-Za-z0-9\s'.-]{2,}$/;
        let isFieldValid = true;

        if (value === '') {
            isFieldValid = false;
        } else {
            if (fieldName === 'name' || fieldName?.includes('[test_name]') || fieldName?.includes('[sub_tests]')) {
                isFieldValid = namePattern.test(value);
            } else if ([
                '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'
            ].includes(fieldName)) {
                // ✅ Only allow whole numbers greater than 0
                isFieldValid = /^[1-9][0-9]*$/.test(value);
            }
        }


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

    // Add / Remove dynamic test & sub-test handlers
    let testIndex = 1;

    $('#addTest').on('click', function () {
        const testHtml = `
        <div class="test-group mb-3">
          <div class="card p-3 mb-2 border position-relative">
            <button type="button" class="btn-close position-absolute top-0 end-0 m-2 removeTest" aria-label="Remove Test"></button>
            <div class="mb-2">
              <label class="form-label">Test Name *</label>
              <input type="text" name="tests[${testIndex}][test_name]" class="form-control" placeholder="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">
                <input type="text" name="tests[${testIndex}][sub_tests][]" class="form-control me-2" placeholder="Sub Test Name" required>
                <button type="button" class="btn btn-danger btn-sm removeSubTest">Remove</button>
              </div>
            </div>
            <button type="button" class="btn btn-sm btn-outline-primary addSubTest">+ Add Sub Test</button>
          </div>
        </div>`;
        $('#testsContainer').append(testHtml);
        testIndex++;
    });

    $('#testsContainer').on('click', '.removeTest', function () {
        $(this).closest('.test-group').remove();
    });

    $('#testsContainer').on('click', '.addSubTest', function () {
        const testGroup = $(this).closest('.test-group');
        const inputName = testGroup.find('input[name*="[test_name]"]').attr('name');
        const match = inputName.match(/tests\[(\d+)\]/);
        const index = match ? match[1] : 0;

        const subTestHtml = `
        <div class="sub-test-row mb-1 d-flex">
          <input type="text" name="tests[${index}][sub_tests][]" class="form-control me-2" placeholder="Sub Test Name" required>
          <button type="button" class="btn btn-danger btn-sm removeSubTest">Remove</button>
        </div>`;
        testGroup.find('.sub-tests').append(subTestHtml);
    });

    $('#testsContainer').on('click', '.removeSubTest', function () {
        $(this).closest('.sub-test-row').remove();
    });
});
</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>
            