<?php
include "config.php";

require_once __DIR__ . "/dompdf/autoload.inc.php";

use Dompdf\Dompdf;
use Dompdf\Options;

$id = $_GET['id'];

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

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

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

/* HTML */
$html = "
<h2>{$doc['clinic_name']}</h2>
<b>Dr. {$doc['doctor_name']}</b><br>
{$doc['qualification']}<br>
<hr>

Patient: {$p['name']}<br>
Age: {$p['age']} | Gender: {$p['gender']}<br>
Date: {$p['created_at']}<br>

<hr>

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

<hr>

<table border='1' width='100%' cellpadding='5'>
<tr>
<th>Medicine</th>
<th>Dosage</th>
<th>Frequency</th>
<th>Duration</th>
</tr>
$med
</table>

<hr>

Advice:<br>
{$p['advice']}
<br>
<br>
<br>
<br>
<br>




<br> Doctor Signature<br>
";

/* Generate PDF */
$options = new Options();
$options->set('isRemoteEnabled', true);

$dompdf = new Dompdf($options);

$dompdf->loadHtml($html);

$dompdf->setPaper('A4', 'portrait');

$dompdf->render();

/* Show in browser ONLY (no save) */
$dompdf->stream("Prescription_$id.pdf", ["Attachment"=>false]);
