<?php  
session_start();
ini_set('display_errors', 1);
error_reporting(E_ALL);

require_once __DIR__ . '/../../dripend/includes/db.php';

$patient_id = isset($_GET['patient_id']) ? trim($_GET['patient_id']) : null;

$patient_data = null;
$visits = [];
$vitals_map = [];
$notes_map = [];
$diag_map = [];
$rx_map = [];
$lab_map = [];
$admit_map = [];

if ($patient_id) {
    // 1. Fetch Patient Demographics
    $stmtP = $conn->prepare("SELECT * FROM patient WHERE patient_no = ? LIMIT 1");
    $stmtP->bind_param("s", $patient_id);
    $stmtP->execute();
    $patient_data = $stmtP->get_result()->fetch_assoc();
    $stmtP->close();

    if ($patient_data) {
        // 2. Fetch All Visits (with the new next_review_date and clinical_outcome columns)
        $stmtV = $conn->prepare("SELECT * FROM visit_master WHERE patient_no = ? ORDER BY visit_date DESC, visit_time DESC");
        $stmtV->bind_param("s", $patient_id);
        $stmtV->execute();
        $resV = $stmtV->get_result();
        while ($row = $resV->fetch_assoc()) {
            $vid = $row['id'];
            $visits[$vid] = $row;
            
            $vitals_map[$vid] = [];
            $notes_map[$vid] = [];
            $diag_map[$vid] = [];
            $rx_map[$vid] = [];
            $lab_map[$vid] = [];
            $admit_map[$vid] = [];
        }
        $stmtV->close();

        // Helper function to fetch and map data safely
        function fetchMappedData($conn, $table, $patient_id, &$map_array) {
            try {
                $stmt = $conn->prepare("SELECT * FROM `$table` WHERE patient_no = ?");
                if ($stmt) {
                    $stmt->bind_param("s", $patient_id);
                    $stmt->execute();
                    $res = $stmt->get_result();
                    while ($row = $res->fetch_assoc()) {
                        if (isset($map_array[$row['visit_master_id']])) {
                            $map_array[$row['visit_master_id']][] = $row;
                        }
                    }
                    $stmt->close();
                }
            } catch (Exception $e) { /* Skip if table is empty or missing */ }
        }

        // Fetch all clinical data modules using the new schema
        fetchMappedData($conn, 'clinical_vitals', $patient_id, $vitals_map);
        fetchMappedData($conn, 'clinical_notes', $patient_id, $notes_map);
        fetchMappedData($conn, 'clinical_diagnoses', $patient_id, $diag_map);
        fetchMappedData($conn, 'clinical_prescriptions', $patient_id, $rx_map);
        fetchMappedData($conn, 'clinical_lab_requests', $patient_id, $lab_map);
        fetchMappedData($conn, 'clinical_admission_requests', $patient_id, $admit_map);
    }
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Patient Medical Folder | DripDental</title>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.5.0/css/all.min.css">

<style>
:root {
  --sidebar-width: 240px;
  --bg: #f8fafc;
  --dark: #0f172a;
  --muted: #64748b;
  --border: #e2e8f0;
  --primary: #0284c7;
  --success: #10b981;
  --danger: #ef4444;
  --warning: #f59e0b;
  --purple: #8b5cf6;
  --card-bg: #ffffff;
}

* { box-sizing: border-box; margin: 0; padding: 0; }
body { font-family: 'Segoe UI', system-ui, sans-serif; background: var(--bg); color: var(--dark); overflow-x: hidden; }

/* -------------------------------------
   LAYOUT & GRID
   ------------------------------------- */
.page-wrapper { position: absolute; top: 0; left: var(--sidebar-width); width: calc(100% - var(--sidebar-width)); padding: 30px; min-height: 100vh; }
.max-width-container { max-width: 1400px; margin: 0 auto; display: flex; flex-direction: column; gap: 20px; }

/* -------------------------------------
   HEADER & ACTION BAR
   ------------------------------------- */
.header-bar { display: flex; justify-content: space-between; align-items: center; background: var(--card-bg); padding: 20px 25px; border-radius: 12px; border: 1px solid var(--border); box-shadow: 0 4px 6px -1px rgba(0,0,0,0.05); }
.header-bar h1 { font-size: 22px; font-weight: 800; display: flex; align-items: center; gap: 12px; margin: 0; color: var(--dark); }
.header-bar h1 i { color: #fff; background: var(--primary); padding: 10px; border-radius: 10px; }

.export-actions { display: flex; gap: 10px; }
.btn-export { padding: 10px 18px; border-radius: 8px; font-weight: 700; font-size: 14px; border: none; cursor: pointer; display: inline-flex; align-items: center; gap: 8px; transition: 0.2s; color: #fff; }
.btn-export:hover { transform: translateY(-2px); box-shadow: 0 4px 12px rgba(0,0,0,0.15); }
.btn-pdf { background: #dc2626; }
.btn-word { background: #2563eb; }
.btn-print { background: var(--dark); }

/* -------------------------------------
   MEDICAL TIMELINE (FULL WIDTH)
   ------------------------------------- */
.timeline-container { position: relative; padding-left: 30px; border-left: 3px solid #cbd5e1; margin-left: 15px; margin-top: 10px; }
.visit-card { background: var(--card-bg); border: 1px solid var(--border); border-radius: 12px; padding: 25px; margin-bottom: 35px; position: relative; box-shadow: 0 10px 15px -3px rgba(0,0,0,0.05); transition: 0.3s; }
.visit-card:hover { border-color: #bae6fd; box-shadow: 0 10px 20px -3px rgba(2, 132, 199, 0.1); }
.visit-card::before { content: ''; position: absolute; left: -46px; top: 25px; width: 20px; height: 20px; border-radius: 50%; background: #fff; border: 5px solid var(--primary); box-shadow: 0 0 0 4px var(--bg); z-index: 2; }

.visit-header { display: flex; justify-content: space-between; align-items: center; margin-bottom: 25px; padding-bottom: 15px; border-bottom: 2px dashed var(--border); }
.visit-date { font-size: 20px; font-weight: 800; color: var(--dark); display: flex; align-items: center; gap: 10px; }
.visit-meta { font-size: 14px; color: var(--muted); font-weight: 700; background: #f8fafc; padding: 8px 15px; border-radius: 8px; border: 1px solid var(--border); }

/* Accordion Clinical Sections */
.clinical-section { margin-bottom: 15px; border: 1px solid var(--border); border-radius: 8px; overflow: hidden; }
.section-title { background: #f8fafc; padding: 15px 20px; font-size: 15px; font-weight: 800; color: var(--dark); display: flex; justify-content: space-between; cursor: pointer; user-select: none; transition: 0.2s; border-left: 4px solid transparent; }
.section-title:hover { background: #f1f5f9; color: var(--primary); border-left-color: var(--primary); }
.section-title i.icon-left { width: 25px; color: var(--muted); }
.section-content { padding: 20px; background: #fff; display: none; border-top: 1px solid var(--border); }
.section-content.active { display: block; }

/* Internal Data Tables */
.data-table { width: 100%; border-collapse: collapse; font-size: 14px; }
.data-table th, .data-table td { padding: 12px 15px; border-bottom: 1px solid #f1f5f9; text-align: left; vertical-align: top; }
.data-table th { color: var(--muted); font-weight: 800; text-transform: uppercase; font-size: 12px; background:#f8fafc;}

/* Vitals Grid */
.vitals-grid { display: grid; grid-template-columns: repeat(auto-fit, minmax(140px, 1fr)); gap: 15px; }
.vital-box { background: #f8fafc; border: 1px solid var(--border); padding: 15px; border-radius: 8px; text-align: center; }
.vital-box span { display: block; font-size: 11px; font-weight: 800; color: var(--muted); text-transform: uppercase; margin-bottom: 6px; }
.vital-box strong { font-size: 22px; color: var(--primary); font-weight: 800;}

/* Status Badges */
.badge { padding: 4px 10px; border-radius: 6px; font-size: 12px; font-weight: 800; text-transform: uppercase; border: 1px solid transparent;}
.badge-green { background: #ecfdf5; color: #065f46; border-color: #a7f3d0;}
.badge-blue { background: #e0f2fe; color: #0369a1; border-color: #bae6fd;}
.badge-orange { background: #fffbeb; color: #b45309; border-color: #fde68a;}
.badge-purple { background: #faf5ff; color: #6d28d9; border-color: #e9d5ff;}

/* Search Gate */
.search-modal { position: fixed; inset: 0; background: rgba(15, 23, 42, 0.85); display: flex; justify-content: center; align-items: center; z-index: 9999; backdrop-filter: blur(5px); }
.search-box { background: #fff; width: 550px; padding: 40px; border-radius: 16px; text-align: center; box-shadow: 0 25px 50px rgba(0,0,0,0.25); }

/* =========================================
   EXPORT / PRINT ENGINE
   ========================================= */
#printWrapper { display: none; }
@media print {
    body * { visibility: hidden; }
    #printWrapper, #printWrapper * { visibility: visible; }
    #printWrapper { display: block; position: absolute; left: 0; top: 0; width: 100%; background:#fff; padding: 0; margin: 0; }
    .page-wrapper { display: none; }
    
    .print-container { padding: 20px; font-family: 'Times New Roman', serif; }
    .print-header-info { margin: 20px 0; border: 2px solid #000; padding: 15px; display: flex; justify-content: space-between; font-size: 14px; font-weight: bold; }
    .print-visit { margin-bottom: 30px; border-bottom: 2px solid #000; padding-bottom: 20px; page-break-inside: avoid; }
    .print-visit h3 { background: #f1f1f1; padding: 8px; border: 1px solid #000; font-size: 16px; margin-bottom: 10px; -webkit-print-color-adjust: exact; }
    .print-table { width: 100%; border-collapse: collapse; margin-bottom: 15px; font-size: 12px; }
    .print-table th, .print-table td { border: 1px solid #000; padding: 6px 8px; }
    .print-table th { background: #f9f9f9; -webkit-print-color-adjust: exact; }
    .print-section-title { font-weight: bold; text-decoration: underline; margin: 10px 0 5px 0; font-size: 14px; text-transform: uppercase;}
    .print-notes-box { font-size: 12px; margin-bottom: 10px; line-height: 1.4;}
}
</style>
</head>
<body>

<?php
include_once __DIR__ . '/../../dripend/statpages/sidebar.php';
?>

<?php if (!$patient_id || !$patient_data): ?>
<div class="search-modal">
    <div class="search-box">
        <i class="fa-solid fa-folder-open" style="font-size:60px; color:var(--primary); margin-bottom:20px;"></i>
        <h2 style="margin-bottom:10px; color:var(--dark);">Patient Medical Folder</h2>
        <p style="color:var(--muted); margin-bottom:25px;">Enter a Patient ID to pull their complete medical history, records, and clinical files.</p>
        <form method="GET" action="">
            <input type="text" name="patient_id" placeholder="e.g. DDC-K2026-06-0001" required autofocus style="width:100%; padding:15px; font-size:16px; border:2px solid var(--border); border-radius:8px; margin-bottom:20px; outline:none;">
            <button type="submit" class="btn-export btn-print" style="width:100%; justify-content:center; font-size:16px; padding:15px;"><i class="fa-solid fa-search"></i> Open Folder</button>
        </form>
    </div>
</div>
<?php else: ?>

<div class="page-wrapper" id="mainUI">
  <div class="max-width-container">
    
    <div class="header-bar">
        <h1><i class="fa-solid fa-book-medical"></i> Complete Medical Folder</h1>
        <div class="export-actions">
            <button class="btn-export btn-word" onclick="exportToWord('<?php echo htmlspecialchars($patient_data['patient_no']); ?>')"><i class="fa-solid fa-file-word"></i> Export Word</button>
            <button class="btn-export btn-pdf" onclick="window.print()"><i class="fa-solid fa-file-pdf"></i> Save PDF</button>
            <button class="btn-export btn-print" onclick="window.print()"><i class="fa-solid fa-print"></i> Print Folder</button>
        </div>
    </div>

    <?php include_once DRIPEND_PATH . 'statpages/patientProfileHeader.php'; ?>

    <div>
        <?php if (empty($visits)): ?>
            <div style="background:#fff; border:2px dashed var(--border); border-radius:12px; padding:60px; text-align:center; box-shadow: 0 4px 6px rgba(0,0,0,0.02);">
                <i class="fa-solid fa-folder-open" style="font-size:70px; color:var(--muted); opacity:0.3; margin-bottom:20px;"></i>
                <h3 style="color:var(--dark); font-size:22px;">No Clinical Encounters Found</h3>
                <p style="color:var(--muted); font-size:16px; margin-top:10px;">This patient has registered but has not had any documented visits yet.</p>
            </div>
        <?php else: ?>
            <div class="timeline-container">
                <?php foreach ($visits as $vid => $visit): ?>
                    <div class="visit-card">
                        <div class="visit-header">
                            <div class="visit-date"><i class="fa-regular fa-calendar-check" style="color:var(--primary);"></i> <?php echo date('l, d F Y', strtotime($visit['visit_date'])); ?></div>
                            <div class="visit-meta">
                                Encounter: <span style="color:var(--primary);"><?php echo htmlspecialchars($visit['appointment_no']); ?></span> &nbsp;|&nbsp; 
                                Time: <?php echo date('h:i A', strtotime($visit['visit_time'])); ?>
                            </div>
                        </div>

                        <?php if (!empty($vitals_map[$vid])): ?>
                        <div class="clinical-section">
                            <div class="section-title" onclick="toggleSection(this)"><span ><i class="fa-solid fa-heart-pulse icon-left"></i> Triage & Vitals</span> <i class="fa-solid fa-chevron-down"></i></div>
                            <div class="section-content">
                                <?php foreach($vitals_map[$vid] as $vit): ?>
                                <div class="vitals-grid">
                                    <div class="vital-box"><span>BP (mmHg)</span><strong><?php echo htmlspecialchars($vit['bp_systolic'] ?? '--'); ?>/<?php echo htmlspecialchars($vit['bp_diastolic'] ?? '--'); ?></strong></div>
                                    <div class="vital-box"><span>Temp (°C)</span><strong><?php echo htmlspecialchars($vit['temperature'] ?? '--'); ?></strong></div>
                                    <div class="vital-box"><span>Weight (kg)</span><strong><?php echo htmlspecialchars($vit['weight'] ?? '--'); ?></strong></div>
                                    <div class="vital-box"><span>Pulse (bpm)</span><strong><?php echo htmlspecialchars($vit['pulse'] ?? '--'); ?></strong></div>
                                    <div class="vital-box"><span>SpO2 (%)</span><strong><?php echo htmlspecialchars($vit['spo2'] ?? '--'); ?></strong></div>
                                    <div class="vital-box"><span>BMI</span><strong><?php echo htmlspecialchars($vit['bmi'] ?? '--'); ?></strong></div>
                                </div>
                                <?php endforeach; ?>
                            </div>
                        </div>
                        <?php endif; ?>

                        <?php if (!empty($notes_map[$vid])): ?>
                        <div class="clinical-section">
                            <div class="section-title" onclick="toggleSection(this)"><span><i class="fa-solid fa-user-doctor icon-left"></i> Clinical Notes (SOAP)</span> <i class="fa-solid fa-chevron-down"></i></div>
                            <div class="section-content">
                                <?php foreach($notes_map[$vid] as $note): ?>
                                    <div style="margin-bottom:15px;">
                                        <strong style="color:var(--muted); font-size:12px; text-transform:uppercase;">Chief Complaint:</strong>
                                        <div style="font-size:15px; background:#f8fafc; padding:12px; border-radius:8px; border:1px solid var(--border); color:var(--dark);">
                                            <?php echo nl2br(htmlspecialchars($note['chief_complaint'] ?? 'N/A')); ?>
                                        </div>
                                    </div>
                                    <div style="margin-bottom:15px;">
                                        <strong style="color:var(--muted); font-size:12px; text-transform:uppercase;">Clinical History:</strong>
                                        <div style="font-size:15px; background:#f8fafc; padding:12px; border-radius:8px; border:1px solid var(--border); color:var(--dark);">
                                            <?php echo nl2br(htmlspecialchars($note['clinical_history'] ?? 'N/A')); ?>
                                        </div>
                                    </div>
                                    <div style="margin-bottom:15px;">
                                        <strong style="color:var(--muted); font-size:12px; text-transform:uppercase;">Examination & Treatment Plan:</strong>
                                        <div style="font-size:15px; background:#f8fafc; padding:12px; border-radius:8px; border:1px solid var(--border); color:var(--dark);">
                                            <?php echo nl2br(htmlspecialchars($note['examination_notes'] ?? '')); ?>
                                            <hr style="border:none; border-top:1px dashed var(--border); margin:10px 0;">
                                            <?php echo nl2br(htmlspecialchars($note['treatment_plan_notes'] ?? '')); ?>
                                        </div>
                                    </div>
                                <?php endforeach; ?>
                            </div>
                        </div>
                        <?php endif; ?>

                        <?php if (!empty($diag_map[$vid])): ?>
                        <div class="clinical-section">
                            <div class="section-title" onclick="toggleSection(this)"><span><i class="fa-solid fa-virus icon-left"></i> Diagnoses (ICD/GDRG)</span> <i class="fa-solid fa-chevron-down"></i></div>
                            <div class="section-content">
                                <table class="data-table">
                                    <thead><tr><th>Code Type</th><th>Diagnosis Code</th><th>Description</th><th>Type</th></tr></thead>
                                    <tbody>
                                        <?php foreach($diag_map[$vid] as $diag): ?>
                                        <tr style="<?php echo $diag['is_principal'] ? 'background:#fffbeb;' : ''; ?>">
                                            <td><span class="badge badge-purple"><?php echo htmlspecialchars($diag['code_type']); ?></span></td>
                                            <td><strong style="color:var(--danger);"><?php echo htmlspecialchars($diag['code']); ?></strong> <?php echo $diag['is_principal'] ? '<span class="badge badge-orange">Principal</span>' : ''; ?></td>
                                            <td style="font-weight:600;"><?php echo htmlspecialchars($diag['description']); ?></td>
                                            <td><?php echo htmlspecialchars($diag['diagnosis_type']); ?></td>
                                        </tr>
                                        <?php endforeach; ?>
                                    </tbody>
                                </table>
                            </div>
                        </div>
                        <?php endif; ?>

                        <?php if (!empty($lab_map[$vid])): ?>
                        <div class="clinical-section">
                            <div class="section-title" onclick="toggleSection(this)"><span><i class="fa-solid fa-microscope icon-left"></i> Laboratory & Radiology Requests</span> <i class="fa-solid fa-chevron-down"></i></div>
                            <div class="section-content">
                                <table class="data-table">
                                    <thead><tr><th>Test Requested</th><th>Result Value</th><th>Result Notes</th><th>Status</th></tr></thead>
                                    <tbody>
                                        <?php foreach($lab_map[$vid] as $lab): ?>
                                        <tr>
                                            <td><strong style="color:var(--primary);"><?php echo htmlspecialchars($lab['test_name']); ?></strong></td>
                                            <td style="font-weight:700; color:var(--dark);"><?php echo htmlspecialchars($lab['result_value'] ?? '-'); ?></td>
                                            <td><?php echo nl2br(htmlspecialchars($lab['result_notes'] ?? 'Pending analysis')); ?></td>
                                            <td><span class="badge badge-blue"><?php echo htmlspecialchars($lab['status']); ?></span></td>
                                        </tr>
                                        <?php endforeach; ?>
                                    </tbody>
                                </table>
                            </div>
                        </div>
                        <?php endif; ?>

                        <?php if (!empty($rx_map[$vid])): ?>
                        <div class="clinical-section">
                            <div class="section-title" onclick="toggleSection(this)"><span><i class="fa-solid fa-prescription-bottle-medical icon-left"></i> Prescriptions</span> <i class="fa-solid fa-chevron-down"></i></div>
                            <div class="section-content">
                                <table class="data-table">
                                    <thead><tr><th>Drug Name & Form</th><th>Dosage Instructions</th><th>Days</th><th>Qty</th><th>Status</th></tr></thead>
                                    <tbody>
                                        <?php foreach($rx_map[$vid] as $rx): ?>
                                        <tr>
                                            <td><strong style="font-size:15px; color:var(--dark);"><?php echo htmlspecialchars($rx['drug_name']); ?></strong><br><span style="color:var(--muted); font-size:13px;"><?php echo htmlspecialchars($rx['formulation'] ?? ''); ?></span></td>
                                            <td style="font-weight:600;"><?php echo htmlspecialchars($rx['dose'] . ' - ' . $rx['frequency']); ?></td>
                                            <td><?php echo htmlspecialchars($rx['duration_days']); ?></td>
                                            <td><strong style="font-size:16px;"><?php echo htmlspecialchars($rx['quantity']); ?></strong></td>
                                            <td>
                                                <?php 
                                                    $badge = 'badge-orange';
                                                    if($rx['status'] == 'Dispensed') $badge = 'badge-green';
                                                ?>
                                                <span class="badge <?php echo $badge; ?>"><?php echo htmlspecialchars($rx['status']); ?></span>
                                            </td>
                                        </tr>
                                        <?php endforeach; ?>
                                    </tbody>
                                </table>
                            </div>
                        </div>
                        <?php endif; ?>
                        
                        <?php if (!empty($admit_map[$vid])): ?>
                        <div class="clinical-section">
                            <div class="section-title" onclick="toggleSection(this)"><span><i class="fa-solid fa-bed-pulse icon-left"></i> Ward Admission Request</span> <i class="fa-solid fa-chevron-down"></i></div>
                            <div class="section-content">
                                <?php foreach($admit_map[$vid] as $admit): ?>
                                    <div style="display:flex; gap:20px; flex-wrap:wrap;">
                                        <div style="flex:1; background:#fef2f2; padding:15px; border-radius:8px; border:1px solid #fecaca;">
                                            <strong style="color:var(--danger); font-size:12px; text-transform:uppercase;">Admission Diagnosis:</strong>
                                            <div style="font-size:16px; color:#991b1b; font-weight:800; margin-top:5px;"><?php echo htmlspecialchars($admit['admission_diagnosis']); ?></div>
                                        </div>
                                        <div style="flex:1; background:#f0fdf4; padding:15px; border-radius:8px; border:1px solid #bbf7d0;">
                                            <strong style="color:var(--success); font-size:12px; text-transform:uppercase;">Requested Ward:</strong>
                                            <div style="font-size:16px; color:#065f46; font-weight:800; margin-top:5px;"><i class="fa-solid fa-hospital"></i> <?php echo htmlspecialchars($admit['requested_ward']); ?></div>
                                        </div>
                                    </div>
                                    <div style="margin-top:15px;">
                                        <strong style="color:var(--muted); font-size:12px; text-transform:uppercase;">Treatment Plan / Notes:</strong>
                                        <div style="font-size:14px; background:#f8fafc; padding:12px; border-radius:8px; border:1px solid var(--border); color:var(--dark); margin-top:5px;">
                                            <?php echo nl2br(htmlspecialchars($admit['treatment_plan'] ?? 'N/A')); ?>
                                        </div>
                                    </div>
                                <?php endforeach; ?>
                            </div>
                        </div>
                        <?php endif; ?>

                        <div style="margin-top:20px; padding-top:15px; border-top:1px dashed var(--border); display:flex; justify-content:space-between; align-items:center;">
                            <?php if(!empty($visit['next_review_date'])): ?>
                                <span style="font-size:14px; color:var(--dark);"><i class="fa-regular fa-calendar-check" style="color:var(--primary);"></i> Next Review Date: <strong><?php echo date('d M Y', strtotime($visit['next_review_date'])); ?></strong></span>
                            <?php else: ?>
                                <span></span>
                            <?php endif; ?>
                            <span style="font-size:14px; color:var(--muted);">Visit Outcome: <span class="badge badge-purple"><?php echo htmlspecialchars($visit['clinical_outcome'] ?? 'Pending'); ?></span></span>
                        </div>

                    </div>
                <?php endforeach; ?>
            </div>
        <?php endif; ?>
    </div>

  </div>
</div>

<div id="printWrapper">
    <div class="print-container" id="exportContent">
   <?php include_once DRIPEND_PATH . 'statpages/letterHead.php'; ?>
        
        <h2 style="text-align:center; text-transform:uppercase; text-decoration:underline; margin: 20px 0;">Complete Medical Folder</h2>
        
        <div class="print-header-info">
            <div>Patient: <?php echo htmlspecialchars($patient_data['first_name'] . ' ' . $patient_data['last_name']); ?></div>
            <div>ID: <?php echo htmlspecialchars($patient_data['patient_no']); ?></div>
            <div>DOB: <?php echo date('d M, Y', strtotime($patient_data['dob'])); ?></div>
            <div>Printed: <?php echo date('d-M-Y H:i:s'); ?></div>
        </div>

        <?php foreach ($visits as $vid => $visit): ?>
            <div class="print-visit">
                <h3>Encounter Date: <?php echo date('l, d F Y - h:i A', strtotime($visit['visit_date'] . ' ' . $visit['visit_time'])); ?> | No: <?php echo htmlspecialchars($visit['appointment_no']); ?></h3>
                
                <?php if (!empty($vitals_map[$vid])): ?>
                    <div class="print-section-title">Vitals</div>
                    <table class="print-table">
                        <tr>
                            <?php foreach($vitals_map[$vid] as $vit): ?>
                                <th>BP</th><td><?php echo htmlspecialchars($vit['bp_systolic'] ?? '-'); ?>/<?php echo htmlspecialchars($vit['bp_diastolic'] ?? '-'); ?></td>
                                <th>Temp</th><td><?php echo htmlspecialchars($vit['temperature'] ?? '-'); ?></td>
                                <th>Weight</th><td><?php echo htmlspecialchars($vit['weight'] ?? '-'); ?></td>
                                <th>Pulse</th><td><?php echo htmlspecialchars($vit['pulse'] ?? '-'); ?></td>
                            <?php endforeach; ?>
                        </tr>
                    </table>
                <?php endif; ?>

                <?php if (!empty($notes_map[$vid])): ?>
                    <div class="print-section-title">Clinical Notes (SOAP)</div>
                    <?php foreach($notes_map[$vid] as $note): ?>
                        <div class="print-notes-box">
                            <strong>Chief Complaint:</strong> <?php echo htmlspecialchars($note['chief_complaint'] ?? 'N/A'); ?><br>
                            <strong>History:</strong> <?php echo htmlspecialchars($note['clinical_history'] ?? 'N/A'); ?><br>
                            <strong>Plan:</strong> <?php echo htmlspecialchars($note['treatment_plan_notes'] ?? 'N/A'); ?>
                        </div>
                    <?php endforeach; ?>
                <?php endif; ?>

                <?php if (!empty($diag_map[$vid])): ?>
                    <div class="print-section-title">Diagnoses</div>
                    <table class="print-table">
                        <tr><th>Type</th><th>Code</th><th>Description</th></tr>
                        <?php foreach($diag_map[$vid] as $diag): ?>
                        <tr>
                            <td><?php echo htmlspecialchars($diag['code_type']); ?></td>
                            <td><?php echo htmlspecialchars($diag['code']); ?></td>
                            <td><?php echo htmlspecialchars($diag['description']); ?></td>
                        </tr>
                        <?php endforeach; ?>
                    </table>
                <?php endif; ?>

                <?php if (!empty($lab_map[$vid])): ?>
                    <div class="print-section-title">Investigations</div>
                    <table class="print-table">
                        <tr><th>Test</th><th>Result</th><th>Status</th></tr>
                        <?php foreach($lab_map[$vid] as $lab): ?>
                        <tr>
                            <td><?php echo htmlspecialchars($lab['test_name']); ?></td>
                            <td><?php echo htmlspecialchars($lab['result_value'] ?? '-'); ?></td>
                            <td><?php echo htmlspecialchars($lab['status']); ?></td>
                        </tr>
                        <?php endforeach; ?>
                    </table>
                <?php endif; ?>

                <?php if (!empty($rx_map[$vid])): ?>
                    <div class="print-section-title">Prescriptions</div>
                    <table class="print-table">
                        <tr><th>Drug Name</th><th>Dosage</th><th>Days</th><th>Qty</th><th>Status</th></tr>
                        <?php foreach($rx_map[$vid] as $rx): ?>
                        <tr>
                            <td><?php echo htmlspecialchars($rx['drug_name']); ?></td>
                            <td><?php echo htmlspecialchars($rx['dose'] . ' ' . $rx['frequency']); ?></td>
                            <td><?php echo htmlspecialchars($rx['duration_days']); ?></td>
                            <td><?php echo htmlspecialchars($rx['quantity']); ?></td>
                            <td><?php echo htmlspecialchars($rx['status']); ?></td>
                        </tr>
                        <?php endforeach; ?>
                    </table>
                <?php endif; ?>
            </div>
        <?php endforeach; ?>
        
        <div style="margin-top: 50px; text-align:right; font-size:12px; font-weight:bold;">
            ________________________________________<br>
            Authorized Medical Records Officer
        </div>
    </div>
</div>

<script>
// UI Accordion Toggle
function toggleSection(element) {
    const content = element.nextElementSibling;
    const icon = element.querySelector('.fa-chevron-down');
    
    if(content.style.display === "block") {
        content.style.display = "none";
        if(icon) icon.style.transform = "rotate(0deg)";
    } else {
        content.style.display = "block";
        if(icon) icon.style.transform = "rotate(180deg)";
    }
}

// Export to Word Logic (Using HTML Blob generation)
function exportToWord(patientNo) {
    const header = "<html xmlns:o='urn:schemas-microsoft-com:office:office' xmlns:w='urn:schemas-microsoft-com:office:word' xmlns='http://www.w3.org/TR/REC-html40'><head><meta charset='utf-8'><title>Export HTML To Doc</title></head><body>";
    const footer = "</body></html>";
    // Clone the print container safely
    const htmlContent = document.getElementById("exportContent").innerHTML;
    const sourceHTML = header + htmlContent + footer;
    
    const source = 'data:application/vnd.ms-word;charset=utf-8,' + encodeURIComponent(sourceHTML);
    const fileDownload = document.createElement("a");
    document.body.appendChild(fileDownload);
    fileDownload.href = source;
    fileDownload.download = 'Medical_Folder_' + patientNo + '.doc';
    fileDownload.click();
    document.body.removeChild(fileDownload);
}

// Auto-open the first visit's accordions for UX (so the user doesn't face a wall of closed tabs)
window.onload = function() {
    const firstVisit = document.querySelector('.visit-card');
    if(firstVisit) {
        const sections = firstVisit.querySelectorAll('.section-content');
        const icons = firstVisit.querySelectorAll('.fa-chevron-down');
        sections.forEach(sec => sec.style.display = 'block');
        icons.forEach(icon => icon.style.transform = 'rotate(180deg)');
    }
};
</script>

<?php endif; ?>
</body>
</html>