<?php
include('head.php');
include('header.php'); 
include('sidebar.php'); 
$stmt3 = $pdo->prepare("SELECT * FROM tblpsp WHERE isDeleted='N' ORDER BY pspName ASC");
$stmt3->execute();
$psps = $stmt3->fetchAll();
$stmt6 = $pdo->prepare("SELECT * FROM tblpatient WHERE isDeleted='N' ORDER BY patientName ASC");
$stmt6->execute();
$addedpatient = $stmt6->fetchAll();
$stmt7 = $pdo->prepare("SELECT * FROM tbldrugs WHERE isDeleted='N' ORDER BY drugName ASC");
$stmt7->execute();
$medications = $stmt7->fetchAll();
$stmt8 = $pdo->prepare("SELECT * FROM tblprovince WHERE countryId='1' ORDER BY provinceName ASC");
$stmt8->execute();
$provinces = $stmt8->fetchAll();
$stmt1 = $pdo->prepare("SELECT empId,userName from tbluser WHERE isDeleted='N' AND department='P' || department='R'");
$stmt1->execute();
$np = $stmt1->fetchAll();
$stmt = $pdo->prepare("SELECT * FROM tblphysicians where isDeleted='N' order by lastName ASC");
$stmt->execute();
$physicians = $stmt->fetchAll();

   $stmt81 = $pdo->prepare("SELECT title FROM `tblfiletitles` WHERE isDeleted='N' ORDER BY title ASC");
    $stmt81->execute();
    $fileTitles = $stmt81->fetchAll();
?>
<style>
    ::backdrop {
        background-image: linear-gradient(
            45deg,
            magenta,
            rebeccapurple,
            dodgerblue,
            green
        );
        opacity: 0.75;
    }
        dialog#deadd {
        position: absolute;
        margin: 0px auto;
        top: 40%;
        width: 500px;
        height: 250px;
        padding:10px;
    }
    #deadd h3{
        font-weight:600;
        text-align:center;
        margin:10px;
        font-size:28px;
    }
    #deadd img {
    width: 100px;
    margin: 0px auto;
}
.dfooter {
    justify-content: center;
    align-items: center;
    text-align: center;
    margin-top: 30px;
}
#deadd .close{
        float:right;
        margin-right:10px;
        color:red;
    }
    .autocapitalize{
        text-transform: capitalize;  
    }
    section.content.w70 {
        width: 80%;
        margin-left: 15%;
    }
    aside{
    width:15%;
    }
    .custom-radio.is-invalid {
     border: 1px solid red;
    }
    span.req {
    line-height: 20px !important;
    padding: 0px !important;
    display: inline-flex !important;
    margin-left: 5px;
   }
</style>
<dialog id="deadd">
<a class="close" href="add_patient.php"><i class="fa fa-times" aria-hidden="true"></i></a>
  <img src="images/success.gif">
  <h3>Patient Added Successfully</h3>
  <div class="dfooter">
    <a class="btn btn-secondary" href="" id="viewAddedPatient">View Patient</a>
    <a href="add_patient.php" class="btn btn-primary">Add New Patient</a>
  </div>
</dialog>
<!-- form start -->
<form method="POST" class="araddpatient editWc mg30" enctype="multipart/form-data">
    <!-- Content Wrapper. Contains page content -->
    <div class="content-wrapper">
        <!-- Content Header (Page header) -->
        <!-- Main content -->
        <section class="content w70">
            <div class="container-fluid">
                <div class="row">
                    <!-- left column -->
                    <div class="col-md-12">
                        <!-- general form elements -->
                        <div class="card card-default">
                            <div class="card-header">
                                <h3 class="card-title">Add Patient</h3>
                                <div class="offset-10 ">
                                <a href="../de/" class="btn btn-secondary bg-gradient-primary">BACK</a>
                            </div>
                        </div>
                            <!-- /.card-header -->
                            <div class="card-body">
                            <div class="form-wizard"> 
                            <div class="myContainer">
                                <div class="form-container animated">
                                <h3 class="text-center ftitle">Create Account </h3>
                                <div class="formnote text-left"><span class="colorred">*</span> Mandatory Fields</div>
                                <div class="row">
                                <div class="clearfix"></div>
                                    <div class="col-sm-4">
                                        <div class="form-group">
                                            <label for="drugName">First Name <span class="req">*</span></label>
                                            <input type="text" class="form-control autocapitalize" id='patientFName' required name="patientFName" placeholder="Enter Patient First Name">
                                            <div class="invalid-feedback">Please enter First Name</div>
                                        </div>
                                    </div>
                                    <div class="col-sm-4">
                                        <div class="form-group">
                                            <label for="drugName">Last Name </label>
                                            <input type="text" class="form-control autocapitalize" id='patientLName'  name="patientLName" placeholder="Enter Patient Last Name">
                                        </div>
                                    </div>
                                    <div class="clearfix"></div>
                                    <div class="col-sm-4">
                                        <div class="form-group">
                                            <label for="drugName">DOB <span class="req">*</span></label>
                                            <input type="date" class="form-control" id='dob' required name="dob" placeholder="Enter Patient DOB">
                                            <div class="invalid-feedback">Please enter Date of Birth</div>
                                        </div>
                                    </div>
                                    <div class="col-sm-4">
                                        <div class="form-group">
                                            <label for="drugName">Gender <span class="req">*</span></label>
                                            <select class="form-control" id="gender" name="gender" required>
                                                <option value="">Select Gender</option>
                                                <option value="F">Female</option>
                                                <option value="M">Male</option>
                                                <option value="O">Other</option>
                                            </select>
                                            <div class="invalid-feedback">Please Select Gender</div>
                                        </div>
                                    </div>
                                    <div class="clearfix"></div>
                                    <div class="col-sm-4">
                                                <div class="form-group">
                                                    <label>Mobile Number </label>
                                                    <div class="input-group">
                                                        <div class="input-group-prepend">
                                                            <span class="input-group-text"><i class="fas fa-phone"></i></span>
                                                        </div>
                                                        <input type="text" class="form-control" name="phone" id="phone"  data-inputmask="&quot;mask&quot;: &quot;(999) 999-9999&quot;" data-mask="" required="" inputmode="text">
                                                        <div class="invalid-feedback">Please enter phone number</div>
                                                    </div>
                                                    <!-- /.input group -->
                                                </div>
                                    </div>
                                    <div class="col-sm-4">
                                        <div class="form-group">
                                            <label for="drugName">Email </label>
                                            <input type="email" class="form-control" id='email' required name="email" placeholder="Enter Patient Email">
                                            <div class="invalid-feedback">Please enter Email</div>
                                        </div>
                                    </div>
                                    <div class="clearfix"></div>
                                    <div class="col-sm-4">
                                        <div class="form-group">
                                            <label for="drugName">Address 1 <span class="req">*</span></label>
                                            <input type="text" class="form-control" id='address1' required name="address1" placeholder="Enter Address">
                                            <div class="invalid-feedback">Please enter Address</div>
                                        </div>
                                    </div>
                                    <div class="col-sm-4">
                                        <div class="form-group">
                                            <label for="drugName">Address 2</label>
                                            <input type="text" class="form-control" id='address2' name="address2" placeholder="Enter Address">
                                        </div>
                                    </div>
                                    <div class="clearfix"></div>
                                    <div class="col-sm-4">
                                        <div class="form-group">
                                            <label for="drugName">City <span class="req">*</span></label>
                                            <input type="text" class="form-control autocapitalize" id='city' required name="city" placeholder="Enter City">
                                            <div class="invalid-feedback">Please enter City</div>
                                        </div>
                                    </div>
                                    <div class="col-sm-4 fixselect">
                                        <div class="form-group">
                                            <label for="drugName">Province <span class="req">*</span></label>
                                            <select class="form-control select2bs4" name='province' required id="province">
                                                <option>Select Province</option>
                                                <?php foreach($provinces as $province) { ?>
                                                    <option value="<?php echo $province['provinceName']; ?>"><?php echo $province['provinceName']; ?></option>
                                                <?php } ?>
                                            </select>
                                            <div class="invalid-feedback">Please Select Province</div>
                                           <!-- <input type="text" class="form-control" id='province' required name="province" placeholder="Enter Province"> -->
                                        </div>
                                    </div>
                                    <div class="clearfix"></div>
                                    <div class="col-sm-4">
                                        <div class="form-group">
                                            <label for="drugName">Postal Code <span class="req">*</span></label>
                                            <input type="text" class="form-control" id='postalCode' required name="postalCode" data-inputmask="&quot;mask&quot;: &quot;A9A 9A9&quot;" data-mask="" placeholder="Enter Postal Code">
                                            <div class="invalid-feedback">Please enter Postal Code</div>
                                        </div>
                                    </div>
                                    <div class="col-sm-4">
                                        <div class="form-group">
                                            <label for="krollId">Kroll ID  (RXCON00XXXXX) XXXXX is Kroll ID. ON is province code <span class="req">*</span></label>
                                            <input type="text" class="form-control" id='krollId' required name="krollId" placeholder="Enter Kroll Id">
                                           
                                            <div class="invalid-feedback">Please enter Kroll Id</div>
                                            <div class="hidden" id="krollMessage"></div>
                                        </div>
                                    </div>
                                    <div class="clearfix"></div>
                                    <div class="col-sm-4">
                                        <div class="form-group">
                                            <label for="provincialHCN">Provincial Health Card Number </label>
                                            <input type="text" class="form-control" id='provincialHCN' required name="provincialHCN" placeholder="Enter Provincial Health Card Number">
                                        </div>
                                    </div>
                                    <div class="clearfix"></div>
                                </div>
                                <div class="row"  id="fileInputs">    
                                <div class="col-md-4">
                                    <div class="form-group fileRow">
                                    <label for="paymentId">File Name (Title) <span class="req">*</span></label>
                                        <select name="fileTitle[]" class="form-control fileTitle" id="fileTitle" required>
                                            <option disabled selected>Select File Name</option>
                                            <option>Select File Name</option>
                                              <?php foreach($fileTitles as $titles) {
                                                    $titleRaw = $titles['title'];
                                                    // Remove any unwanted characters from the title for the value attribute
                                                    $titleSanitized = preg_replace('/[^A-Za-z0-9 ]/', '', $titleRaw);
                                                ?>
                                              <option value="<?= htmlspecialchars($titleSanitized) ?>">
                                                <?= htmlspecialchars($titleRaw) ?>
                                              </option>
                                            <?php } ?>
                                        </select>
                                        <div class="invalid-feedback">Please select prescription</div>
                                    </div>
                                </div>
                                    <div class="col-md-4">
                                        <div class="fileRow form-group">
                                        <label for="paymentId">File Attachment <span class="req">*</span></label> 
                                            <input type="file" name="files[]" class="form-control fileInput defiles" id="files" required>
                                            <div class="invalid-feedback">Please upload prescription</div>
                                        </div>
                                    </div>
                                    <div class="right flex">
                                            <button type="button" class="btn btn-default" id="addRowBtn"><i title="Add New Attachment" class="fa fa-plus"></i></button>
                                    </div>
                                </div>
                                    <div class="form-group col-md-4">
                                        <label for="switch">Notes</label>
                                    <textarea class="form-control" id="notes" rows="2"></textarea>
                                    </div>
                                    <ul class="inbuiltwc row">
                                    <li class="text-center ftitle accordion">
                                       <h3>Prescription Drug Information</h3>
                                    </li>
                                    <li class="col-md-4">
                                       <label class="description" for="patientDrugName">Drug Name:  <span class="req">*</span></label>
                                       <div class="fixselect">
                                          <select class="form-control select2bs4" id="patientDrugName" required name="patientDrugName">
                                             <option value="Select Drug">Select Drug</option>
                                             <?php foreach($medications as $medication) { 
                                             if($medication['drugName']!='Dupixent'){
                                             ?>
                                            
                                          <option value="<?php echo $medication['drugName']; ?>"><?php echo $medication['drugName']; ?></option>
                                          <?php } } ?>
                                          </select>
                                            <div class="invalid-feedback">Please Select Drug</div>
                                       </div>
                                    </li>
                                    <li class="col-md-4">
                                       <label class="description" for="dose">Dose: </label>
                                       <div>
                                          <input id="dose" name="dose" class="form-control" type="text" autocomplete="off">
                                       </div>
                                    </li>
                                    <li class="clearfix"></li>
                                    <li class="col-md-4">
                                       <label class="description" for="roa">Route of Administration: </label>
                                       <div>
                                          <select class="form-control" id="roa" name="roa">
                                             <option value=""></option>
                                             <option value="Subcutaneous">Subcutaneous</option>
                                             <option value="Intramuscular">Intramuscular</option>
                                             <option value="Intravenous">Intravenous</option>
                                             <option value="Oral">Oral</option>
                                          </select>
                                       </div>
                                    </li>
                                    <li class="clearfix"></li>
                                    <!-- <li class="col-md-4">
                                       <label class="description" for="pwkl">Patient Weight (kg/lb) </label>
                                       <div>
                                          <input id="pwkl" name="pwkl" class="form-control" type="text" autocomplete="off">
                                       </div>
                                    </li> -->
                                    <!-- <li class="clearfix"></li> -->
                                    <!-- <li class="col-md-4">
                                       <label class="description" for="indication">Indication: </label>
                                       <div>
                                          <input id="indication" name="indication"  class="form-control" type="text" autocomplete="off">
                                       </div>
                                    </li> -->
                                    <!-- <li class="clearfix"></li> -->
                                    <!-- <li class="col-md-4">
                                       <label class="description" for="oluse">Off-Label Use: </label>
                                       <div>
                                          <select class="form-control" id="oluse" name="oluse">
                                             <option value="" selected="selected"></option>
                                             <option value="Y">Yes</option>
                                             <option value="N">No</option>
                                          </select>
                                       </div>
                                    </li> -->
                                    <!-- <li class="clearfix"></li> -->
                                    <li class="col-md-4">
                                       <label class="description" for="prescriberName">Prescriber's Name : </label>
                                       <div  class="fixselect">
                                          <!-- <input id="prescriberName" name="prescriberName" class="form-control" type="text"  autocomplete="off"> -->
                                          <select class="form-control select2bs4" id="prescriberName" name="prescriberName"  autocomplete="off">
                                             <option value="">Select Prescriber Name</option>
                                             <?php foreach($physicians as $medication) { 
                                                $physicianFullname=$medication['firstName']." ".$medication['lastName'];
                                                $assignedTo=getuserName($pdo,$medication['assignedTo']);
                                                $primarySpecialty=$medication['primarySpecialty'];
                                                ?>
                                          <option data-staff="<?=$assignedTo;?>" data-specialty="<?=$primarySpecialty;?>" value="<?php echo $physicianFullname; ?>"><?php echo $medication['lastName']." ".$medication['firstName']; ?></option>
                                          <?php } ?>
                                          </select>
                                       </div>
                                    </li>
                                    <li class="col-md-4">
                                       <label class="description" for="prescriberSpecialty">Prescriber's Specialty: </label>
                                       <div>
                                          <input id="prescriberSpecialty" name="prescriberSpecialty" class="form-control" type="text" autocomplete="off"> 
                                       </div>
                                    </li>
                                    <li class="clearfix"></li>
                                    <!-- <li class="col-md-4">
                                       <label class="description" for="team">Team: </label>
                                       <div>
                                          <input id="team" name="team" class="form-control" type="text" autocomplete="off">
                                       </div>
                                    </li> -->
                                    <li class="col-md-4">
                                       <label class="description" for="staff">Staff: </label>
                                       <div>
                                          <!-- <input id="staff" name="staff" class="form-control" type="text"  autocomplete="off"> -->
                                          <div class="fixselect">
                                             <select class="form-control select2bs4" id="staff" name="staff">
                                                <option value="" >Select Staff</option>
                                                <?php foreach ($np as $emp) { ?>
                                                   <option value="<?= $emp['userName']; ?>"><?= $emp['userName']; ?></option>
                                                <?php } ?>
                                             </select>
                                          </div>
                                       </div>
                                    </li>
                                    <li class="clearfix"></li>
                                    <li class="col-md-8">
                                       <label class="description">Did Patient get Sample Dose from Prescribers office? <span class="req">*</span></label>
                                       <div>
                                          <fieldset>
                                             <span class="flex">
												<input type="radio" id="yesDpgsd"  name="Dpgsd" value="Y" class="custom-radio">
												<label for="yesDpgsd" class="radio-label">Yes</label>				
                                             </span>
                                             <span class="flex">
												<input type="radio" id="noDpgsd"  name="Dpgsd" value="N" class="custom-radio">
												<label for="noDpgsd" class="radio-label">No</label>
                                             </span>
                                             <span class="flex">
												<input type="radio" id="unsureDpgsd"  name="Dpgsd" value="U" class="custom-radio">
												<label for="unsureDpgsd" class="radio-label">Unsure</label>
                                                <div style='margin-left:10px;' class="invalid-feedback">Please Select Yes / No / Unsure</div>
                                             </span>
                                          </fieldset>
                                       </div>
                                    </li>
                                    <li class="clearfix"></li>
                                    <li class="sampleDosePrescriber col-md-4">
                                       <fieldset>
                                          <label class="smpDate">Date Patient Received Sample Dose: </label>
                                          <div>
                                             <input type="date" class="form-control" id="smpDate"  name="smpDate">
                                          </div>
                                       </fieldset>
                                    </li>
                                     <li>
                                       <span class="description">Is Patient Ready for Welcome Call? </span>
                                       <div>
                                          <fieldset>

                                             <span class="flex">
                                                <input  type="radio" id="yesiprfwc" name="iprfwc" value="Y" class="custom-radio">
                                                <label for="yesiprfwc" class="radio-label">Yes</label>
                                             </span>

                                             <span class="flex">
                                                <input  type="radio" id="noiprfwc" name="iprfwc" value="N" class="custom-radio">
                                                <label for="noiprfwc" class="radio-label">No</label>
                                             </span>
                                            
                                          </fieldset>
                                       </div>
                                    </li>
                                      <li class="clearfix"></li>
                                      <li class="col-md-4">
                                       <fieldset>
                                          <label class="description">Enrolment Form Receive Date and Time: </label>
                                          <div>
                                             <input type="datetime-local" class="form-control" id="enrolmentFormReceiveDate"  max="<?php echo date('Y-m-d\TH:i'); ?>" name="enrolmentFormReceiveDate" required>
                                              <div class="invalid-feedback">Please enter Enrolment Form Receive Date and Time</div>
                                          </div>
                                       </fieldset>
                                    </li>
                                    </ul>
                                    <div class="form-group mar-b-0">
                                    <!-- <input type="button" value="NEXT" class="btn btn-primary next">   -->   
                                        <button type="submit" value="SAVE" name="savepatientdetials" id="savegeneral" class="btn btn-success save"> SAVE  </button>   
                                    </div>
                                    </div>
                                </div>
                                </div>
                            <!-- /.card-body -->
                        </div>
                        <!-- /.card -->
                    </div>
                </div>
                <!-- /.container-fluid -->
            </div>
        </section>
        <!-- /.content -->
    </div>
    <!-- /.content-wrapper -->
</form>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
 <script>
       $(document).ready(function() {
        $('.accordion').click(function() {
        var $ftitle = $(this).closest('.ftitle');
        var $nextftitle = $ftitle.nextUntil('.ftitle');
        // Hide all li elements between current and next .ftitle
        if ($nextftitle.hasClass('accordion-hide')) {
        $nextftitle.removeClass('accordion-hide');
        } else {
        // Hide all li elements between current and next .ftitle
        $nextftitle.addClass('accordion-hide');
        }
        });
    // Attach change event to the Prescriber Name dropdown
    $('#prescriberName').on('change', function () {
        // Get the selected option's data-specialty value
        const specialty = $(this).find('option:selected').data('specialty');
        const staff = $(this).find('option:selected').data('staff');
        // Update the Prescriber Specialty input field with the value
        $('#prescriberSpecialty').val(specialty || ''); // Default to empty if no value
        $('#staff').select2().val(staff || '').trigger('change');
    });

    });
   $('#psp').change(function(){
           var psp = $("#psp option:selected").val();
           $.ajax({
               type: "POST",
               dataType: "html",
               url: "ajax_call.php?ajaxcall=4&id="+psp,
               success: function (data){
                   $('#drug').append(data);
               }
           })
       });
	   $(window).scroll(function() {
            var scrollHeight = $(this).scrollTop();
            var content = $('#shift');
            if (scrollHeight > 20) {
                content.addClass('moveToRight');
            } else {
                content.removeClass('moveToRight');
            }
        });
       $('#medicationId').change(function() {
           $('#pspId').remove();
           var medication = $("#medicationId option:selected").val();
           $.ajax({
               type: "POST",
               dataType: "html",
               url: "ajax_call.php?ajaxcall=1&id="+medication,
               success: function (data){
                   $('#pspDiv').append(data);
               }
           });
       });
const dialog = document.querySelector("dialog");
const showButton = document.querySelector("dialog + button");
// const closeButton = document.querySelector("dialog button");
     // Function to check if input is empty
     function isFieldEmpty(field) {
        return $(field).val().trim() === "";
    }
    // Function to set input field red if invalid
    function setFieldInvalid(field) {
        $(field).addClass('is-invalid');
    }
    // Function to reset field validation (remove red border)
    function resetFieldValidation(field) {
        $(field).removeClass('is-invalid');
    }
    function isRadioGroupValid(name) {
        return $('input[name="' + name + '"]:checked').length > 0;
    }
   $("#savegeneral").on("click", function (e) {
    e.preventDefault(); // Prevent form submission for validation
        let validationPassed = true; // Flag to track if validation passed
        let firstInvalidField = null; // Track the first invalid field
        // Reset validation classes before new validation
        resetFieldValidation('#patientFName');
        resetFieldValidation('#dob');
        resetFieldValidation('#enrolmentFormReceiveDate');
        resetFieldValidation('#gender');
        resetFieldValidation('#phone');
        resetFieldValidation('#email');
        resetFieldValidation('#address1');
        resetFieldValidation('#city');
        resetFieldValidation('#province');
        resetFieldValidation('#postalCode');
        resetFieldValidation('#krollId');
        resetFieldValidation('input[name="Dpgsd"]'); // Reset radio button validation
        resetFieldValidation('#files');
        resetFieldValidation('#fileTitle');
        resetFieldValidation('#patientDrugName');
        
        // Check each required field and add red border if empty
        if (isFieldEmpty('#patientFName')) {
            setFieldInvalid('#patientFName');
            validationPassed = false;
            firstInvalidField = firstInvalidField || '#patientFName';
        }
        if (isFieldEmpty('#dob')) {
            setFieldInvalid('#dob');
            validationPassed = false;
            firstInvalidField = firstInvalidField || '#dob';
        }
         if (isFieldEmpty('#enrolmentFormReceiveDate')) {
            setFieldInvalid('#enrolmentFormReceiveDate');
            validationPassed = false;
            firstInvalidField = firstInvalidField || '#enrolmentFormReceiveDate';
        }
        
        if ($('#gender').val() === "") {
            setFieldInvalid('#gender');
            validationPassed = false;
            firstInvalidField = firstInvalidField || '#gender';
        }
        if (isFieldEmpty('#phone')) {
            // setFieldInvalid('#phone');
            // validationPassed = false;
        }
        if (isFieldEmpty('#email')) {
            // setFieldInvalid('#email');
            // validationPassed = false;
        }
        if (isFieldEmpty('#address1')) {
            setFieldInvalid('#address1');
            validationPassed = false;
            firstInvalidField = firstInvalidField || '#address1';
        }
        if (isFieldEmpty('#city')) {
            setFieldInvalid('#city');
            validationPassed = false;
            firstInvalidField = firstInvalidField || '#city';
        }
        //alert($('#province').val());
        if ($('#province').val() === "Select Province") {
            setFieldInvalid('#province');
            validationPassed = false;
            toastr.error('Please Select Province');
            firstInvalidField = firstInvalidField || '#province'; 
        }
         if ($('#patientDrugName').val() === "Select Drug") {
            setFieldInvalid('#patientDrugName');
            validationPassed = false;
            toastr.error('Please Select Drug');
            firstInvalidField = firstInvalidField || '#patientDrugName'; 
        }
        
        if (isFieldEmpty('#postalCode')) {
            setFieldInvalid('#postalCode');
            validationPassed = false;
            firstInvalidField = firstInvalidField || '#postalCode'; 
        }
        if (!isRadioGroupValid('Dpgsd')) {
            setFieldInvalid('input[name="Dpgsd"]');
            validationPassed = false;
            toastr.error('Required Field : Did Patient get Sample Dose from Prescribers office?');
            firstInvalidField = firstInvalidField || 'input[name="Dpgsd"]'; 
        }
        if (isFieldEmpty('#krollId')) {
            setFieldInvalid('#krollId');
            validationPassed = false;
            firstInvalidField = firstInvalidField || '#krollId'; 
        }
        ////file validation 
        let fileInputsx = document.getElementsByClassName('defiles');
        let fileTitlesx = document.getElementsByClassName('fileTitle');
        let fileValidationPassed = false;

        // for (let i = 0; i < fileInputsx.length; i++) {
        //     let files = fileInputsx[i].files;
        //     let title = fileTitlesx[i].value;

        //     if (files.length > 0 && title !== "Select File Name" && title !== "") {
        //         fileValidationPassed = true; // At least one valid file and title are present
        //         break;
        //     }
        // }
        if(fileInputsx[0].files.length==0){
            setFieldInvalid('#files');
            validationPassed = false; 
            firstInvalidField = firstInvalidField || '#fileInputs'; // Focus on the file inputs section
        }
        if(fileTitlesx[0].value == "Select File Name" || fileTitlesx[0].value == ""){
            setFieldInvalid('#fileTitle');
            validationPassed = false; 
            firstInvalidField = firstInvalidField || '#fileInputs'; // Focus on the file inputs section
        }
            ////file validation end
        // Scroll to the first invalid field if validation fails
        if (!validationPassed && firstInvalidField) {
            $(firstInvalidField)[0].scrollIntoView({ behavior: 'smooth', block: 'center' });
            return; // Exit if validation fails
        }
        /////file validation
        if (!validationPassed && firstInvalidField) {
            $(firstInvalidField)[0].scrollIntoView({ behavior: 'smooth', block: 'center' });
            return; // Exit if validation fails
        }
        // If validation passes, submit the form
       // if (validationPassed) {
        // If validation failed, show alert dialog
        if (validationPassed){
           var formData = new FormData();
           // Append files to the FormData object
           var pspId =$("#pspId option:selected").val();
           var medicationId = $("#medicationId option:selected").val();
           var patientFName = $('#patientFName').val();
           var patientLName = $('#patientLName').val();
           var patientId = $('#patientId').val();
           var dob = $('#dob').val();
           var enrolmentFormReceiveDate = $('#enrolmentFormReceiveDate').val();
           var gender = $("#gender option:selected").val();
           var phone = $('#phone').val();
           var email = $('#email').val();
           var address1 = $('#address1').val();
           var address2 = $('#address2').val();
           var city = $('#city').val();
           var province = $('#province').val();
           var postalCode = $('#postalCode').val();
           var krollId = $('#krollId').val();
           var notes = $('#notes').val();
           //wcpart 5
           var patientDrugName = $("#patientDrugName option:selected").val();
           var dose = $('#dose').val();
           var roa = $("#roa option:selected").val();
           var prescriberName = $('#prescriberName').val();
           var prescriberSpecialty = $('#prescriberSpecialty').val();
           var team = $('#team').val();
           var staff = $('#staff').val();           
           var Dpgsd = $("input[name='Dpgsd']:checked").val();
           var smpDate = $('#smpDate').val();
           var provincialHCN = $('#provincialHCN').val();
           var iprfwc=$("input[name='iprfwc']:checked").val();
           //wc part 5
            var fileInputs = document.getElementsByClassName('defiles');
            var fileTitles = document.getElementsByClassName('fileTitle');
            for (var i = 0; i < fileInputs.length; i++) {
                var files = fileInputs[i].files;
                var title = fileTitles[i].value;
                for (var j = 0; j < files.length; j++) {
                    formData.append('files[]', files[j]); // Append each file
                    formData.append('fileTitle[]', title); // Append corresponding file title
                }
            }
        // Append text data to the FormData object
        formData.append('pspId', pspId);
        formData.append('medicationId', medicationId);
        formData.append('patientFName', patientFName);
        formData.append('patientLName', patientLName);
        //formData.append('patientId', patientId);
        formData.append('dob', dob);
        formData.append('enrolmentFormReceiveDate', enrolmentFormReceiveDate);
        formData.append('gender', gender);
        formData.append('phone', phone);
        formData.append('email', email);
        formData.append('address1', address1);
        formData.append('address2', address2);
        formData.append('city', city);
        formData.append('province', province);
        formData.append('postalCode', postalCode);
        formData.append('notes', notes);
        formData.append('krollId', krollId);
        //wc part 5
        formData.append('patientDrugName', patientDrugName);
        formData.append('dose', dose);
        formData.append('roa', roa);
        formData.append('prescriberName', prescriberName);
        formData.append('prescriberSpecialty', prescriberSpecialty);
        formData.append('team', team);
        formData.append('staff', staff);
        formData.append('Dpgsd', Dpgsd);
        formData.append('smpDate', smpDate);
        formData.append('provincialHCN', provincialHCN);
        formData.append('iprfwc', iprfwc);
        //
           $.ajax({
                 url: 'ajax_call.php?ajaxcall=addPatient',
                type: 'POST',
                data: formData,
                processData: false,  // Required to prevent jQuery from automatically transforming the data into a query string
                contentType: false,  // Required to prevent jQuery from setting the content type header (it will be set automatically)
                success: function(response) {
                   console.log('Data sent successfully');
                   ///////////////////////////////////////
                   //////////////////////////////////////
                   if(response!='failed'){
                        dialog.showModal();
                        $('#viewAddedPatient').attr("href", response);
                    }
                //    var notyf = new Notyf();
                //    // Display an error notification
                //    notyf.success('Patient Updated Successfully');
                   // Reload the page after 2 seconds (adjust the delay as needed)
                   // 2000 milliseconds = 2 seconds
                   //   updateinvoice();
               },
               error: function (xhr, status, error) {
                   console.error('Error sending data:', error);
                   // Handle error if needed
               }
           });
        }
   });
$('.sampleDosePrescriber').hide();
$("input[name='Dpgsd']").on("change", function () {
    if ($(this).val() === 'Y') {
        $('.sampleDosePrescriber').show();
    } else if ($(this).val() === 'N') {
        $('.sampleDosePrescriber').hide();
    } else if ($(this).val() === 'U') {
        $('.sampleDosePrescriber').hide();
    }
});
$("input[name='krollId']").on("input", function () {
    $("input[name='krollId']").on("input", function () {
    const krollId = $(this).val().trim();

    // Check if input is not empty
    if (krollId) {
        $.ajax({
            url: "ajax_call.php?ajaxcall=checkKrollId", // Replace with your actual API endpoint
            method: "POST",
            data: { krollId: krollId },
            success: function (response) {
          debugger;   
    // KROLL ID already exists
    const data = typeof response === "string" ? JSON.parse(response) : response;

   if (data.exists) {
    $('#krollMessage')
        .html("KROLL ID already exists. Please use a unique ID.")
        .removeClass("hidden") // Make the message visible
        .css("color", "red");  // Optional: Add styling for visibility
} else {
    $('#krollMessage')
        .html("")              // Clear the message
        .addClass("hidden")    // Hide the element
        .css("color", "");     // Reset any previously applied styles
    console.log("KROLL ID is available.");
}

            },
            error: function () {
                alert("An error occurred while checking the KROLL ID.");
            }
        });
    }
});

});

      var totalSteps = $(".steps li").length;
      var currentPage=1;
      const searchParams = new URLSearchParams(window.location.search);
    	if(searchParams.get('token')){
       		currentPage=searchParams.get('token'); // price_descending
   		}
   	$(".steps li:nth-of-type("+currentPage+")").addClass("active");
   	$(".myContainer .form-container:nth-of-type("+currentPage+")").addClass("active");
//       $(".steps li").on("click", function () {
//   var stepVal = $(this).find("span").text();
//   $(this).prevAll().addClass("active");
//   $(this).addClass("active");
//   $(this).nextAll().removeClass("active");
//   $(".myContainer .form-container").removeClass("active flipInX");
//   $(".myContainer .form-container:nth-of-type(" + stepVal + ")").addClass(
//     "active flipInX"
//   );
// });
   $(".form-container").on("click", ".next", function () {
     $(".steps li")
       .eq($(this).parents(".form-container").index() + 1)
       .addClass("active");
       $(this)
       .parents(".form-container")
       .removeClass("active")
       .next()
       .addClass("active flipInX");
   });
   $(".form-container").on("click", ".back", function () {
     $(".steps li")
       .eq($(this).parents(".form-container").index() - totalSteps)
       .removeClass("active");
     $(this)
       .parents(".form-container")
       .removeClass("active flipInX")
       .prev()
       .addClass("active flipInY");
   });
    window.fileTitles = <?php echo json_encode(array_map(function($t) {
    return $t['title'];
  }, $fileTitles)); ?>;
document.addEventListener('DOMContentLoaded', function () {
    const addRowBtn = document.getElementById('addRowBtn');
    const fileInputsContainer = document.getElementById('fileInputs');
    const addRowBtn1 = document.getElementById('addRowBtn1');
    const fileInputsContainer1 = document.getElementById('fileInputs1');
    const addRowBtn2 = document.getElementById('addRowBtn2');
    const fileInputsContainer2 = document.getElementById('fileInputs2');

    function getFileTitleOptions() {
        const titles = window.fileTitles || [];
        let options = '<option disabled selected>Select File Name</option>';
        titles.forEach(function(title) {
            options += `<option>${title}</option>`;
        });
        return options;
    }

    addRowBtn.addEventListener('click', function () {
        const fileRow = document.createElement('div');
        fileRow.classList.add('row');
        fileRow.innerHTML = `
            <div class="col-md-4">
                <div class="form-group fileRow">
                    <label for="fileTitle">File Name (Title)</label>
                    <select name="fileTitle[]" class="form-control">
                        ${getFileTitleOptions()}
                    </select>
                </div>
            </div>
            <div class="col-md-4">
                <div class="fileRow form-group">
                    <label for="files[]">File Attachment</label>
                    <input type="file" name="files[]" class="form-control fileInput">
                </div>
            </div>`;
        fileInputsContainer.appendChild(fileRow);
    });

    addRowBtn1.addEventListener('click', function () {
        const fileRow = document.createElement('div');
        fileRow.classList.add('row');
        fileRow.innerHTML = `
            <div class="col-md-4">
                <input type="file" name="pmmd[]" multiple class="form-control fileInput">
            </div>`;
        fileInputsContainer1.appendChild(fileRow);
    });

    addRowBtn2.addEventListener('click', function () {
        const fileRow = document.createElement('div');
        fileRow.classList.add('row');
        fileRow.innerHTML = `
            <div class="col-md-4">
                <input type="file" name="screeningDocs[]" multiple class="form-control fileInput">
            </div>`;
        fileInputsContainer2.appendChild(fileRow);
    });
});
</script>
<!-- bs-custom-file-input -->
<script src="plugins/bs-custom-file-input/bs-custom-file-input.min.js"></script>
<?php include('footer.php'); ?>