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

ob_start();

try {
    if ($_SERVER['REQUEST_METHOD'] == 'POST') {
        $action = $_POST['action'] ?? '';
        
        $staff_id = $_SESSION['staff_id'] ?? null;
        if (!$staff_id) {
            $fallback = $conn->query("SELECT staff_id FROM staff LIMIT 1")->fetch_assoc();
            $staff_id = $fallback ? (int)$fallback['staff_id'] : null;
        }

        // =====================================
        // AJAX DROPDOWN SYNCHRONIZER
        // =====================================
        if ($action === 'fetch_dynamic_dropdowns') {
            $wards = []; $res = $conn->query("SELECT id, ward_name FROM ipd_wards WHERE is_active=1");
            if($res) while($r = $res->fetch_assoc()) $wards[] = $r;

            $ipd_services = []; $res = $conn->query("SELECT s.id, s.service_name, s.cash_price_adult, c.category_name FROM ipd_services s LEFT JOIN ipd_service_categories c ON s.category_id = c.id WHERE s.is_active=1 ORDER BY c.category_name, s.service_name ASC");
            if($res) while($r = $res->fetch_assoc()) $ipd_services[] = $r;

            $ward_cats = []; $res = $conn->query("SELECT id, type_name FROM ipd_setup_ward_types WHERE is_active=1");
            if($res) while($r = $res->fetch_assoc()) $ward_cats[] = $r;

            $room_cats = []; $res = $conn->query("SELECT id, type_name FROM ipd_setup_room_types WHERE is_active=1");
            if($res) while($r = $res->fetch_assoc()) $room_cats[] = $r;

            $svc_cats = []; $res = $conn->query("SELECT id, category_name FROM ipd_service_categories WHERE is_active=1");
            if($res) while($r = $res->fetch_assoc()) $svc_cats[] = $r;

            $freqs = []; $res = $conn->query("SELECT id, frequency_name, interval_days FROM ipd_charge_frequencies WHERE is_active=1");
            if($res) while($r = $res->fetch_assoc()) $freqs[] = $r;

            $insurances = []; $res = $conn->query("SELECT id, insurance_name FROM insurance_type WHERE is_active=1");
            if($res) while($r = $res->fetch_assoc()) $insurances[] = $r;

            $blocks = []; $res = $conn->query("SELECT id, block_name FROM ipd_facility_blocks WHERE is_active=1");
            if($res) while($r = $res->fetch_assoc()) $blocks[] = $r;

            $floors_raw = []; $res = $conn->query("SELECT f.id, f.floor_name, b.block_name FROM ipd_facility_floors f JOIN ipd_facility_blocks b ON f.block_id = b.id WHERE f.is_active=1 ORDER BY b.id, f.id");
            if($res) while($r = $res->fetch_assoc()) $floors_raw[] = $r;
            
            $grouped_floors = [];
            foreach($floors_raw as $row) {
                $grouped_floors[$row['block_name']][] = $row;
            }

            if (ob_get_length()) ob_clean();
            echo json_encode(['status' => 'success', 'data' => [
                'wards' => $wards, 'ipd_services' => $ipd_services, 'ward_cats' => $ward_cats, 
                'room_cats' => $room_cats, 'svc_cats' => $svc_cats, 'freqs' => $freqs, 
                'insurances' => $insurances, 'blocks' => $blocks, 'grouped_floors' => $grouped_floors
            ]]);
            exit;
        }

        // =====================================
        // KPI ENGINE
        // =====================================
        if ($action === 'fetch_kpis') {
            $wards = $conn->query("SELECT COUNT(id) as c FROM ipd_wards WHERE is_active=1")->fetch_assoc()['c'] ?? 0;
            $rooms = $conn->query("SELECT COUNT(id) as c FROM ipd_rooms WHERE is_active=1")->fetch_assoc()['c'] ?? 0;
            $beds = $conn->query("SELECT COUNT(id) as c FROM ipd_beds WHERE is_active=1")->fetch_assoc()['c'] ?? 0;
            $rules = $conn->query("SELECT COUNT(id) as c FROM ipd_billing_rules WHERE is_active=1")->fetch_assoc()['c'] ?? 0;
            
            if (ob_get_length()) ob_clean();
            echo json_encode(['status' => 'success', 'data' => ['wards' => $wards, 'rooms' => $rooms, 'beds' => $beds, 'rules' => $rules]]);
            exit;
        }

        // =====================================
        // DATATABLES
        // =====================================
        if ($action === 'fetch_wards') {
            $query = "SELECT w.id, w.ward_name, w.physical_bed_capacity, w.is_active, w.floor_id, w.ward_type_id,
                             wt.type_name AS category_name, 
                             (SELECT hospital_name FROM facility_profile LIMIT 1) AS clinic_name,
                             CONCAT(b.block_name, ' - ', f.floor_name) AS location_name
                      FROM ipd_wards w 
                      LEFT JOIN ipd_setup_ward_types wt ON w.ward_type_id = wt.id 
                      LEFT JOIN ipd_facility_floors f ON w.floor_id = f.id
                      LEFT JOIN ipd_facility_blocks b ON f.block_id = b.id
                      ORDER BY w.id DESC";
            $res = $conn->query($query);
            $data = []; if ($res) while ($row = $res->fetch_assoc()) $data[] = $row;
            if (ob_get_length()) ob_clean(); echo json_encode(['data' => $data]); exit;
        }

        if ($action === 'fetch_rooms') {
            $res = $conn->query("SELECT r.id, r.room_number_or_name, r.physical_bed_capacity, r.room_nightly_rate, r.is_active, r.ward_id, r.room_type_id, w.ward_name, rt.type_name AS category_name FROM ipd_rooms r JOIN ipd_wards w ON r.ward_id = w.id LEFT JOIN ipd_setup_room_types rt ON r.room_type_id = rt.id ORDER BY r.id DESC");
            $data = []; if ($res) while ($row = $res->fetch_assoc()) $data[] = $row;
            if (ob_get_length()) ob_clean(); echo json_encode(['data' => $data]); exit;
        }

        if ($action === 'fetch_beds') {
            $res = $conn->query("SELECT b.id, b.bed_number, b.is_active, 
                                 IFNULL(r.room_number_or_name, 'Direct to Ward') AS room_name, 
                                 w.ward_name, s.status_name 
                                 FROM ipd_beds b 
                                 LEFT JOIN ipd_rooms r ON b.room_id = r.id 
                                 LEFT JOIN ipd_wards w ON b.ward_id = w.id 
                                 JOIN ipd_setup_bed_statuses s ON b.bed_status_id = s.id 
                                 ORDER BY b.id DESC");
            $data = []; if ($res) while ($row = $res->fetch_assoc()) $data[] = $row;
            if (ob_get_length()) ob_clean(); echo json_encode(['data' => $data]); exit;
        }

        if ($action === 'fetch_ipd_services') {
            $res = $conn->query("SELECT s.*, c.category_name FROM ipd_services s LEFT JOIN ipd_service_categories c ON s.category_id = c.id ORDER BY s.id DESC");
            $data = []; if ($res) while ($row = $res->fetch_assoc()) $data[] = $row;
            if (ob_get_length()) ob_clean(); echo json_encode(['data' => $data]); exit;
        }

        if ($action === 'fetch_ward_charges') {
            $res = $conn->query("SELECT r.id, w.ward_name, IFNULL(rm.room_number_or_name, 'Entire Ward') AS room_name, 
                                 s.service_name, c.category_name, f.frequency_name, r.is_active 
                                 FROM ipd_billing_rules r 
                                 JOIN ipd_wards w ON r.ward_id = w.id 
                                 LEFT JOIN ipd_rooms rm ON r.room_id = rm.id
                                 JOIN ipd_services s ON r.ipd_service_id = s.id 
                                 LEFT JOIN ipd_service_categories c ON s.category_id = c.id
                                 LEFT JOIN ipd_charge_frequencies f ON r.frequency_id = f.id
                                 ORDER BY r.id DESC");
            $data = []; if ($res) while ($row = $res->fetch_assoc()) $data[] = $row;
            if (ob_get_length()) ob_clean(); echo json_encode(['data' => $data]); exit;
        }

        if ($action === 'fetch_floors') {
            $res = $conn->query("SELECT f.id, f.floor_name, b.block_name, f.is_active FROM ipd_facility_floors f JOIN ipd_facility_blocks b ON f.block_id = b.id ORDER BY f.id DESC");
            $data = []; if ($res) while ($row = $res->fetch_assoc()) $data[] = $row;
            if (ob_get_length()) ob_clean(); echo json_encode(['data' => $data]); exit;
        }

        if ($action === 'fetch_dictionaries') {
            $type = $_POST['dict_type'] ?? '';
            $table = '';
            if($type === 'ward_cat') $table = 'ipd_setup_ward_types';
            elseif($type === 'room_cat') $table = 'ipd_setup_room_types';
            elseif($type === 'svc_cat') $table = 'ipd_service_categories';
            elseif($type === 'freq_cat') $table = 'ipd_charge_frequencies';
            elseif($type === 'floor') $table = 'ipd_facility_floors';
            
            $data = [];
            if($table) {
                if ($type === 'freq_cat') {
                    $res = $conn->query("SELECT id, frequency_name AS name, interval_days, is_active FROM $table ORDER BY id DESC");
                } elseif ($type === 'floor') {
                    $res = $conn->query("SELECT id, floor_name AS name, block_id, is_active FROM $table ORDER BY id DESC");
                } else {
                    $name_col = ($type === 'ward_cat' || $type === 'room_cat') ? 'type_name' : 'category_name';
                    $res = $conn->query("SELECT id, $name_col AS name, is_active FROM $table ORDER BY id DESC");
                }
                if($res) while ($row = $res->fetch_assoc()) $data[] = $row;
            }
            if (ob_get_length()) ob_clean(); echo json_encode(['data' => $data]); exit;
        }

        // =====================================
        // ACTIONS
        // =====================================
        if ($action === 'get_ward_rooms') {
            $ward_id = (int)$_POST['ward_id'];
            $res = $conn->query("SELECT id, room_number_or_name FROM ipd_rooms WHERE ward_id = $ward_id AND is_active = 1");
            
            $rooms = [];
            if ($res && $res->num_rows > 0) {
                while($r = $res->fetch_assoc()) $rooms[] = $r;
            }
            
            if (ob_get_length()) ob_clean();
            echo json_encode(['status' => 'success', 'data' => $rooms]); exit;
        }

        if ($action === 'get_record') {
            $table = $_POST['table']; $id = (int)$_POST['id'];
            $allowed = ['ipd_wards', 'ipd_rooms', 'ipd_services', 'ipd_setup_ward_types', 'ipd_setup_room_types', 'ipd_service_categories', 'ipd_charge_frequencies', 'ipd_facility_floors'];
            
            if(!in_array($table, $allowed)) {
                if (ob_get_length()) ob_clean(); echo json_encode(['status' => 'error', 'message' => 'Unauthorized table access']); exit;
            }
            
            $stmt = $conn->prepare("SELECT * FROM $table WHERE id = ?");
            $stmt->bind_param("i", $id); $stmt->execute();
            $record = $stmt->get_result()->fetch_assoc();

            if ($table === 'ipd_services') {
                $corp_res = $conn->query("SELECT * FROM ipd_service_corporate_tariffs WHERE ipd_service_id = $id");
                $record['corporate_tariffs'] = [];
                if($corp_res) while($c = $corp_res->fetch_assoc()) $record['corporate_tariffs'][] = $c;
            }

            if (ob_get_length()) ob_clean(); echo json_encode(['status' => 'success', 'data' => $record]); exit;
        }

        if ($action === 'save_ipd_service') {
            $id = !empty($_POST['id']) ? (int)$_POST['id'] : null;
            $name = trim($_POST['service_name']);
            $cat_id = (int)$_POST['category_id'];
            
            $cash_a = (float)($_POST['cash_price_adult'] ?? 0);
            $cash_c = (float)($_POST['cash_price_child'] ?? 0);
            
            $is_nhis = isset($_POST['is_nhis_covered']) ? 1 : 0;
            $nhis_t_a = $is_nhis ? (float)($_POST['nhis_tariff_adult'] ?? 0) : 0;
            $nhis_t_c = $is_nhis ? (float)($_POST['nhis_tariff_child'] ?? 0) : 0;
            $nhis_cp_a = $is_nhis ? (float)($_POST['nhis_copay_adult'] ?? 0) : 0;
            $nhis_cp_c = $is_nhis ? (float)($_POST['nhis_copay_child'] ?? 0) : 0;

            $conn->begin_transaction();
            try {
                if($id) {
                    $stmt = $conn->prepare("UPDATE ipd_services SET service_name=?, category_id=?, cash_price_adult=?, cash_price_child=?, is_nhis_covered=?, nhis_tariff_adult=?, nhis_tariff_child=?, nhis_copay_adult=?, nhis_copay_child=? WHERE id=?");
                    $stmt->bind_param("sidddddddi", $name, $cat_id, $cash_a, $cash_c, $is_nhis, $nhis_t_a, $nhis_t_c, $nhis_cp_a, $nhis_cp_c, $id);
                    $stmt->execute();
                    $conn->query("DELETE FROM ipd_service_corporate_tariffs WHERE ipd_service_id = $id");
                } else {
                    $stmt = $conn->prepare("INSERT INTO ipd_services (service_name, category_id, cash_price_adult, cash_price_child, is_nhis_covered, nhis_tariff_adult, nhis_tariff_child, nhis_copay_adult, nhis_copay_child, created_by) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)");
                    $stmt->bind_param("sidddddddi", $name, $cat_id, $cash_a, $cash_c, $is_nhis, $nhis_t_a, $nhis_t_c, $nhis_cp_a, $nhis_cp_c, $staff_id);
                    $stmt->execute();
                    $id = $conn->insert_id;
                }

                if(isset($_POST['corp_insurance_id']) && is_array($_POST['corp_insurance_id'])) {
                    $stmt_corp = $conn->prepare("INSERT INTO ipd_service_corporate_tariffs (ipd_service_id, insurance_type_id, tariff_amount, copay_amount_adult, copay_amount_child) VALUES (?, ?, ?, ?, ?)");
                    foreach($_POST['corp_insurance_id'] as $idx => $ins_id) {
                        if(empty($ins_id)) continue;
                        $t_amt = (float)($_POST['corp_tariff'][$idx] ?? 0);
                        $cp_a = (float)($_POST['corp_copay_adult'][$idx] ?? 0);
                        $cp_c = (float)($_POST['corp_copay_child'][$idx] ?? 0);
                        $stmt_corp->bind_param("iiddd", $id, $ins_id, $t_amt, $cp_a, $cp_c);
                        $stmt_corp->execute();
                    }
                }
                $conn->commit();
                if (ob_get_length()) ob_clean(); echo json_encode(['status' => 'success']);
            } catch(Exception $e) {
                $conn->rollback();
                if (ob_get_length()) ob_clean(); echo json_encode(['status' => 'error', 'message' => $e->getMessage()]);
            }
            exit;
        }

        if ($action === 'save_ward') {
            $id = !empty($_POST['id']) ? (int)$_POST['id'] : null;
            $ward_name = trim($_POST['ward_name']); 
            $ward_type_id = (int)$_POST['ward_type_id']; 
            $floor_id = (int)$_POST['floor_id'];

            if($id) { 
                $stmt = $conn->prepare("UPDATE ipd_wards SET ward_name=?, ward_type_id=?, floor_id=? WHERE id=?"); 
                $stmt->bind_param("siii", $ward_name, $ward_type_id, $floor_id, $id); 
            } else { 
                if ($staff_id) {
                    $stmt = $conn->prepare("INSERT INTO ipd_wards (ward_name, ward_type_id, floor_id, created_by) VALUES (?, ?, ?, ?)"); 
                    $stmt->bind_param("siii", $ward_name, $ward_type_id, $floor_id, $staff_id); 
                } else {
                    $stmt = $conn->prepare("INSERT INTO ipd_wards (ward_name, ward_type_id, floor_id) VALUES (?, ?, ?)"); 
                    $stmt->bind_param("sii", $ward_name, $ward_type_id, $floor_id); 
                }
            }
            if (ob_get_length()) ob_clean(); echo json_encode(['status' => $stmt->execute() ? 'success' : 'error', 'message' => $stmt->error]); exit;
        }

        if ($action === 'save_room') {
            $id = !empty($_POST['id']) ? (int)$_POST['id'] : null;
            $ward_id = (int)$_POST['ward_id']; $room_type_id = (int)$_POST['room_type_id'];
            $room_name = trim($_POST['room_name']); $rate = (float)$_POST['room_nightly_rate'];

            if($id) { 
                $stmt = $conn->prepare("UPDATE ipd_rooms SET ward_id=?, room_type_id=?, room_number_or_name=?, room_nightly_rate=? WHERE id=?"); 
                $stmt->bind_param("iisdi", $ward_id, $room_type_id, $room_name, $rate, $id); 
            } else { 
                if ($staff_id) {
                    $stmt = $conn->prepare("INSERT INTO ipd_rooms (ward_id, room_type_id, room_number_or_name, room_nightly_rate, created_by) VALUES (?, ?, ?, ?, ?)"); 
                    $stmt->bind_param("iisdi", $ward_id, $room_type_id, $room_name, $rate, $staff_id); 
                } else {
                    $stmt = $conn->prepare("INSERT INTO ipd_rooms (ward_id, room_type_id, room_number_or_name, room_nightly_rate) VALUES (?, ?, ?, ?)"); 
                    $stmt->bind_param("iisd", $ward_id, $room_type_id, $room_name, $rate); 
                }
            }
            if (ob_get_length()) ob_clean(); echo json_encode(['status' => $stmt->execute() ? 'success' : 'error', 'message' => $stmt->error]); exit;
        }

        if ($action === 'generate_beds') {
            $assignment_type = $_POST['assignment_type'];
            $ward_id = (int)$_POST['ward_id'];
            $room_id = ($assignment_type === 'room' && !empty($_POST['room_id'])) ? (int)$_POST['room_id'] : null;
            $num_beds = (int)$_POST['num_beds'];
            
            $conn->begin_transaction();
            try {
                if ($staff_id) {
                    $stmt = $conn->prepare("INSERT INTO ipd_beds (ward_id, room_id, bed_number, bed_status_id, created_by) VALUES (?, ?, ?, 1, ?)");
                } else {
                    $stmt = $conn->prepare("INSERT INTO ipd_beds (ward_id, room_id, bed_number, bed_status_id) VALUES (?, ?, ?, 1)");
                }
                
                for($i=1; $i<=$num_beds; $i++){
                    $bname = "Bed " . rand(100, 999) . "-$i"; 
                    if ($staff_id) {
                        $stmt->bind_param("iisi", $ward_id, $room_id, $bname, $staff_id);
                    } else {
                        $stmt->bind_param("iis", $ward_id, $room_id, $bname);
                    }
                    $stmt->execute();
                }
                
                if ($room_id) {
                    $conn->query("UPDATE ipd_rooms SET physical_bed_capacity = physical_bed_capacity + $num_beds WHERE id = $room_id");
                }
                $conn->query("UPDATE ipd_wards SET physical_bed_capacity = physical_bed_capacity + $num_beds WHERE id = $ward_id");
                
                $conn->commit();
                if (ob_get_length()) ob_clean(); echo json_encode(['status' => 'success']);
            } catch(Exception $e) {
                $conn->rollback();
                if (ob_get_length()) ob_clean(); echo json_encode(['status' => 'error', 'message' => $e->getMessage()]);
            }
            exit;
        }

        if ($action === 'save_billing_rule') {
            $ward_id = (int)$_POST['ward_id'];
            $room_id = !empty($_POST['room_id']) ? (int)$_POST['room_id'] : null;
            $ipd_service_id = (int)$_POST['ipd_service_id'];
            $freq_id = (int)$_POST['frequency_id'];
            
            $stmt = $conn->prepare("INSERT INTO ipd_billing_rules (ward_id, room_id, ipd_service_id, frequency_id, created_by) VALUES (?, ?, ?, ?, ?)");
            $stmt->bind_param("iiiii", $ward_id, $room_id, $ipd_service_id, $freq_id, $staff_id);
            if (ob_get_length()) ob_clean(); echo json_encode(['status' => $stmt->execute() ? 'success' : 'error', 'message' => $stmt->error]); exit;
        }

        if ($action === 'save_dictionary') {
            $id = !empty($_POST['id']) ? (int)$_POST['id'] : null;
            $type = $_POST['dict_type'];
            $name = trim($_POST['dict_name']);

            if($type === 'ward_cat') { $table = 'ipd_setup_ward_types'; $col = 'type_name'; }
            elseif($type === 'room_cat') { $table = 'ipd_setup_room_types'; $col = 'type_name'; }
            elseif($type === 'svc_cat') { $table = 'ipd_service_categories'; $col = 'category_name'; }
            elseif($type === 'freq_cat') { $table = 'ipd_charge_frequencies'; $col = 'frequency_name'; }
            elseif($type === 'floor') { $table = 'ipd_facility_floors'; $col = 'floor_name'; }
            else { if (ob_get_length()) ob_clean(); echo json_encode(['status' => 'error', 'message' => 'Invalid dictionary type']); exit; }

            if ($type === 'freq_cat') {
                $interval = isset($_POST['interval_days']) ? (int)$_POST['interval_days'] : 1;
                if($id) { 
                    $stmt = $conn->prepare("UPDATE $table SET $col=?, interval_days=? WHERE id=?"); 
                    $stmt->bind_param("sii", $name, $interval, $id); 
                } else { 
                    $stmt = $conn->prepare("INSERT INTO $table ($col, interval_days) VALUES (?, ?)"); 
                    $stmt->bind_param("si", $name, $interval); 
                }
            } elseif ($type === 'floor') {
                $block_id = (int)$_POST['block_id'];
                if($id) { 
                    $stmt = $conn->prepare("UPDATE $table SET $col=?, block_id=? WHERE id=?"); 
                    $stmt->bind_param("sii", $name, $block_id, $id); 
                } else { 
                    if ($staff_id) {
                        $stmt = $conn->prepare("INSERT INTO $table ($col, block_id, created_by) VALUES (?, ?, ?)"); 
                        $stmt->bind_param("sii", $name, $block_id, $staff_id); 
                    } else {
                        $stmt = $conn->prepare("INSERT INTO $table ($col, block_id) VALUES (?, ?)"); 
                        $stmt->bind_param("si", $name, $block_id);
                    }
                }
            } else {
                if($id) { 
                    $stmt = $conn->prepare("UPDATE $table SET $col=? WHERE id=?"); 
                    $stmt->bind_param("si", $name, $id); 
                } else { 
                    $stmt = $conn->prepare("INSERT INTO $table ($col) VALUES (?)"); 
                    $stmt->bind_param("s", $name); 
                }
            }
            if (ob_get_length()) ob_clean(); echo json_encode(['status' => $stmt->execute() ? 'success' : 'error', 'message' => $stmt->error]); exit;
        }

        if ($action === 'toggle_status') {
            $table = $_POST['table']; $id = (int)$_POST['id']; $status = (int)$_POST['status'];
            $allowed = ['ipd_wards', 'ipd_rooms', 'ipd_setup_ward_types', 'ipd_setup_room_types', 'ipd_service_categories', 'ipd_charge_frequencies', 'ipd_facility_floors', 'ipd_beds', 'ipd_billing_rules', 'ipd_services'];
            if(in_array($table, $allowed)) {
                $stmt = $conn->prepare("UPDATE $table SET is_active = ? WHERE id = ?");
                $stmt->bind_param("ii", $status, $id);
                $stmt->execute();
            }
            if (ob_get_length()) ob_clean(); echo json_encode(['status' => 'success']); exit;
        }

        if ($action === 'delete_record') {
            $table = $_POST['table']; $id = (int)$_POST['id'];
            $allowed = ['ipd_wards', 'ipd_rooms', 'ipd_setup_ward_types', 'ipd_setup_room_types', 'ipd_service_categories', 'ipd_charge_frequencies', 'ipd_facility_floors', 'ipd_beds', 'ipd_billing_rules', 'ipd_services'];
            
            if(in_array($table, $allowed)) {
                // Dependency Safety Checks
                $dep_count = 0;
                if($table === 'ipd_facility_floors') { $check = $conn->query("SELECT COUNT(*) as c FROM ipd_wards WHERE floor_id = $id"); $dep_count = $check->fetch_assoc()['c']; }
                if($table === 'ipd_setup_ward_types') { $check = $conn->query("SELECT COUNT(*) as c FROM ipd_wards WHERE ward_type_id = $id"); $dep_count = $check->fetch_assoc()['c']; }
                if($table === 'ipd_setup_room_types') { $check = $conn->query("SELECT COUNT(*) as c FROM ipd_rooms WHERE room_type_id = $id"); $dep_count = $check->fetch_assoc()['c']; }
                if($table === 'ipd_wards') { $check = $conn->query("SELECT COUNT(*) as c FROM ipd_rooms WHERE ward_id = $id"); $dep_count = $check->fetch_assoc()['c']; }
                if($table === 'ipd_rooms') { $check = $conn->query("SELECT COUNT(*) as c FROM ipd_beds WHERE room_id = $id"); $dep_count = $check->fetch_assoc()['c']; }
                if($table === 'ipd_services') { $check = $conn->query("SELECT COUNT(*) as c FROM ipd_billing_rules WHERE ipd_service_id = $id"); $dep_count = $check->fetch_assoc()['c']; }

                if($dep_count > 0) {
                    if (ob_get_length()) ob_clean(); echo json_encode(['status' => 'error', 'message' => "Record is actively linked to $dep_count sub-records. Deactivate (Freeze) it instead."]);
                    exit;
                }

                $stmt = $conn->prepare("DELETE FROM $table WHERE id = ?");
                $stmt->bind_param("i", $id);
                $stmt->execute();
            }
            if (ob_get_length()) ob_clean(); echo json_encode(['status' => 'success']); exit;
        }
    }
} catch (Exception $e) {
    if (ob_get_length()) ob_clean();
    echo json_encode(['status' => 'error', 'message' => 'Processing Error: ' . $e->getMessage()]);
    exit;
}
?>