<?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;
$req_id = isset($_GET['req_id']) ? (int)$_GET['req_id'] : 0;

if ($visit_id === 0 || $req_id === 0) die("<div style='padding:40px; text-align:center;'><h2>Invalid Surgical Context.</h2></div>");

$stmt = $conn->prepare("
    SELECT t.*, p.patient_no, p.first_name, p.last_name, p.dob, g.gender_name,
           tr.room_name, w.ward_name as origin_ward, b.bed_number as origin_bed,
           CONCAT(s.first_name, ' ', s.last_name) as surgeon_name,
           CONCAT(a.first_name, ' ', a.last_name) as anesthetist_name
    FROM ipd_theatre_requests t
    JOIN visit_master vm ON t.visit_id = vm.id
    JOIN patient p ON vm.patient_no = p.patient_no
    LEFT JOIN gender g ON p.gender_id = g.id
    LEFT JOIN ipd_setup_theatre_rooms tr ON t.room_id = tr.id
    LEFT JOIN ipd_admission_episodes e ON t.origin_episode_id = e.id
    LEFT JOIN ipd_wards w ON e.ward_id = w.id
    LEFT JOIN ipd_beds b ON t.origin_bed_id = b.id
    LEFT JOIN staff s ON t.surgeon_id = s.staff_id
    LEFT JOIN staff a ON t.anesthetist_id = a.staff_id
    WHERE t.id = ? LIMIT 1
");
$stmt->bind_param("i", $req_id);
$stmt->execute();
$theatre = $stmt->get_result()->fetch_assoc();
$stmt->close();

if(!$theatre) die("<div style='padding:40px; text-align:center;'><h2>Theatre Request Not Found.</h2></div>");

$patient_no = $theatre['patient_no'];
$location_str = "Operating Room: " . ($theatre['room_name'] ?? 'Unassigned');
$origin_str = ($theatre['origin_ward'] ? $theatre['origin_ward'] . ' - Bed ' . $theatre['origin_bed'] : 'OPD / Direct');

$stages = [];
$resStages = $conn->query("SELECT id, stage_name FROM ipd_setup_clinical_stages WHERE is_active = 1 ORDER BY id ASC");
if($resStages) {
    while($s = $resStages->fetch_assoc()) $stages[] = $s;
}

$dynamicReports = [];
$qRep = $conn->query("SELECT DISTINCT field_type, field_label FROM theatre_form_setup WHERE field_type LIKE 'Report:%' AND is_active=1");
if($qRep) {
    while($rp = $qRep->fetch_assoc()) {
        $icon = 'fa-chart-line text-primary';
        if(stripos($rp['field_type'], 'Vitals') !== false) $icon = 'fa-heart-pulse text-danger';
        if(stripos($rp['field_type'], 'Fluid') !== false) $icon = 'fa-droplet text-info';
        if(stripos($rp['field_type'], 'Medication') !== false) $icon = 'fa-pills text-warning';
        
        $dynamicReports[] = ['type' => $rp['field_type'], 'label' => $rp['field_label'], 'icon' => $icon];
    }
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Surgical 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: 290px !important; padding: 2.5rem; width: calc(100% - 290px); min-height: 100vh; box-sizing: border-box; }
        
        .theatre-header-box { background: linear-gradient(135deg, #1e3a8a, #3b82f6); color: #fff; padding: 25px; border-radius: 16px; margin-bottom: 25px; box-shadow: 0 4px 15px rgba(0,0,0,0.1); }
        .theatre-badge { background: rgba(255, 255, 255, 0.2); color: #e0f2fe; border: 1px solid rgba(255, 255, 255, 0.3); }

        .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; text-align:center; gap: 10px; cursor: pointer; transition: 0.2s; color: #334155;}
        .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; }
    </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="theatreManager.php" class="btn btn-light border rounded-circle me-3"><i class="fa-solid fa-arrow-left"></i></a> Surgical Command Center</div>
        <span class="badge bg-white text-primary border border-primary px-4 py-2 rounded-pill shadow-sm"><i class="fa-solid fa-scalpel-line-dashed me-2"></i> <?php echo htmlspecialchars($location_str); ?></span>
    </div>

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

    <!-- THEATRE PATIENT HIGHLIGHT CARD -->
    <div class="card border-0 shadow-sm rounded-4 mb-4" style="background: linear-gradient(135deg, #1e3a8a, #3b82f6); color: white;">
        <div class="card-body p-4 d-flex justify-content-between align-items-center">
             <div>
                 <h6 class="text-uppercase text-info fw-bold mb-1" style="letter-spacing:1px; color:#bfdbfe!important;">Active Surgical Procedure</h6>
                 <h3 class="fw-bold mb-0"><i class="fa-solid fa-scalpel-line-dashed me-2"></i> <?php echo htmlspecialchars($theatre['procedure_name']); ?></h3>
             </div>
             <div class="text-end">
                 <div class="badge bg-white text-primary fs-6 px-3 py-2 rounded-pill shadow-sm mb-2"><i class="fa-solid fa-location-dot me-1"></i> <?php echo htmlspecialchars($theatre['room_name']); ?></div>
                 <div class="small fw-bold text-light">Lead Surg: Dr. <?php echo htmlspecialchars($theatre['surgeon_name'] ?? 'Unassigned'); ?> | Anes: Dr. <?php echo htmlspecialchars($theatre['anesthetist_name'] ?? 'Unassigned'); ?></div>
             </div>
        </div>
    </div>

    <div id="clinicalAlertsBanner"></div>

    <div class="row g-4 mt-1">
        <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> Surgery Overview</button></li>
                        <li class="nav-item"><button class="nav-link text-dark" onclick="loadTab('full_history')"><i class="fa-solid fa-clock-rotate-left me-2"></i> Full Theatre Record</button></li>
                        <?php foreach($stages as $s): ?>
                            <li class="nav-item"><button class="nav-link" onclick="loadTab('<?php echo $s['id']; ?>')"><i class="fa-solid fa-file-medical me-2"></i> <?php echo htmlspecialchars($s['stage_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 
                if(empty($stages)) echo "<div class='text-center py-5 text-muted small fw-bold'>No clinical stages configured for Theatre.</div>";
                else {
                    $icon_map = [1 => 'fa-clipboard-user text-primary', 2 => 'fa-scalpel text-primary', 3 => 'fa-bed-pulse text-success'];
                    
                    echo "<div class='fw-bold text-dark small text-uppercase mb-3 border-bottom pb-2'>Clinical Stage Documentation</div><div class='action-grid'>";
                    foreach($stages as $stage) {
                        $icon = $icon_map[$stage['id']] ?? 'fa-file-medical text-dark';
                        echo "<div class='action-btn shadow-sm' onclick=\"openUniversalModal({$stage['id']})\"><i class='fa-solid {$icon} fs-4'></i><span class='fw-bold' style='font-size:12.5px;'>".htmlspecialchars($stage['stage_name'])."</span></div>";
                    }
                    echo "</div>";
                }
                ?>
                
                <?php if (!empty($dynamicReports)): ?>
                    <div class='fw-bold text-dark small text-uppercase mb-3 mt-4 border-bottom pb-2'>Theatre Flowsheets & Reports</div>
                    <div class='action-grid' style='grid-template-columns: 1fr;'>
                        <?php foreach($dynamicReports as $r): ?>
                        <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-primary px-5 fw-bold w-100 shadow-sm" id="uModalBtn" onclick="submitUniversalAction()"><i class="fa-solid fa-save me-2"></i> Save Theatre Record</button>
            </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 ALERT MODAL -->
<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>

<!-- CUSTOM CONFIRMATION MODAL -->
<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>

<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_REQ_ID = <?php echo $req_id; ?>; 
    const P_NO = "<?php echo $patient_no; ?>"; 
    const P_PROCEDURE_ID = "<?php echo $theatre['procedure_id'] ?? ''; ?>";
</script>
<script src="/rimax/application/assets/js/theatrePatientRecords.js"></script>

</body>
</html>