<?php
// =========================================================================
// UNIVERSAL SMART PATIENT HEADER (COMPACT PRO DESIGN)
// Features: Light Blue Theme, Reduced Height, Interactive Saving
// Bulletproofed: Auto-resolves Ward Admissions, OPD, and Direct Walk-ins
// =========================================================================

if (!isset($conn)) {
    require_once dirname(__DIR__, 2) . '/dripend/includes/db.php';
}

$target_patient_no = null;
if (isset($patient_no) && !empty($patient_no)) {
    $target_patient_no = $patient_no; 
} elseif (isset($_GET['patient_no']) && !empty($_GET['patient_no'])) {
    $target_patient_no = trim($_GET['patient_no']);
} elseif (isset($_GET['patient_id']) && !empty($_GET['patient_id'])) {
    $target_patient_no = trim($_GET['patient_id']);
}

// -------------------------------------------------------------------------
// 1. CONTEXT ENGINE: Resolve Visit ID to Patient & Determine Location
// -------------------------------------------------------------------------
$current_visit_id = $visit_id ?? ($_GET['visit_id'] ?? 0);
$encounter_context = "Direct Prescription / Walk-In";

if (!$target_patient_no && $current_visit_id > 0) {
    try {
        $vq = $conn->query("SELECT patient_no, nhis_service_type FROM visit_master WHERE id = " . (int)$current_visit_id);
        if ($vq && $vr = $vq->fetch_assoc()) {
            $target_patient_no = $vr['patient_no'];
            $encounter_context = "OPD Consult"; 
            if ($vr['nhis_service_type'] === 'In-patient') {
                $encounter_context = "IPD Admission";
            }
        }
    } catch (Throwable $e) {}
}

// -------------------------------------------------------------------------
// 2. PATIENT DATA FETCH
// -------------------------------------------------------------------------
if ($target_patient_no && !isset($patient_data_loaded)) {
    try {
        $stmt = $conn->prepare("
            SELECT 
                p.*,
                COALESCE(pr.prefix_name, '') AS prefix_name,
                COALESCE(g.gender_name, 'NA') AS gender_name,
                COALESCE(i.insurance_name, 'Private Cash') AS insurance_name,
                COALESCE(er.relation_name, 'Not Specified') AS emergency_relation,
                TIMESTAMPDIFF(YEAR, p.dob, CURDATE()) AS age,
                
                -- Outstanding Balance Calculation
                COALESCE((SELECT SUM(balance_due) FROM patient_invoices WHERE patient_no = p.patient_no AND status IN ('Unpaid', 'Partially Paid')), 0.00) AS outstanding_balance, 
                
                -- Last Visit Fetch
                (SELECT CONCAT(visit_date, ' ', visit_time) FROM visit_master WHERE patient_no = p.patient_no AND status != 'Cancelled' ORDER BY visit_date DESC, visit_time DESC LIMIT 1) AS last_visit,
                
                CASE 
                    WHEN p.nhis_no IS NOT NULL AND p.nhis_no != '' THEN 'NHIS Subscriber'
                    WHEN p.other_insurance_id IS NOT NULL THEN COALESCE(i.insurance_name, 'Corporate')
                    ELSE 'Private Cash'
                END AS membership_type

            FROM patient p
            LEFT JOIN prefix pr ON p.prefix_id = pr.id
            LEFT JOIN gender g ON p.gender_id = g.id
            LEFT JOIN insurance_type i ON p.other_insurance_id = i.id
            LEFT JOIN emergency_relation er ON p.emergency_relation_id = er.id
            WHERE p.patient_no = ? LIMIT 1
        ");
        
        if ($stmt) {
            $stmt->bind_param("s", $target_patient_no);
            $stmt->execute();
            $patient = $stmt->get_result()->fetch_assoc();
            $stmt->close();
            $patient_data_loaded = true;
        }
    } catch (Throwable $e) {
        // Silently catch missing table/column errors during development
        $patient = null;
    }
}

// -------------------------------------------------------------------------
// 3. WARD / VIP ROOM CHECK
// -------------------------------------------------------------------------
if (isset($patient_data_loaded) && $patient_data_loaded && $current_visit_id > 0) {
    try {
        $ward_q = $conn->query("
            SELECT w.ward_name 
            FROM ipd_admission_episodes e 
            JOIN ipd_wards w ON e.ward_id = w.id 
            WHERE e.visit_master_id = " . (int)$current_visit_id . " 
            ORDER BY e.id DESC LIMIT 1
        ");
        if ($ward_q && $ward_res = $ward_q->fetch_assoc()) {
            $encounter_context = "Admitted: " . $ward_res['ward_name'];
        }
    } catch (Throwable $e) {}
}

// -------------------------------------------------------------------------
// 4. GRACEFUL FALLBACK (No red error boxes)
// -------------------------------------------------------------------------
if (!isset($patient) || empty($patient)) {
    $patient = [
        'patient_no' => $target_patient_no ?: 'WALK-IN',
        'prefix_name' => '',
        'first_name' => 'Unregistered',
        'middle_name' => '',
        'last_name' => 'Encounter',
        'dob' => date('Y-m-d'),
        'age' => '0',
        'gender_name' => 'Unknown',
        'mobile' => 'N/A',
        'membership_type' => 'Cash / Walk-in',
        'ghana_card_no' => 'N/A',
        'emergency_name' => 'N/A',
        'emergency_number' => 'N/A',
        'emergency_relation' => 'N/A',
        'emergency_address' => 'N/A',
        'blood_group' => 'Unknown',
        'allergies' => 'None',
        'medical_conditions' => 'None',
        'outstanding_balance' => 0.00,
        'last_visit' => null
    ];
}

$full_name = trim($patient['prefix_name'] . ' ' . $patient['first_name'] . ' ' . $patient['middle_name'] . ' ' . $patient['last_name']);
$initials = strtoupper(substr($patient['first_name'], 0, 1) . substr($patient['last_name'], 0, 1));
$last_visit_display = !empty($patient['last_visit']) ? date('d M Y, h:i A', strtotime($patient['last_visit'])) : 'No Previous Visits';
$has_balance = ($patient['outstanding_balance'] > 0);
?>

<style>
    .ph-card {
        background: linear-gradient(to bottom, #f8fafc, #eff6ff);
        border-radius: 12px;
        box-shadow: 0 4px 15px rgba(37, 99, 235, 0.08);
        border: 1px solid #bfdbfe;
        border-top: 4px solid #3b82f6; 
        font-family: 'Inter', sans-serif;
        margin-bottom: 20px;
        position: relative;
    }

    .ph-body { padding: 16px 24px; }

    /* Top Identity Row */
    .ph-identity-row {
        display: flex;
        justify-content: space-between;
        align-items: center;
        margin-bottom: 16px;
        padding-bottom: 16px;
        border-bottom: 1px dashed #bfdbfe;
    }

    .ph-id-left { display: flex; align-items: center; gap: 16px; }

    .ph-avatar-circle {
        width: 65px; height: 65px; flex-shrink: 0;
        border-radius: 50%; background-color: #ffffff;
        color: #1e40af; display: flex; align-items: center; justify-content: center;
        font-size: 24px; font-weight: 800; letter-spacing: 1px;
        border: 2px solid #bfdbfe;
    }

    .ph-name { font-size: 22px; font-weight: 800; color: #0f172a; margin: 0 0 4px 0; display: flex; align-items: center; flex-wrap: wrap; gap: 10px; }
    .ph-id-badge { font-size: 12px; font-weight: 700; color: #1d4ed8; background: #ffffff; padding: 4px 12px; border-radius: 20px; border: 1px solid #bfdbfe; }
    .ph-loc-badge { font-size: 12px; font-weight: 700; color: #0f766e; background: #ecfdf5; padding: 4px 12px; border-radius: 20px; border: 1px solid #a7f3d0; }
    .ph-last-visit { font-size: 12px; font-weight: 600; color: #3b82f6; width: 100%;}

    .ph-id-right { position: relative; }
    .ph-balance-box {
        background: #ffffff; padding: 8px 16px; border-radius: 10px; text-align: center;
        border: 1px solid <?php echo $has_balance ? '#fca5a5' : '#a7f3d0'; ?>;
        color: <?php echo $has_balance ? '#dc2626' : '#059669'; ?>;
        min-width: 150px;
    }
    .ph-balance-lbl { font-size: 9px; font-weight: 800; text-transform: uppercase; color: #64748b; margin-bottom: 2px; }
    .ph-balance-val { font-size: 15px; font-weight: 800; }

    .ph-collapse-btn {
        position: absolute; top: -30px; right: 0; width: 28px; height: 28px; border-radius: 50%; background: #ffffff; border: 1px solid #bfdbfe; color: #1e40af; display: flex; align-items: center; justify-content: center; cursor: pointer;
    }

    /* Sections */
    .ph-sections-grid { display: grid; grid-template-columns: repeat(3, 1fr); gap: 16px; transition: max-height 0.3s; overflow: hidden; }
    .ph-card.collapsed .ph-sections-grid { display: none; }

    .ph-section { background: #ffffff; border-radius: 10px; padding: 14px; border: 1px solid #e2e8f0; }
    .ph-section-title { font-size: 11px; font-weight: 800; color: #64748b; text-transform: uppercase; letter-spacing: 0.5px; margin-bottom: 12px; display: flex; align-items: center; justify-content: space-between; border-bottom: 1px solid #f1f5f9; padding-bottom: 6px; }

    .ph-data-row { display: flex; justify-content: space-between; margin-bottom: 6px; font-size: 12px; }
    .ph-data-lbl { color: #64748b; font-weight: 600; }
    .ph-data-val { color: #1e293b; font-weight: 700; text-align: right; }

    .ph-pill { width: 100%; text-align: left; padding: 8px 12px; border-radius: 6px; font-size: 12px; font-weight: 700; cursor: pointer; display: flex; justify-content: space-between; margin-bottom: 8px; border: 1px solid transparent; }
    .ph-pill:hover { filter: brightness(0.95); }
    .ph-pill-blood { background: #fef2f2; color: #b91c1c; border-color: #fecaca; }
    .ph-pill-allergy { background: #fffbeb; color: #b45309; border-color: #fde68a; }
    .ph-pill-condition { background: #eff6ff; color: #1d4ed8; border-color: #bfdbfe; }

    /* Footer */
    .ph-footer { padding: 12px 24px; background: #ffffff; border-top: 1px solid #bfdbfe; border-radius: 0 0 12px 12px; display: flex; gap: 10px; align-items: center; }
    .ph-btn { padding: 8px 16px; border-radius: 6px; font-size: 13px; font-weight: 700; cursor: pointer; border: none; text-decoration: none; display: inline-flex; align-items: center; gap: 6px; }
    .ph-btn-dark { background: #0f172a; color: white; }
    .ph-btn-green { background: #059669; color: white; }
    .ph-btn-blue { background: #2563eb; color: white; }
    .ph-btn-outline { background: white; color: #1e40af; border: 1px solid #bfdbfe; margin-left: auto; }

    .edit-modal-overlay { display: none; position: fixed; inset: 0; background: rgba(15, 23, 42, 0.6); z-index: 9999; align-items: center; justify-content: center; }
    .edit-modal-overlay.open { display: flex; }
    .edit-modal-box { background: #fff; width: 400px; padding: 24px; border-radius: 12px; }
    .edit-modal-box textarea { width: 100%; border: 1px solid #cbd5e1; border-radius: 6px; padding: 10px; min-height: 80px; margin-bottom: 15px; }

    @media (max-width: 768px) {
        .ph-identity-row { flex-direction: column; text-align: center; gap: 16px; }
        .ph-name { justify-content: center; }
        .ph-sections-grid { grid-template-columns: 1fr; }
        .ph-footer { flex-direction: column; }
        .ph-btn, .ph-btn-outline { width: 100%; justify-content: center; margin-left: 0; }
    }
</style>

<div class="ph-card" id="proPatientHeader">
    <div class="ph-body">
        
        <!-- Identity Row -->
        <div class="ph-identity-row">
            <div class="ph-id-left">
                <div class="ph-avatar-circle"><?php echo htmlspecialchars($initials); ?></div>
                <div>
                    <h2 class="ph-name">
                        <?php echo htmlspecialchars($full_name); ?>
                        <div class="ph-id-badge"># <?php echo htmlspecialchars($patient['patient_no']); ?></div>
                        <div class="ph-loc-badge"><i class="fas fa-hospital-user me-1"></i> <?php echo htmlspecialchars($encounter_context); ?></div>
                    </h2>
                    <div class="ph-last-visit"><i class="far fa-clock"></i> Last Visit: <?php echo htmlspecialchars($last_visit_display); ?></div>
                </div>
            </div>

            <div class="ph-id-right">
                <button class="ph-collapse-btn" onclick="toggleProHeader()"><i class="fas fa-chevron-up" id="phCollapseIcon"></i></button>
                <div class="ph-balance-box">
                    <div class="ph-balance-lbl">Outstanding Balance</div>
                    <div class="ph-balance-val">GHS <?php echo number_format((float)$patient['outstanding_balance'], 2); ?></div>
                </div>
            </div>
        </div>

        <!-- Sections Grid -->
        <div class="ph-sections-grid">
            
            <div class="ph-section">
                <div class="ph-section-title"><span><i class="fas fa-user text-primary me-1"></i> Core Demographics</span></div>
                <div class="ph-data-row"><span class="ph-data-lbl">DOB / Age</span><span class="ph-data-val"><?php echo date('d M, Y', strtotime($patient['dob'])); ?> (<?php echo htmlspecialchars($patient['age']); ?>y)</span></div>
                <div class="ph-data-row"><span class="ph-data-lbl">Gender</span><span class="ph-data-val"><?php echo htmlspecialchars($patient['gender_name']); ?></span></div>
                <div class="ph-data-row"><span class="ph-data-lbl">Contact</span><span class="ph-data-val"><?php echo htmlspecialchars($patient['mobile']); ?></span></div>
                <div class="ph-data-row"><span class="ph-data-lbl">Payer Type</span><span class="ph-data-val highlight"><?php echo htmlspecialchars($patient['membership_type']); ?></span></div>
                <div class="ph-data-row"><span class="ph-data-lbl">Ghana Card</span><span class="ph-data-val"><?php echo !empty($patient['ghana_card_no']) ? htmlspecialchars($patient['ghana_card_no']) : 'N/A'; ?></span></div>
            </div>

            <div class="ph-section">
                <div class="ph-section-title"><span><i class="fas fa-truck-medical text-danger me-1"></i> Emergency Details</span></div>
                <div class="ph-data-row"><span class="ph-data-lbl">Name</span><span class="ph-data-val text-truncate" style="max-width: 130px;"><?php echo !empty($patient['emergency_name']) ? htmlspecialchars($patient['emergency_name']) : 'N/A'; ?></span></div>
                <div class="ph-data-row"><span class="ph-data-lbl">Phone</span><span class="ph-data-val text-danger"><?php echo !empty($patient['emergency_number']) ? htmlspecialchars($patient['emergency_number']) : 'N/A'; ?></span></div>
                <div class="ph-data-row"><span class="ph-data-lbl">Relation</span><span class="ph-data-val"><?php echo htmlspecialchars($patient['emergency_relation']); ?></span></div>
                <div class="mt-2 pt-2 border-top" style="font-size: 11px; color: #64748b;">
                    <i class="fas fa-map-marker-alt"></i> <?php echo !empty($patient['emergency_address']) ? htmlspecialchars($patient['emergency_address']) : 'No address provided'; ?>
                </div>
            </div>

            <div class="ph-section">
                <div class="ph-section-title"><span><i class="fas fa-heart-pulse text-success me-1"></i> Clinical Alerts</span> <span style="font-size:8px;">CLICK TO EDIT</span></div>
                <button type="button" class="ph-pill ph-pill-blood" onclick="openEditModal('blood_group', 'Blood Group', '<?php echo addslashes($patient['blood_group']); ?>')">
                    <span><i class="fas fa-droplet"></i> Blood: <span id="lbl_blood_group"><?php echo htmlspecialchars($patient['blood_group']); ?></span></span>
                </button>
                <button type="button" class="ph-pill ph-pill-allergy" onclick="openEditModal('allergies', 'Allergies', '<?php echo addslashes($patient['allergies']); ?>')">
                    <span><i class="fas fa-triangle-exclamation"></i> Allergies: <span id="lbl_allergies"><?php echo htmlspecialchars($patient['allergies']); ?></span></span>
                </button>
                <button type="button" class="ph-pill ph-pill-condition" onclick="openEditModal('medical_conditions', 'Conditions', '<?php echo addslashes($patient['medical_conditions']); ?>')">
                    <span><i class="fas fa-stethoscope"></i> Conditions: <span id="lbl_medical_conditions"><?php echo htmlspecialchars($patient['medical_conditions']); ?></span></span>
                </button>
            </div>

        </div>
    </div>

    <div class="ph-footer">
        <button class="ph-btn ph-btn-dark"><i class="fas fa-print"></i> Print Patient Profile</button>
        <a href="../patient/ViewPatientRecord.php?patient_id=<?php echo urlencode($patient['patient_no']); ?>" class="ph-btn ph-btn-green"><i class="fas fa-folder-open"></i> View Clinical Folder</a>
        <a href="../appointment/add_appointment.php?patient_id=<?php echo urlencode($patient['patient_no']); ?>" class="ph-btn ph-btn-blue"><i class="fas fa-calendar-plus"></i> Book Appointment</a>
        <button class="ph-btn ph-btn-outline">Quick View</button>
    </div>
</div>

<!-- Edit Modal -->
<div class="edit-modal-overlay" id="clinicalEditModal">
    <div class="edit-modal-box">
        <h5 id="editModalTitle" class="fw-bold text-dark">Update Record</h5>
        <p class="text-muted small">Changes reflect instantly.</p>
        <input type="hidden" id="editFieldKey">
        <textarea id="editFieldValue"></textarea>
        <div class="d-flex justify-content-end gap-2">
            <button class="btn btn-light border btn-sm fw-bold" onclick="closeEditModal()">Cancel</button>
            <button class="btn btn-primary btn-sm fw-bold" id="btnSaveAlert" onclick="saveClinicalAlert()">Save Changes</button>
        </div>
    </div>
</div>

<script>
const currentPatientNo = "<?php echo htmlspecialchars($patient['patient_no']); ?>";

function toggleProHeader() {
    const card = document.getElementById('proPatientHeader');
    const icon = document.getElementById('phCollapseIcon');
    card.classList.toggle('collapsed');
    icon.className = card.classList.contains('collapsed') ? 'fas fa-chevron-down' : 'fas fa-chevron-up';
}

function openEditModal(key, title, val) {
    document.getElementById('editFieldKey').value = key;
    document.getElementById('editModalTitle').innerText = "Update " + title;
    document.getElementById('editFieldValue').value = val;
    document.getElementById('clinicalEditModal').classList.add('open');
}

function closeEditModal() {
    document.getElementById('clinicalEditModal').classList.remove('open');
}

function saveClinicalAlert() {
    const key = document.getElementById('editFieldKey').value;
    const val = document.getElementById('editFieldValue').value;
    const btn = document.getElementById('btnSaveAlert');
    
    btn.innerHTML = 'Saving...';
    btn.disabled = true;

    // Use absolute path to guarantee the fetch finds the file from anywhere
    fetch('/rimax/application/dripend/includes/updateClinicalCondition.php', {
        method: 'POST',
        headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
        body: `patient_no=${encodeURIComponent(currentPatientNo)}&field=${encodeURIComponent(key)}&value=${encodeURIComponent(val)}`
    })
    .then(res => res.json())
    .then(data => {
        if (data.status === 'success') {
            document.getElementById('lbl_' + key).innerText = val;
            closeEditModal();
        } else {
            alert('Error: ' + data.message);
        }
    })
    .catch(err => alert('A network error occurred while saving.'))
    .finally(() => {
        btn.innerHTML = 'Save Changes';
        btn.disabled = false;
    });
}
</script>