<?php
if (session_status() === PHP_SESSION_NONE) { session_start(); }
require_once '../../dripend/includes/db.php';
function fetchDict($conn, $query) {
    $data = [];
    $res = $conn->query($query);
    if ($res) while($row = $res->fetch_assoc()) $data[] = $row;
    return $data;
}
$wards = fetchDict($conn, "SELECT id, ward_name FROM ipd_wards WHERE is_active=1");
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Discharge Manager | 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">
    
    <style>
        body { background-color: #f8fafc; margin: 0; overflow-x: hidden; 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; }
        @media (max-width: 992px) { .main-content-wrapper { margin-left: 0 !important; width: 100% !important; padding: 1.5rem; } }

        .dashboard-header { display: flex; justify-content: space-between; align-items: center; padding-bottom: 15px; margin-bottom: 25px;}
        
        .stat-card { background: #fff; border-radius: 16px; padding: 25px; border: 1px solid #e2e8f0; display: flex; align-items: center; gap: 20px; box-shadow: 0 4px 15px rgba(0,0,0,0.03); height: 100%;}
        .stat-icon { width: 65px; height: 65px; border-radius: 14px; display: flex; align-items: center; justify-content: center; font-size: 26px; color:#fff; flex-shrink: 0;}
        .stat-icon.orange { background: linear-gradient(135deg, #fbbf24, #d97706); }
        .stat-icon.green { background: linear-gradient(135deg, #10b981, #059669); }
        .stat-icon.blue { background: linear-gradient(135deg, #0ea5e9, #0284c7); }
        .stat-body h3 { font-size: 32px; font-weight: 800; margin: 0; color: #0f172a;}
        .stat-body p { font-size: 11px; font-weight: 800; color: #64748b; margin: 6px 0 0 0; text-transform: uppercase; letter-spacing: 0.5px; }

        .filter-bar { background: #fff; padding: 25px; border-radius: 16px; box-shadow: 0 4px 15px rgba(0,0,0,0.03); margin-bottom: 30px; border: 1px solid #e2e8f0; }
        .filter-grid { display: grid; grid-template-columns: repeat(auto-fit, minmax(200px, 1fr)); gap: 20px; align-items: end; }
        .filter-group { display: flex; flex-direction: column; gap: 8px; }
        .filter-group label { font-size: 11.5px; font-weight: 800; color: #475569; text-transform: uppercase; letter-spacing: 0.5px;}
        
        .input-control { padding: 12px 16px; border-radius: 10px; border: 1px solid #cbd5e1; outline: none; font-size:14px; font-weight: 600; background: #f8fafc; transition: 0.2s; width: 100%;}
        .input-control:focus { border-color: #0ea5e9; box-shadow: 0 0 0 4px rgba(14, 165, 233, 0.15); background:#fff;}
        .btn-filter { background: #10b981; color: #fff; border: none; border-radius: 10px; padding: 12px 20px; font-weight: 800; font-size: 14px; cursor: pointer; transition: 0.2s; height: 46px; display:flex; align-items:center; justify-content:center; gap:8px;}
        .btn-filter:hover { background: #059669; transform: translateY(-2px); box-shadow: 0 6px 15px rgba(16, 185, 129, 0.3); color:#fff;}
        
        .list-table-container { background: #fff; border-radius: 16px; border: 1px solid #e2e8f0; box-shadow: 0 4px 15px rgba(0,0,0,0.03); overflow:hidden;}
        table.dataTable { width: 100% !important; margin: 0 !important; font-size: 13.5px; }
        table.dataTable thead th { background: #f1f5f9; color: #475569; padding: 18px 24px; font-weight: 800; font-size: 12.5px; text-transform: uppercase; letter-spacing: 0.5px; border-bottom: none;}
        table.dataTable tbody td { padding: 16px 24px; border-bottom: 1px solid #e2e8f0; vertical-align: middle; }
        
        .dt-serial { font-weight: 800; color: #94a3b8; }
        .badge-pending { background-color: #fffbeb; color: #b45309; border: 1px solid #fcd34d; }
        
        .nav-tabs .nav-link { font-weight: 700; color: #64748b; border: none; border-bottom: 3px solid transparent; padding: 12px 25px;}
        .nav-tabs .nav-link.active { color: #0ea5e9; border-bottom-color: #0ea5e9; background: transparent; }

        .diagnoses-box { background: #f0f9ff; border: 1px solid #bae6fd; border-radius: 8px; padding: 15px; }
        .diag-item { border-bottom: 1px dashed #bae6fd; padding-bottom: 8px; margin-bottom: 8px; }
        .diag-item:last-child { border-bottom: none; padding-bottom: 0; margin-bottom: 0; }
        
        .timeline-box { background: #f8fafc; border: 1px solid #e2e8f0; border-radius: 8px; padding: 15px; max-height: 250px; overflow-y: auto;}
        .timeline-item { border-left: 2px solid #cbd5e1; padding-left: 15px; margin-bottom: 15px; position: relative;}
        .timeline-item::before { content: ''; position: absolute; left: -6px; top: 0; width: 10px; height: 10px; background: #94a3b8; border-radius: 50%;}
    </style>
</head>
<body>

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

<div class="main-content-wrapper">
    <div class="dashboard-header">
        <h3 class="fw-bold text-dark m-0" style="letter-spacing: -0.5px;">
            <i class="fa-solid fa-person-walking-arrow-right text-warning me-2"></i> Clinical Discharge Management
        </h3>
    </div>

    <!-- STATS ROW -->
    <div class="row g-4 mb-4">
        <div class="col-md-3">
            <div class="stat-card">
                <div class="stat-icon orange"><i class="fa-solid fa-clock-rotate-left"></i></div>
                <div class="stat-body">
                    <h3 id="kpi_pending">0</h3>
                    <p>Total Pending <br><span class="text-muted fw-normal text-capitalize">(M: <span id="kpi_male">0</span>, F: <span id="kpi_female">0</span>)</span></p>
                </div>
            </div>
        </div>
        <div class="col-md-3">
            <div class="stat-card">
                <div class="stat-icon green"><i class="fa-solid fa-house-medical-circle-check"></i></div>
                <div class="stat-body">
                    <h3 id="kpi_today">0</h3>
                    <p>Discharged Today</p>
                </div>
            </div>
        </div>
        <div class="col-md-3">
            <div class="stat-card">
                <div class="stat-icon blue"><i class="fa-solid fa-broom"></i></div>
                <div class="stat-body">
                    <h3 id="kpi_cleaning">0</h3>
                    <p>Housekeeping Required</p>
                </div>
            </div>
        </div>
        <div class="col-md-3">
            <div class="stat-card p-3">
                <div class="stat-body w-100">
                    <p class="mb-2 text-dark"><i class="fa-solid fa-hospital me-1"></i> Top Pending Wards</p>
                    <div id="kpi_wards_list" class="small fw-bold text-muted" style="line-height:1.8;">Loading...</div>
                </div>
            </div>
        </div>
    </div>

    <!-- TABS -->
    <ul class="nav nav-tabs mb-4" id="dischargeTabs" role="tablist">
        <li class="nav-item">
            <button class="nav-link active" id="pending-tab" data-bs-toggle="tab" data-bs-target="#pending-pane" type="button"><i class="fa-solid fa-list-check me-2"></i> Active Clearance Queue</button>
        </li>
        <li class="nav-item">
            <button class="nav-link" id="history-tab" data-bs-toggle="tab" data-bs-target="#history-pane" type="button"><i class="fa-solid fa-clock-rotate-left me-2"></i> Discharged History & Audits</button>
        </li>
    </ul>

    <div class="tab-content" id="dischargeTabsContent">
        
        <!-- PENDING QUEUE TAB -->
        <div class="tab-pane fade show active" id="pending-pane" tabindex="0">
            <div class="filter-bar">
                <div class="filter-grid">
                    <div class="filter-group">
                        <label>Date From</label>
                        <input type="date" id="pending_start_date" class="input-control">
                    </div>
                    <div class="filter-group">
                        <label>Date To</label>
                        <input type="date" id="pending_end_date" class="input-control">
                    </div>
                    <div class="filter-group" style="grid-column: span 2;">
                        <label>Ward / Unit Filter</label>
                        <select id="pending_ward_id" class="input-control">
                            <option value="ALL">All Wards / Units</option>
                            <?php foreach($wards as $w): ?>
                                <option value="<?php echo $w['id']; ?>"><?php echo htmlspecialchars($w['ward_name']); ?></option>
                            <?php endforeach; ?>
                        </select>
                    </div>
                    <div class="filter-group">
                        <button class="btn-filter w-100" onclick="applyPendingFilter()"><i class="fa-solid fa-filter"></i> Retrieve Records</button>
                    </div>
                </div>
            </div>

            <div class="list-table-container p-3" id="pending_table_wrapper" style="display:none;">
                <table id="tblPendingDischarges" class="table table-hover align-middle w-100">
                    <thead>
                        <tr>
                            <th width="5%">#</th>
                            <th>Patient Identity & Principal Diagnosis</th>
                            <th>Ward / Location</th>
                            <th>Doctor Outcome</th>
                            <th>Status</th>
                            <th class="text-end">Action</th>
                        </tr>
                    </thead>
                    <tbody></tbody>
                </table>
            </div>
            
            <div id="pending_empty_state" class="text-center py-5" style="background:#fff; border-radius:16px; border:1px dashed #cbd5e1;">
                <i class="fa-solid fa-filter fa-3x mb-3" style="color:#cbd5e1;"></i><br>
                <span class="fw-bold fs-5 text-dark">Apply Filters to View Active Queue</span>
            </div>
        </div>

        <!-- HISTORY TAB -->
        <div class="tab-pane fade" id="history-pane" tabindex="0">
            <div class="filter-bar">
                <div class="filter-grid">
                    <div class="filter-group">
                        <label>Discharge Date From</label>
                        <input type="date" id="history_start_date" class="input-control">
                    </div>
                    <div class="filter-group">
                        <label>Discharge Date To</label>
                        <input type="date" id="history_end_date" class="input-control">
                    </div>
                    <div class="filter-group" style="grid-column: span 2;">
                        <label>Ward / Unit Filter</label>
                        <select id="history_ward_id" class="input-control">
                            <option value="ALL">All Wards / Units</option>
                            <?php foreach($wards as $w): ?>
                                <option value="<?php echo $w['id']; ?>"><?php echo htmlspecialchars($w['ward_name']); ?></option>
                            <?php endforeach; ?>
                        </select>
                    </div>
                    <div class="filter-group">
                        <button class="btn-filter w-100" onclick="applyHistoryFilter()"><i class="fa-solid fa-filter"></i> Retrieve Log</button>
                    </div>
                </div>
            </div>

            <div class="list-table-container p-3" id="history_table_wrapper" style="display:none;">
                <table id="tblDischargedHistory" class="table table-hover align-middle w-100">
                    <thead>
                        <tr>
                            <th width="5%">#</th>
                            <th>Discharged On</th>
                            <th>Patient Details</th>
                            <th>Final Outcome</th>
                            <th>Discharge Notes</th>
                            <th class="text-end">Action</th>
                        </tr>
                    </thead>
                    <tbody></tbody>
                </table>
            </div>
            
            <div id="history_empty_state" class="text-center py-5" style="background:#fff; border-radius:16px; border:1px dashed #cbd5e1;">
                <i class="fa-solid fa-filter fa-3x mb-3" style="color:#cbd5e1;"></i><br>
                <span class="fw-bold fs-5 text-dark">Apply Filters to View Discharged History</span>
            </div>
        </div>
        
    </div>
</div>

<!-- ========================================== -->
<!-- FINAL DISCHARGE CLEARANCE MODAL -->
<!-- ========================================== -->
<div class="modal fade" id="dischargeClearanceModal" tabindex="-1" data-bs-backdrop="static">
    <div class="modal-dialog modal-xl modal-dialog-centered modal-dialog-scrollable">
        <form id="frmExecuteDischarge" class="modal-content border-0 shadow-lg">
            <div class="modal-header bg-dark text-white border-0 p-4">
                <h5 class="modal-title fw-bold m-0" id="modalClearanceTitle"><i class="fa-solid fa-clipboard-check me-2"></i> Clinical Discharge Clearance</h5>
                <button type="button" class="btn-close btn-close-white" data-bs-dismiss="modal"></button>
            </div>
            
            <div class="modal-body p-4 bg-light">
                <input type="hidden" name="action" value="execute_final_discharge">
                <input type="hidden" name="episode_id" id="m_episode_id">
                <input type="hidden" name="visit_id" id="m_visit_id">
                <input type="hidden" name="bed_id" id="m_bed_id">

                <!-- PATIENT HIGHLIGHT -->
                <div class="d-flex align-items-center bg-white p-3 rounded-3 shadow-sm border mb-4">
                    <div class="flex-grow-1">
                        <h4 class="fw-bold text-primary mb-1" id="m_patient_name">Patient Name</h4>
                        <p class="text-muted small fw-bold mb-0" id="m_patient_sub">ID: | Admission: | Payer:</p>
                    </div>
                    <div class="text-end">
                        <span class="badge bg-dark px-3 py-2 fs-6 shadow-sm"><i class="fa-solid fa-bed text-primary me-2"></i> <span id="m_bed_location">Ward/Bed</span></span>
                    </div>
                </div>

                <div class="row g-4 mb-4">
                    <!-- CLINICAL DETAILS (READONLY) -->
                    <div class="col-md-6">
                        <div class="bg-white p-4 rounded-3 shadow-sm border h-100">
                            <h6 class="fw-bold text-secondary text-uppercase small mb-3 border-bottom pb-2"><i class="fa-solid fa-stethoscope me-2"></i> Clinical Authority & Diagnoses</h6>
                            
                            <div class="row g-3 mb-3">
                                <div class="col-6">
                                    <label class="small fw-bold text-muted text-uppercase mb-1">Doctor's Outcome</label>
                                    <input type="text" id="m_doc_outcome" class="form-control fw-bold text-danger bg-light" readonly>
                                </div>
                                <div class="col-6">
                                    <label class="small fw-bold text-muted text-uppercase mb-1">Next Review Date</label>
                                    <input type="datetime-local" id="m_next_review_date" class="form-control fw-bold text-dark bg-light" readonly>
                                </div>
                            </div>
                            
                            <label class="small fw-bold text-muted text-uppercase mb-1">Clinical Diagnoses & Insurance Codes</label>
                            <div class="diagnoses-box" id="m_diagnoses_list"></div>
                        </div>
                    </div>
                    
                    <!-- CLEARANCE & LATEST WARD TIMELINE -->
                    <div class="col-md-6">
                        <div class="bg-white p-4 rounded-3 shadow-sm border h-100">
                            <h6 class="fw-bold text-secondary text-uppercase small mb-3 border-bottom pb-2"><i class="fa-solid fa-list-check me-2"></i> Pre-Discharge Clearances & Updates</h6>
                            
                            <div class="d-flex justify-content-between align-items-center mb-2">
                                <span class="fw-bold text-dark"><i class="fa-solid fa-file-invoice-dollar text-primary me-2"></i> Unpaid Bills:</span>
                                <span class="badge bg-danger fs-6 shadow-sm" id="m_total_billed">GHS 0.00</span>
                            </div>
                            <div class="d-flex justify-content-between align-items-center mb-2">
                                <span class="fw-bold text-dark"><i class="fa-solid fa-pills text-warning me-2"></i> Discharged on Orals (Pharmacy):</span>
                                <span class="badge bg-secondary fs-6 shadow-sm" id="m_tto_status">0 / 0 Dispensed</span>
                            </div>
                            <div class="d-flex justify-content-between align-items-center mb-4">
                                <span class="fw-bold text-dark"><i class="fa-solid fa-microscope text-success me-2"></i> Pending Labs:</span>
                                <span id="m_labs_status"></span>
                            </div>

                            <label class="small fw-bold text-muted text-uppercase mb-1">Latest Ward Activity (Last 5 Entries)</label>
                            <div class="timeline-box" id="m_latest_records"></div>
                        </div>
                    </div>
                </div>

                <!-- EXECUTION FORM -->
                <div class="bg-white p-4 rounded-3 shadow-sm border border-primary">
                    <h6 class="fw-bold text-primary text-uppercase small mb-3 border-bottom pb-2 border-primary"><i class="fa-solid fa-pen-to-square me-2"></i> Final Nursing Validation</h6>
                    
                    <div class="col-12">
                        <label class="small fw-bold text-dark mb-1">Nursing Discharge Notes / Education Given <span class="text-danger">*</span></label>
                        <textarea name="discharge_notes" id="m_discharge_notes" class="form-control bg-light" rows="3" placeholder="e.g. Patient educated on medication timing. Discharged on Orals handed over. IV cannula removed." required></textarea>
                    </div>
                </div>
            </div>
            
            <div class="modal-footer bg-white border-0 p-4">
                <button type="button" class="btn btn-light border fw-bold px-4" data-bs-dismiss="modal">Cancel</button>
                <button type="submit" class="btn btn-primary fw-bold px-5 shadow-sm" id="btnSubmitDischarge"><i class="fa-solid fa-check-double me-2"></i> Validate & Free Bed</button>
            </div>
        </form>
    </div>
</div>

<!-- ========================================== -->
<!-- UPDATE POST-DISCHARGE NOTES MODAL -->
<!-- ========================================== -->
<div class="modal fade" id="updateNotesModal" tabindex="-1">
    <div class="modal-dialog modal-dialog-centered">
        <div class="modal-content border-0 shadow-lg">
            <div class="modal-header bg-warning text-dark border-0 p-3">
                <h6 class="modal-title fw-bold m-0"><i class="fa-solid fa-pen me-2"></i> Amend Discharge Notes</h6>
                <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
            </div>
            <form id="frmUpdateNotes">
                <input type="hidden" name="action" value="update_discharge_notes">
                <input type="hidden" name="edit_episode_id" id="edit_episode_id">
                <div class="modal-body p-4 bg-light">
                    <div class="alert alert-warning py-2 small fw-bold"><i class="fa-solid fa-triangle-exclamation me-1"></i> Updates will be recorded in the system audit trail.</div>
                    <label class="small fw-bold text-dark mb-1">Discharge Notes</label>
                    <textarea name="edit_discharge_notes" id="edit_discharge_notes" class="form-control" rows="5" required></textarea>
                </div>
                <div class="modal-footer bg-white border-0 p-3">
                    <button type="submit" class="btn btn-dark fw-bold w-100" id="btnSubmitUpdate"><i class="fa-solid fa-save me-2"></i> Update Notes</button>
                </div>
            </form>
        </div>
    </div>
</div>

<!-- SUCCESS & ERROR APP MODALS (Replaces Alert) -->
<div class="modal fade" id="appResponseModal" tabindex="-1" style="z-index: 1060;">
    <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>

<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.datatables.net/1.13.6/js/jquery.dataTables.min.js"></script>
<script src="https://cdn.datatables.net/1.13.6/js/dataTables.bootstrap5.min.js"></script>
<script src="/rimax/application/assets/js/dischargeManager.js"></script>

</body>
</html>