<?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();
$sql="SELECT * FROM tbldrugs WHERE isDeleted='N'";
if($_GET['pspId']){
    $pspId=$_GET['pspId'];
    $sql.=" and pspId=$pspId";
}
$sql .=" ORDER BY drugName ASC";
$stmt7 = $pdo->prepare($sql); 
$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();
$stmt = $pdo->prepare("SELECT * from tblphysiciansaddress WHERE isDeleted = 'N'");
$stmt->execute();
$primaryAddress = $stmt->fetchAll();
////consent
$stmt = $pdo->prepare("SELECT * FROM tblconsentversions where isDeleted = 'N' ORDER BY STR_TO_DATE(version, '%b %Y') DESC;");
$stmt->execute();
$mats = $stmt->fetchAll();
/////consent

// tblgender
function getGender($pdo){
    $stmt1 = $pdo->prepare("Select * from tblgender where tblgender.isActive='Y'");
    $stmt1->execute();
    return $stmt1->fetchAll();
}

// tblrouteofadministration
function getRouteofadministration($pdo){
    $stmt1 = $pdo->prepare("Select * from tblrouteofadministration where tblrouteofadministration.isActive='Y'");
    $stmt1->execute();
    return $stmt1->fetchAll();
}

//master tables start
$gender_pl = getGender($pdo);
$routeofadministration_pl = getRouteofadministration($pdo);
//master tables end

?>
<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;
   }
   .prescriber-address-fields{
        display: none;
    }
.fixselectmultiple span.select2.select2-container.select2-container--default {
    padding: 0px !important;
    margin: 0px !important;
    height: 45px !important;
}
.fixselectmultiple span.select2-selection.select2-selection--multiple {
    display: inline-flex;
    padding:0px !important;
    width: 100%;
    text-align: left;
    justify-content: left;
}
.fixselectmultiple .select2-selection--multiple span{
   padding:0px 5px !important;
}
.fixselectmultiple button.select2-selection__choice__remove {
    padding: 0px !important;
}
</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 Existing 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">Patient Info </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 existingPatient fixselect">
                                   <div class="form-group">
                                      <label for="drugName">Select Patient <span class="req">*</span></label>
                                      <select class="form-control select2bs4" id="patientId" name="patientId">
                                         <option>Select Patient</option>
                                         <?php foreach($addedpatient as $patient){ ?>
                                         <option value="<?=$patient['id'];?>"><?=$patient['patientName'];?></option>
                                         <?php } ?>
                                      </select>
                                      <div class="invalid-feedback">Please Select Patient</div>
                                   </div>
                                </div>
                                 <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 readonly 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 style="pointer-events: none;">
                                                <option value="">Select Gender</option>
                                                <?php 
                                                    foreach($gender_pl as $picklist){?>
                                                    <option value="<?=$picklist['value'];?>"><?=$picklist['name'];?></option>
                                                <?php } ?>
                                            </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" 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'){
                                             if($medication['drugName']!='Dupixent' 
                                             && $medication['drugName']!='Idacio' && $medication['drugName']!='Tyenne' && $medication['drugName']!='Otulfi' 
                                             && $medication['drugName']!='Taro-Tofacitinib' && $medication['drugName']!='Ilumya'
                                             && $medication['drugName']!='Omlyclo' && $medication['drugName']!='Remdantry'&& $medication['drugName']!='Remsima' && $medication['drugName']!='Steqeyma'&& $medication['drugName']!='Yuflyma'){
                                             ?>
                                            
                                          <option value="<?php echo $medication['drugName']; ?>"><?php echo $medication['drugName']; ?></option>
                                          <?php } } ?>
                                          </select>
                                            <div class="invalid-feedback">Please Select Drug</div>
                                       </div>
                                    </li>
                                    <!--// indication added start-->
                                    <li class="col-md-4 fixselectmultiple">
                                          <label class="description" for="indication">Indications: <span
                                                class="req">*</span></label>
                                                <select class="form-control select2bs4" multiple name="indication[]" id="indication" placeholder="Please Select Indication">
                                                   <option value="" disabled>Select Indication</option>
                                                </select>
                                             <div class="invalid-feedback">Please Select Indication</div>
                                    </li>
                                    <!--// indication added end-->
                                    <!--// loading dose start-->
                                    <li class="clearfix"></li> 
                                    <li class="clearfix isAppealNo"><h2 style="color: #9C27B0;">Loading Details</h2></li>
                                    <li class="clearfix"></li>
                                    <li class="col-md-4">
                                       <label class="description" for="ldosage">Dose: </label>
                                       <div class="fixselect">
                                            <select class="form-control select2bs4 addTags" name="ldosage" id="ldosage">
                                                <option selected value="">Select Dose</option>
                                            </select>
                                        </div>
                                    </li>
                                     <li class="col-md-4">
                                          <label class="description" for="lfrequency">Frequency:</label>
                                          <div class="fixselect">
                                            <select class="form-control select2bs4 addTags" name="lfrequency" id="lfrequency">
                                                  <option selected value="">Select Frequency</option>
                                            </select>
                                          </div>
                                       </li>
                                    <li class="clearfix"></li>
                                    <li class="col-md-4">
                                       <label class="description" for="lroa">Route of Administration: </label>
                                       <div>
                                          <select class="form-control" id="lroa" name="lroa">
                                             <option selected value="">Select Route of Administration</option>
                                          </select>
                                       </div>
                                    </li>
                                    <li class="clearfix"></li> 
                                    <li class="clearfix isAppealNo"><h2 style="color: #9C27B0;">Maintenance Details</h2></li>
                                    <li class="clearfix"></li>
                                    <!--// loading dose end-->
                                    <li class="col-md-4">
                                       <label class="description" for="dose">Dose: </label>
                                       <!--// changed from input to select-->
                                       <div class="fixselect">
                                            <select class="form-control select2bs4 addTags" name="dose" id="dose">
                                                <option selected value="">Select Dose</option>
                                            </select>
                                        </div>
                                    </li>
                                    <!--// Maintenance frequency start-->
                                    <li class="col-md-4">
                                        <label class="description" for="currentFrequency">Frequency:</label>
                                        <div class="fixselect">
                                          <select class="form-control select2bs4 addTags" name="currentFrequency" id="currentFrequency">
                                                <option selected value="">Select Frequency</option>
                                          </select>
                                        </div>
                                    </li>
                                    <!--// Maintenance frequency end-->
                                    <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>
                                             <?php 
                                                    foreach($routeofadministration_pl as $picklist){?>
                                                    <option value="<?=$picklist['value'];?>"><?=$picklist['name'];?></option>
                                                <?php } ?>
                                          </select>
                                       </div>
                                    </li>
                                    <li class="clearfix"></li>
                                     <!--PHYSICIAN SECTION END -->
                                    <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 required 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'];
                                                $physicianId=$medication['id']; // physician Id
                                                $physicianType=$medication['physicianType'];
                                                $primaryaddressData="";
                                                $secondaryaddressData="";
                                                foreach($primaryAddress as $Address) { 
                                                    if($Address['physicianId']==$physicianId)
                                                    {
                                                    $AddressId = $Address['id'];
                                                    $physicianId=$Address['physicianId'];
                                                    $hospital=$Address['hospital'];
                                                    $streetAddress=$Address['streetAddress'];
                                                    $city=$Address['city'];
                                                    $province=$Address['province'];
                                                    $postalCode=$Address['postalCode'];
                                                    $phone=$Address['phone'];
                                                    $email=$Address['email'];
                                                    $fax=$Address['fax'];
                                                    $notes=$Address['notes'];
                                                    $AddressType = $Address['addressType'];
                                                    if($Address['addressType']=='Primary'){
                                                        $primaryaddressData=$physicianId."||".$hospital."||".$streetAddress."||".$city."||".$province."||".$postalCode."||".$phone."||".$email."||".$fax."||".$notes."||".$AddressId."||".$AddressType;
                                                    }
                                                    else if($Address['addressType']=='Secondary'){
                                                        $secondaryaddressData=$physicianId."||".$hospital."||".$streetAddress."||".$city."||".$province."||".$postalCode."||".$phone."||".$email."||".$fax."||".$notes."||".$AddressId."||".$AddressType;
                                                    }
                                                }
                                                }
                                                ?>
                                                <option data-staff="<?=$assignedTo;?>" data-physicianType="<?=$physicianType;?>" data-specialty="<?=$primarySpecialty;?>" data-physicianId="<?=$physicianId;?>" data-primaryaddressData="<?=$primaryaddressData;?>" data-secondaryaddressData="<?=$secondaryaddressData;?>" 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="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="col-md-4">
                                       <label class="description" for="AddType">Prescriber Address Type: </label>
                                       <div>
                                          <!-- <input id="staff" name="staff" class="form-control" type="text"  autocomplete="off"> -->
                                          <div class="fixselect">
                                             <select class="form-control select2bs4" id="AddType" name="AddType" disabled>
                                             <option value="">Select Prescriber Address Type</option>
                                             </select>
                                          </div>
                                       </div>
                                    </li>
                                  
                                    <!-- Address fields start -->
                                    <div class="card-body row prescriber-address-fields" id="prescriber-address-fields">
                                        <input hidden readonly type="text" class="form-control" name="prescriber-address-pID" id="prescriber-address-pID" value="">
                                        
                                        <div class="form-group col-md-4">
                                            <label for="prescriber-address-hospital">Prescriber Hospital/Site :</label>
                                            <input readonly type="text" class="form-control" name="prescriber-address-hospital" id="prescriber-address-hospital" value="<?= isset($secondaryAddress['hospital']) && !empty($secondaryAddress['hospital']) ? $secondaryAddress['hospital'] : ''; ?>" placeholder="Enter Hospital">
                                        </div>
                                       
                                        <div class="form-group col-md-4">
                                            <label for="prescriber-address-email">Prescriber Email</label>
                                            <input readonly type="email" class="form-control" name="prescriber-address-email" id="prescriber-address-email" value="<?= isset($secondaryAddress['email']) && !empty($secondaryAddress['email']) ? $secondaryAddress['email'] : ''; ?>" placeholder="Enter Email">
                                        </div>
                                        <div class="clearfix"></div>
                                        <div class="form-group col-md-4">
                                            <label for="prescriber-address-fax">Prescriber Fax</label>
                                            <input readonly type="text" class="form-control" name="prescriber-address-fax" id="prescriber-address-fax" value="<?= isset($secondaryAddress['fax']) && !empty($secondaryAddress['fax']) ? $secondaryAddress['fax'] : ''; ?>" placeholder="Enter Fax">
                                        </div>
                                       
                                        <div class="form-group col-md-4">
                                            <label for="prescriber-address-phone">Prescriber Phone</label>
                                            <input readonly type="text" class="form-control" name="prescriber-address-phone" id="prescriber-address-phone" value="<?= isset($secondaryAddress['phone']) && !empty($secondaryAddress['phone']) ? $secondaryAddress['phone'] : ''; ?>" placeholder="Enter Phone" data-inputmask="&quot;mask&quot;: &quot;(999) 999-9999&quot;"
                                            data-mask="" inputmode="text">
                                        </div>
                                        <div class="clearfix"></div>
                                        <div class="form-group col-md-4">
                                            <label for="prescriber-address-address">Prescriber Address</label>
                                            <input readonly type="text" class="form-control" name="prescriber-address-address" id="prescriber-address-address" value="<?= isset($secondaryAddress['streetAddress']) && !empty($secondaryAddress['streetAddress']) ? $secondaryAddress['streetAddress'] : ''; ?>" placeholder="Enter Street Address">
                                        </div>

                                        <div class="form-group col-md-4">
                                            <label for="prescriber-address-city">Prescriber City</label>
                                            <input readonly type="text" class="form-control" name="prescriber-address-city" id="prescriber-address-city" value="<?= isset($secondaryAddress['city']) && !empty($secondaryAddress['city']) ? $secondaryAddress['city'] : ''; ?>" placeholder="Enter City">
                                        </div>
                                        <div class="clearfix"></div>
                                        <div class="form-group col-md-4">
                                            <label for="prescriber-address-physicianProvince">Prescriber Province</label>
                                            <input readonly type="text" class="form-control" name="prescriber-address-physicianProvince" id="prescriber-address-physicianProvince" value="<?= isset($secondaryAddress['province']) && !empty($secondaryAddress['province']) ? $secondaryAddress['province'] : ''; ?>" placeholder="Enter Province">
                                        </div>

                                        <div class="form-group col-md-4">
                                            <label for="prescriber-address-postalCode">Prescriber Postal Code</label>
                                            <input readonly type="text" class="form-control" id="prescriber-address-postalCode" name="prescriber-address-postalCode" value="<?= isset($secondaryAddress['postalCode']) && !empty($secondaryAddress['postalCode']) ? $secondaryAddress['postalCode'] : ''; ?>" placeholder="Enter Postal Code">
                                        </div>
                                        <div class="clearfix"></div>
                                       

                                        <div class="form-group col-md-4">
                                            <label for="prescriber-address-notes">Prescriber Notes:</label>
                                            <textarea readonly class="form-control" name="prescriber-address-notes" id="prescriber-address-notes"><?= isset($secondaryAddress['notes']) && !empty($secondaryAddress['notes']) ? $secondaryAddress['notes'] : ''; ?></textarea>
                                        </div>
                                    </div>
                                    <!--PHYSICIAN SECTION END -->
                                   
                                    <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>
                                      <li class="clearfix"></li>
                                    <li class="col-md-4" id="EnrollmentMAT">
                                       <label class="description" for="mat">Enrolment Form MAT Code <span class="req">*</span></label>
                                       <div  class="fixselect">
                                          <select class="form-control select2bs4" required id="mat" name="mat">
                                             <option value="">Select MAT Code</option>
                                              <?php foreach($mats as $mat) { ?>
                                             <option value="<?=$mat['form_id'];?>"><?=$mat['version'];?></option>
                                             <?php } ?>
                                          </select>
                                           <div class="invalid-feedback">Please Select MAT Code</div>
                                       </div>
                                    </li>
                                     <li id="consentInsideEF">
                                       <span class="description" style="padding-bottom:0px;">Did the patient provide consent on the enrolment form? <span class="req">*</span></span>
                                       <span class="description" style="padding-top:0px;">(Please select 'Yes' in case consent was received on latest enrollment form version i.e. <?=$mats[0]['version']?>)</span>
                                       <div>
                                          <fieldset>
                                             <span class="flex">
                                                <input  type="radio" id="yesconsent" name="consent" value="Y" class="custom-radio">
                                                <label for="yesconsent" class="radio-label">Yes</label>
                                             </span>

                                             <span class="flex">
                                                <input  type="radio" id="noconsent" name="consent" value="N" class="custom-radio">
                                                <label for="noconsent" class="radio-label">No</label>
                                                <div style='margin-left:10px;' class="invalid-feedback">Please Select Yes / No </div>
                                             </span>
                                            
                                          </fieldset>
                                       </div>
                                    </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');
        }
        });
        
    if($('#prescriberName').val() != '' && $('#prescriberName').val() == 'Pilot' && $('#patientDrugName').val().includes('Dupi')){
        // make fields mandatory and visible
        $('#mat')[0].setAttribute("required","true");
        $('#consentInsideEF')[0].removeAttribute("hidden");
        $('#EnrollmentMAT')[0].removeAttribute("hidden");
    }
    else{
        //make fields non-mandatory and hide the fields
        $('#mat')[0].removeAttribute("required");
        $('#consentInsideEF')[0].setAttribute("hidden","true");
        $('#EnrollmentMAT')[0].setAttribute("hidden","true");
    }
    
    // Attach change event to the Prescriber Name dropdown
    $('#prescriberName').on('change', function () {
        var valCheck=$(this).find('option:selected').val();
        const AddType = $(this).find('option:selected').data('AddType');
        
       
        if(valCheck==""){
            $('#AddType').select2().val(AddType || '').trigger('change');
               $('#AddType')[0].disabled =  true;
            $('#prescriber-address-fields')[0].style.display = "none";
            $('#prescriber-address-email')[0].value=''; 
            $('#prescriber-address-fax')[0].value=''; 
            $('#prescriber-address-phone')[0].value=''; 
            $('#prescriber-address-address')[0].value=''; 
            $('#prescriber-address-city')[0].value=''; 
            $('#prescriber-address-hospital')[0].value=''; 
            $('#prescriber-address-postalCode')[0].value=''; 
            $('#prescriber-address-physicianProvince')[0].value='';
            $('#prescriber-address-notes')[0].innerHTML = '';
            $('#prescriber-address-pID')[0].value = '';
            $('#prescriberSpecialty').val('');
             $('#staff').select2().val('').trigger('change');
            return false;
        }
        // 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');
        //update prescriber address details
        const prescriberId = $(this).find('option:selected').data('physicianid');
        const physicianType = $(this).find('option:selected').data('physiciantype'); // added to check if physician is pilot - RJ
        // console.log($(".AddressType-"+prescriberId));
        // console.log(".AddressType-"+prescriberId);
        $('#AddType')[0].value =  '';
        $('#AddType')[0].disabled =  false;
        //remove values from address type       <option value="">Select Prescriber Address Type</option>
        $('#AddType')
        .find('option')
        .remove()
        .end()
        .append('<option value="">Select Prescriber Address Type</option>')
        .val('');
        // remove prefilled address
            $('#prescriber-address-fields')[0].style.display = "none";
            $('#prescriber-address-email')[0].value=''; 
            $('#prescriber-address-fax')[0].value=''; 
            $('#prescriber-address-phone')[0].value=''; 
            $('#prescriber-address-address')[0].value=''; 
            $('#prescriber-address-city')[0].value=''; 
            $('#prescriber-address-hospital')[0].value=''; 
            $('#prescriber-address-postalCode')[0].value=''; 
            $('#prescriber-address-physicianProvince')[0].value='';
            $('#prescriber-address-notes')[0].innerHTML = '';
            $('#prescriber-address-pID')[0].value = '';
        // check new address if present
        if($(this).find('option:selected').data('primaryaddressdata')!=''){
            var data = $(this).find('option:selected').data('primaryaddressdata').split("||");
            $('#AddType')
            .append('<option disabled="true" class="AddressType-'+data[0]+'" data-pID="'+data[0]+'" data-hospital="'+data[1]+'"data-streetAddress="'+data[2]+'" data-city="'+data[3]+'" data-province="'+data[4]+'" data-postalCode="'+data[5]+'" data-phone="'+data[6]+'" data-email="'+data[7]+'" data-fax="'+data[8]+'" data-notes="'+data[9]+'"value="'+data[10]+'">'+data[11]+'</option>');
        }
        if($(this).find('option:selected').data('secondaryaddressdata')!=''){
            var data2 = $(this).find('option:selected').data('secondaryaddressdata').split("||");
            $('#AddType')
            .append('<option disabled="true" class="AddressType-'+data2[0]+'" data-pID="'+data[0]+'" data-hospital="'+data2[1]+'"data-streetAddress="'+data2[2]+'" data-city="'+data2[3]+'" data-province="'+data2[4]+'" data-postalCode="'+data2[5]+'" data-phone="'+data2[6]+'" data-email="'+data2[7]+'" data-fax="'+data2[8]+'" data-notes="'+data2[9]+'"value="'+data2[10]+'">'+data2[11]+'</option>');
        }
        //<option value="">Select Prescriber Address Type</option>
        if($(".AddressType-"+prescriberId)[0]){
            for(var l=0;l<$('.AddressType-'+prescriberId).length;l++)
            {
                $('.AddressType-'+prescriberId)[l].disabled=false;
            }
            $('.AddressType-'+prescriberId)[0].selected=true; // set primary data selected
            $('#prescriber-address-email')[0].value=$(".AddressType-"+prescriberId)[0].getAttribute('data-email');
            $('#prescriber-address-fax')[0].value=$(".AddressType-"+prescriberId)[0].getAttribute('data-fax');
            $('#prescriber-address-phone')[0].value=$(".AddressType-"+prescriberId)[0].getAttribute('data-phone');
            $('#prescriber-address-address')[0].value=$(".AddressType-"+prescriberId)[0].getAttribute('data-streetaddress');
            $('#prescriber-address-city')[0].value=$(".AddressType-"+prescriberId)[0].getAttribute('data-city');
            $('#prescriber-address-hospital')[0].value=$(".AddressType-"+prescriberId)[0].getAttribute('data-hospital');
            $('#prescriber-address-postalCode')[0].value=$(".AddressType-"+prescriberId)[0].getAttribute('data-postalcode');
            $('#prescriber-address-physicianProvince')[0].value=$(".AddressType-"+prescriberId)[0].getAttribute('data-province');
            $('#prescriber-address-notes')[0].value=$(".AddressType-"+prescriberId)[0].getAttribute('data-notes');
            $('#prescriber-address-pID')[0].value=$(".AddressType-"+prescriberId)[0].getAttribute('data-pID');
            $('#prescriber-address-fields')[0].style.display = "flex";
        }
    
        if(physicianType != '' && physicianType == 'Pilot' && $('#patientDrugName').val().includes('Dupi')){
            // make fields mandatory and visible
            $('#mat')[0].setAttribute("required","true");
            $('#consentInsideEF')[0].removeAttribute("hidden");
            $('#EnrollmentMAT')[0].removeAttribute("hidden");
        }
        else{
            //make fields non-mandatory and hide the fields
            $('#mat')[0].removeAttribute("required");
            $('#consentInsideEF')[0].setAttribute("hidden","true");
            $('#EnrollmentMAT')[0].setAttribute("hidden","true");
        }
    });

  
        // Attach change event to the Address Type dropdown
        $('#AddType').on('change', function () {
        console.log('inside onchange of add type '+$('#AddType')[0].value);

        if($('#AddType')[0].value != ''){
            $('#prescriber-address-fields')[0].style.display = "flex";
            $('#prescriber-address-email')[0].value=$(this).find('option:selected').data('email'); //$(".AddressType-"+prescriberId)[0].getAttribute('data-email');
            $('#prescriber-address-fax')[0].value=$(this).find('option:selected').data('fax'); //$(".AddressType-"+prescriberId)[0].getAttribute('data-fax');
            $('#prescriber-address-phone')[0].value=$(this).find('option:selected').data('phone'); //$(".AddressType-"+prescriberId)[0].getAttribute('data-phone');
            $('#prescriber-address-address')[0].value=$(this).find('option:selected').data('streetaddress'); //$(".AddressType-"+prescriberId)[0].getAttribute('data-streetaddress');
            $('#prescriber-address-city')[0].value=$(this).find('option:selected').data('city'); //$(".AddressType-"+prescriberId)[0].getAttribute('data-city');
            $('#prescriber-address-hospital')[0].value=$(this).find('option:selected').data('hospital'); //$(".AddressType-"+prescriberId)[0].getAttribute('data-hospital');
            $('#prescriber-address-postalCode')[0].value=$(this).find('option:selected').data('postalcode'); //$(".AddressType-"+prescriberId)[0].getAttribute('data-postalcode');
            $('#prescriber-address-physicianProvince')[0].value=$(this).find('option:selected').data('province'); //$(".AddressType-"+prescriberId)[0].getAttribute('data-province');
            $('#prescriber-address-notes')[0].innerHTML = $(this).find('option:selected').data('notes');
            $('#prescriber-address-pID')[0].value=$(this).find('option:selected').data('pid');
        }
        else{
            $('#prescriber-address-fields')[0].style.display = "none";
            $('#prescriber-address-email')[0].value=''; 
            $('#prescriber-address-fax')[0].value=''; 
            $('#prescriber-address-phone')[0].value=''; 
            $('#prescriber-address-address')[0].value=''; 
            $('#prescriber-address-city')[0].value=''; 
            $('#prescriber-address-hospital')[0].value=''; 
            $('#prescriber-address-postalCode')[0].value=''; 
            $('#prescriber-address-physicianProvince')[0].value='';
            $('#prescriber-address-notes')[0].innerHTML = '';
            $('#prescriber-address-pID')[0].value='';
        }
    });

    $('#patientId').change(function() {
        var pId = $(this).val();
        $.ajax({
            type: "POST",
            data: {pId:pId},
            dataType:"json",
            url: "ajax_call.php?ajaxcall=getPatientDetails",
            success: function (data){
                console.log(data);
                $('#patientFName').val(data.firstName);
                $('#patientLName').val(data.lastName);
                $('#dob').val(data.dob);
                $('#gender').val(data.gender);
                $('#email').val(data.email);
                $('#phone').val(data.phone);
                $('#address1').val(data.address1);
                $('#address2').val(data.address2);
                $('#city').val(data.city);
                $('#province').val(data.province).trigger('change'); // Notify Select2 to update its UI
                $('#postalCode').val(data.postalCode);
                $('#krollId').val(data.krollId);
                $('#provincialHCN').val(data.provincialHCN);
                $('#notes').val(data.notes);
            }
        });
    });
});
   $('#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');
        //consent form
        resetFieldValidation('#mat');
        resetFieldValidation('input[name="consent"]');
        //consent form
        // 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 ($('#prescriberName').val() === "") {
            setFieldInvalid('#prescriberName');
            validationPassed = false;
            toastr.error('Please Select Prescriber Name');
            firstInvalidField = firstInvalidField || '#prescriberName'; 
        }
        //consent form validation 
        if($('#prescriberName').find('option:selected').data('physiciantype')!="" && $('#prescriberName').find('option:selected').data('physiciantype')=="Pilot" && $('#patientDrugName').val().includes('Dupi'))
        { //incase prescriber is pilot validate if below fields are filled out - RJ
            //consent form validation 
            if (!isRadioGroupValid('consent')) {
                setFieldInvalid('input[name="consent"]');
                validationPassed = false;
                toastr.error('Required Field : Did patient provided consent in enrolment form?');
                firstInvalidField = firstInvalidField || 'input[name="consent"]'; 
            }
            //consent form validation 
            if ($('#mat').val() === "") {
                setFieldInvalid('#mat');
                validationPassed = false;
                toastr.error('Please Select MAT Code');
                firstInvalidField = firstInvalidField || '#mat'; 
            }
        }
        
        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 option:selected').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
            //physician address
            var AddType=$('#AddType').val();
            var secondary_email=$('#prescriber-address-email').val();
            var secondary_fax=$('#prescriber-address-fax').val();
            var secondary_phone=$('#prescriber-address-phone').val();
            var secondary_address=$('#prescriber-address-address').val();
            var secondary_city=$('#prescriber-address-city').val();
            var secondary_physicianProvince=$('#prescriber-address-physicianProvince').val();
            var secondary_postalCode=$('#prescriber-address-postalCode').val();
            var secondary_hospital=$('#prescriber-address-hospital').val();
            var secondary_notes=$('#prescriber-address-notes').val();
            var secondary_pID=$('#prescriber-address-pID').val();
            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
                }
            }
        //consent form
        var consent = $("input[name='consent']:checked").val();
        var mat = $("#mat option:selected").val();
        //consent form
        
        var indication = $("#indication").val();
        var currentFrequency = $("#currentFrequency").val();
        var ldosage = $("#ldosage").val();
        var lfrequency = $("#lfrequency").val();
        var lroa = $("#lroa").val();
        
        // 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);
        
        formData.append('indication',indication);
        formData.append('currentFrequency',currentFrequency);
        formData.append('ldosage',ldosage);
        formData.append('lfrequency',lfrequency);
        formData.append('lroa',lroa);
        //
        //physician address
        formData.append('AddType', AddType);
        formData.append('secondary_email', secondary_email);
        formData.append('secondary_fax', secondary_fax);
        formData.append('secondary_phone', secondary_phone);
        formData.append('secondary_address', secondary_address);
        formData.append('secondary_city', secondary_city);
        formData.append('secondary_physicianProvince', secondary_physicianProvince);
        formData.append('secondary_postalCode', secondary_postalCode);
        formData.append('secondary_hospital', secondary_hospital);
        formData.append('secondary_notes', secondary_notes);
        formData.append('secondary_pID', secondary_pID);
        //consent form
        formData.append('consent', consent);
        formData.append('mat', mat);
        //consent form
           $.ajax({
                 url: 'ajax_call.php?ajaxcall=addPatientExisting',
                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>
<script>document.write('<script src="js/editPatient.js?version=' + Date.now() + '"><\/script>');</script>
<?php include('footer.php'); ?>