<?php
session_start();
ini_set('display_errors', 0);
error_reporting(E_ALL);
ob_start();

require_once '../db.php';
header('Content-Type: application/json');

$action = $_POST['action'] ?? '';

try {
    if ($action === 'fetch_dashboard_data') {
        $date_today = date('Y-m-d');
        
        $data = [
            'kpis' => [
                'active_admissions' => 0,
                'available_beds' => 0,
                'total_beds' => 0,
                'pending_discharges' => 0,
                'admitted_today' => 0,
                'discharged_today' => 0,
                'housekeeping_beds' => 0
            ],
            'ward_occupancy' => [
                'labels' => [],
                'occupied' => [],
                'vacant' => []
            ],
            'recent_admissions' => []
        ];

        // 1. Fetch Core KPIs
        $qEp = $conn->query("SELECT 
            SUM(CASE WHEN status IN ('Admitted', 'Transferred') THEN 1 ELSE 0 END) as active,
            SUM(CASE WHEN status = 'Pending Discharge' THEN 1 ELSE 0 END) as pending,
            SUM(CASE WHEN DATE(admission_date) = '$date_today' THEN 1 ELSE 0 END) as admit_today,
            SUM(CASE WHEN status = 'Discharged' AND DATE(discharge_date) = '$date_today' THEN 1 ELSE 0 END) as disc_today
            FROM ipd_admission_episodes");
        if ($qEp && $row = $qEp->fetch_assoc()) {
            $data['kpis']['active_admissions'] = (int)$row['active'];
            $data['kpis']['pending_discharges'] = (int)$row['pending'];
            $data['kpis']['admitted_today'] = (int)$row['admit_today'];
            $data['kpis']['discharged_today'] = (int)$row['disc_today'];
        }

        $qBeds = $conn->query("SELECT 
            COUNT(id) as total,
            SUM(CASE WHEN bed_status = 'Available' THEN 1 ELSE 0 END) as available,
            SUM(CASE WHEN bed_status = 'Housekeeping' THEN 1 ELSE 0 END) as housekeeping
            FROM ipd_beds WHERE is_active = 1");
        if ($qBeds && $row = $qBeds->fetch_assoc()) {
            $data['kpis']['total_beds'] = (int)$row['total'];
            $data['kpis']['available_beds'] = (int)$row['available'];
            $data['kpis']['housekeeping_beds'] = (int)$row['housekeeping'];
        }

        // 2. Fetch Ward Occupancy for Charting
        $qWard = $conn->query("SELECT 
            w.ward_name, 
            COUNT(b.id) as total_beds,
            SUM(CASE WHEN b.bed_status = 'Available' THEN 1 ELSE 0 END) as vacant_beds,
            SUM(CASE WHEN b.bed_status IN ('Occupied', 'Reserved') THEN 1 ELSE 0 END) as occupied_beds
            FROM ipd_wards w
            LEFT JOIN ipd_beds b ON w.id = b.ward_id AND b.is_active = 1
            WHERE w.is_active = 1
            GROUP BY w.id ORDER BY w.ward_name ASC");
        
        if ($qWard) {
            while($w = $qWard->fetch_assoc()) {
                $data['ward_occupancy']['labels'][] = $w['ward_name'];
                $data['ward_occupancy']['occupied'][] = (int)$w['occupied_beds'];
                $data['ward_occupancy']['vacant'][] = (int)$w['vacant_beds'];
            }
        }

        // 3. Fetch Recent Admissions (Last 10)
        $qRecent = $conn->query("SELECT e.visit_master_id, e.patient_no, e.admission_date, e.status, 
                       p.first_name, p.last_name, w.ward_name, b.bed_number,
                       CONCAT(s.first_name, ' ', s.last_name) as doc_name
                FROM ipd_admission_episodes e
                JOIN patient p ON e.patient_no = p.patient_no
                JOIN ipd_wards w ON e.ward_id = w.id
                JOIN ipd_beds b ON e.bed_id = b.id
                LEFT JOIN staff s ON e.primary_doctor_id = s.staff_id
                ORDER BY e.admission_date DESC LIMIT 10");
        
        if ($qRecent) {
            while($r = $qRecent->fetch_assoc()) {
                $r['patient_name'] = trim($r['first_name'] . ' ' . $r['last_name']);
                $r['date_fmt'] = date('d M Y, h:i A', strtotime($r['admission_date']));
                $data['recent_admissions'][] = $r;
            }
        }

        ob_end_clean(); echo json_encode(['status' => 'success', 'data' => $data]); exit;
    }

} catch (Exception $e) {
    ob_end_clean(); echo json_encode(['status' => 'error', 'message' => $e->getMessage()]); exit;
}
?>