<?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>Ward Transfer 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">
    <link href="https://cdn.jsdelivr.net/npm/select2@4.1.0-rc.0/dist/css/select2.min.css" 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%; transition: 0.3s;}
        .stat-card:hover { transform: translateY(-3px); box-shadow: 0 8px 25px rgba(0,0,0,0.06); }
        .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.blue { background: linear-gradient(135deg, #0ea5e9, #0284c7); }
        .stat-icon.orange { background: linear-gradient(135deg, #fbbf24, #d97706); }
        .stat-icon.green { background: linear-gradient(135deg, #10b981, #059669); }
        .stat-icon.red { background: linear-gradient(135deg, #ef4444, #dc2626); }
        .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(180px, 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-theatre { background-color: #fef2f2; color: #dc2626; border: 1px solid #fca5a5; }
        .badge-ward { background-color: #f0fdf4; color: #15803d; border: 1px solid #86efac; }
        
        .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; }
        .select2-container { width: 100% !important; text-align: left; }
        
        /* Clinical Summary Styles */
        .clinical-summary-box { background: #f8fafc; border: 1px solid #e2e8f0; border-radius: 8px; padding: 15px; font-size:13px; line-height:1.6;}
        .vital-pill { display: inline-block; background: #fff; border: 1px solid #cbd5e1; border-radius: 50px; padding: 5px 12px; margin: 0 5px 5px 0; font-weight: 600; color: #334155;}
    </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-right-left text-primary me-2"></i> Ward Transfer Manager
        </h3>
        <button class="btn btn-dark fw-bold px-4 shadow-sm" onclick="openInitiateModal()"><i class="fa-solid fa-plus me-2"></i> Initiate Transfer</button>
    </div>

    <div class="row g-4 mb-4">
        <div class="col-md-3">
            <div class="stat-card">
                <div class="stat-icon blue"><i class="fa-solid fa-inbox"></i></div>
                <div class="stat-body">
                    <h3 id="kpi_incoming">0</h3>
                    <p>Total Incoming Pending</p>
                </div>
            </div>
        </div>
        <div class="col-md-3">
            <div class="stat-card">
                <div class="stat-icon orange"><i class="fa-solid fa-paper-plane"></i></div>
                <div class="stat-body">
                    <h3 id="kpi_outgoing">0</h3>
                    <p>Total Outgoing Pending</p>
                </div>
            </div>
        </div>
        <div class="col-md-3">
            <div class="stat-card">
                <div class="stat-icon green"><i class="fa-solid fa-check-double"></i></div>
                <div class="stat-body">
                    <h3 id="kpi_completed">0</h3>
                    <p>Completed Transfers</p>
                </div>
            </div>
        </div>
        <div class="col-md-3">
            <div class="stat-card">
                <div class="stat-icon red"><i class="fa-solid fa-ban"></i></div>
                <div class="stat-body">
                    <h3 id="kpi_rejected">0</h3>
                    <p>Rejected Transfers</p>
                </div>
            </div>
        </div>
    </div>

    <!-- FILTER BAR -->
    <div class="filter-bar">
        <div class="filter-grid">
            <div class="filter-group">
                <label>Date From</label>
                <input type="date" id="flt_start" class="input-control">
            </div>
            <div class="filter-group">
                <label>Date To</label>
                <input type="date" id="flt_end" class="input-control">
            </div>
            <div class="filter-group">
                <label>Ward / Unit Filter</label>
                <select id="flt_ward" 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">
                <label>Routing Direction</label>
                <select id="flt_direction" class="input-control">
                    <option value="ALL">All Directions</option>
                    <option value="Incoming">Incoming to Selected Ward</option>
                    <option value="Outgoing">Outgoing from Selected Ward</option>
                </select>
            </div>
            <div class="filter-group">
                <button class="btn-filter w-100" onclick="applyFilter()"><i class="fa-solid fa-filter"></i> Apply Filters</button>
            </div>
        </div>
    </div>

    <!-- TABS -->
    <ul class="nav nav-tabs mb-4" id="transferTabs" role="tablist">
        <li class="nav-item">
            <button class="nav-link active" id="pending-tab" onclick="switchTab('Pending')" type="button"><i class="fa-solid fa-list-check me-2"></i> Active Pending Queue</button>
        </li>
        <li class="nav-item">
            <button class="nav-link text-success" id="history-tab" onclick="switchTab('Completed')" type="button"><i class="fa-solid fa-check-double me-2"></i> Completed Transfers</button>
        </li>
        <li class="nav-item">
            <button class="nav-link text-danger" id="rejected-tab" onclick="switchTab('Rejected')" type="button"><i class="fa-solid fa-ban me-2"></i> Rejected / Cancelled</button>
        </li>
    </ul>

    <!-- DATA TABLE CONTAINER -->
    <div class="list-table-container p-3" id="table_wrapper" style="display:none;">
        <table id="tblTransferQueue" class="table table-hover align-middle w-100">
            <thead>
                <tr>
                    <th width="5%">#</th>
                    <th>Date & Time</th>
                    <th>Patient Identity</th>
                    <th>Routing Pathway</th>
                    <th>Transfer Notes & Status</th>
                    <th class="text-end">Action</th>
                </tr>
            </thead>
            <tbody></tbody>
        </table>
    </div>
    
    <div id="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 Transfers</span>
    </div>

</div>

<!-- ========================================== -->
<!-- INITIATE TRANSFER MODAL -->
<!-- ========================================== -->
<div class="modal fade" id="initiateTransferModal" tabindex="-1" data-bs-backdrop="static">
    <div class="modal-dialog modal-dialog-centered modal-lg">
        <form id="frmInitiateTransfer" class="modal-content border-0 shadow-lg" style="border-radius:12px;">
            <div class="modal-header bg-primary text-white border-0 p-3">
                <h6 class="modal-title fw-bold m-0"><i class="fa-solid fa-paper-plane me-2"></i> Initiate Patient Transfer</h6>
                <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="initiate_transfer">
                
                <div class="row g-3">
                    <div class="col-12">
                        <label class="small fw-bold text-dark mb-1">Select Active Patient <span class="text-danger">*</span></label>
                        <select name="visit_id" id="init_visit_id" class="form-select select2-modal" required></select>
                        <div class="form-text small"><i class="fa fa-info-circle"></i> Patients currently "Admitted" will appear here.</div>
                    </div>

                    <div class="col-12 mt-4 border-bottom pb-2">
                        <h6 class="fw-bold text-primary m-0"><i class="fa-solid fa-map-location-dot me-2"></i> Destination Routing</h6>
                    </div>

                    <div class="col-md-6">
                        <label class="small fw-bold text-dark mb-1">Target Ward / Unit <span class="text-danger">*</span></label>
                        <select name="target_ward_id" id="init_target_ward" class="form-select select2-modal" required></select>
                    </div>

                    <div class="col-md-6">
                        <label class="small fw-bold text-dark mb-1">Target Bed (Optional / Direct Transfer)</label>
                        <select name="target_bed_id" id="init_target_bed" class="form-select select2-modal" disabled>
                            <option value="">Select Ward First</option>
                        </select>
                        <div class="form-text small text-primary fw-bold"><i class="fa fa-bolt"></i> If selected, patient is instantly moved.</div>
                    </div>

                    <div class="col-12 mt-2">
                        <label class="small fw-bold text-dark mb-1">Transfer Clinical Notes</label>
                        <textarea name="transfer_notes" class="form-control" rows="3" placeholder="Reason for transfer, hand-over notes, equipment needed..."></textarea>
                    </div>
                </div>
            </div>
            <div class="modal-footer bg-white border-0 p-3">
                <button type="button" class="btn btn-light border fw-bold" data-bs-dismiss="modal">Cancel</button>
                <button type="submit" class="btn btn-primary fw-bold px-4" id="btnInitiateTransfer">Send Transfer Request</button>
            </div>
        </form>
    </div>
</div>

<!-- ========================================== -->
<!-- ACCEPT TRANSFER MODAL (SPLIT SCREEN) -->
<!-- ========================================== -->
<div class="modal fade" id="acceptTransferModal" tabindex="-1" data-bs-backdrop="static">
    <div class="modal-dialog modal-dialog-centered modal-xl modal-dialog-scrollable">
        <form id="frmAcceptTransfer" class="modal-content border-0 shadow-lg" style="border-radius:12px; overflow:hidden;">
            <div class="modal-header bg-success text-white border-0 p-3">
                <h6 class="modal-title fw-bold m-0" id="lblAcceptTitle"><i class="fa-solid fa-bed me-2"></i> Accept Transfer & Allocate Bed</h6>
                <button type="button" class="btn-close btn-close-white" data-bs-dismiss="modal"></button>
            </div>
            <div class="modal-body p-0 bg-light">
                <div class="row g-0 h-100">
                    <!-- Left Col: Clinical Handover Summary -->
                    <div class="col-lg-8 p-4 border-end bg-white overflow-auto" style="max-height: 65vh;">
                        <h6 class="fw-bold text-primary mb-3 text-uppercase"><i class="fa-solid fa-file-medical me-2"></i> Patient Clinical Handover Summary</h6>
                        <div id="transfer_clinical_summary">
                            <div class="text-center py-4"><i class="fa fa-spinner fa-spin fa-2x text-muted"></i></div>
                        </div>
                    </div>
                    
                    <!-- Right Col: Bed Allocation -->
                    <div class="col-lg-4 p-4 bg-light">
                        <input type="hidden" name="action" value="accept_transfer">
                        <input type="hidden" name="request_id" id="accept_req_id">
                        <input type="hidden" name="transfer_type" id="accept_transfer_type">
                        
                        <div class="alert alert-info py-2 small fw-bold mb-4 shadow-sm border-info border-opacity-50"><i class="fa-solid fa-info-circle me-1"></i> Approving this allocates the patient to your ward and marks their old bed for housekeeping.</div>

                        <div class="form-group mb-4" id="bed_allocation_box">
                            <label class="small fw-bold text-dark mb-2">Assign Vacant Bed in <span id="lbl_accept_ward" class="text-primary"></span> <span class="text-danger">*</span></label>
                            <select name="target_bed_id" id="accept_bed_id" class="form-select fw-bold border-success text-success" required style="height:45px;"></select>
                        </div>
                        
                        <hr class="my-4">
                        <button type="button" class="btn btn-light border fw-bold w-100 mb-2" data-bs-dismiss="modal">Cancel Review</button>
                        <button type="submit" class="btn btn-success fw-bold w-100 py-2 shadow-sm" id="btnAcceptTransfer"><i class="fa-solid fa-check-double me-1"></i> Accept & Admit Patient</button>
                    </div>
                </div>
            </div>
        </form>
    </div>
</div>

<!-- ========================================== -->
<!-- REJECT TRANSFER MODAL -->
<!-- ========================================== -->
<div class="modal fade" id="rejectTransferModal" tabindex="-1" data-bs-backdrop="static">
    <div class="modal-dialog modal-dialog-centered">
        <form id="frmRejectTransfer" class="modal-content border-0 shadow-lg" style="border-radius:12px;">
            <div class="modal-header bg-danger text-white border-0 p-3">
                <h6 class="modal-title fw-bold m-0"><i class="fa-solid fa-ban me-2"></i> Reject Transfer</h6>
                <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="reject_transfer">
                <input type="hidden" name="request_id" id="reject_req_id">
                <input type="hidden" name="transfer_type" id="reject_transfer_type">
                
                <div class="alert alert-danger py-2 small fw-bold bg-danger bg-opacity-10 border-danger border-opacity-25 text-danger"><i class="fa-solid fa-triangle-exclamation me-1"></i> The patient will remain securely in their original location.</div>

                <div class="row g-3">
                    <div class="col-12">
                        <label class="small fw-bold text-dark mb-1">Reason for Rejection / Cancellation <span class="text-danger">*</span></label>
                        <textarea name="rejection_reason" class="form-control border-danger" rows="3" placeholder="e.g. No beds available, wrong ward selected..." required></textarea>
                    </div>
                </div>
            </div>
            <div class="modal-footer bg-white border-0 p-3">
                <button type="button" class="btn btn-light border fw-bold" data-bs-dismiss="modal">Cancel</button>
                <button type="submit" class="btn btn-danger fw-bold px-4 shadow-sm" id="btnRejectTransfer">Reject Transfer</button>
            </div>
        </form>
    </div>
</div>

<!-- SUCCESS & ERROR APP MODALS -->
<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="https://cdn.jsdelivr.net/npm/select2@4.1.0-rc.0/dist/js/select2.min.js"></script>
<script src="/rimax/application/assets/js/wardTransferManager.js"></script>

</body>
</html>