<?php

ob_start();
include 'head.php';
include 'header.php';
include 'sidebar.php';
// error_reporting(E_ALL);ini_set('display_errors', 'On');
function getMatVersion($pdo,$form_id){
   // global $pdo;
  $stmt1 = $pdo->prepare("SELECT version from tblconsentversions where form_id=?");
  $stmt1->execute([$form_id]);
  $patientDetails = $stmt1->fetchColumn();
  return $patientDetails;
}
if (isset($_POST['savepatientdetials'])) {
   $pId = $_GET['id'];
   $fileId = $_GET['fileId'];
   // $pspId = $_POST['pspId'];
   // $medicationId = $_POST['medicationId'];
   $patientFName = $_POST['patientFName'];
   $patientLName = $_POST['patientLName'];
   $patientName = $patientFName . " " . $patientLName;
   $dob = $_POST['dob'];
   $gender = $_POST['gender'];
   $phone = $_POST['phone'];
   $email = $_POST['email'];
   $address1 = $_POST['address1'];
   $address2 = $_POST['address2'];
   $city = $_POST['city'];
   $province = $_POST['province'];
   $postalCode = $_POST['postalCode'];
   $createdBy = $_SESSION['empId'];
   $notes = $_POST['notes'];
   $krollId = $_POST['krollId'];
   $iprfwc = $_POST['iprfwc'];
   $enrolmentFormReceiveDate = $_POST['enrolmentFormReceiveDate'];
   $phcn = $_POST['phcn'];
   // Add Address Details
   $secondary_email=$_POST['prescriber-address-email'];
   $secondary_fax=$_POST['prescriber-address-fax'];
   $secondary_phone=$_POST['prescriber-address-phone'];
   $secondary_address=$_POST['prescriber-address-address'];
   $secondary_city=$_POST['prescriber-address-city'];
   $secondary_physicianProvince=$_POST['prescriber-address-physicianProvince'];
   $secondary_postalCode=$_POST['prescriber-address-postalCode'];
   $secondary_hospital=$_POST['prescriber-address-hospital'];
   $secondary_notes=$_POST['prescriber-address-notes'];
   $secondary_pID=$_POST['prescriber-address-pID'];
   $AddType=$_POST['AddType'];
   // $patientId = $patientFName[0] . $patientLName[0] . date('YmdHis');
   $patientId=$_POST['patientId'];
   // Handle file uploads
    //wc part5
    $patientDrugName=$_POST['patientDrugName'];
    $stmt = $pdo->prepare("SELECT id as drugId,pspId FROM tbldrugs WHERE drugName = ? and isDeleted='N'");
   $stmt->execute([$patientDrugName]); 
   $drugDetails = $stmt->fetch();
   $pspId=0;
   $drugId='';
   if(isset($drugDetails['pspId'])){
       $pspId=$drugDetails['pspId'];
   }
   if(isset($drugDetails['drugId'])){
       $medicationId=$drugDetails['drugId'];
   }
    $dosage=$_POST['dose'];
    $routeOfAdmin=$_POST['roa'];
    $prescriberName=$_POST['prescriberName'];
    $prescriberSpecialty=$_POST['prescriberSpecialty'];
    $team=$_POST['team'];
    $staff=$_POST['staff'];
    $presciberOffice=$_POST['Dpgsd'];
    $sampleDoseReceived=$_POST['smpDate'];
    //wc part5
   $uploadedFiles = [];
   if (!file_exists('uploads/' . $province .'/'. $krollId)) {
      mkdir('uploads/' . $province .'/'. $krollId, 0777, true);
   }
   $uploadDir = 'uploads/' . $province .'/'. $krollId . '/';
   
    //consent form data
    $form_id=$_POST['mat'];
    $consentInEnrolment=$_POST['consent'];
    //consent form data
    
    // additional medication details
    $indicationString=$_POST['indication'];
    $indication=implode(',', $indicationString);
    $currentFrequency=$_POST['currentFrequency'];
    $ldosage=$_POST['ldosage'];
    $lfrequency=$_POST['lfrequency'];
    $lrouteOfAdmin=$_POST['lroa'];
   try {
      $pdo->beginTransaction();
      // Insert patient data
      $stmt = $pdo->prepare("UPDATE tblpatient set krollId=?,patientName=?,dob=?,firstName=?,lastName=?,gender=?,phone=?,email=?,address1=?,address2=?,city=?,province=?,postalCode=?,notes=?,modifiedBy=? where id=?");
      $result = $stmt->execute([$krollId, $patientName, $dob, $patientFName, $patientLName, $gender, $phone, $email, $address1, $address2, $city, $province, $postalCode, $notes, $createdBy, $pId]);

      // Insert patient details
      $stmt1 = $pdo->prepare("Update tblpatientdetails set pspId=?,medicationId=?,enrolmentFormReceiveDate=?,modifiedBy=? where fileId=? and pId=?");
      $result = $stmt1->execute([$pspId, $medicationId,$enrolmentFormReceiveDate,$createdBy, $fileId, $pId]);

      $query5_update = "UPDATE tblwcpart5 
                  SET patientDrugName=?, dosage=?, routeOfAdmin=?, prescriberName=?, prescriberSpecialty=?, team=?, staff=?, presciberOffice=?, sampleDoseReceived=? ,iprfwc=?,modifiedBy=?,
                  indication=?,currentFrequency=?,ldosage=?,lfrequency=?,lrouteOfAdmin=?
                  WHERE fileId = ? AND pId = ?";
      $stmt5_update = $pdo->prepare($query5_update);
      $stmt5_update->execute([$patientDrugName, $dosage, $routeOfAdmin, $prescriberName, $prescriberSpecialty, $team, $staff, $presciberOffice, $sampleDoseReceived,$iprfwc,$createdBy,
      $indication,$currentFrequency,$ldosage,$lfrequency,$lrouteOfAdmin,
      $fileId, $pId]);
        
     //update physician Id in reimbursement table if pt entry exists.
     $query6_update = "UPDATE tblreimbursement 
                  SET physicianId = (Select id from tblphysicians where CONCAT(firstName,' ',LastName)=? limit 1), modifiedBy=? WHERE fileId = ? AND pId = ?";
      $stmt6_update = $pdo->prepare($query6_update);
      $stmt6_update->execute([$prescriberName, $createdBy, $fileId, $pId]); 
     
    
     $queryx = "UPDATE tblwcpart2 SET provincialHCN = ?,modifiedBy=? WHERE pId = ? and fileId = ?";
     $stmtx = $pdo->prepare($queryx);
     $stmtx->execute([$phcn,$createdBy, $pId, $fileId]);
      //custom code
    $stmt1 = $pdo->prepare("SELECT * FROM tblphysiciansaddresshistory where  pId=? and fileId=? and isDeleted='N' ORDER BY ID DESC LIMIT 1");
    $stmt1->execute([$_GET['id'],$_GET['fileId']]);
    $physicianoldAddress = $stmt1->fetch();
    
    // check if we have entry in system
    if(isset($physicianoldAddress)){
    // added check that address type was changed as well | (incase addtype is 0 or '')
        if(($secondary_pID!='') && ($AddType!='') && ($physicianoldAddress['physicianId']!=$secondary_pID || $physicianoldAddress['hospital']!=$secondary_hospital  || $physicianoldAddress['streetAddress']!=$secondary_address  ||  $physicianoldAddress['city'] !=$secondary_city  ||  
        $physicianoldAddress['province']!=$secondary_physicianProvince  ||  $physicianoldAddress['postalCode']!=$secondary_postalCode  ||   $physicianoldAddress['phone']!=$secondary_phone  ||    $physicianoldAddress['email']!=$secondary_email  ||    
        $physicianoldAddress['fax'] !=$secondary_fax  ||   $physicianoldAddress['notes']!=$secondary_notes  || $physicianoldAddress['physiciansaddressId']!=$AddType)){
            // add new address details
            $queryadd = "INSERT INTO tblphysiciansaddresshistory(physicianId, hospital,streetAddress,city,province,postalCode,phone,email,fax,notes,pId,physiciansaddressId,createdBy,fileId) VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?,?)";
            $stmtxadd = $pdo->prepare($queryadd);
            $stmtxadd->execute([$secondary_pID, $secondary_hospital,$secondary_address, $secondary_city, $secondary_physicianProvince,$secondary_postalCode,$secondary_phone,$secondary_email,$secondary_fax,$secondary_notes,$pId,$AddType,$createdBy,$fileId]);
        }
    }
    else{
        //if no details are present in address history
        // add new address details
        $queryadd = "INSERT INTO tblphysiciansaddresshistory(physicianId, hospital,streetAddress,city,province,postalCode,phone,email,fax,notes,pId,physiciansaddressId,createdBy,fileId) VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?,?)";
        $stmtxadd = $pdo->prepare($queryadd);
        $stmtxadd->execute([$secondary_pID, $secondary_hospital,$secondary_address, $secondary_city, $secondary_physicianProvince,$secondary_postalCode,$secondary_phone,$secondary_email,$secondary_fax,$secondary_notes,$pId,$AddType,$createdBy,$fileId]);
    }
    
    foreach ($_FILES['files']['tmp_name'] as $key => $tmp_name) {
                    $originalFileName = $_FILES['files']['name'][$key];
                    $file_tmp = $_FILES['files']['tmp_name'][$key];
                    if (isset($_POST['fileTitle'][$key])) {
                        $title = $_POST['fileTitle'][$key];
                        $title = preg_replace('/[^A-Za-z0-9 ]/', '', $title); // Clean the title if needed
                
                        // Extract file extension and base name
                        $fileExtension = pathinfo($originalFileName, PATHINFO_EXTENSION);
                        $file_base_name = pathinfo($originalFileName, PATHINFO_FILENAME); // Filename without extension
                        $file_base_name = preg_replace('/[^A-Za-z0-9 ]/', '-', $file_base_name); // Replace invalid characters
                
                        // Generate a truly unique filename
                        $unique_suffix = time() . '-' . mt_rand(1000, 9999); // Timestamp + Random Number
                        $file_name = $file_base_name . '-' . $unique_suffix . '.' . $fileExtension;
                
                        // Define the destination path
                        $file_destination = $uploadDir . $file_name;
                
                        // Ensure unique filename
                        while (file_exists($file_destination)) {
                            $unique_suffix = time() . '-' . mt_rand(1000, 9999); // Regenerate unique suffix
                            $file_name = $file_base_name . '-' . $unique_suffix . '.' . $fileExtension;
                            $file_destination = $uploadDir . $file_name;
                        }
                
                        if (move_uploaded_file($file_tmp, $file_destination)) {
                            $uploadedFiles[] = $file_name;
                
                            // Insert into tblpatientdocs
                            $stmt2 = $pdo->prepare("INSERT INTO tblpatientdocs(pId, fileId, title, filename, module) VALUES (?,?,?,?,?)");
                            $result2 = $stmt2->execute([$pId, $fileId, $title, $file_name, 'patient']);
                        } else {
                            // Handle upload error
                        }
                    }
                }
      if ($pdo->commit()) {
        // check if physician is marked as pilot, if yes the execute below code:
        $stmtPhysicianType = $pdo->prepare("Select physicianType from tblphysicians where concat(tblphysicians.firstName,' ',tblphysicians.lastName) =? and tblphysicians.isDeleted='N'");
        $stmtPhysicianType->execute([$prescriberName]);
        $activePhysicianType = $stmtPhysicianType->fetchColumn();
            if(isset($activePhysicianType) && $activePhysicianType=='Pilot')
            {
                //consent form
                // fetch the most recent consent txn for this patient/file
                $stmt = $conn->prepare("SELECT * FROM rx_consentFormTransactions WHERE isDeleted = 'N'  AND pId = ? AND fileId = ? ORDER BY id DESC LIMIT 1");
                $stmt->execute([$pId, $fileId]);
                $prev = $stmt->fetch(PDO::FETCH_ASSOC);
                $status='P';$response='';$resultDate='';
                if($consentInEnrolment=='Y'){ $status='C';$response='Accept';$resultDate = date('Y-m-d H:i:s');}
                $versionInEnrolmentForm=getMatVersion($pdo,$form_id);
                // echo($prev['versionInEnrolmentForm'].' codes '.$versionInEnrolmentForm);
                $stmtlatestversion = $pdo->prepare("SELECT form_id FROM tblconsentversions where isDeleted='N' ORDER BY STR_TO_DATE(version, '%b %Y') desc limit 1");
                $stmtlatestversion->execute(); // formid is of the form used to send emails/ differs from id passed in params of URL
                $active_form_id = $stmtlatestversion->fetchColumn();
                if(strpos($patientDrugName, 'Dupixent') !== false){
                if (!$prev) {
                    //first consent to be taken
                    $stmt1 = $conn->prepare("INSERT INTO rx_consentFormTransactions(pId, fileId,form_id,versionInEnrolmentForm,emailTo,pspPatientID,fullName,createdBy,status,consentInEnrolment,type,resultDate,response) VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?)");
                    $result = $stmt1->execute([$pId, $fileId,$active_form_id,$versionInEnrolmentForm, $email,$patientId, $patientName,$createdBy,$status,$consentInEnrolment,'consent',$resultDate,$response]);
                    // No prior record: always insert
                }
                // not a new consent
                elseif ($prev['versionInEnrolmentForm']!=$versionInEnrolmentForm) {
              
                    // maybe an entry is already there for current selected form_id/ but check if entry already exists for latest consent form - RJ
                    $stmtversioncount = $conn->prepare("SELECT COUNT(*) as countV FROM rx_consentFormTransactions where isDeleted = 'N'  AND pId = ? AND fileId = ? AND form_id=?");
                    $stmtversioncount->execute([$pId,$fileId,$active_form_id]);
                    $active_version_count = $stmtversioncount->fetchColumn();
                
                    // Different form selected: insert new transaction
                    // echo('count is '.$active_version_count);
                    // die();
                    if($active_version_count == 0){
                        $stmt1 = $conn->prepare("INSERT INTO rx_consentFormTransactions(pId, fileId,form_id,versionInEnrolmentForm,emailTo,pspPatientID,fullName,createdBy,status,consentInEnrolment,type,resultDate,response) VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?)");
                        $result = $stmt1->execute([$pId, $fileId,$active_form_id,$versionInEnrolmentForm, $email,$patientId, $patientName,$createdBy,$status,$consentInEnrolment,'consent',$resultDate,$response]);
                    }else{
                        if($prev['status']=="P"){
                            // echo('update 1');
                            // die();
                        $update = $conn->prepare("UPDATE rx_consentFormTransactions  SET consentInEnrolment = ?,modifiedBy = ?,modifiedAt = NOW(),status=?,resultDate=?,response=?,versionInEnrolmentForm=? WHERE id=?");
                        $update->execute([$consentInEnrolment, $createdBy,$status,$resultDate,$response,$versionInEnrolmentForm,$prev['id']]);
                        }
                    }
                  // can have update for previous  form_id
                } 
                elseif ($prev['consentInEnrolment'] != $consentInEnrolment && $prev['versionInEnrolmentForm'] == $versionInEnrolmentForm && $prev['status']=="P") 
                { 
                    //  echo('update 2');
                    //         die();
                   // Same form, but answer changed: update the existing record
                   $update = $conn->prepare("UPDATE rx_consentFormTransactions  SET consentInEnrolment = ?,modifiedBy = ?,modifiedAt = NOW(),status=?,resultDate=?,response=? WHERE versionInEnrolmentForm=? and fileId=?");
                   $update->execute([$consentInEnrolment, $createdBy,$status,$resultDate,$response,$versionInEnrolmentForm,$fileId]);
                }
            }
                //consent form
                if ($_POST['savepatientdetials'] === 'SAVE & NEXT') {
                   echo "<script>toastr.success('Patient Updated Successfully');
                   setTimeout(function() {window.location.href = 'edit_de_patient.php?id=" . $pId . "&fileId=" . $fileId . "';
                   }, 2000);</script>";
                }
                else{
                   echo "<script>toastr.success('Patient Updated Successfully');</script>";
                }
            }
        } else {
         echo "<script>toastr.error('Failed to update patient details');</script>";
      }

   } catch (\PDOException $e) {
      $pdo->rollBack();
      echo "Transaction failed: " . $e->getMessage();
   }
}

// validate transfered out - start
    $isTransferOut = isset($_GET['isTransferOut']) && $_GET['isTransferOut'] === 'Y';
    if ($isTransferOut){
    echo("<script>
        window.onload = function() {
            const allElements = document.querySelectorAll('input, select, textarea, button');
            allElements.forEach(el => el.disabled = true);
            
            var navTabs = ['home-tab'
                            ,'home4-tab'
                            ,'patientNotes-tab'
                            ,'home2-tab'];
                        
            setTimeout(() => {
                navTabs.forEach(id => {
                  const tab = document.getElementById(id);
                  if (tab) {
                    tab.removeAttribute('disabled');
                  }
                });
            }, 1000);
        
        }
    </script>");
    }
// validate transfered out - end

$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 tblphysicians WHERE isDeleted='N' ORDER BY firstName ASC");
$stmt8->execute();
$physicians = $stmt8->fetchAll();

$stmt8 = $pdo->prepare("SELECT * FROM tblprovince WHERE countryId='1' ORDER BY provinceName ASC");
$stmt8->execute();
$provinces = $stmt8->fetchAll();


$stmt80 = $pdo->prepare("SELECT * FROM tblpatientstatus WHERE isDeleted='N' ORDER BY StatusName ASC");
$stmt80->execute();
$pstatus = $stmt80->fetchAll();

$stmt1 = $pdo->prepare("SELECT empId,userName from tbluser WHERE isDeleted='N' AND department='P' || department='R'");
$stmt1->execute();
$np = $stmt1->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

if (isset($_GET['id'])) {
//   $stmt1 = $pdo->prepare("SELECT tblpatient.*, tblpatientdetails.*, tblwcpart1.*, tblwcpart2.*, tblwcpart3.*, tblwcpart4.*, tblwcpart5.*, tblwcpart6.* FROM tblpatient 
//                                 inner join tblpatientdetails on tblpatient.id=tblpatientdetails.pId 
//                                 LEFT JOIN tblwcpart1 ON tblpatientdetails.pId = tblwcpart1.pId and tblpatientdetails.fileId=tblwcpart1.fileId
//                                 LEFT JOIN tblwcpart2 ON tblpatientdetails.pId = tblwcpart2.pId and tblpatientdetails.fileId=tblwcpart2.fileId
//                                 LEFT JOIN tblwcpart3 ON tblpatientdetails.pId = tblwcpart3.pId and tblpatientdetails.fileId=tblwcpart3.fileId 
//                                 LEFT JOIN tblwcpart4 ON tblpatientdetails.pId = tblwcpart4.pId and tblpatientdetails.fileId=tblwcpart4.fileId  
//                                 LEFT JOIN tblwcpart5 ON tblpatientdetails.pId = tblwcpart5.pId and tblpatientdetails.fileId=tblwcpart5.fileId      
//                                 LEFT JOIN tblwcpart6 ON tblpatientdetails.pId = tblwcpart6.pId and tblpatientdetails.fileId=tblwcpart6.fileId      
//                                 WHERE tblpatient.isDeleted='N' AND tblwcpart1.isDeleted='N' AND tblwcpart2.isDeleted='N' AND tblwcpart3.isDeleted='N' 
//                                 AND tblwcpart4.isDeleted='N' AND tblwcpart5.isDeleted='N' AND tblwcpart6.isDeleted='N' 
//                                 AND tblpatient.id=? AND tblpatientdetails.fileId = ?");
    
    $stmt1 = $pdo->prepare("SELECT * FROM tblpatient 
                                inner join tblpatientdetails on tblpatient.id=tblpatientdetails.pId 
                                LEFT JOIN tblwcpart1 ON tblpatientdetails.pId = tblwcpart1.pId and tblpatientdetails.fileId=tblwcpart1.fileId AND tblwcpart1.isDeleted='N'
                                LEFT JOIN tblwcpart2 ON tblpatientdetails.pId = tblwcpart2.pId and tblpatientdetails.fileId=tblwcpart2.fileId AND tblwcpart2.isDeleted='N'
                                LEFT JOIN tblwcpart3 ON tblpatientdetails.pId = tblwcpart3.pId and tblpatientdetails.fileId=tblwcpart3.fileId AND tblwcpart3.isDeleted='N'
                                LEFT JOIN tblwcpart4 ON tblpatientdetails.pId = tblwcpart4.pId and tblpatientdetails.fileId=tblwcpart4.fileId  AND tblwcpart4.isDeleted='N'
                                LEFT JOIN tblwcpart5 ON tblpatientdetails.pId = tblwcpart5.pId and tblpatientdetails.fileId=tblwcpart5.fileId  AND tblwcpart5.isDeleted='N'
                                LEFT JOIN tblwcpart6 ON tblpatientdetails.pId = tblwcpart6.pId and tblpatientdetails.fileId=tblwcpart6.fileId AND tblwcpart6.isDeleted='N'
                                WHERE tblpatient.isDeleted='N' AND tblpatientdetails.isDeleted='N'
                                AND tblpatient.id=? AND tblpatientdetails.fileId =?");
   $stmt1->execute([$_GET['id'], $_GET['fileId']]);
   $patientDetails = $stmt1->fetch();
   
    
//   $stmt7 = $pdo->prepare("SELECT * FROM tbldrugs WHERE isDeleted='N' and pspId=".$patientDetails['pspId']."  ORDER BY drugName ASC");
//   $stmt7->execute();
//   $medications = $stmt7->fetchAll();

  // drug listing according to pspId
  if(isset($patientDetails) && isset($patientDetails['pspId']) && $patientDetails['pspId']!="")
   {
       $drugname = '';
       if(isset($patientDetails['patientDrugName']) && $patientDetails['patientDrugName']!=''){
           $drugname = '%'.explode(" ", $patientDetails['patientDrugName'])[0].'%';
           // in case name has no space
           if($drugname==''){
               $drugname=$patientDetails['patientDrugName'];
           }
       }
        $stmt7 = $pdo->prepare("SELECT * FROM tbldrugs WHERE pspid=? AND drugName like ? AND isDeleted='N' ORDER BY drugName ASC");
        $stmt7->execute([$patientDetails['pspId'],$drugname]);
        $medications = $stmt7->fetchAll();
   }

   $stmt7 = $pdo->prepare("SELECT * FROM tblpatientdocs WHERE isDeleted='N'  AND pId=? AND fileId=? AND module='patient' ORDER BY id ASC");
   $stmt7->execute([$_GET['id'], $_GET['fileId']]);
   $generaldocs = $stmt7->fetchAll();

   $stmt7 = $pdo->prepare("SELECT * FROM tblpatientdocs WHERE isDeleted='N'  AND pId=? AND fileId=? AND module='MedicationDocuments' ORDER BY id ASC");
   $stmt7->execute([$_GET['id'], $_GET['fileId']]);
   $medicaldocs = $stmt7->fetchAll();

   $stmt7 = $pdo->prepare("SELECT * FROM tblpatientdocs WHERE isDeleted='N'  AND pId=? AND fileId=? AND module='ScreeningImmunizationDocuments' ORDER BY id ASC");
   $stmt7->execute([$_GET['id'], $_GET['fileId']]);
   $screeningdocs = $stmt7->fetchAll();

   $stmt1 = $pdo->prepare("SELECT * from tblreimbursement      
                                 WHERE pId=? and fileId=?");
   $stmt1->execute([$_GET['id'], $_GET['fileId']]);
   $repatientDetails = $stmt1->fetch();
   if(isset($repatientDetails['physicianId'])) {
   $stmtz1 = $pdo->prepare("SELECT * from tblphysicians WHERE id=?");
   $stmtz1->execute([$repatientDetails['physicianId']]);
   $physicianDetails = $stmtz1->fetch();
   }
   if(isset($repatientDetails['patientType'])) {
      $stmtz1z = $pdo->prepare("SELECT * from tblstatuslogs WHERE pId=? and fileId=? and operationName='Patient Status Updated'");
      $stmtz1z->execute([$repatientDetails['pId'],$repatientDetails['fileId']]);
      $typeStatus = $stmtz1z->fetchAll();
   }
   if(isset($patientDetails['wcStatus'])) {
      $stmtz1z = $pdo->prepare("SELECT * from tblstatuslogs WHERE pId=? and fileId=? and operationName='Welcome Call Status Updated'");
      $stmtz1z->execute([$patientDetails['pId'],$patientDetails['fileId']]);
      $welcometypeStatus = $stmtz1z->fetchAll();
   }   

   $stmt1 = $pdo->prepare("SELECT empId,userName from tbluser WHERE isDeleted='N'");
   $stmt1->execute();
   $employees = $stmt1->fetchAll();


   $stmt1z = $pdo->prepare("SELECT * from tblindication WHERE pId=? and fileId=? and isDeleted='N' ORDER BY id DESC");
   $stmt1z->execute([$_GET['id'],$_GET['fileId']]);
   $indicationDetails = $stmt1z->fetch();
   $stmt1 = $conn->prepare("SELECT form_id,form_name from ap_forms WHERE FIND_IN_SET('Pharmacy',form_tags)>0 AND form_active IN(0,1) ");
   $stmt1->execute();
   $form_list_array = $stmt1->fetchAll();
   
   $stmt81 = $pdo->prepare("SELECT title FROM `tblfiletitles` WHERE isDeleted='N' ORDER BY title ASC");
    $stmt81->execute();
    $fileTitles = $stmt81->fetchAll();

// get address for all physicians
$stmt = $pdo->prepare("SELECT * from tblphysiciansaddress WHERE isDeleted = 'N'");
$stmt->execute();
$primaryAddress = $stmt->fetchAll();

// get details for selected physician");
//SELECT TOP 1 * FROM tblphysiciansaddresshistory where physicianId=(Select id from tblphysicians Concat(firstName,' ',lastName) = patientDetails['prescriberName']) and patientId='' ORDER BY ID DESC
$stmt1 = $pdo->prepare("SELECT * FROM tblphysiciansaddresshistory where  pId=? and fileId=? and isDeleted='N' ORDER BY id DESC LIMIT 1");
$stmt1->execute([$_GET['id'],$_GET['fileId']]);
$physicianoldAddress = $stmt1->fetch();

// get selected physician address options
$stmt = $pdo->prepare("SELECT * from tblphysiciansaddress WHERE isDeleted = 'N' and physicianId=?");
$stmt->execute([$physicianoldAddress['physicianId']]);
$selectedphysicianOptions = $stmt->fetchAll();

//consent 
$stmt = $conn->prepare("SELECT * from rx_consentFormTransactions WHERE isDeleted = 'N' and pId = ?  and fileId=? order by id DESC limit 1");
$stmt->execute([$_GET['id'],$_GET['fileId']]);
$selectedConsent = $stmt->fetch();
//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();
}

// tblindicationtype
function getIndicationtypeacctomed($pdo,$med){
    if(isset($med) && $med!=''){
        if(strpos($med, " ") !== false)
        {
            $med=explode(" ", $med)[0];
        }
    }
    $stmt1 = $pdo->prepare("Select distinct(name) as name from tblindicationtype where drug=? and tblindicationtype.isActive='Y'");
    $stmt1->execute([$med]);
    return $stmt1->fetchAll();
}

//master tables start
$gender_pl = getGender($pdo);
$routeofadministration_pl = getRouteofadministration($pdo);
$indicationtype_pl = getIndicationtypeacctomed($pdo,$patientDetails['patientDrugName']);
//master tables end

} else {
   header("location:index.php");
}
?>
<style>
   ul.inbuiltwc fieldset span {
      display: -webkit-box;
   }
   ul.inbuiltwc fieldset span input {
      margin: 0px 10px;
   }
   .editWc span.nextline,
   .reviewform span.nextline {
      display: block !important;
   }
   .editWc span.nextline label,
   .reviewform span.nextline label {
      margin-left: 10px;
   }
   .row.mg10 {
      margin: 10px 0px;
   }
   .editWc .ftitle h3,
   .editWc h3.ftitle {
      font-size: 18px !important;
      padding: 5px 0px;
      font-weight: 600;
   }
   .editWc label.description,
   .editWc label {
      font-weight: 600 !important;
      font-size: 16px;
   }
   .editWc select.form-control,
   .editWc input.form-control,
   .editWc .select2-results__options li,
   .editWc .select2-search__field {
      font-size: 14px !important;
   }
   .editWc fieldset span {
      vertical-align: middle !important;
      display: inline-flex !important;
   }
   li.line {
      border: 1px solid #cccccc;
   }
   section.content.w70 {
      width: 80%;
      margin-left: 15%;
   }
   aside {
      width: 15%;
   }
   .myeditpatient span.req {
      line-height: 0px !important;
      padding: 0px !important;
      display: inline-flex !important;
      margin-left: 5px;
   }
   .patientType i.fa.fa-info-circle {
      padding: 0;
      vertical-align: middle;
      display: flex;
      justify-content: center;
      align-items: center;
      margin-left: 5px;
   }
   ul#select2-patientType-results li:after {
      content: "\f05a";
      font-family: var(--fa-style-family, "Font Awesome 6 Free");
      font-weight: var(--fa-style, 900);
      float: right;
   }
   ul#select2-patientType-results li:first-child:after {
      content: "";
      font-family: var(--fa-style-family, "Font Awesome 6 Free");
      font-weight: var(--fa-style, 900);
      float: right;
   }
   .popupActivityStatus,
   .popupWelcomeCallActivityStatus {
      position: fixed;
      z-index: 99999999 !important;
      justify-content: center;
      align-items: center;
      vertical-align: middle;
      text-align: center;
      left: 40%;
      top: 30%;
      background: white;
      padding: 20px;
      box-shadow: 0 0 30px rgba(0, 0, 0, 0.9);
   }
   i#patientTypeClose,
   i#welcomeTypeClose {
      float: right;
      top: 10px;
      position: absolute;
      right: 10px;
      background: black;
      color: white;
      border-radius: 50%;
      width: 20px;
      line-height: 20px;
      height: 20px;
      cursor: pointer;
   }
   .popupActivityStatus h3,
   .popupWelcomeCallActivityStatus h3 {
      font-size: 22px;
      margin: 10px 0px;
      font-weight: 600;
   }
   a#getWelcomeActivityInfo,
   a#getActivityInfo {
      margin-bottom: 0 !important;
      padding-bottom: 0px !important;
      line-height: 20px !important;
      margin-left: 10px;
      color: #0d6efd;
      cursor: pointer !important;
   }
   form.araddpatient.editWc {
      background: white;
      width: 100%;
      margin: 0px auto;
      padding: 0px 30px;
   }
   .vcalign {
      justify-content: center;
      align-items: center;
      vertical-align: middle;
      display: inline-flex;
   }
   .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;
}
div#myTabContent,ul#myTab {
    background: white;
}
ul#myTab li button {
    font-size: 16px !important;
    font-weight: 600;
}
button.btn.btn-success.save {
    background: #9c27b0;
    border-color: #9c27b0;
    margin-bottom: 30px;
    margin-top: 10px;
}
#iframe{width:100%;border:none}
.card-header.mgtop.inlineflex{padding:20px}
a.white{color:#fff}
.mgtop{margin-top:20px;margin-bottom:30px}
#example_wrapper select:not([size]){width:10%;margin:10px}
.rxtitle{font-size:24px;font-weight:600}
table a.btn{height:max-content;width:max-content;display:inline-flex}
.dt-length,.dt-search{display:flex;vertical-align:middle;align-items:center}
.customdewidth{margin-left:15%;margin-top:80px;width:85%;background-color:#f5f5f5}
aside{width:15%}
.deindexpage .dt-search{float:right}
ul#myTab{background:#fff}
div#myTabContent{background:#fff;padding:10px}
ul#myTab li button{font-size:16px!important;font-weight:600} 
#fullScreenModal{display:none;position:fixed;top:0;left:0;width:100%;height:100%;background-color:rgba(0,0,0,.8);z-index:1000}
#fullScreenModal button{position:absolute;top:100px;right:20px;z-index:1001}
#popupIframe{width:100%;height:100%;border:none;margin-top: 70px;}
.dt-search {float: right;}
ul#myTab { position: sticky !important;   top: 70px !important;   z-index: 999999 !important;   background: white !important;}

</style>
<!-- form start -->


<!-- Content Wrapper. Contains page content -->
<div class="content-wrapper">
   <!-- Content Header (Page header) -->
   <!-- Main content -->
   <section class="content myeditpatient">
      <div class="container-fluid customdewidth">
         <div class="row">
            <!-- left column -->
            <div class="col-md-12">
            <ul class="nav nav-tabs" id="myTab" role="tablist">
                  <li class="nav-item" role="presentation">
                     <button class="nav-link active" id="home-tab" data-bs-toggle="tab" data-bs-target="#home" type="button" role="tab" aria-controls="home" aria-selected="true">Patient Information</button>
                  </li>
                  <li class="nav-item" role="presentation">
                     <button class="nav-link" id="home4-tab" data-bs-toggle="tab" data-bs-target="#home4" type="button" role="tab" aria-controls="home4" aria-selected="false">More Information</button>
                  </li>
                  <li class="nav-item" role="presentation">
                     <button class="nav-link" id="patientNotes-tab" data-bs-toggle="tab" data-bs-target="#patientNotes" type="button" role="tab" aria-controls="patientNotes" aria-selected="true">FORM LIST</button>
                  </li>
                  <li class="nav-item" role="presentation">
                     <button class="nav-link" id="home2-tab" data-bs-toggle="tab" data-bs-target="#home2" type="button" role="tab" aria-controls="home2" aria-selected="false">NEW FORM</button>
                  </li>
                  <li class="nav-item ml-auto vcalign" role="presentation">
                     <a class="btn btn-secondary" href="index.php">BACK</a>
                  </li>
               </ul>
               <div class="tab-content" id="myTabContent">
             
               <div class="tab-pane fade" id="patientNotes" role="tabpanel" aria-labelledby="patientNotes-tab">
                    
                <table id="example" class="table table-bordered" style="width:100%">
                  <thead>
                        <tr>
                           <th class="text-center">S.No.</th>
                           <th class="text-center">Form Name</th>
                           <th class="text-center">File Name</th>
                           <th class="text-center">Created By</th>
                           <th class="text-center">Date & Time</th>
                           <th class="text-center">Action</th>
                        </tr>
                  </thead>
                  <tbody>
                     <?php 
                         $checkPV=false;
                         if(strpos($userRole,"PV") !==false){
                            $checkPV=true;
                         }
                         $i=1;
                         $stmt1 = $conn->prepare("SELECT rx_forms.*,ap_forms.form_name from rx_forms inner join ap_forms on rx_forms.form_id=ap_forms.form_id  WHERE FIND_IN_SET('Pharmacy',ap_forms.form_tags)>0 AND ap_forms.form_active IN(0,1) AND rx_forms.isDeleted='N' AND rx_forms.fileId=?");       
                         $stmt1->execute([$_GET['fileId']]);    
                         $patientForms = $stmt1->fetchAll();
                     foreach($patientForms as $pf) { 
                       
                        ?>
                        <tr>
                           <td><?=$i;?></td>
                           <td><?=$pf['form_name'];?></td>
                           <td class="text-center"><?=$pf['patientfileId'];?></td>
                           <td><?=getuserName($pdo,$pf['createdBy']);?></td>
                           <td class="text-center"><?=$pf['createdAt'];?></td>
                           <td  class="text-center">
                                 <?php 
                                 
                                 
                                 if($pf['createdBy']==$empId || $_SESSION['empType']=='S'  || $checkPV){ ?>
                           <button title="Update" class="" data-url="<?=$publicURL;?>rxforms/edit_patient_entry.php?form_id=<?= $pf['form_id']; ?>&entry_id=<?= $pf['record_id']; ?>" onclick="openFullScreenPopup(this)">
                                <i class="fa fa-edit"></i> 
                            </button>   
                            <?php } ?>
                             <a class="" title="Download" style='margin:0px 15px' target="_blank" href="<?=$publicURL;?>rxforms/view_entry_pdf.php?form_id=<?= $pf['form_id']; ?>&entry_id=<?= $pf['record_id']; ?>">
                                <i class="fa fa-file"></i> 
                            </a>
                              <?php if($pf['form_id']=='23530' || $pf['form_id']=='35612' || $pf['form_id']=='38356'){ ?>
                             <button title="Follow-Up" class="followBtn" data-url="<?=$publicURL;?>rxforms/copy_patient_entry.php?form_id=<?= $pf['form_id']; ?>&entry_id=<?= $pf['record_id']; ?>" onclick="openFullScreenPopup(this)">
                                Follow-up
                            </button>
                            <?php } ?>
                           </td>
                        </tr>
                     <?php $i++; } ?>
                  </tbody>
               </table>
             
               <div id="fullScreenModal">
                                 <!-- Close button inside the modal -->
                                 <button class="btn btn-secondary" onclick="closeFullScreenPopup()">Close</button>
                                 <!-- Iframe to load the external page -->
                                 <iframe id="popupIframe" src=""></iframe>
               </div>
               </div>
               
               
                <div class="tab-pane fade" id="home4" role="tabpanel" aria-labelledby="home4-tab">
                       <div class="content_body sendNewForm">
        					<div class="row content_body_main">
                                <iframe width="100%" frameborder="0"  height="1200vh" src="<?=$publicURL;?>/de/more_info.php?search=<?=$_GET['fileId'];?>&table=patient_address"></iframe>
                            </div>
                        </div>
                </div>
               
               
               <div class="tab-pane fade" id="home2" role="tabpanel" aria-labelledby="home2-tab">
               <div class="content_body sendNewForm">
					<div class="row content_body_main">
                        <input type="hidden" class="form-control" id="patientId" name="patientId" value="<?=$_GET['id'];?>">
                        <input type="hidden" class="form-control" id="fileId" name="fileId" value="<?=$_GET['fileId'];?>">
                        <input type="hidden" class="form-control" id="createdBy" name="createdBy" value="<?=$_SESSION['empId'];?>">
						<div class="form-group col-md-3">
							<label>Select Form to Send</label>
							<select class="form-control" id="mf_form_list" name="mf_form_list">
								<option>Select Form</option>
								<?php 
			   					$row_num = 1;
                           foreach($form_list_array as $form_data){
                              $form_name   	 = htmlspecialchars($form_data['form_name']);
                              $form_id   	 	 = $form_data['form_id'];
                           ?>
								   <option value="<?php echo $form_id; ?>"><?php echo $form_name; ?></option>
								   <?php 
										$row_num++; 
									}
                           //end foreach $form_list_array 
								?>
							</select>
						</div>
                        <div id="form_iframe_container" style="margin-top: 20px;">
                            <iframe frameborder="0" scrolling="no" id="form_iframe" src="" width="100%" style="border: 1px solid #ccc; display: none;"></iframe>
                        </div>   
                    </div>
               </div>
               </div>
                  <div class="tab-pane fade show active" id="home" role="tabpanel" aria-labelledby="home-tab">

                        <div class="editmycontainer myContainer">

                           <div class="">
                           <div class="formnote2 text-left"><span class="colorred">*</span> Mandatory Fields</div>
                              <h3 class="text-center ftitle">Update Account</h3>
                              <form method="POST" class="araddpatient editWc " enctype="multipart/form-data">
                                 <div class="row">

                                    <div class="col-sm-4">
                                       <div class="form-group">
                                          <label for="drugName">First Name <span class="req">*</span></label>
                                          <input type="text" required class="form-control" id='patientFName' 
                                             name="patientFName" value="<?php if (isset($patientDetails['firstName'])) {
                                                echo $patientDetails['firstName'];
                                             } ?>" placeholder="Enter Patient First Name">
                                       </div>
                                    </div>
                                    <div class="col-sm-4">
                                       <div class="form-group">
                                          <label for="drugName">Last Name</label>
                                          <input type="text" class="form-control" id='patientLName' value="<?php if (isset($patientDetails['lastName'])) {
                                             echo $patientDetails['lastName'];
                                          } ?>" 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" required class="form-control" id='dob'  value="<?php if (isset($patientDetails['dob'])) {
                                             echo $patientDetails['dob'];
                                          } ?>" name="dob" placeholder="Enter Patient DOB">
                                       </div>
                                    </div>
                                    <div class="col-sm-4">
                                       <div class="form-group">
                                          <label for="gender">Gender <span class="req">*</span></label>
                                          <select required class="form-control" id="gender" name="gender" >
                                             <option value="">Select Gender</option>
                                             <?php 
                                                foreach($gender_pl as $picklist){?>
                                                <option <?php if(isset($patientDetails["gender"])) { if($patientDetails["gender"]==$picklist['value']){ echo 'selected'; }} ?> value="<?=$picklist['value'];?>"><?=$picklist['name'];?></option>
                                             <?php } ?>
                                          </select>
                                       </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" value="<?php if (isset($patientDetails['phone'])) {echo $patientDetails['phone'];} ?>" name="phone" id="phone" data-inputmask="&quot;mask&quot;: &quot;(999) 999-9999&quot;"
                                                data-mask="" 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' value="<?php if (isset($patientDetails['email'])) { echo $patientDetails['email'];} ?>"  name="email" placeholder="Enter Patient Email">
                                       </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' value="<?php if (isset($patientDetails['address1'])) {echo $patientDetails['address1']; } ?>" required name="address1" placeholder="Enter Address">
                                       </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' value="<?php if (isset($patientDetails['address2'])) {echo $patientDetails['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" id='city' value="<?php if (isset($patientDetails['city'])) { echo $patientDetails['city']; } ?>" required name="city" placeholder="Enter City">
                                       </div>
                                    </div>
                                    <div class="col-sm-4 fixselect">
                                       <div class="form-group">
                                          <label for="drugName">Province <span class="req">*</span></label>
                                          <input type="text" class="form-control" id='province' value="<?php if (isset($patientDetails['province'])) { echo $patientDetails['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' value="<?php if (isset($patientDetails['postalCode'])) { echo $patientDetails['postalCode']; } ?>" required name="postalCode" placeholder="Enter Postal Code">
                                       </div>
                                    </div>
                                    <div class="col-sm-4">
                                       <div class="form-group">
                                          <label for="krollId">Kroll ID <span class="req">*</span></label>
                                          <input type="text" class="form-control" id='krollId' required readonly name="krollId" value="<?php if (isset($patientDetails['krollId'])) { echo $patientDetails['krollId']; } ?>" placeholder="Enter Kroll Id">
                                       </div>
                                    </div>
                                    <div class="clearfix"></div>
                                    <div class="col-sm-4">
                                       <div class="form-group">
                                          <label for="patientId">Patient Id </label>
                                          <input type="text" class="form-control" id='patientId' readonly name="patientId" value="<?php if (isset($patientDetails['patientId'])) { echo $patientDetails['patientId']; } ?>">      
                                       </div>
                                    </div>
                                    <div class="col-sm-4">
                                       <div class="form-group">
                                          <label for="phcn">Provincial Health Card Number</label>
                                          <input type="text" class="form-control" id='phcn'  name="phcn" value="<?php if (isset($patientDetails['provincialHCN'])) { echo $patientDetails['provincialHCN'];} ?>" placeholder="Enter Health Card Number">
                                       </div>
                                    </div>
                                    <div class="clearfix"></div>
                           
                                 </div>
                                 <div class="row" id="fileInputs">
                                    <?php foreach ($generaldocs as $ge) { ?>
                                       <div class="col-md-4">
                                          <div class="form-group fileRow">
                                             <label for="paymentId">File Name (Title) <span class="req">*</span></label>
                                             <select disabled name="fileTitle[]" class="form-control">
                                                <option disabled>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) ?>" <?= ($ge['title'] == $titleSanitized) ? 'selected' : '' ?>>
                                                <?= htmlspecialchars($titleRaw) ?>
                                              </option>
                                                <?php } ?>
                                             </select>
                                          </div>
                                       </div>
                                       <div class="col-md-4">
                                          <div class="fileRow form-group">
                                             <label for="paymentId">File Attachment <span class="req">*</span></label>
                                             <input type="text" disabled name="files[]" readonly value="<?= $ge['filename']; ?>" class="form-control fileInput">
                                          </div>
                                       </div>
                                       <div class="right flex">
                                          <a class="btn btn-success"
                                             href="uploads/<?= $patientDetails['province']; ?>/<?= $patientDetails['krollId']; ?>/<?= $ge['filename']; ?>" download><i title="Download Attachment" class="fa fa-download"></i></a>
                                          <a class="btn btn-info text-white" href="uploads/<?= $patientDetails['province']; ?>/<?= $patientDetails['krollId']; ?>/<?= $ge['filename']; ?>" target="_blank"><i title="View Attachment" class="fa fa-eye"></i></a>
                                          <!-- <button type="button" data-id="<?//= $ge['id']; ?>"
                                             class="btn btn-danger deleteDocument" id="delete"><i title="Delete Attachment"
                                                class="fa fa-trash"></i></button> -->
                                       </div>
                                    <?php } ?>
                                    <div class="clearfix"></div>
                                    <div class="col-md-4">
                                       <div class="form-group fileRow">
                                          <label for="paymentId">New File Name (Title)</label>
                                          <select name="fileTitle[]" class="form-control">
                                             <option disabled selected>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>
                                    </div>
                                    <div class="col-md-4">
                                       <div class="fileRow form-group">
                                          <label for="paymentId">New File Attachment</label>
                                          <input type="file" name="files[]" class="form-control fileInput">
                                       </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" name="notes" id="notes" rows="2"><?php if (isset($patientDetails['notes'])) {
                                       echo $patientDetails['notes'];
                                    } ?></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: </label>
                                       <div>
                                          <select  class="form-control form-control" id="patientDrugName"
                                             name="patientDrugName">
                                             <option value="">Select Drug</option>
                                             <?php foreach ($medications as $medication) { ?>
                                                <option value="<?php echo $medication['drugName']; ?>" <?php echo ($medication['drugName'] == $patientDetails['patientDrugName']) ? 'selected' : ''; ?>><?php echo $medication['drugName']; ?></option>
                                             <?php } ?>
                                          </select>
                                       </div>
                                    </li>
                                    <!--// new fields start-->
                                    <!--// 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>
                                                   <?php 
                                                        foreach($indicationtype_pl as $picklist){?>
                                                        <option <?php if (in_array($picklist['name'], explode(",", $patientDetails['indication']))) {  echo "selected"; } ?> value="<?=$picklist['name'];?>"><?=$picklist['name'];?></option>
                                                   <?php } ?>
                                                </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">
                                                <?php if (!isset($patientDetails['ldosage']) || $patientDetails['ldosage']==""): ?>
                                                  <option selected value="">Select Dose</option>
                                                <?php else: ?>
                                                  <option selected value="<?=$patientDetails['ldosage']?>"><?=$patientDetails['ldosage']?></option>
                                                <?php endif; ?>
                                            </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">
                                                <?php if (!isset($patientDetails['lfrequency']) || $patientDetails['lfrequency']==""): ?>
                                                  <option selected value="">Select Frequency</option>
                                                <?php else: ?>
                                                  <option selected value="<?=$patientDetails['lfrequency']?>"><?=$patientDetails['lfrequency']?></option>
                                                <?php endif; ?>
                                            </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">
                                             <?php if (!isset($patientDetails['lrouteOfAdmin']) || $patientDetails['lrouteOfAdmin']==""): ?>
                                                  <option selected value="">Select Route of Administration</option>
                                                <?php else: ?>
                                                  <option selected value="<?=$patientDetails['lrouteOfAdmin']?>"><?=$patientDetails['lrouteOfAdmin']?></option>
                                                <?php endif; ?>
                                          </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">
                                                <?php if (!isset($patientDetails['dosage']) || $patientDetails['dosage']==""): ?>
                                                  <option selected value="">Select Dose</option>
                                                <?php else: ?>
                                                  <option selected value="<?=$patientDetails['dosage']?>"><?=$patientDetails['dosage']?></option>
                                                <?php endif; ?>
                                            </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">
                                                <?php if (!isset($patientDetails['currentFrequency']) || $patientDetails['currentFrequency']==""): ?>
                                                  <option selected value="">Select Frequency</option>
                                                <?php else: ?>
                                                  <option selected value="<?=$patientDetails['currentFrequency']?>"><?=$patientDetails['currentFrequency']?></option>
                                                <?php endif; ?>
                                          </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">
                                            <?php if (!isset($patientDetails['routeOfAdmin']) || $patientDetails['routeOfAdmin']==""): ?>
                                                  <option selected value="">Select Frequency</option>
                                                <?php else: ?>
                                                  <option selected value="<?=$patientDetails['routeOfAdmin']?>"><?=$patientDetails['routeOfAdmin']?></option>
                                                <?php endif; ?>
                                          </select>
                                       </div>
                                    </li>
                                    <li class="clearfix"></li>
                                    <!--// new fields end-->

                                    <li class="clearfix"></li>

                                    <li class="col-md-4">
                                       <label class="description" for="prescriberName">Prescriber's Name : </label>
                                       
                                       <div>
                                          <!-- <input  id="prescriberName" name="prescriberName" class="form-control"
                                             type="text" value="<?php //echo $patientDetails['prescriberName']; ?>"
                                             autocomplete="off"> -->
                                             <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'];
                                                $physicianType=$medication['physicianType'];
                                                $selected='';
                                                $primaryaddressData='';
                                                $secondaryaddressData='';
                                                if($patientDetails['prescriberName']==$physicianFullname){
                                                   $selected='selected';
                                                }
                                                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 <?=$selected;?> 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"
                                             value="<?php echo $patientDetails['prescriberSpecialty']; ?>"
                                             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"
                                             value="<?php // echo $patientDetails['team']; ?>" 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"
                                             value="<?php // echo $patientDetails['staff']; ?>" autocomplete="off">
                                       </div> -->
                                       <div class="fixselect">
                                             <select class="form-control select2bs4" id="staff" name="staff">
                                                <option value="" >Select Staff</option>
                                                <?php foreach ($np as $emp) {
                                                   $selected='';
                                                   if($emp['userName']==$patientDetails['staff']){
                                                      $selected='selected';
                                                   }
                                                   ?>
                                                   <option <?=$selected;?> value="<?= $emp['userName']; ?>"><?= $emp['userName']; ?></option>
                                                <?php } ?>
                                             </select>
                                          </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" >
                                             <option value="">Select Prescriber Address Type</option>
                                             <!-- //selectedphysicianOptions -->
                                             <?php foreach ($selectedphysicianOptions as $address) {
                                                   ?>
                                                   <option class="AddressType-<?= $address['physicianId']; ?>" data-pID="<?= $address['physicianId']; ?>" 
                                                   data-hospital="<?= $address['hospital']; ?>" data-streetAddress="<?= $address['streetAddress']; ?>" 
                                                   data-city="<?= $address['city']; ?>" data-province="<?= $address['province']; ?>" data-postalCode="<?= $address['postalCode']; ?>"
                                                   data-phone="<?= $address['phone']; ?>" data-email="<?= $address['email']; ?>" 
                                                   data-fax="<?= $address['fax']; ?>" data-notes="<?= $address['notes']; ?>" value="<?= $address['id']; ?>"><?= $address['addressType']; ?></option>
                                                <?php } ?>
                                             </select>
                                          </div>
                                       </div>
                                    </li>
                                   
                                    <!-- Address fields start -->
                                   
                                    <li class="card-body row prescriber-address-fields" id="prescriber-address-fields">
                                       <input type="hidden" class="form-control" name="prescriber-address-pID" id="prescriber-address-pID" value="<?= isset($physicianoldAddress['physicianId']) && !empty($physicianoldAddress['physicianId']) ? $physicianoldAddress['physicianId'] : ''; ?>">
                                       <div class="form-group col-md-4">
                                            <label for="prescriber-address-hospital">Prescriber Hospital/Site :</label>
                                            <input disabled type="text" class="form-control" name="prescriber-address-hospital" id="prescriber-address-hospital" value="<?= isset($physicianoldAddress['hospital']) && !empty($physicianoldAddress['hospital']) ? $physicianoldAddress['hospital'] : ''; ?>" placeholder="Enter Hospital">
                                        </div>
                                        <div class="form-group col-md-4">
                                            <label for="prescriber-address-email">Prescriber Email</label>
                                            <input disabled  type="email" class="form-control" name="prescriber-address-email" id="prescriber-address-email" value="<?= isset($physicianoldAddress['email']) && !empty($physicianoldAddress['email']) ? $physicianoldAddress['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 disabled type="text" class="form-control" name="prescriber-address-fax" id="prescriber-address-fax" value="<?= isset($physicianoldAddress['fax']) && !empty($physicianoldAddress['fax']) ? $physicianoldAddress['fax'] : ''; ?>" placeholder="Enter Fax">
                                        </div>
                                       
                                        <div class="form-group col-md-4">
                                            <label for="prescriber-address-phone">Prescriber Phone</label>
                                            <input disabled type="text" class="form-control" name="prescriber-address-phone" id="prescriber-address-phone" value="<?= isset($physicianoldAddress['phone']) && !empty($physicianoldAddress['phone']) ? $physicianoldAddress['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 disabled type="text" class="form-control" name="prescriber-address-address" id="prescriber-address-address" value="<?= isset($physicianoldAddress['streetAddress']) && !empty($physicianoldAddress['streetAddress']) ? $physicianoldAddress['streetAddress'] : ''; ?>" placeholder="Enter Street Address">
                                        </div>

                                        <div class="form-group col-md-4">
                                            <label for="prescriber-address-city">Prescriber City</label>
                                            <input disabled type="text" class="form-control" name="prescriber-address-city" id="prescriber-address-city" value="<?= isset($physicianoldAddress['city']) && !empty($physicianoldAddress['city']) ? $physicianoldAddress['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 disabled type="text" class="form-control" name="prescriber-address-physicianProvince" id="prescriber-address-physicianProvince" value="<?= isset($physicianoldAddress['province']) && !empty($physicianoldAddress['province']) ? $physicianoldAddress['province'] : ''; ?>" placeholder="Enter Province">
                                        </div>
                                        <div class="form-group col-md-4">
                                            <label for="prescriber-address-postalCode">Prescriber Postal Code</label>
                                            <input disabled type="text" class="form-control" id="prescriber-address-postalCode" name="prescriber-address-postalCode" value="<?= isset($physicianoldAddress['postalCode']) && !empty($physicianoldAddress['postalCode']) ? $physicianoldAddress['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 disabled class="form-control" name="prescriber-address-notes" id="prescriber-address-notes"><?= isset($physicianoldAddress['notes']) && !empty($physicianoldAddress['notes']) ? $physicianoldAddress['notes'] : ''; ?></textarea>
                                        </div>
                                    </li>
                                  

                                    <li>
                                       <span class="description">Did Patient get Sample Dose from Prescribers office?<span class="req">*</span> </span>
                                       <div>
                                          <fieldset>

                                             <span class="flex">
                                                <input  type="radio" id="yesDpgsd" <?php echo ("Y" == $patientDetails['presciberOffice']) ? 'checked' : ''; ?>
                                                   name="Dpgsd" value="Y" class="custom-radio">
                                                <label for="yesDpgsd" class="radio-label">Yes</label>
                                             </span>

                                             <span class="flex">
                                                <input  type="radio" id="noDpgsd" <?php echo ("N" == $patientDetails['presciberOffice']) ? 'checked' : ''; ?>
                                                   name="Dpgsd" value="N" class="custom-radio">
                                                <label for="noDpgsd" class="radio-label">No</label>
                                             </span>
                                             <span class="flex">
                                                <input  type="radio" id="unsureDpgsd" <?php echo ("U" == $patientDetails['presciberOffice']) ? 'checked' : ''; ?>
                                                   name="Dpgsd" value="U" class="custom-radio">
                                                <label for="unsureDpgsd" class="radio-label">Unsure</label>
                                             </span>
                                          </fieldset>
                                       </div>
                                    </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"  value="<?php echo $patientDetails['sampleDoseReceived']; ?>"  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" <?php echo ("Y" == $patientDetails['iprfwc']) ? 'checked' : ''; ?>
                                                   name="iprfwc" value="Y" class="custom-radio">
                                                <label for="yesiprfwc" class="radio-label">Yes</label>
                                             </span>

                                             <span class="flex">
                                                <input  type="radio" id="noiprfwc" <?php echo ("N" == $patientDetails['iprfwc']) ? 'checked' : ''; ?>
                                                   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"   max="<?php echo date('Y-m-d\TH:i'); ?>" value="<?php if (isset($patientDetails['enrolmentFormReceiveDate'])) { echo $patientDetails['enrolmentFormReceiveDate'];} ?>" id="enrolmentFormReceiveDate"  name="enrolmentFormReceiveDate">
                                          </div>
                                       </fieldset>
                                    </li>
                                     <li class="clearfix"></li>
                                    <li class="col-md-4" id="EnrollmentMAT">
                                       <label class="description" for="roa">Enrolment Form MAT Code <span class="req">*</span></label>
                                       <div>
                                          <select class="form-control" required id="mat" name="mat">
                                             <option value=""></option>
                                              <?php foreach($mats as $mat) { ?>
                                             <option <?php echo (isset($selectedConsent)) && (isset($selectedConsent['versionInEnrolmentForm'])) && ($selectedConsent['versionInEnrolmentForm'] == $mat['version']) ? 'selected' : ''; ?> value="<?=$mat['form_id'];?>"><?=$mat['version'];?></option>
                                             <?php } ?>
                                          </select>
                                       </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" <?php echo (isset($selectedConsent)) && (isset($selectedConsent['consentInEnrolment'])) && ("Y" == $selectedConsent['consentInEnrolment']) ? 'checked' : ''; ?> name="consent" value="Y" class="custom-radio">
                                                <label for="yesconsent" class="radio-label">Yes</label>
                                             </span>

                                             <span class="flex">
                                                <input  type="radio" id="noconsent" <?php echo (isset($selectedConsent)) && (isset($selectedConsent['consentInEnrolment'])) && ("N" == $selectedConsent['consentInEnrolment']) ? 'checked' : ''; ?> name="consent" value="N" class="custom-radio">
                                                <label for="noconsent" class="radio-label">No</label>
                                             </span>
                                            
                                          </fieldset>
                                       </div>
                                    </li>

                                 </ul>
                                 <div class="form-group mar-b-0">
                                 
                                    <button type="submit" value="SAVE" name="savepatientdetials" id="savepatientdetials"
                                       class="btn btn-success save"> SAVE </button>
                                 </div>
                              </form>
                           </div>

                           </div>
<script>
 window.fileTitles = <?php echo json_encode(array_map(function($t) {
    return $t['title'];
  }, $fileTitles)); ?>;
</script>
<script>document.write('<script src="js/editPatient.js?version=' + Date.now() + '"><\/script>');</script>
                           <!-- bs-custom-file-input -->
                           <script src="plugins/bs-custom-file-input/bs-custom-file-input.min.js"></script>
                           
<!-- /.card-header -->
<!-- bs-custom-file-input -->
<script src="plugins/bs-custom-file-input/bs-custom-file-input.min.js"></script>
<script>
    $(document).ready(function() {
        
      $('#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');
         var valCheck=$(this).find('option:selected').val();
        const AddType = $(this).find('option:selected').data('AddType');
        const physicianType = $(this).find('option:selected').data('physiciantype'); // added to check if physician is pilot - RJ
        
        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;
        }
        // Update the Prescriber Specialty input field with the value
        $('#prescriberSpecialty').val(specialty || ''); // Default to empty if no value
        $('#staff').select2().val(staff || '').trigger('change');
        // rishabh
        const prescriberId = $(this).find('option:selected').data('physicianid');
        // 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='';
        }
    });
   
        const phyType = $('#prescriberName').find('option:selected').data('physiciantype'); // added to check if physician is pilot - RJ
        if(phyType != '' && phyType == '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");
        }
    });
 function openFullScreenPopup(button) {
    // Retrieve the URL from the button's data attribute
    const url = button.getAttribute("data-url");
    document.getElementById("popupIframe").src = url;
    // Display the modal
    document.getElementById("fullScreenModal").style.display = "block";
    $('#myTab').hide();
 }
    $('.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();
        }
    });

  function closeFullScreenPopup() {
    // Hide the modal
    document.getElementById("fullScreenModal").style.display = "none";
     // Clear the iframe URL to stop the page from running in the background
      document.getElementById("popupIframe").src = "";
      $('#myTab').show();
    }
$("#mf_form_list").change(function() {
    var formId = $(this).val();
    var patientId = $('#patientId').val();
    var fileId = $('#fileId').val();
    var createdBy = $('#createdBy').val();
    
    if (formId && formId !== 'Select Form') {
        var iframe = $("#form_iframe");
        iframe.attr("src", "<?=$publicURL;?>rxforms/viewRxForm.php?id=" + formId + "&patientId=" + patientId + "&fileId=" + fileId + "&createdBy=" + createdBy).show();
        // Adjust iframe height on load and on content size change
        iframe.on('load', function() {
            adjustIframeHeight(this);
        });
    } else {
        $("#form_iframe").hide();
    }
});

function adjustIframeHeight(iframe) {
    var doc = iframe.contentDocument || iframe.contentWindow.document;
    
    function updateHeight() {
        console.log(doc.body.scrollHeight+100);
        $(iframe).height(doc.body.scrollHeight+100);
    }

    updateHeight();

    // Optional: Add resize observer to adjust height dynamically
    var resizeObserver = new ResizeObserver(updateHeight);
    resizeObserver.observe(doc.body);
}
document.addEventListener('DOMContentLoaded', function () {
  const editPtBtn = document.getElementById('savepatientdetials');

  editPtBtn.addEventListener('click', function () {
    // only target disabled elements inside #prescriber-address-fields
    $('#prescriber-address-fields')
      .find(':disabled')
      // you can use prop for better consistency:
      .prop('disabled', false);
  });
});
$('#example').dataTable( {
    "order": [],
    // Your other options here...
} );
</script>
<?php include('footer.php');
ob_end_flush();
?>
                          