<?php 
namespace Dompdf;
require('../assets/dompdf/vendor/autoload.php');
use Dompdf\Dompdf as DOMPDF;
session_start();
include('../connect.php');
if(!isset($_SESSION['empId'])){
    header("location: login.php");
}
if(isset($_GET['id']) && isset($_GET['fileId'])){
$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 tblpatient.id=? AND tblpatientdetails.fileId=?");
$stmt1->execute([$_GET['id'],$_GET['fileId']]);
$patientDetails = $stmt1->fetch();

$stmt1 = $pdo->prepare("SELECT * from tblreimbursement      
                                 WHERE pId=? and fileId=?");
                                 $stmt1->execute([$_GET['id'],$_GET['fileId']]);
                                 $repatientDetails = $stmt1->fetch();
                                 $gender='';
                                 if($patientDetails['gender']=="M"){
                                    $gender= "Male";
                                 }elseif ($patientDetails['gender']=="F") {
                                    $gender= "Female";
                                 }else{
                                  $gender= "Other";
                                 }

                                 //wc status
                                 $wcStatus='';
                                 if($patientDetails['wcStatus'] == 1){$wcStatus='New - Patient Not Yet Contacted';}
                                 if($patientDetails['wcStatus'] == 2){$wcStatus='Pending - 1st Patient Contact Attempted';}
                                 if($patientDetails['wcStatus'] == 3){$wcStatus='Pending - 2nd Patient Contact Attempted';}
                                 if($patientDetails['wcStatus'] == 4){$wcStatus='Pending - 3rd Patient Contact Attempted';}
                                 if($patientDetails['wcStatus'] == 5){$wcStatus='Complete - Contact Complete';}
                                 if($patientDetails['wcStatus'] == 6){$wcStatus='Incomplete - Enrollment Discontinued - Patient Cannot be reached';}
                                 if($patientDetails['wcStatus'] == 7){$wcStatus='Clarification: Waiting for information from prescriber';}
                                 if($patientDetails['wcStatus'] == 8){$wcStatus='PPN: No welcome call required';}
                                 if($patientDetails['wcStatus'] == 9){$wcStatus='Other pharmacy: No welcome call required';}
                                 if($patientDetails['wcStatus'] == 10){$wcStatus='Patient not getting medication - closed';}
                                 if($patientDetails['wcStatus'] == 11){$wcStatus='Entered in error - disregard';}
                                 if($patientDetails['wcStatus'] == 12){$wcStatus='Pending patient update - patient contacted waiting for info';}
                                 //end wc status
}else{
    header("index.php"); 
 }

$html = '
<!DOCTYPE html>
<html lang="en">
    <head>
        <meta charset="utf-8">
        <meta content="width=device-width, initial-scale=1.0" name="viewport">
        <title>Patient form</title>
        <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.3/dist/css/bootstrap.min.css" rel="stylesheet">
        <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.3/dist/js/bootstrap.bundle.min.js"></script>
        <link href="https://fonts.cdnfonts.com/css/adobe-clean" rel="stylesheet">
        <link href="https://fonts.cdnfonts.com/css/poppins" rel="stylesheet">
                
    </head>
    <style>
        table {
            width:100%;
            border-collapse: collapse;
        }
        .text-left{
            text-align:left;
        }
        .image{
            width: 130px;
            height: 40px;
            position:relative;
            background-size:contain;
            background-repeat:no-repeat;
            background-image: url(data:image/png;base64, )
        }
        td,th{
        font-size:12px;   
        padding:2px !important;
        }
        .table,
        .table th,
        .table td {
            border: 1px solid #dddddd;
            border-collapse: collapse;
            padding: 5px;
            font-family: "adobe-clean", sans-serif !important;
        }
        tr:nth-child(odd) {
            background-color: #dddddd;
        }
         tr.bgwhite{
            background:white !important;
        }
        .borderless,.borderless td{
           border:none !important; 
        }
           html{
            margin:10px 20px;
            font-family: "Poppins", sans-serif;                               
            }
            body,table,tr,td,th,p{
            font-family: "Poppins", sans-serif;   
            }
    </style>
    <body>
        
        
        <table class="table table-bordered table-striped">
          <thead>
           <tr class="borderless bgwhite">
              <td colspan="2" ><div class="image"></div></td>
              </tr>
              <tr class="bgwhite">
              <td style="width:50%;"><b>Form Name</b> NGW: Patient Enrollment Information 12.23</td>
              <td style="width:50%;"><b>Submitted On</b> 11/24/2023 03:39 PM(CDT)</td>
           </tr>  
            <tr class="bgwhite">
              <th style="width:50%;">Questions</th>
              <th style="width:50%;">Answers</th>
            </tr>
          </thead>
          <tbody>
           <tr>
              <th class="text-center" colspan="2">Pre-Treatment Phase <br> Welcome Call, Counseling....</th>
            </tr>
            <tr>
              <td>Entry Date:</td>
              <td>'.date('M j, Y', strtotime($patientDetails['createdDate'])).'</td>
            </tr>
            <tr>
              <td>Patient First Name:</td>
              <td>'.$patientDetails['firstName'].'</td>
            </tr>
             <tr>
              <td>Patient Last Name</td>
              <td>'.$patientDetails['lastName'].'</td>
            </tr>
            <tr>
              <td>Kroll Patient ID</td>
              <td>'.$patientDetails['krollId'].'</td>
            </tr>
            <tr>
              <td>Patient DOB</td>
              <td>'.$patientDetails['dob'].'</td>
            </tr>
            <tr>
              <td>Year of Birth</td>
              <td>'.date('Y', strtotime($patientDetails['dob'])).'</td>
            </tr>
            <tr>
              <td>Gender</td>
              <td>'.$gender.'</td>
            </tr>
             <tr>
              <th class="text-center" colspan="2">Welcome Call</th>
            </tr>
             <tr>
              <td>Welcome Call Status</td>
              <td>'.$wcStatus.'</td>
            </tr>
            <tr>
              <td>Welcome Call Status Due Date</td>
              <td>'.date('M j, Y', strtotime($patientDetails['wcStatusDueDate'])).'</td>
            </tr>
            <tr>
              <td>Welcome Call Completion Date</td>
              <td>'.date('M j, Y', strtotime($patientDetails['wcCompletionDate'])).'</td>
            </tr>
            <tr>
              <td>Welcome Call Notes</td>
              <td>'.$patientDetails['wcNotes'].'</td>
            </tr>
             <tr>
              <th class="text-center" colspan="2">Patient Demographic Information</th>
            </tr>
             <tr>
              <td>Provincial Health Card Number:</td>
              <td>'.$patientDetails['provincialHCN'].'</td>
            </tr>
             <tr>
              <td>Patient Street Address: </td>
              <td>'.$patientDetails['address1'].' '.$patientDetails['address2'].'</td>
            </tr>
            <tr>
              <td>City:</td>
              <td>'.$patientDetails['city'].'</td>
            </tr>
            <tr>
              <td>Province:</td>
              <td>'.$patientDetails['province'].'</td>
            </tr>
            <tr>
              <td>Postal:</td>
              <td>'.$patientDetails['postalCode'].'</td>
            </tr>
            <tr>
              <td>Patient Phone Number:</td>
              <td>'.$patientDetails['phone'].'</td>
            </tr>
            <tr>
              <td>Patient Email:</td>
              <td>'.$patientDetails['email'].'</td>
            </tr>
            <tr>
              <th colspan="2" class="text-left">Medication & Medical History Information</th>
            </tr>
            <tr>
              <td>Medication Allergies:</td>
              <td>'.$patientDetails['medicationAllergies'].'</td>
            </tr>
             <tr>
              <td>Latex Allergies:</td>
              <td>'.$patientDetails['latexAllergies'].'</td>
            </tr>
             <tr>
              <td>Medical Conditions Comments/Other</td>
              <td>'.$patientDetails['medicalConditionsComments'].'</td>
            </tr>';
            $currentMedications = $patientDetails['currentMedications'];

// Decode JSON string
$medications = json_decode($currentMedications, true);

$html.='<tr>';
$html.='<td>Current Medications (OTC, Prescribed, Herbal)</td>';
$html.='<td>';

// Check if the JSON is valid and decoded properly
if (!empty($medications)) {
  $html.='<table border="1" style="width: 100%; border-collapse: collapse;">';
    $html.='<tr>
            <th>Name & Strength</th>
            <th>Condition</th>
            <th>Frequency</th>
            <th>Comments</th>
          </tr>';
    foreach ($medications as $med) {
        $html.='<tr>';
        $html.='<td>' . htmlspecialchars($med['nameStrength']) . '</td>';
        $html.='<td>' . htmlspecialchars($med['condition'] ?? '-') . '</td>';
        $html.='<td>' . htmlspecialchars($med['frequency'] ?? '-') . '</td>';
        $html.='<td>' . htmlspecialchars($med['comments'] ?? '-') . '</td>';
        $html.='</tr>';
    }
    $html.='</table>';
} else {
    $html.='No Current Medications.';
}

$html.='</td></tr>';
             $html.='<tr>
              <td>Patient Medical/Medication Documents</td>
              <td>'.$patientDetails['pmmd'].'</td>
            </tr>
             <tr>
              <td colspan="2"><b>Pre-Biologic Medications</b> <br>List all previous Medication(s) the patient has taken for their condition.</td>
            </tr>';
            $previosMedications = explode(',', $patientDetails['pmName']);
            $pmDosage = explode(',', $patientDetails['pmDosage']);
            $pmSwitchReason = explode(',', $patientDetails['pmSwitchReason']);
            $pmStartDate = explode(',', $patientDetails['pmStartDate']);
            $pmEndDate = explode(',', $patientDetails['pmEndDate']);
            $confirmStartEndDate = explode(',', $patientDetails['confirmStartEndDate']);


            $previousMedCount=count($previosMedications);
            $j=1;
            for($i=0;$i<$previousMedCount;$i++){
              $html.='<tr>
              <td>Previous Medication #'.$j.' Patient was on for their Condition</td>
              <td>'.$previosMedications[$i].'</td>
            </tr>
             <tr>
              <td>Previous Medication #'.$j.' Dosage</td>
              <td>'.$pmDosage[$i].'</td>
            </tr>
            <tr>
              <td>Why did Patient switch from previous Medication #'.$j.'?</td>
              <td>'.$pmSwitchReason[$i].'</td>
            </tr>';
           
            if($pmStartDate[$i]==""){             
            $html.='<tr>
            <td></td>
            <td>Patient does not know Start/End Date</td>
            </tr>';
            }else{
                $html.='<tr>
              <td>Start Date</td>
              <td>'.$pmStartDate[$i].'</td>
              </tr>
              <tr>
              <td>End Date</td>
              <td>'.$pmEndDate[$i].'</td>
              </tr>';
            }
            $j++;
            }
             $html.='<tr>
              <th class="text-left" colspan="2">Prescription Drug Information</th>
            </tr>
             <tr>
              <td>Drug Name</td>
              <td>'.$patientDetails['patientDrugName'].'</td>
            </tr>
            <tr>
              <td>Dose</td>
              <td>'.$patientDetails['dosage'].'</td>
            </tr>
            <tr>
              <td>Route of Administration</td>
              <td>'.$patientDetails['routeOfAdmin'].'</td>
            </tr>
             <tr>
              <td>Indication</td>
              <td>'.$patientDetails['indication'].'</td>
            </tr>
              <tr>
              <td>Off-Label Use</td>
              <td>'.$patientDetails['offLabelUse'].'</td>
            </tr>
             <tr>
              <td>Prescriber’s Name</td>
              <td>'.$patientDetails['prescriberName'].'</td>
            </tr>
            <tr>
              <td>Prescriber’s Specialty</td>
              <td>'.$patientDetails['prescriberSpecialty'].'</td>
            </tr>
              <tr>
              <td>Team</td>
              <td>'.$patientDetails['team'].'</td>
            </tr>
             <tr>
              <td>Staff</td>
              <td>'.$patientDetails['staff'].'</td>
            </tr>
             <tr>
              <td>Did Patient get Sample Dose from Prescribers office?</td>
              <td>'.$patientDetails['presciberOffice'].'</td>
            </tr>
             <tr>
              <th class="text-center" colspan="2">Pre-Treatment Phase</th>
            </tr>';
            $screeningStatus='';
            if("1" == $patientDetails['sis']){$screeningStatus='Pending - Screening/Immunization Required';}
            if("2" == $patientDetails['sis']){$screeningStatus='Pending - Patient Update';}
            if("3" == $patientDetails['sis']){$screeningStatus='Pending - Medical Clerance Received';}
            if("4" == $patientDetails['sis']){$screeningStatus='Completed - Medical Clerance Confirmed';}
            if("5" == $patientDetails['sis']){$screeningStatus='Screening/Immunization Not Required';}

             $html.='<tr>
              <th class="text-left" colspan="2">Screening/Immunization</th>
            </tr>
             <tr>
              <td>Screening/Immunization Status</td>
              <td>'.$screeningStatus.'</td>
            </tr>
             <tr>
              <td>Screenings/Vaccinations Required</td>
              <td>'.$patientDetails['svr'].'</td>
            </tr>
             <tr>
              <td>TB Skin Screening Status</td>
              <td>'.$patientDetails['tbskinscreening'].'</td>
            </tr>
             <tr>
              <td>Chest X-Ray Screening Status</td>
              <td>'.$patientDetails['cxss'].'</td>
            </tr>
            
            <tr>
              <th class="text-center" style="text-align:Center;" colspan="2">Counseling</th>
            </tr>';
            $counselingStatus='';
            if($repatientDetails['counselingStatus']=="1"){ $counselingStatus='Pending - Not Yet Completed';}
            if($repatientDetails['counselingStatus']=="2"){ $counselingStatus='Completed - Counseling Complete';}
            $reimbursementStatusOptions = [
              "1" => "Pending - SA Submitted by RX Connect",
              "2" => "Pending - SA Submitted by PSP",
              "3" => "Pending - EAP Submitted",
              "4" => "Pending - Limited Use Code",
              "8" => "Pending - Appeal Submission",
              "11" => "Pending - patient to be enrolled into PSP",
              "12" => "Pending - PSP to initiate SA process",
              "13" => "Pending - patient to provide PSP with more information",
              "14" => "Pending - Patient to provide Rx Connect with more information",
              "15" => "Pending - Patient Signature",
              "16" => "Pending - Physician Signature",
              "17" => "Pending- Insurance decision",
              "10" => "Complete - Free of Charge",
              "6" => "Complete - Coverage Established",
              "24" => "Complete - Coverage Established- PPN",
              "25" => "Complete - Coverage Established - Not using Rx Pharmacy",
              "26" => "Complete- Coverage Established - Not using Rx Connect",
              "27" => "Complete- Compassionate",
              "30" => "Patient prefers local pharmacy - No reimb",
              "7" => "Reimbursement Not Required",
              "18" => "PSP to start EAP process",
              "19" => "Rx Connect to start EAP Process",
              "20" => "Rx Connect to start SA process",
              "21" => "Pending EAP decision",
              "22" => "Patient transferred out",
              "23" => "Pending Medical clearance from MD",
              "37" => "Pending - Screening Test/Immunization"
          ];
          
          // Check if the reimbursement status exists in the array, and if so, assign the corresponding description
          $reimbursementStatus = isset($repatientDetails['reimbursementStatus']) && isset($reimbursementStatusOptions[$repatientDetails['reimbursementStatus']])
              ? $reimbursementStatusOptions[$repatientDetails['reimbursementStatus']]
              : '';
            $html.='<tr>
              <td>Counseling Status:</td>
              <td>'.$counselingStatus.'</td>
            </tr>
            <tr>
              <td>Counseling Completion Date:</td>
              <td>'.$repatientDetails['ccd'].'</td>
            </tr>
            <tr>
              <th class="text-center" colspan="2">Coverage Details</th>
            </tr>
             <tr>
              <td>Reimbursement Status</td>
              <td>'.$reimbursementStatus.'</td>
            </tr>
             <tr>
              <td>Reimbursement Completion Date</td>
              <td>'.$repatientDetails['rcd'].'</td>
            </tr>
              <tr>
              <th class="text-left" colspan="2">Primary Plan</th>
            </tr>
            <tr>
              <td>Carrier</td>
              <td>'.$repatientDetails['Carrier'].'</td>
            </tr>
             <tr>
              <td>Group/Contract Number</td>
              <td>'.$repatientDetails['groupCN'].'</td>
            </tr>
              <tr>
              <td>Client ID/Certificate Number</td>
              <td>'.$repatientDetails['certificateNumber'].'</td>
            </tr>
             <tr>
              <td>Cardholder</td>
              <td>'.$repatientDetails['cardholder'].'</td>
            </tr>
             <tr>
              <td>Coverage Percentage</td>
              <td>'.$repatientDetails['coveragePercentage'].'</td>
            </tr>
             <tr>
              <td>Coinsurance Payment</td>
              <td>'.$repatientDetails['coinsurancePayment'].'</td>
            </tr>
             <tr>
              <td>Copay Max (Sliding Copay)</td>
              <td>'.$repatientDetails['copayMax'].'</td>
            </tr>
             <tr>
              <td>SA/EAP Required (Primary Plan)?</td>
              <td>'.$repatientDetails['sarequired'].'</td>
            </tr>
             <tr>
              <td>SA/EAP Submission Date (Primary)</td>
              <td>'.$repatientDetails['saEapSub'].'</td>
            </tr>
             <tr>
              <td>Does Patient Have a Secondary Plan?</td>
              <td>'.$repatientDetails['dphsp'].'</td>
            </tr>
             
             <tr>
              <td>Financial Assistance</td>
              <td>'.$repatientDetails['financialAssistance'].'</td>
            </tr>
             <tr>
              <td>CoPay Card</td>
              <td>'.$repatientDetails['copayCard'].'</td>
            </tr>
            <tr>
              <th class="text-center" colspan="2">First Appointment Details</th>
            </tr>';
            $itl='';
            if($repatientDetails['injTraLoc']=="1"){
              $itl='Virtual';
            }
            if($repatientDetails['injTraLoc']=="2"){
              $itl='Clinic';
            }
            if($repatientDetails['injTraLoc']=="3"){
              $itl='Patient Denied';
            }
            $clinicInjTrainingSitesOptions = [
              "" => "",
              "4" => "Rx Connect Pharmacy Solutions - Alberta",
              "5" => "Bowmanville Infusion Clinic",
              "7" => "Burlington North Infusion Centre",
              "8" => "Burlington South Infusion Clinic",
              "9" => "Calgary Infusion Clinic",
              "10" => "Cambridge Injection Centre",
              "11" => "Hamilton Infusion Clinic",
              "12" => "Markham Injection Centre",
              "13" => "Milton Infusion Clinic",
              "14" => "Mississauga North Infusion Clinic",
              "16" => "Niagara Infusion Centre",
              "18" => "Oakville Infusion Clinic (Dr Dua)",
              "19" => "Rx Connect Specialty Pharmacy - ONTARIO",
              "20" => "Ottawa Infusion Clinic",
              "23" => "Virtual",
              "24" => "Waterloo Infusion Clinic",
              "25" => "Windsor Infusion Clinic",
              "27" => "Chatam Infusion Clinic",
              "28" => "Not Rx Connect clinic",
              "29" => "Scarborough Clinic Dr. Hessami - Injection Clinic",
              "33" => "St. Catherines clinic",
              "30" => "NS Clinic",
              "34" => "Toronto Clinic Dr.Morris/Dr.Bacher - Injection Clinic"
          ];
          
          // Store the selected site ID for easier comparison
          $selectedClinicSite = isset($repatientDetails['clinicInjTrainingSites']) ? $repatientDetails['clinicInjTrainingSites'] : '';
          $selectedClinicSiteText = isset($clinicInjTrainingSitesOptions[$selectedClinicSite]) ? $clinicInjTrainingSitesOptions[$selectedClinicSite] : '';
          $trtStatusOptions = [
            "" => "",
            "1" => "Pending",
            "11" => "Pending - Patient unreachable",
            "13" => "Pending - Medical clearance",
            "20" => "Pending - test",
            "2" => "On treatment",
            "21" => "On Treatment - Rx Connect",
            "6" => "On treatment-Transfer out PPN",
            "7" => "On treatment-Transfer out pt choice",
            "9" => "On treatment-Transfer for bridging",
            "14" => "On treatment - Transfer compassionate use",
            "3" => "On hold",
            "23" => "Not enrolled due to high deductible - changed medication",
            "4" => "Discontinued",
            "15" => "Discontinued - Pt choice",
            "16" => "Discontinued - MD choice",
            "5" => "Transferred to other pharmacy",
            "17" => "Transfer to other pharmacy - Pt choice",
            "8" => "Transferred PPN"
        ];
        
        // Store the selected status ID for easier comparison
        $selectedTrtStatus = isset($repatientDetails['trtStatus']) ? $repatientDetails['trtStatus'] : '';
        $selectedTrtStatusText = isset($trtStatusOptions[$selectedTrtStatus]) ? $trtStatusOptions[$selectedTrtStatus] : '';

        $coverageTypeOptions = [
          "1" => "Public",
          "2" => "Private",
          "3" => "Public + Private",
          "4" => "Compassionate"
      ];
      
      $selectedCoverageType = isset($repatientDetails['coverageType']) ? $repatientDetails['coverageType'] : '';
      $selectedCoverageTypeText = isset($coverageTypeOptions[$selectedCoverageType]) ? $coverageTypeOptions[$selectedCoverageType] : '';
             $html.='<tr>
              <td>Injection Training Location</td>
              <td>'.$itl.'</td>
            </tr>
             <tr>
              <td>Clinic Injection Training Sites</td>
              <td>'.$selectedClinicSiteText.'</td>
            </tr>
             <tr>
              <td>First Appointment Date</td>
              <td>'.$repatientDetails['firstAppDate'].'</td>
            </tr>
             <tr>
              <td>Treatment Start Date</td>
              <td>'.$repatientDetails['trtStrtDate'].'</td>
            </tr>
             
             <tr>
              <td>Coverage Type</td>
              <td>'.$selectedCoverageTypeText.'</td>
            </tr>
             <tr>
              <td>Treatment Status</td>
              <td>'.$selectedTrtStatusText.'</td>
            </tr>
          </tbody>
        </table>
    </body>
</html>';
$dompdf = new DOMPDF();
$dompdf->load_html($html);
$dompdf->setPaper('A4', 'portrait');
$dompdf->render();
ob_end_clean();
$dompdf->stream("download.pdf",["Attachment" => 0]);
$dompdf->clear();
?>
