<?php
session_start();
$doc_root = $_SERVER['DOCUMENT_ROOT'];
require_once $doc_root . '/rimax/application/dripend/includes/db.php';

$visit_id = isset($_GET['visit_id']) ? intval($_GET['visit_id']) : 0;
$patient_no = '';
$payment_category = 'Cash'; 
$ccc_code = '';
$insurance_id = 0;
$insurance_no = '';

// Fetch all active corporate insurance types for the Walk-in Dropdown
$insurances = [];
$resIns = $conn->query("SELECT id, insurance_name FROM insurance_type WHERE is_active = 1 ORDER BY insurance_name ASC");
if ($resIns) {
    while($row = $resIns->fetch_assoc()){
        $insurances[] = $row;
    }
}

// If Consultation (Mode A), auto-fetch existing visit & patient insurance details
if ($visit_id > 0) {
    $stmt = $conn->prepare("
        SELECT v.patient_no, v.payment_category, v.ccc_code, p.other_insurance_id, p.other_insurance_no 
        FROM visit_master v 
        JOIN patient p ON v.patient_no = p.patient_no 
        WHERE v.id = ? LIMIT 1
    ");
    if ($stmt) {
        $stmt->bind_param("i", $visit_id);
        $stmt->execute();
        $res = $stmt->get_result();
        if ($row = $res->fetch_assoc()) {
            $patient_no = $row['patient_no'];
            $payment_category = $row['payment_category'];
            $ccc_code = $row['ccc_code'];
            $insurance_id = intval($row['other_insurance_id']);
            $insurance_no = $row['other_insurance_no'];
        }
        $stmt->close();
    }
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Clinical Service Requests - RiMax</title>
    
    <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/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://cdn.jsdelivr.net/npm/select2@4.1.0-rc.0/dist/css/select2.min.css" rel="stylesheet" />
    <link href="https://cdn.jsdelivr.net/npm/select2-bootstrap-5-theme@1.3.0/dist/select2-bootstrap-5-theme.min.css" rel="stylesheet" />
    
    <style>
        body { font-family: 'Inter', sans-serif; background-color: #f8fafc; color: #334155; }
        .main-content { margin-left: 260px; padding: 2rem; transition: all 0.3s ease; }
        @media (max-width: 992px) { .main-content { margin-left: 0; padding: 1rem; } }

        .pro-card { background: #ffffff; border: 1px solid #e2e8f0; border-radius: 12px; box-shadow: 0 10px 25px rgba(0,0,0,0.03); overflow: hidden; margin-bottom: 24px; }
        .pro-card-header { background: #ffffff; border-bottom: 1px solid #f1f5f9; padding: 20px 24px; display: flex; justify-content: space-between; align-items: center; }
        .pro-card-header h5 { font-weight: 800; color: #0f172a; margin: 0; display: flex; align-items: center; gap: 12px; }
        .icon-circle { display: flex; align-items: center; justify-content: center; width: 42px; height: 42px; border-radius: 10px; background: #eff6ff; color: #2563eb; font-size: 1.2rem; }

        .select2-container .select2-selection--single { height: 50px; padding: 10px 16px; font-size: 15px; border-radius: 8px; border: 2px solid #e2e8f0; }
        .select2-container--default .select2-selection--single:focus { border-color: #3b82f6; outline: none; }
        
        .table-cart th { background-color: #f8fafc; color: #64748b; font-weight: 700; text-transform: uppercase; font-size: 12px; border-bottom: 2px solid #e2e8f0; padding: 16px; }
        .table-cart td { padding: 16px; vertical-align: middle; border-bottom: 1px solid #f1f5f9; }
        
        .btn-pro { border-radius: 8px; padding: 12px 28px; font-weight: 700; transition: all 0.2s; }
        .btn-pro-primary { background: #2563eb; border: none; color: white; }
        .btn-pro-primary:hover:not(:disabled) { background: #1d4ed8; transform: translateY(-2px); box-shadow: 0 8px 20px rgba(37, 99, 235, 0.25); }
    </style>
</head>
<body>
    
    <?php 
    $sidebar_path = $doc_root . '/rimax/application/dripend/statpages/sidebar.php';
    if(file_exists($sidebar_path)) { include_once $sidebar_path; }
    ?>

    <div class="main-content">
        
        <!-- WALK-IN MODE: PATIENT & VISIT SETUP -->
        <div id="walkinSetupContainer" style="<?php echo $visit_id > 0 ? 'display:none;' : ''; ?>">
            
            <div class="pro-card" id="patientSelectionCard">
                <div class="pro-card-header">
                    <h5><div class="icon-circle"><i class="fas fa-walking"></i></div> Step 1: Select Patient</h5>
                </div>
                <div class="card-body p-4">
                    <select id="walkinPatientSearch" class="form-select" style="width: 100%;"></select>
                </div>
            </div>

            <div class="pro-card" id="visitConfigCard" style="display:none;">
                <div class="pro-card-header">
                    <h5><div class="icon-circle"><i class="fas fa-file-invoice-dollar"></i></div> Step 2: Visit & Billing Setup</h5>
                </div>
                <div class="card-body p-4">
                    <div class="row g-3 align-items-end">
                        
                        <div class="col-md-2">
                            <label class="fw-bold mb-2 text-dark">Category</label>
                            <select id="visitPaymentCategory" class="form-select" style="height: 50px; border: 2px solid #e2e8f0; border-radius: 8px;">
                                <option value="Cash">Cash</option>
                                <option value="NHIS">NHIS</option>
                                <option value="Corporate">Corporate</option>
                            </select>
                        </div>
                        
                        <!-- NHIS CCC Code Section -->
                        <div class="col-md-7" id="nhisCCCContainer" style="display: none;">
                            <label class="fw-bold mb-2 text-dark">NHIS Claim Check Code (CCC)</label>
                            <div class="input-group">
                                <input type="text" id="visitCCC" class="form-control fw-bold text-primary" placeholder="Enter or Generate CCC..." style="height: 50px; border: 2px solid #e2e8f0;">
                                <button class="btn btn-outline-primary fw-bold px-4" type="button" id="btnGenerateCCC">
                                    <i class="fas fa-sync-alt me-2"></i> Fetch CCC
                                </button>
                            </div>
                        </div>

                        <!-- Corporate Insurance Section -->
                        <div class="col-md-4" id="corpProviderContainer" style="display: none;">
                            <label class="fw-bold mb-2 text-dark">Provider</label>
                            <select id="visitCorpProvider" class="form-select fw-bold text-primary" style="height: 50px; border: 2px solid #e2e8f0;">
                                <option value="">-- Choose Provider --</option>
                                <?php foreach($insurances as $ins): ?>
                                    <option value="<?php echo $ins['id']; ?>"><?php echo htmlspecialchars($ins['insurance_name']); ?></option>
                                <?php endforeach; ?>
                            </select>
                        </div>
                        
                        <div class="col-md-3" id="corpPolicyContainer" style="display: none;">
                            <label class="fw-bold mb-2 text-dark">Policy Number</label>
                            <input type="text" id="visitCorpNo" class="form-control fw-bold text-primary" placeholder="Policy No..." style="height: 50px; border: 2px solid #e2e8f0;">
                        </div>

                        <div class="col-md-3">
                            <button type="button" class="btn btn-pro btn-pro-primary w-100" style="height: 50px;" id="btnProceedToCart">
                                Open Cart <i class="fas fa-arrow-right ms-2"></i>
                            </button>
                        </div>
                    </div>
                </div>
            </div>

        </div>

        <!-- PATIENT HEADER -->
        <div id="patientHeaderContainer">
            <?php 
            if ($patient_no) {
                $header_path = $doc_root . '/rimax/application/dripend/statpages/patientProfileHeader.php';
                if(file_exists($header_path)) { include_once $header_path; }
            }
            ?>
        </div>

        <!-- THE CLINICAL ORDER CART -->
        <div class="pro-card" id="clinicalCartCard" style="<?php echo empty($patient_no) ? 'display:none;' : ''; ?>">
            <div class="pro-card-header">
                <h5><div class="icon-circle"><i class="fas fa-microscope"></i></div> Clinical Order Cart</h5>
                <div class="text-end">
                    <span class="badge bg-light text-primary border border-primary px-3 py-2 fw-bold me-2" id="visitBadge">
                        <?php echo $visit_id ? '# Visit ID: ' . htmlspecialchars((string)$visit_id) : 'New Diagnostic Visit'; ?>
                    </span>
                    <span class="badge bg-success text-white px-3 py-2 fw-bold shadow-sm" id="paymentBadge">
                        <i class="fas fa-wallet me-1"></i> Payer: <?php echo htmlspecialchars($payment_category); ?>
                    </span>
                </div>
            </div>
            
            <div class="card-body p-4">
                <div class="mb-4">
                    <select id="serviceSearch" class="form-select" data-placeholder="Search catalog for procedures, labs, imaging..."></select>
                </div>

                <div class="table-responsive border rounded-3">
                    <table class="table table-hover table-cart mb-0">
                        <thead>
                            <tr>
                                <th width="30%">Service Name</th>
                                <th width="15%">Priority</th>
                                <th width="15%" class="text-end">Patient Copay / Amount (GHS)</th>
                                <th width="30%">Notes / Justification</th>
                                <th width="10%" class="text-center">Action</th>
                            </tr>
                        </thead>
                        <tbody id="cartBody">
                            <tr id="emptyCartRow">
                                <td colspan="5" class="text-center py-5">
                                    <i class="fas fa-shopping-basket fa-3x text-muted mb-3" style="opacity: 0.3;"></i>
                                    <h6 class="fw-bold text-secondary">Your request cart is empty</h6>
                                </td>
                            </tr>
                        </tbody>
                        <tfoot id="cartFooter" style="display:none; background: #f8fafc;">
                            <tr>
                                <td colspan="2" class="text-end fw-bold text-dark fs-5">Total Payable Now:</td>
                                <td class="text-end fw-bold text-danger fs-5" id="cartTotalDisplay">GHS 0.00</td>
                                <td colspan="2"></td>
                            </tr>
                        </tfoot>
                    </table>
                </div>

                <div class="text-end mt-4">
                    <button type="button" class="btn btn-pro btn-pro-primary" id="btnSubmitOrders" disabled>
                        <i class="fas fa-paper-plane me-2"></i> Route Orders & Save Bill
                    </button>
                </div>
            </div>
        </div>
    </div>

    <script src="https://code.jquery.com/jquery-3.6.0.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/sweetalert2@11"></script>
    
    <script>
        let currentVisitId = "<?php echo htmlspecialchars((string)$visit_id); ?>";
        let currentPatientNo = "<?php echo htmlspecialchars((string)$patient_no); ?>";
        let currentPaymentCat = "<?php echo htmlspecialchars((string)$payment_category); ?>";
        let currentCCC = "<?php echo htmlspecialchars((string)$ccc_code); ?>";
        let currentInsuranceId = "<?php echo intval($insurance_id); ?>";
        let currentCorpNo = "<?php echo htmlspecialchars((string)$insurance_no); ?>";
    </script>
    <script src="/rimax/application/assets/js/serviceRequest.js"></script>
</body>
</html>