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

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

$visit_id = isset($_GET['visit_id']) ? (int)$_GET['visit_id'] : 0;
if ($visit_id === 0) die("<div style='padding:40px; text-align:center;'><h2>Invalid Context.</h2></div>");

$stmt = $conn->prepare("
    SELECT e.*, p.first_name, p.last_name, w.ward_name, w.managing_department_id, b.bed_number, rm.room_number_or_name, d.department_name
    FROM ipd_admission_episodes e
    JOIN patient p ON e.patient_no = p.patient_no
    JOIN ipd_wards w ON e.ward_id = w.id
    JOIN ipd_beds b ON e.bed_id = b.id
    LEFT JOIN ipd_rooms rm ON e.room_id = rm.id
    LEFT JOIN departments d ON w.managing_department_id = d.id
    WHERE e.visit_master_id = ? LIMIT 1
");
$stmt->bind_param("i", $visit_id);
$stmt->execute();
$episode = $stmt->get_result()->fetch_assoc();
$stmt->close();

$patient_no = $episode['patient_no'];
$location_str = $episode['ward_name'] . ($episode['room_number_or_name'] ? ' ('.$episode['room_number_or_name'].')' : '') . ' - Bed ' . $episode['bed_number'];
$dept_safe = $conn->real_escape_string($episode['department_name'] ?? '');

$categories = [];
$resCat = $conn->query("SELECT id, category_name FROM ipd_form_categories WHERE is_active = 1 ORDER BY id ASC");
while($cat = $resCat->fetch_assoc()) {
    $cat_id = $cat['id'];
    $resForms = $conn->query("SELECT id, form_name FROM ipd_forms WHERE category_id = $cat_id AND (target_module = 'Global Application' OR target_module = '$dept_safe') AND is_active = 1 ORDER BY id ASC");
    $forms = [];
    while($f = $resForms->fetch_assoc()) $forms[] = $f;
    if(count($forms) > 0) $categories[] = ['name' => $cat['category_name'], 'forms' => $forms];
}

$all_forms = []; foreach($categories as $c) foreach($c['forms'] as $f) $all_forms[] = $f;

// DYNAMIC REPORTS FETCHER
$dynamicReports = [];
$qRep = $conn->query("SELECT DISTINCT fld.field_type, fld.field_label FROM ipd_form_fields fld JOIN ipd_form_sections sec ON fld.section_id = sec.id JOIN ipd_forms f ON sec.form_id = f.id WHERE fld.field_type LIKE 'Report:%' AND (f.target_module = 'Global Application' OR f.target_module = '$dept_safe') AND f.is_active=1");
if($qRep) while($rp = $qRep->fetch_assoc()) $dynamicReports[] = ['type' => $rp['field_type'], 'label' => $rp['field_label']];
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Clinical Command Center | eRHAMS</title>
    
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css" rel="stylesheet">
    <link href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css" rel="stylesheet">
    <link href="https://fonts.googleapis.com/css2?family=Inter:wght@400;500;600;700;800&display=swap" rel="stylesheet">
    <link href="https://cdn.jsdelivr.net/npm/select2@4.1.0-rc.0/dist/css/select2.min.css" rel="stylesheet" />
    <link href="https://cdn.jsdelivr.net/npm/summernote@0.8.18/dist/summernote-lite.min.css" rel="stylesheet">
    <script src="https://cdn.jsdelivr.net/npm/chart.js"></script>
    
    <style>
        body { background-color: #f1f5f9; margin: 0; font-family: 'Inter', sans-serif;}
        .main-content-wrapper { margin-left: 260px !important; padding: 2.5rem; width: calc(100% - 260px); min-height: 100vh; box-sizing: border-box; }
        .content-card { background: #fff; border-radius: 16px; border: 1px solid #e2e8f0; box-shadow: 0 4px 15px rgba(0,0,0,0.02); min-height: 700px;}
        .tabs-wrapper { overflow-x: auto; background: #f8fafc; border-bottom: 1px solid #cbd5e1; border-radius: 16px 16px 0 0; }
        .nav-tabs { display: flex; flex-wrap: nowrap; padding: 10px 15px 0 15px; border: none; }
        .nav-tabs .nav-link { color: #64748b; font-weight: 700; font-size: 13px; border: none; border-bottom: 3px solid transparent; padding: 12px 18px; cursor: pointer; white-space: nowrap; transition: 0.2s;}
        .nav-tabs .nav-link.active { color: #0284c7; border-bottom-color: #0284c7; background: transparent; }
        
        .command-center { background: #fff; border-radius: 16px; border: 1px solid #e2e8f0; padding: 25px;}
        .action-grid { display: grid; grid-template-columns: 1fr 1fr; gap: 16px; margin-bottom: 25px;}
        .action-btn { background: #f8fafc; border: 1px solid #e2e8f0; border-radius: 12px; padding: 18px 10px; display: flex; flex-direction: column; align-items: center; justify-content: center; gap: 10px; cursor: pointer; transition: 0.2s; color: #334155; text-align:center;}
        .action-btn:hover { background: #e0f2fe; border-color: #bae6fd; color: #0284c7; transform: translateY(-3px); box-shadow: 0 8px 15px rgba(2, 132, 199, 0.1);}
        
        .deleted-record { opacity: 0.65; background-color: #f8fafc !important; }
        .deleted-record .card-body { text-decoration: line-through; pointer-events: none;}
        .select2-container { width: 100% !important; z-index: 1055; text-align: left; }
        .note-editor { background: #fff; border-radius: 8px; border: 1px solid #cbd5e1 !important; }
        .select2-results__option { font-size: 13px; font-weight: 600; }
    </style>
</head>
<body>

<?php include '../../dripend/statpages/sidebar.php'; ?>

<div class="main-content-wrapper">
    <div class="d-flex justify-content-between align-items-center mb-4">
        <div class="fs-4 fw-bold text-dark"><a href="admissionManager.php" class="btn btn-light border rounded-circle me-3"><i class="fa-solid fa-arrow-left"></i></a> Clinical Command Center</div>
        <span class="badge bg-white text-dark border px-4 py-2 rounded-pill shadow-sm"><i class="fa-solid fa-bed text-primary me-2"></i> <?php echo htmlspecialchars($location_str); ?></span>
    </div>

    <!-- UNIVERSAL SMART PATIENT HEADER -->
    <?php include('../../dripend/statpages/patientProfileHeader.php'); ?>

    <!-- CLINICAL ALERTS BANNER ZONE -->
    <div id="clinicalAlertsBanner" class="mt-3 mb-1"></div>

    <div class="row g-4 mt-2">
        <div class="col-lg-8">
            <div class="content-card">
                <div class="tabs-wrapper">
                    <ul class="nav nav-tabs" id="recordTabs">
                        <li class="nav-item"><button class="nav-link active" onclick="loadTab('overview')"><i class="fa-solid fa-info-circle me-2"></i> Overview</button></li>
                        <li class="nav-item"><button class="nav-link text-primary" onclick="loadTab('full_history')"><i class="fa-solid fa-clock-rotate-left me-2"></i> Full Clinical Records</button></li>
                        <li class="nav-item"><button class="nav-link text-success" onclick="loadTab('labs_imaging')"><i class="fa-solid fa-microscope me-2"></i> Diagnostics</button></li>
                        <li class="nav-item"><button class="nav-link text-warning" onclick="loadTab('pharmacy_meds')"><i class="fa-solid fa-pills me-2"></i> Medications</button></li>
                        <?php foreach($all_forms as $f): ?>
                            <li class="nav-item"><button class="nav-link" onclick="loadTab('<?php echo $f['id']; ?>')"><i class="fa-solid fa-file-medical me-2"></i> <?php echo htmlspecialchars($f['form_name']); ?></button></li>
                        <?php endforeach; ?>
                    </ul>
                </div>
                <div class="p-4" id="tab_container"></div>
            </div>
        </div>

        <div class="col-lg-4">
            <div class="command-center border-primary border-opacity-25 border-top border-4">
                <?php 
                $icons = [['icon' => 'fa-heart-pulse', 'color' => 'text-danger'],['icon' => 'fa-user-doctor', 'color' => 'text-primary'],['icon' => 'fa-vial', 'color' => 'text-info'],['icon' => 'fa-stethoscope', 'color' => 'text-dark']];
                if(empty($categories)) echo "<div class='text-center py-5 text-muted small fw-bold'>No clinical forms mapped to this Ward's Department.</div>";
                else {
                    foreach($categories as $cat) {
                        echo "<div class='fw-bold text-muted small text-uppercase mb-3 mt-4 first:mt-0 border-bottom pb-2'>" . htmlspecialchars($cat['name']) . "</div><div class='action-grid'>";
                        foreach($cat['forms'] as $idx => $form) {
                            $style = $icons[$form['id'] % count($icons)];
                            echo "<div class='action-btn shadow-sm' onclick=\"openUniversalModal({$form['id']})\"><i class='fa-solid {$style['icon']} {$style['color']} fs-4'></i><span class='fw-bold' style='font-size:12.5px;'>".htmlspecialchars($form['form_name'])."</span></div>";
                        }
                        echo "</div>";
                    }
                }
                ?>
                
                <!-- DYNAMIC CLINICAL REPORTS SECTION -->
                <?php if (!empty($dynamicReports)): ?>
                    <div class='fw-bold text-dark small text-uppercase mb-3 mt-4 border-bottom pb-2'>Clinical Reports & Charts</div>
                    <div class='action-grid' style='grid-template-columns: 1fr;'>
                        <?php foreach($dynamicReports as $r): 
                            $r_icon = 'fa-chart-line text-primary';
                            if(strpos($r['type'], 'Vitals') !== false) $r_icon = 'fa-heart-pulse text-danger';
                            if(strpos($r['type'], 'Medication') !== false) $r_icon = 'fa-pills text-warning';
                            if(strpos($r['type'], 'Fluid') !== false) $r_icon = 'fa-droplet text-info';
                        ?>
                        <div class='action-btn shadow-sm text-start flex-row align-items-center justify-content-start px-3 py-2' onclick='printReport("<?php echo htmlspecialchars($r['type'], ENT_QUOTES); ?>")'>
                            <i class='fa-solid <?php echo $r_icon; ?> fs-5 me-3'></i> <span class='fw-bold text-dark text-start' style='font-size:13px;'><?php echo htmlspecialchars($r['label']); ?></span>
                        </div>
                        <?php endforeach; ?>
                    </div>
                <?php endif; ?>
            </div>
        </div>
    </div>
</div>

<!-- UNIVERSAL ACTION MODAL -->
<div class="modal fade" id="universalActionModal" tabindex="-1" data-bs-backdrop="static">
    <div class="modal-dialog modal-dialog-centered modal-xl modal-dialog-scrollable">
        <div class="modal-content border-0 shadow-lg">
            <div class="modal-header bg-primary text-white border-0 p-3">
                <h6 class="modal-title fw-bold m-0" id="uModalTitle"></h6>
                <button type="button" class="btn-close btn-close-white" data-bs-dismiss="modal"></button>
            </div>
            <div class="modal-body p-4 bg-light" id="uModalBody"></div>
            <div class="modal-footer bg-white border-0 p-3">
                <button type="button" class="btn btn-dark px-5 fw-bold w-100 shadow-sm py-3 fs-5" id="uModalBtn" onclick="submitUniversalAction()"><i class="fa-solid fa-save me-2"></i> Save Record & Process Request</button>
            </div>
        </div>
    </div>
</div>

<!-- DYNAMIC CLINICAL OUTCOMES INTERCEPTOR MODAL -->
<div class="modal fade" id="dynamicOutcomeModal" tabindex="-1" style="z-index: 1060;" data-bs-backdrop="static">
    <div class="modal-dialog modal-dialog-centered">
        <div class="modal-content border-0 shadow-lg" style="border-radius: 16px;">
            <div class="modal-body p-4 text-center">
                <i id="dynOutIcon" class="fa-solid fa-circle-info text-primary fa-4x mb-3"></i>
                <h5 class="fw-bold text-dark" id="dynOutTitle">Clinical Decision</h5>
                <p class="text-muted" id="dynOutMsg"></p>
                <div class="d-flex justify-content-center gap-2 mt-4">
                    <button type="button" class="btn btn-light fw-bold border" data-bs-dismiss="modal">Cancel & Review</button>
                    <button type="button" class="btn btn-primary fw-bold px-4 shadow-sm" id="btnConfirmOutcome">Yes, Confirm Action</button>
                </div>
            </div>
        </div>
    </div>
</div>

<!-- CLINICAL REPORT VIEWER -->
<div class="modal fade" id="reportViewerModal" tabindex="-1"><div class="modal-dialog modal-dialog-centered modal-xl modal-dialog-scrollable"><div class="modal-content border-0 shadow-lg"><div class="modal-header bg-dark text-white p-3 border-0 d-flex justify-content-between"><h6 class="modal-title fw-bold m-0" id="reportTitle"><i class="fa-solid fa-chart-line me-2"></i> Clinical Report</h6><div><button class="btn btn-sm btn-outline-light me-2" onclick="window.print()"><i class="fa-solid fa-print"></i> Print</button><button type="button" class="btn-close btn-close-white" data-bs-dismiss="modal"></button></div></div><div class="modal-body p-4 bg-light"><div class="bg-white p-4 rounded border shadow-sm mb-4" id="reportChartContainer" style="display:none;"><canvas id="reportChart" style="max-height:350px;"></canvas></div><div id="reportTableData" class="table-responsive bg-white rounded border"></div></div></div></div></div>

<!-- CUSTOM APPLICATION RESPONSE MODALS -->
<div class="modal fade" id="appResponseModal" tabindex="-1" style="z-index: 1070;" data-bs-backdrop="static">
    <div class="modal-dialog modal-dialog-centered modal-sm">
        <div class="modal-content border-0 shadow-lg" style="border-radius:16px;">
            <div class="modal-body p-4 text-center">
                <i id="appResIcon" class="fa-solid fa-circle-check text-success fa-4x mb-3"></i>
                <h5 class="fw-bold text-dark" id="appResTitle">Success</h5>
                <p class="text-muted small" id="appResMsg"></p>
                <button type="button" id="appResBtn" class="btn btn-success fw-bold px-4 mt-2" data-bs-dismiss="modal">Close</button>
            </div>
        </div>
    </div>
</div>

<div class="modal fade" id="appConfirmModal" tabindex="-1" style="z-index: 1070;" data-bs-backdrop="static">
    <div class="modal-dialog modal-dialog-centered modal-sm">
        <div class="modal-content border-0 shadow-lg" style="border-radius:16px;">
            <div class="modal-body p-4 text-center">
                <i class="fa-solid fa-triangle-exclamation text-warning fa-4x mb-3"></i>
                <h5 class="fw-bold text-dark" id="appConfTitle">Confirm Action</h5>
                <p class="text-muted small" id="appConfMsg"></p>
                <div class="d-flex justify-content-center gap-2 mt-4">
                    <button type="button" class="btn btn-light fw-bold border" data-bs-dismiss="modal">Cancel</button>
                    <button type="button" class="btn btn-danger fw-bold px-4 shadow-sm" id="btnAppConfirm">Yes, Proceed</button>
                </div>
            </div>
        </div>
    </div>
</div>

<div class="modal fade" id="appPromptModal" tabindex="-1" style="z-index: 1075;" data-bs-backdrop="static">
    <div class="modal-dialog modal-dialog-centered modal-sm">
        <div class="modal-content border-0 shadow-lg" style="border-radius:16px;">
            <div class="modal-body p-4 text-center">
                <i class="fa-solid fa-clipboard-question text-primary fa-4x mb-3"></i>
                <h5 class="fw-bold text-dark mb-1" id="appPromptTitle">Enter Information</h5>
                <p class="text-muted small mb-3" id="appPromptMsg"></p>
                <input type="text" id="appPromptInput" class="form-control border-primary fw-bold text-center mb-3">
                <div class="d-flex justify-content-center gap-2">
                    <button type="button" class="btn btn-light fw-bold border" data-bs-dismiss="modal">Cancel</button>
                    <button type="button" class="btn btn-primary fw-bold px-4 shadow-sm" id="btnAppPromptSubmit">Submit</button>
                </div>
            </div>
        </div>
    </div>
</div>

<script src="https://code.jquery.com/jquery-3.7.1.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/js/bootstrap.bundle.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/select2@4.1.0-rc.0/dist/js/select2.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/summernote@0.8.18/dist/summernote-lite.min.js"></script>

<script> const P_VISIT_ID = <?php echo $visit_id; ?>; const P_NO = "<?php echo $patient_no; ?>"; </script>
<script src="/rimax/application/assets/js/patientIPDRecords.js?v=<?= time() ?>"></script>

</body>
</html>