<?php
if (session_status() === PHP_SESSION_NONE) { session_start(); }
require_once '../../dripend/includes/db.php';

$visit_id = isset($_GET['visit_id']) ? (int)$_GET['visit_id'] : 0;

// CRITICAL FIX: Extract patient_no so patientProfileHeader.php has the data it needs to render
$patient_no = '';
if ($visit_id > 0) {
    $qPat = $conn->query("SELECT patient_no FROM visit_master WHERE id = $visit_id LIMIT 1");
    if ($qPat && $r = $qPat->fetch_assoc()) {
        $patient_no = $r['patient_no'];
    }
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Clinical Dispensing Desk | 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; font-family: 'Inter', sans-serif; overflow: hidden; }
        .main-content-wrapper { margin-left: 260px; padding: 1.5rem 2rem; width: calc(100% - 260px); height: 100vh; display: flex; flex-direction: column;}
        @media (max-width: 992px) { .main-content-wrapper { margin-left: 0; width: 100%; overflow-y:auto; height: auto;} .split-layout { flex-direction:column; } .left-pane, .right-pane { width: 100% !important;} }
        
        .desk-header { display: flex; justify-content: space-between; align-items: center; margin-bottom: 20px;}
        .desk-header h4 { font-weight: 800; color: #0f172a; margin: 0; display:flex; align-items:center; letter-spacing: -0.5px; font-size: 22px;}
        .desk-header .back-btn { color: #64748b; font-size: 18px; margin-right: 15px; cursor: pointer; text-decoration: none; padding: 8px 12px; border-radius: 50%; background: #fff; border: 1px solid #e2e8f0; transition: 0.2s;}

        .split-layout { flex: 1; display: flex; gap: 25px; overflow: hidden; align-items: stretch;}
        .left-pane { flex: 0 0 450px; max-width: 450px; display: flex; flex-direction: column; overflow-y: auto; overflow-x: hidden; padding-right: 5px; background: transparent; }
        .right-pane { flex: 1; background: #fff; border-radius: 16px; border: 1px solid #e2e8f0; box-shadow: 0 4px 15px rgba(0,0,0,0.02); display: flex; flex-direction: column; overflow: hidden;}
        
        .nav-tabs { border-bottom: 1px solid #e2e8f0; padding: 0 20px; background: #f8fafc;}
        .nav-tabs .nav-link { color: #64748b; font-weight: 700; border: none; padding: 15px 20px; border-bottom: 3px solid transparent; margin-bottom: -1px; transition: 0.2s; cursor: pointer;}
        .nav-tabs .nav-link.active { color: #0284c7; border-bottom-color: #0284c7; background: transparent; }

        .rx-scroll-area { flex: 1; overflow-y: auto; padding: 20px; background: #f8fafc;}
        
        .accordion-item { border: 1px solid #e2e8f0; border-radius: 12px !important; overflow: hidden; margin-bottom: 15px; box-shadow: 0 2px 8px rgba(0,0,0,0.02); }
        .accordion-button { padding: 15px 20px; font-weight: 800; color: #0f172a; background-color: #fff; box-shadow: none !important;}
        .accordion-button:not(.collapsed) { background-color: #f8fafc; color: #0284c7;}
        .accordion-button::after { filter: invert(50%); }
        .accordion-body { background: #fff; padding: 20px; border-top: 1px solid #f1f5f9;}

        .rx-sig-badge { background: #f1f5f9; border: 1px solid #e2e8f0; color: #475569; font-weight: 700; font-size: 12px; padding: 4px 10px; border-radius: 6px;}
        .custom-checkbox { width: 24px; height: 24px; cursor: pointer; border-radius: 6px; border: 2px solid #cbd5e1; appearance: none; background: #fff; position: relative; margin-right: 15px; transition: 0.2s;}
        .custom-checkbox:checked { background: #10b981; border-color: #10b981; }
        .custom-checkbox:checked::after { content: '\f00c'; font-family: 'Font Awesome 6 Free'; font-weight: 900; color: white; position: absolute; left: 3px; top: 1px; font-size: 14px;}
        .prepay-lock-banner { background: #fffbeb; color: #b45309; border: 1px solid #fcd34d; padding: 15px 20px; border-radius: 8px; font-weight: 700; display: flex; align-items: center; gap: 15px; margin-bottom: 20px;}
        .select2-container { width: 100% !important; text-align: left; }
    </style>
</head>
<body>

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

<div class="main-content-wrapper">
    <div class="desk-header">
        <h4><a href="pendingDrugDispense.php" class="back-btn"><i class="fa-solid fa-arrow-left"></i></a> Clinical Dispensing Desk</h4>
        <div class="d-flex align-items-center gap-3 bg-white px-4 py-2 rounded-pill border shadow-sm">
            <span class="fw-bold text-muted small text-uppercase">Active Dispensary:</span>
            <select id="active_dispensary" class="form-select form-select-sm fw-bold border-0 text-primary p-0" style="width:200px; box-shadow:none; cursor:pointer; font-size:14px;"></select>
        </div>
    </div>

    <div class="split-layout">
        <!-- LEFT PANE -->
        <div class="left-pane" id="left_pane_container">
            <div class="bg-white p-3 rounded-4 shadow-sm border mb-3">
                <label class="small fw-bold text-muted mb-1 text-uppercase"><i class="fa-solid fa-search"></i> Switch Patient Desk</label>
                <select id="global_patient_search" class="form-select select2-search w-100"></select>
            </div>

            <?php if ($visit_id > 0): ?>
                <!-- CRITICAL FIX: Removed visibility:hidden so the header displays -->
                <div id="pat_card_ui" class="w-100 mb-4" style="display:flex; flex-direction:column; gap:15px;">
                    <?php include('../../dripend/statpages/patientProfileHeader.php'); ?>
                    <button type="button" class="btn btn-dark fw-bold py-3 shadow-sm w-100 mt-2" onclick="openAddRxModal()"><i class="fa-solid fa-plus-circle me-2"></i> Add Additional Prescription</button>
                </div>
            <?php else: ?>
                <div class="text-center py-5 text-muted h-100 d-flex flex-column align-items-center justify-content-center bg-white border rounded-4 shadow-sm w-100">
                    <i class="fa-solid fa-hospital-user fa-4x mb-3 opacity-25"></i>
                    <h5 class="fw-bold text-dark">No Patient Selected</h5>
                    <p class="small">Use the search bar above or return to the queue.</p>
                </div>
            <?php endif; ?>
        </div>

        <!-- RIGHT PANE: 3-TAB ENGINE -->
        <div class="right-pane">
            <ul class="nav nav-tabs" role="tablist">
                <li class="nav-item" role="presentation">
                    <button class="nav-link active" id="tab-unbilled" data-bs-toggle="tab" type="button" onclick="switchTab('unbilled')">
                        <i class="fa-solid fa-file-invoice me-2"></i>Unbilled (Review)
                    </button>
                </li>
                <li class="nav-item" role="presentation">
                    <button class="nav-link" id="tab-dispense" data-bs-toggle="tab" type="button" onclick="switchTab('dispense')">
                        <i class="fa-solid fa-hand-holding-medical me-2"></i>Pending Dispense
                    </button>
                </li>
                <li class="nav-item" role="presentation">
                    <button class="nav-link" id="tab-issued" data-bs-toggle="tab" type="button" onclick="switchTab('issued')">
                        <i class="fa-solid fa-clock-rotate-left me-2"></i>Issued History
                    </button>
                </li>
            </ul>

            <div class="rx-scroll-area" id="rx_container">
                <div class="text-center py-5 mt-5">
                    <i class="fa fa-spinner fa-spin fa-3x text-primary mb-3"></i>
                    <h5 class="fw-bold text-dark mt-3">Initializing Real-Time Engine...</h5>
                </div>
            </div>

            <div class="p-4 border-top bg-white" id="action_footer" style="display:none;"></div>
        </div>
    </div>
</div>

<!-- ========================================================================= -->
<!-- MODALS -->
<!-- ========================================================================= -->
<div class="modal fade" id="addRxModal" tabindex="-1" data-bs-backdrop="static">
    <div class="modal-dialog modal-dialog-centered modal-lg">
        <form id="frmAddRx" class="modal-content border-0 shadow-lg" style="border-radius:16px;">
            <div class="modal-header bg-dark text-white border-0 p-4">
                <h5 class="modal-title fw-bold m-0"><i class="fa-solid fa-plus-circle me-2"></i> Add Medication</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="add_prescription">
                <input type="hidden" name="visit_id" value="<?php echo $visit_id; ?>">
                <input type="hidden" id="add_rx_loc_id" name="location_id">

                <div class="mb-3">
                    <label class="small fw-bold text-dark mb-1">Search Master Drug Catalog <span class="text-danger">*</span></label>
                    <select name="service_id" id="add_rx_drug" class="form-select select2-modal" required></select>
                </div>
                <div class="row g-3 mb-3">
                    <div class="col-md-4"><label class="small fw-bold text-dark mb-1">Target Dose <span class="text-danger">*</span></label><input type="text" name="dose" id="add_rx_dose" class="form-control fw-bold border-secondary" required></div>
                    <div class="col-md-4"><label class="small fw-bold text-dark mb-1">Frequency <span class="text-danger">*</span></label><select name="frequency" id="add_rx_freq" class="form-select fw-bold border-secondary" required></select></div>
                    <div class="col-md-4"><label class="small fw-bold text-dark mb-1">Duration (Days) <span class="text-danger">*</span></label><input type="number" name="duration" id="add_rx_dur" class="form-control fw-bold border-secondary" value="1" min="1" required></div>
                    <div class="col-12 bg-white p-3 border rounded-3 text-end"><label class="small fw-bold text-success mb-1 text-uppercase">Final Physical Qty <span class="text-danger">*</span></label><input type="number" name="total_qty" id="add_rx_qty" class="form-control fw-bold border-success text-success bg-success bg-opacity-10 shadow-sm d-inline-block" style="font-size:20px; text-align:center; width: 120px;" required></div>
                    <div class="col-12"><label class="small fw-bold text-dark mb-1">Prescriber / Pharmacist Remarks</label><input type="text" name="remarks" id="add_rx_remarks" class="form-control border-secondary" placeholder="Optional notes..."></div>
                </div>
            </div>
            <div class="modal-footer bg-white border-0 p-3">
                <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="btnAddRxSubmit"><i class="fa-solid fa-paper-plane me-1"></i> Add to Queue</button>
            </div>
        </form>
    </div>
</div>

<div class="modal fade" id="editRxModal" tabindex="-1" data-bs-backdrop="static">
    <div class="modal-dialog modal-dialog-centered modal-lg">
        <form id="frmEditRx" class="modal-content border-0 shadow-lg" style="border-radius:16px;">
            <div class="modal-header bg-dark text-white border-0 p-4">
                <h5 class="modal-title fw-bold m-0"><i class="fa-solid fa-pen-to-square me-2"></i> Modify Prescription</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="update_prescription">
                <input type="hidden" name="rx_id" id="edit_rx_id">
                <div class="bg-white p-3 rounded-3 border border-secondary mb-3 shadow-sm text-center">
                    <span class="small text-muted fw-bold text-uppercase d-block">Target Medication</span>
                    <h5 class="fw-bold text-primary mb-0" id="edit_lbl_drug">Drug Name</h5>
                </div>
                <div class="row g-3 mb-3">
                    <div class="col-md-4"><label class="small fw-bold text-dark mb-1">Target Dose <span class="text-danger">*</span></label><input type="text" name="dose" id="edit_rx_dose" class="form-control fw-bold border-secondary" required></div>
                    <div class="col-md-4"><label class="small fw-bold text-dark mb-1">Frequency <span class="text-danger">*</span></label><select name="frequency" id="edit_rx_freq" class="form-select fw-bold border-secondary" required></select></div>
                    <div class="col-md-4"><label class="small fw-bold text-dark mb-1">Duration (Days) <span class="text-danger">*</span></label><input type="number" name="duration" id="edit_rx_dur" class="form-control fw-bold border-secondary" min="1" required></div>
                    <div class="col-12 bg-white p-3 border rounded-3 text-end"><label class="small fw-bold text-success mb-1 text-uppercase">Final Dispense Qty <span class="text-danger">*</span></label><input type="number" name="total_qty" id="edit_rx_qty" class="form-control fw-bold border-success text-success bg-success bg-opacity-10 shadow-sm d-inline-block" style="font-size:20px; text-align:center; width: 120px;" required></div>
                    <div class="col-12"><label class="small fw-bold text-dark mb-1">Modification Notes</label><input type="text" name="remarks" id="edit_rx_remarks" class="form-control border-secondary" placeholder="Reason for change..."></div>
                </div>
            </div>
            <div class="modal-footer bg-white border-0 p-3">
                <button type="button" class="btn btn-light border fw-bold px-4" data-bs-dismiss="modal">Cancel</button>
                <button type="submit" class="btn btn-dark fw-bold px-5 shadow-sm" id="btnEditRxSubmit"><i class="fa-solid fa-save me-1"></i> Update Dynamics</button>
            </div>
        </form>
    </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> const TARGET_VISIT_ID = <?php echo $visit_id; ?>; </script>
<script src="/rimax/application/assets/js/drugDispensary.js?v=<?= time() ?>"></script>

</body>
</html>