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

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

function getAge($dob) {
    if (empty($dob) || $dob === '0000-00-00') return 'N/A';
    $date = date_create($dob);
    if (!$date) return 'N/A';
    return date_diff($date, date_create('today'))->y;
}

try {
    $action = $_POST['action'] ?? $_GET['action'] ?? '';

    if ($action === 'fetch_filters') {
        $wards = [];
        $resW = $conn->query("SELECT id, ward_name FROM ipd_wards WHERE is_active = 1 ORDER BY ward_name ASC");
        if($resW) while($r = $resW->fetch_assoc()) $wards[] = $r;

        $doctors = [];
        $resD = $conn->query("SELECT staff_id, CONCAT(first_name, ' ', last_name) as doc_name FROM staff WHERE is_doctor_id = 1 AND is_active = 1");
        if($resD) while($r = $resD->fetch_assoc()) $doctors[] = $r;

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

    if ($action === 'fetch_stats') {
        $date_from = !empty($_POST['date_from']) ? $_POST['date_from'] : '1970-01-01';
        $date_to = !empty($_POST['date_to']) ? $_POST['date_to'] : date('Y-m-d');

        $qActive = $conn->query("SELECT 
            COUNT(e.id) as total_active,
            SUM(CASE WHEN p.gender_id = 1 THEN 1 ELSE 0 END) as male_count,
            SUM(CASE WHEN p.gender_id = 2 THEN 1 ELSE 0 END) as female_count,
            SUM(CASE WHEN TIMESTAMPDIFF(YEAR, p.dob, CURDATE()) < 12 THEN 1 ELSE 0 END) as child_count,
            SUM(CASE WHEN TIMESTAMPDIFF(YEAR, p.dob, CURDATE()) >= 12 OR p.dob IS NULL THEN 1 ELSE 0 END) as adult_count
            FROM ipd_admission_episodes e
            JOIN patient p ON e.patient_no = p.patient_no
            WHERE e.status IN ('Admitted', 'Transferred', 'Pending Discharge', 'In Theatre')");
        $act = $qActive->fetch_assoc();

        $qDisc = $conn->prepare("SELECT 
            COUNT(e.id) as total_discharged,
            SUM(CASE WHEN p.gender_id = 1 THEN 1 ELSE 0 END) as male_disc,
            SUM(CASE WHEN p.gender_id = 2 THEN 1 ELSE 0 END) as female_disc
            FROM ipd_admission_episodes e
            JOIN patient p ON e.patient_no = p.patient_no
            WHERE e.status = 'Discharged' AND DATE(e.discharge_date) BETWEEN ? AND ?");
        $qDisc->bind_param("ss", $date_from, $date_to);
        $qDisc->execute();
        $disc = $qDisc->get_result()->fetch_assoc();
        $qDisc->close();

        ob_end_clean();
        echo json_encode([
            'status' => 'success',
            'active_total' => $act['total_active'] ?? 0,
            'male_active' => $act['male_count'] ?? 0,
            'female_active' => $act['female_count'] ?? 0,
            'child_active' => $act['child_count'] ?? 0,
            'adult_active' => $act['adult_count'] ?? 0,
            'discharged_period' => $disc['total_discharged'] ?? 0,
            'discharged_male' => $disc['male_disc'] ?? 0,
            'discharged_female' => $disc['female_disc'] ?? 0
        ]);
        exit;
    }

    if ($action === 'fetch_admissions') {
        $date_from = !empty($_POST['date_from']) ? $_POST['date_from'] : null;
        $date_to = !empty($_POST['date_to']) ? $_POST['date_to'] : null;
        $ward_id = $_POST['ward_id'] ?? 'ALL';
        $doctor_id = $_POST['doctor_id'] ?? 'ALL';
        $status = $_POST['status'] ?? 'Active'; 

        if (!$date_from || !$date_to) {
            ob_end_clean(); echo json_encode(['status' => 'success', 'data' => []]); exit;
        }

        $sql = "SELECT e.*, 
                       p.first_name, p.last_name, p.dob, p.mobile, g.gender_name,
                       w.ward_name, b.bed_number, rm.room_number_or_name,
                       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
                LEFT JOIN gender g ON p.gender_id = g.id
                JOIN ipd_wards w ON e.ward_id = w.id
                JOIN ipd_beds b ON e.bed_id = b.id
                LEFT JOIN ipd_rooms rm ON e.room_id = rm.id
                LEFT JOIN staff s ON e.primary_doctor_id = s.staff_id
                WHERE 1=1";

        $params = []; $types = "";

        if ($status === 'Active') {
            $sql .= " AND e.status IN ('Admitted', 'Transferred', 'Pending Discharge', 'In Theatre') AND DATE(e.admission_date) BETWEEN ? AND ?";
            $params[] = $date_from; $params[] = $date_to; $types .= "ss";
        } elseif ($status === 'Closed') {
            $sql .= " AND e.status IN ('Discharged', 'Deceased') AND DATE(e.discharge_date) BETWEEN ? AND ?";
            $params[] = $date_from; $params[] = $date_to; $types .= "ss";
        } else {
            $sql .= " AND DATE(e.admission_date) BETWEEN ? AND ?";
            $params[] = $date_from; $params[] = $date_to; $types .= "ss";
        }

        if ($ward_id !== 'ALL') {
            $sql .= " AND e.ward_id = ?";
            $params[] = (int)$ward_id; $types .= "i";
        }
        if ($doctor_id !== 'ALL') {
            $sql .= " AND e.primary_doctor_id = ?";
            $params[] = (int)$doctor_id; $types .= "i";
        }

        $sql .= " ORDER BY CASE WHEN e.status = 'Pending Discharge' THEN 1 ELSE 2 END ASC, e.admission_date DESC";
        
        $stmt = $conn->prepare($sql);
        if(!empty($params)) $stmt->bind_param($types, ...$params);
        $stmt->execute();
        $res = $stmt->get_result();

        $data = [];
        while($row = $res->fetch_assoc()) {
            $row['age'] = getAge($row['dob']);
            $row['full_name'] = trim($row['first_name'] . ' ' . $row['last_name']);
            $row['initials'] = strtoupper(substr($row['first_name'], 0, 1) . substr($row['last_name'], 0, 1));
            $row['location_str'] = $row['ward_name'] . ($row['room_number_or_name'] ? ' (' . $row['room_number_or_name'].')' : '') . ' - ' . $row['bed_number'];
            $data[] = $row;
        }

        // DYNAMICALLY RESOLVE FORM IDs for the Quick Links
        $form_map = ['vitals' => null, 'fluids' => null, 'meds' => null, 'notes' => null];
        
        $qV = $conn->query("SELECT form_id FROM ipd_form_sections WHERE id IN (SELECT section_id FROM ipd_form_fields WHERE field_type LIKE '%Vitals%') LIMIT 1");
        if($r = $qV->fetch_assoc()) $form_map['vitals'] = $r['form_id'];

        $qF = $conn->query("SELECT form_id FROM ipd_form_sections WHERE id IN (SELECT section_id FROM ipd_form_fields WHERE field_type LIKE '%Fluid%') LIMIT 1");
        if($r = $qF->fetch_assoc()) $form_map['fluids'] = $r['form_id'];

        $qM = $conn->query("SELECT form_id FROM ipd_form_sections WHERE id IN (SELECT section_id FROM ipd_form_fields WHERE field_type LIKE '%Medication%') LIMIT 1");
        if($r = $qM->fetch_assoc()) $form_map['meds'] = $r['form_id'];

        $qN = $conn->query("SELECT id FROM ipd_forms WHERE form_name LIKE '%Nurse Notes%' LIMIT 1");
        if($r = $qN->fetch_assoc()) $form_map['notes'] = $r['id'];

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

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