const apiDashboard = '/rimax/application/dripend/includes/ipd/processIpdDashboard.php';
let occupancyChartInstance = null;

$(document).ready(function() {
    fetchDashboardData();
});

window.fetchDashboardData = function() {
    let btn = $('button[onclick="fetchDashboardData()"]');
    let orig = btn.html();
    btn.prop('disabled', true).html('<i class="fa-solid fa-spinner fa-spin me-2"></i> Refreshing...');

    $.post(apiDashboard, { action: 'fetch_dashboard_data' }, function(res) {
        btn.prop('disabled', false).html(orig);
        if(res.status === 'success') {
            const data = res.data;

            // 1. Render KPIs
            $('#kpi_active').text(data.kpis.active_admissions);
            $('#kpi_available').text(data.kpis.available_beds);
            $('#kpi_total').text(data.kpis.total_beds);
            $('#kpi_pending').text(data.kpis.pending_discharges);
            $('#kpi_housekeeping').text(data.kpis.housekeeping_beds);
            $('#kpi_admitted_today').text(data.kpis.admitted_today);
            $('#kpi_discharged_today').text(data.kpis.discharged_today);

            // 2. Render Chart
            renderOccupancyChart(data.ward_occupancy);

            // 3. Render Recent Admissions Table
            renderRecentAdmissions(data.recent_admissions);
        } else {
            console.error("Dashboard Error:", res.message);
        }
    }, 'json').fail(function() {
        btn.prop('disabled', false).html(orig);
        console.error("Network Error: Could not reach the dashboard API.");
    });
};

function renderOccupancyChart(chartData) {
    const ctx = document.getElementById('wardOccupancyChart').getContext('2d');
    
    if(occupancyChartInstance) {
        occupancyChartInstance.destroy();
    }

    occupancyChartInstance = new Chart(ctx, {
        type: 'bar',
        data: {
            labels: chartData.labels,
            datasets: [
                {
                    label: 'Occupied / Reserved Beds',
                    data: chartData.occupied,
                    backgroundColor: '#0ea5e9',
                    borderRadius: 4,
                    barPercentage: 0.6
                },
                {
                    label: 'Vacant Beds',
                    data: chartData.vacant,
                    backgroundColor: '#cbd5e1',
                    borderRadius: 4,
                    barPercentage: 0.6
                }
            ]
        },
        options: {
            responsive: true,
            maintainAspectRatio: false,
            scales: {
                x: { stacked: true, grid: { display: false } },
                y: { stacked: true, beginAtZero: true, border: { dash: [4, 4] } }
            },
            plugins: {
                legend: { position: 'top', labels: { usePointStyle: true, font: { family: 'Inter', weight: 'bold' } } },
                tooltip: { backgroundColor: 'rgba(15, 23, 42, 0.9)', titleFont: { family: 'Inter' }, bodyFont: { family: 'Inter' } }
            }
        }
    });
}

function renderRecentAdmissions(data) {
    let tbody = $('#tblRecentAdmissions tbody');
    tbody.empty();

    if(data.length === 0) {
        tbody.html('<tr><td colspan="6" class="text-center text-muted py-4">No recent admissions found.</td></tr>');
        return;
    }

    data.forEach(r => {
        let statusBadge = '';
        if(r.status === 'Pending Discharge') statusBadge = `<span class="badge bg-warning text-dark fw-bold px-2 py-1">Pending Discharge</span>`;
        else if(r.status === 'Transferred') statusBadge = `<span class="badge bg-info text-dark fw-bold px-2 py-1">Transferred</span>`;
        else if(r.status === 'Discharged') statusBadge = `<span class="badge bg-success fw-bold px-2 py-1">Discharged</span>`;
        else statusBadge = `<span class="badge bg-primary fw-bold px-2 py-1">Admitted</span>`;

        let tr = `
            <tr>
                <td class="fw-bold text-muted">${r.date_fmt}</td>
                <td>
                    <div class="d-flex flex-column">
                        <span class="fw-bold text-primary" style="font-size:14px;">${r.patient_name}</span>
                        <span class="text-muted small fw-bold">${r.patient_no}</span>
                    </div>
                </td>
                <td><b class="text-dark"><i class="fa-solid fa-bed text-muted me-2"></i> ${r.ward_name} (Bed ${r.bed_number})</b></td>
                <td><span class="text-dark fw-bold"><i class="fa-solid fa-user-doctor text-muted me-1"></i> Dr. ${r.doc_name || 'Unassigned'}</span></td>
                <td>${statusBadge}</td>
                <td class="text-end">
                    <a href="patientIPDRecords.php?visit_id=${r.visit_master_id}" class="btn btn-sm btn-dark fw-bold px-3 py-1 shadow-sm">Command Center</a>
                </td>
            </tr>
        `;
        tbody.append(tr);
    });
}