<?php
// File: /dripend/includes/consultation/exportConsultationPDF.php
session_start();
require_once '../db.php';

if (!isset($_GET['visit_id'])) die("Invalid Visit ID");
$visit_id = (int)$_GET['visit_id'];

// 1. Fetch Master Data (Corrected 'patient' table and joined 'gender' table to get actual text)
$stmtV = $conn->prepare("
    SELECT v.*, p.first_name AS pf, p.last_name AS pl, p.dob, COALESCE(g.gender_name, 'Unknown') AS gender, s.first_name AS sf, s.last_name AS sl 
    FROM visit_master v 
    LEFT JOIN patient p ON v.patient_no = p.patient_no 
    LEFT JOIN gender g ON p.gender_id = g.id
    LEFT JOIN staff s ON v.primary_doctor_id = s.staff_id 
    WHERE v.id = ?
");
$stmtV->bind_param("i", $visit_id); $stmtV->execute(); $v = $stmtV->get_result()->fetch_assoc(); $stmtV->close();

$stmtN = $conn->prepare("SELECT * FROM clinical_notes WHERE visit_id = ?");
$stmtN->bind_param("i", $visit_id); $stmtN->execute(); $note = $stmtN->get_result()->fetch_assoc(); $stmtN->close();

$stmtD = $conn->prepare("SELECT * FROM clinical_diagnoses WHERE visit_id = ? ORDER BY is_principal DESC");
$stmtD->bind_param("i", $visit_id); $stmtD->execute(); $diags = $stmtD->get_result()->fetch_all(MYSQLI_ASSOC); $stmtD->close();

$stmtRx = $conn->prepare("SELECT * FROM clinical_prescriptions WHERE visit_id = ?");
$stmtRx->bind_param("i", $visit_id); $stmtRx->execute(); $rxs = $stmtRx->get_result()->fetch_all(MYSQLI_ASSOC); $stmtRx->close();

$stmtLab = $conn->prepare("SELECT * FROM clinical_lab_requests WHERE visit_id = ?");
$stmtLab->bind_param("i", $visit_id); $stmtLab->execute(); $labs = $stmtLab->get_result()->fetch_all(MYSQLI_ASSOC); $stmtLab->close();
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Consultation Record - <?php echo htmlspecialchars($v['patient_no']); ?></title>
<style>
    body { font-family: 'Helvetica Neue', Helvetica, Arial, sans-serif; color: #000; background: #fff; font-size: 12px; line-height: 1.5; padding: 40px; max-width: 800px; margin: auto; }
    .header { text-align: center; border-bottom: 2px solid #000; padding-bottom: 10px; margin-bottom: 20px; }
    .header h1 { margin: 0; font-size: 24px; color: #1e3a8a; }
    .patient-box { border: 1px solid #000; padding: 15px; margin-bottom: 20px; display: flex; justify-content: space-between; background: #f8fafc; }
    .section { margin-bottom: 20px; }
    .section h3 { border-bottom: 1px solid #cbd5e1; padding-bottom: 5px; color: #1e3a8a; margin-bottom: 10px; font-size: 14px; text-transform: uppercase; }
    .audit-trail { font-size: 10px; color: #555; text-align: center; margin-top: 40px; border-top: 1px dashed #ccc; padding-top: 10px; }
    
    table.data-table { width: 100%; border-collapse: collapse; margin-top: 5px; margin-bottom: 15px; }
    table.data-table th { background: #f1f5f9; padding: 8px; text-align: left; border-bottom: 1px solid #cbd5e1; }
    table.data-table td { padding: 8px; border-bottom: 1px solid #e2e8f0; }

    @media print {
        body { padding: 0; }
        @page { margin: 1cm; }
        .no-print { display: none; }
        .patient-box { background: transparent !important; }
    }
</style>
</head>
<body onload="window.print()">

    <div class="no-print" style="text-align:right; margin-bottom:20px;">
        <button onclick="window.print()" style="padding:10px 20px; background:#1e3a8a; color:#fff; border:none; cursor:pointer; font-weight:bold; border-radius:4px;">Save as PDF / Print</button>
    </div>

    <div class="header">
        <h1>DRIP DENTAL & MEDICAL CENTER</h1>
        <p style="margin:5px 0 0 0; font-weight:bold; text-transform:uppercase;">Official Clinical Encounter Record</p>
    </div>

    <div class="patient-box">
        <div>
            <strong>Patient Name:</strong> <?php echo htmlspecialchars($v['pf'].' '.$v['pl']); ?><br>
            <strong>Patient ID:</strong> <?php echo htmlspecialchars($v['patient_no']); ?><br>
            <strong>Gender / DOB:</strong> <?php echo htmlspecialchars($v['gender'].' / '.$v['dob']); ?>
        </div>
        <div style="text-align: right;">
            <strong>Visit Date:</strong> <?php echo date('d M Y', strtotime($v['visit_date'])); ?><br>
            <strong>Encounter ID:</strong> #<?php echo str_pad($v['id'], 6, '0', STR_PAD_LEFT); ?><br>
            <strong>Attending Doctor:</strong> Dr. <?php echo htmlspecialchars($v['sf'].' '.$v['sl']); ?>
        </div>
    </div>

    <div class="section">
        <h3>History & Examination</h3>
        <p><strong>Chief Complaint:</strong><br><?php echo nl2br(htmlspecialchars($note['chief_complaint'] ?? '--')); ?></p>
        <p><strong>Clinical History (HPI):</strong><br><?php echo nl2br(htmlspecialchars($note['clinical_history'] ?? '--')); ?></p>
        <p><strong>Examination Findings:</strong><br><?php echo nl2br(htmlspecialchars($note['examination_notes'] ?? '--')); ?></p>
    </div>

    <div class="section">
        <h3>Diagnoses</h3>
        <?php if(!empty($diags)): ?>
            <ul style="margin:0; padding-left:20px;">
            <?php foreach($diags as $d): ?>
                <li style="margin-bottom:6px;">
                    <?php if($d['is_principal'] == 1): ?>
                        <strong style="color:#dc2626; border:1px solid #dc2626; padding:1px 4px; font-size:10px;">PRINCIPAL</strong>
                    <?php endif; ?>
                    <strong>[<?php echo htmlspecialchars($d['code']); ?>] - <?php echo htmlspecialchars($d['description']); ?></strong> 
                    <em>(<?php echo htmlspecialchars($d['diagnosis_type']); ?>)</em>
                </li>
            <?php endforeach; ?>
            </ul>
        <?php else: echo "<p>No formal diagnosis recorded.</p>"; endif; ?>
    </div>

    <div class="section">
        <h3>Treatment Plan & Orders</h3>
        <p><?php echo nl2br(htmlspecialchars($note['treatment_plan_notes'] ?? '--')); ?></p>
        
        <?php if(!empty($rxs)): ?>
            <strong>Prescriptions:</strong>
            <table class="data-table">
                <tr><th>Drug Name</th><th>Dose/Freq</th><th>Duration</th><th>Status</th></tr>
                <?php foreach($rxs as $rx): ?>
                <tr>
                    <td><strong><?php echo htmlspecialchars($rx['drug_name']); ?></strong></td>
                    <td><?php echo htmlspecialchars($rx['dose'].' - '.$rx['frequency']); ?></td>
                    <td><?php echo htmlspecialchars($rx['duration_days']); ?> Days</td>
                    <td><?php echo htmlspecialchars($rx['status']); ?></td>
                </tr>
                <?php endforeach; ?>
            </table>
        <?php endif; ?>

        <?php if(!empty($labs)): ?>
            <strong>Investigations & Procedures Ordered:</strong>
            <table class="data-table">
                <tr><th>Test Requested</th><th>Status</th></tr>
                <?php foreach($labs as $lab): ?>
                <tr>
                    <td><strong><?php echo htmlspecialchars($lab['test_name']); ?></strong></td>
                    <td><?php echo htmlspecialchars($lab['status']); ?></td>
                </tr>
                <?php endforeach; ?>
            </table>
        <?php endif; ?>
    </div>

    <div class="section">
        <h3>Outcome & Tracking</h3>
        <p style="margin-bottom:5px;"><strong>Clinical Outcome:</strong> <?php echo htmlspecialchars($v['clinical_outcome'] ?? 'Pending'); ?></p>
        <p style="margin-top:0;"><strong>Scheduled Next Review:</strong> <?php echo !empty($v['next_review_date']) ? date('l, d F Y', strtotime($v['next_review_date'])) : 'None Scheduled'; ?></p>
    </div>

    <div class="audit-trail">
        <p>Record Created: <?php echo date('d M Y, H:i:s', strtotime($note['created_at'])); ?> | Last Updated: <?php echo !empty($note['updated_at']) ? date('d M Y, H:i:s', strtotime($note['updated_at'])) : 'No updates recorded'; ?></p>
        <p><em>Generated securely via Afritechs EMR System</em></p>
    </div>

</body>
</html>