<?php
require 'dompdf/autoload.inc.php';
use Dompdf\Dompdf;

include "config.php";

$id = $_GET['id'];

$p = mysqli_fetch_assoc(mysqli_query($conn,"
SELECT prescriptions.*,patients.name,patients.age,patients.gender,patients.mobile
FROM prescriptions
JOIN patients ON prescriptions.patient_id=patients.id
WHERE prescriptions.id='$id'
"));

$doc = mysqli_fetch_assoc(mysqli_query($conn,"SELECT * FROM doctor_profile LIMIT 1"));

$html = "
<h2 style='text-align:center'>{$doc['clinic_name']}</h2>
<p style='text-align:center'>
<b>Dr. {$doc['doctor_name']}</b><br>
{$doc['qualification']}<br>
Reg No: {$doc['reg_no']}
</p>
<hr>

<b>Patient:</b> {$p['name']}<br>
<b>Age:</b> {$p['age']} | <b>Gender:</b> {$p['gender']}<br>
<b>Date:</b> ".date("d-m-Y",strtotime($p['created_at']))."
<hr>

<b>Diagnosis:</b><br>
{$p['diagnosis']}
<br><br>

<table width='100%' border='1' cellspacing='0' cellpadding='5'>
<tr>
<th>Medicine</th><th>Dosage</th><th>Frequency</th><th>Duration</th>
</tr>
";

$r = mysqli_query($conn,"SELECT * FROM prescription_items WHERE prescription_id='$id'");
while($row=mysqli_fetch_assoc($r)){
$html .= "
<tr>
<td>{$row['medicine_name']}</td>
<td>{$row['dosage']}</td>
<td>{$row['frequency']}</td>
<td>{$row['duration']}</td>
</tr>
";
}

$html .= "
</table>
<br><br>
<b>Advice:</b><br>{$p['advice']}
<br><br>
<img src='uploads/{$doc['signature']}' width='100'>
<br>Doctor Signature
";

$dompdf = new Dompdf();
$dompdf->loadHtml($html);
$dompdf->setPaper('A4','portrait');
$dompdf->render();

/* SAVE PDF */
$pdf_name = "prescription_$id.pdf";
$file_path = "uploads/prescriptions/".$pdf_name;

file_put_contents($file_path,$dompdf->output());

/* DOWNLOAD */
$dompdf->stream($pdf_name, ["Attachment"=>true]);