<?php
session_start();
ini_set('display_errors', 0);
error_reporting(E_ALL);
mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
ob_start();

require_once dirname(__DIR__, 2) . '/includes/db.php';
header('Content-Type: application/json');

$staff_id = (int)($_SESSION['staff_id'] ?? 1);
$action = $_POST['action'] ?? '';

try {
    // ==========================================
    // AGGRESSIVE AUTO-HEALING: THEATRE TABLES
    // ==========================================
    $conn->query("CREATE TABLE IF NOT EXISTS `ipd_setup_theatre_rooms` (
        `id` int(11) NOT NULL AUTO_INCREMENT,
        `room_name` varchar(150) NOT NULL,
        `is_active` tinyint(1) DEFAULT 1,
        PRIMARY KEY (`id`)
    ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;");

    $conn->query("CREATE TABLE IF NOT EXISTS `ipd_setup_theatre_beds` (
        `id` int(11) NOT NULL AUTO_INCREMENT,
        `room_id` int(11) NOT NULL,
        `bed_name` varchar(150) NOT NULL,
        `is_active` tinyint(1) DEFAULT 1,
        PRIMARY KEY (`id`)
    ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;");

    $conn->query("CREATE TABLE IF NOT EXISTS `ipd_theatre_billing_rules` (
        `id` int(11) NOT NULL AUTO_INCREMENT,
        `rule_target_type` enum('Global','Room','Bed','Procedure') NOT NULL DEFAULT 'Global',
        `room_id` int(11) DEFAULT NULL,
        `bed_id` int(11) DEFAULT NULL,
        `procedure_id` int(11) DEFAULT NULL,
        `service_id` int(11) NOT NULL,
        `frequency_id` int(11) DEFAULT NULL,
        `is_active` tinyint(1) DEFAULT 1,
        PRIMARY KEY (`id`)
    ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;");

    $conn->query("CREATE TABLE IF NOT EXISTS `ipd_setup_anesthesia_types` (
        `id` int(11) NOT NULL AUTO_INCREMENT,
        `type_name` varchar(150) NOT NULL,
        `service_id` int(11) DEFAULT NULL,
        `procedure_id` int(11) DEFAULT NULL,
        `is_active` tinyint(1) DEFAULT 1,
        PRIMARY KEY (`id`)
    ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;");
    
    $chkAnes1 = $conn->query("SHOW COLUMNS FROM ipd_setup_anesthesia_types LIKE 'service_id'");
    if($chkAnes1 && $chkAnes1->num_rows == 0) $conn->query("ALTER TABLE `ipd_setup_anesthesia_types` ADD COLUMN `service_id` INT(11) DEFAULT NULL AFTER `type_name`");
    
    $chkAnes2 = $conn->query("SHOW COLUMNS FROM ipd_setup_anesthesia_types LIKE 'procedure_id'");
    if($chkAnes2 && $chkAnes2->num_rows == 0) $conn->query("ALTER TABLE `ipd_setup_anesthesia_types` ADD COLUMN `procedure_id` INT(11) DEFAULT NULL AFTER `service_id`");

    $conn->query("CREATE TABLE IF NOT EXISTS `ipd_setup_theatre_roles` (
        `id` int(11) NOT NULL AUTO_INCREMENT,
        `role_name` varchar(150) NOT NULL,
        `is_active` tinyint(1) DEFAULT 1,
        PRIMARY KEY (`id`)
    ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;");

    $conn->query("CREATE TABLE IF NOT EXISTS `ipd_setup_surgery_categories` (
        `id` int(11) NOT NULL AUTO_INCREMENT,
        `category_name` varchar(150) NOT NULL,
        `is_active` tinyint(1) DEFAULT 1,
        PRIMARY KEY (`id`)
    ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;");

    $conn->query("CREATE TABLE IF NOT EXISTS `ipd_setup_theatre_staff` (
        `id` int(11) NOT NULL AUTO_INCREMENT,
        `staff_id` int(10) UNSIGNED NOT NULL,
        `role_id` int(11) NOT NULL,
        `is_active` tinyint(1) DEFAULT 1,
        PRIMARY KEY (`id`),
        UNIQUE KEY `unique_staff_role` (`staff_id`, `role_id`)
    ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;");

    $conn->query("CREATE TABLE IF NOT EXISTS `ipd_setup_surgical_procedures` (
        `id` int(11) NOT NULL AUTO_INCREMENT,
        `procedure_name` varchar(255) DEFAULT NULL,
        `service_id` int(11) DEFAULT NULL,
        `category_id` int(11) DEFAULT NULL,
        `gdrg_code` varchar(20) DEFAULT NULL,
        `is_active` tinyint(1) DEFAULT 1,
        PRIMARY KEY (`id`)
    ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;");

    $chkProc1 = $conn->query("SHOW COLUMNS FROM ipd_setup_surgical_procedures LIKE 'service_id'");
    if($chkProc1 && $chkProc1->num_rows == 0) $conn->query("ALTER TABLE `ipd_setup_surgical_procedures` ADD COLUMN `service_id` INT(11) DEFAULT NULL AFTER `procedure_name`");

    $chkProc2 = $conn->query("SHOW COLUMNS FROM ipd_setup_surgical_procedures LIKE 'gdrg_code'");
    if($chkProc2 && $chkProc2->num_rows == 0) $conn->query("ALTER TABLE `ipd_setup_surgical_procedures` ADD COLUMN `gdrg_code` VARCHAR(20) DEFAULT NULL AFTER `category_id`");

    // ==========================================
    // FETCH DROPDOWN DEPENDENCIES
    // ==========================================
    if ($action === 'fetch_dependencies') {
        $staff = []; $roles = []; $categories = []; $gdrgs = []; $insurances = []; $procedures = []; $depts = [];
        $theatre_rooms = []; $theatre_beds = []; $ipd_services = []; $frequencies = [];
        
        $qStaff = $conn->query("SELECT s.staff_id, s.first_name, s.last_name, p.name as position FROM staff s LEFT JOIN staff_positions p ON s.position_id = p.id WHERE s.is_active=1 ORDER BY s.first_name ASC");
        if($qStaff) while($r = $qStaff->fetch_assoc()) $staff[] = ['id' => $r['staff_id'], 'name' => trim($r['first_name'] . ' ' . $r['last_name']) . ' (' . ($r['position'] ?? 'Staff') . ')'];
        
        $qRole = $conn->query("SELECT id, role_name FROM ipd_setup_theatre_roles WHERE is_active=1");
        if($qRole) while($r = $qRole->fetch_assoc()) $roles[] = ['id' => $r['id'], 'name' => $r['role_name']];
        
        $qCat = $conn->query("SELECT id, category_name FROM ipd_setup_surgery_categories WHERE is_active=1");
        if($qCat) while($r = $qCat->fetch_assoc()) $categories[] = ['id' => $r['id'], 'name' => $r['category_name']];

        $qGdrg = $conn->query("
            SELECT code, description FROM (
                SELECT code, description FROM gdrg_dictionary WHERE code IS NOT NULL AND code != ''
                UNION
                SELECT gdrg_code AS code, description FROM nhis_gdrg_tariffs WHERE gdrg_code IS NOT NULL AND gdrg_code != ''
                UNION
                SELECT DISTINCT gdrg_code AS code, gdrg_code AS description FROM gdrg_icd_mapping WHERE gdrg_code IS NOT NULL AND gdrg_code != ''
            ) AS combined_gdrg ORDER BY code ASC
        ");
        if($qGdrg) {
            while($r = $qGdrg->fetch_assoc()) {
                $desc = ($r['description'] && $r['description'] !== $r['code']) ? $r['description'] : 'G-DRG Tariff Code';
                $gdrgs[] = ['id' => $r['code'], 'name' => '['.$r['code'].'] ' . $desc];
            }
        }

        $qIns = $conn->query("SELECT id, insurance_name FROM insurance_type WHERE is_active=1 ORDER BY insurance_name ASC");
        if($qIns) while($r = $qIns->fetch_assoc()) $insurances[] = ['id' => $r['id'], 'name' => $r['insurance_name']];

        $qProc = $conn->query("SELECT id, procedure_name FROM ipd_setup_surgical_procedures WHERE is_active=1 ORDER BY procedure_name ASC");
        if($qProc) while($r = $qProc->fetch_assoc()) $procedures[] = ['id' => $r['id'], 'name' => $r['procedure_name']];

        $qDept = $conn->query("SELECT id, department_name FROM departments WHERE is_active=1 ORDER BY department_name ASC");
        if($qDept) while($r = $qDept->fetch_assoc()) $depts[] = ['id' => $r['id'], 'name' => $r['department_name']];

        $qRm = $conn->query("SELECT id, room_name as name FROM ipd_setup_theatre_rooms WHERE is_active=1 ORDER BY room_name ASC");
        if($qRm) while($r = $qRm->fetch_assoc()) $theatre_rooms[] = $r;

        $qBd = $conn->query("SELECT id, bed_name as name FROM ipd_setup_theatre_beds WHERE is_active=1 ORDER BY bed_name ASC");
        if($qBd) while($r = $qBd->fetch_assoc()) $theatre_beds[] = $r;

        $qSvc = $conn->query("SELECT id, service_name as name FROM ipd_services WHERE is_active=1 ORDER BY service_name ASC");
        if($qSvc) while($r = $qSvc->fetch_assoc()) $ipd_services[] = $r;
        
        $qFreq = $conn->query("SELECT id, frequency_name as name FROM ipd_charge_frequencies WHERE is_active=1 ORDER BY frequency_name ASC");
        if($qFreq) while($r = $qFreq->fetch_assoc()) $frequencies[] = $r;

        ob_end_clean(); 
        echo json_encode([
            'status' => 'success', 'staff' => $staff, 'roles' => $roles, 'categories' => $categories, 
            'gdrgs' => $gdrgs, 'insurances' => $insurances, 'procedures' => $procedures, 'departments' => $depts,
            'theatre_rooms' => $theatre_rooms, 'theatre_beds' => $theatre_beds, 'ipd_services' => $ipd_services, 'frequencies' => $frequencies
        ]); 
        exit;
    }

    if ($action === 'fetch_gdrg_details') {
        $code = $_POST['gdrg_code'];
        $q = $conn->query("SELECT adult_tariff, child_tariff, description FROM nhis_gdrg_tariffs WHERE gdrg_code = '".$conn->real_escape_string($code)."' ORDER BY id DESC LIMIT 1");
        
        if ($q && $r = $q->fetch_assoc()) {
            ob_end_clean(); echo json_encode(['status' => 'success', 'data' => $r]); exit;
        } else {
            $q2 = $conn->query("SELECT description FROM gdrg_dictionary WHERE code = '".$conn->real_escape_string($code)."' LIMIT 1");
            if ($q2 && $r2 = $q2->fetch_assoc()) {
                ob_end_clean(); echo json_encode(['status' => 'success', 'data' => ['description' => $r2['description'], 'adult_tariff' => '0.00', 'child_tariff' => '0.00']]); exit;
            }
            ob_end_clean(); echo json_encode(['status' => 'error']); exit;
        }
    }

    // ==========================================
    // FETCH CONFIGURATION DATA
    // ==========================================
    if ($action === 'fetch_config') {
        $type = $_POST['config_type'];
        $data = [];

        if ($type === 'rooms') {
            $res = $conn->query("SELECT id, room_name as name, is_active FROM ipd_setup_theatre_rooms ORDER BY id DESC");
            if($res) while($row = $res->fetch_assoc()) $data[] = $row;
        } elseif ($type === 'beds') {
            $res = $conn->query("SELECT b.id, b.bed_name as name, b.room_id, b.is_active, r.room_name FROM ipd_setup_theatre_beds b LEFT JOIN ipd_setup_theatre_rooms r ON b.room_id = r.id ORDER BY b.id DESC");
            if($res) while($row = $res->fetch_assoc()) $data[] = $row;
        } elseif ($type === 'billing_rules') {
            $sql = "SELECT br.*, s.service_name, f.frequency_name, r.room_name, b.bed_name, p.procedure_name 
                    FROM ipd_theatre_billing_rules br 
                    LEFT JOIN ipd_services s ON br.service_id = s.id 
                    LEFT JOIN ipd_charge_frequencies f ON br.frequency_id = f.id 
                    LEFT JOIN ipd_setup_theatre_rooms r ON br.room_id = r.id 
                    LEFT JOIN ipd_setup_theatre_beds b ON br.bed_id = b.id 
                    LEFT JOIN ipd_setup_surgical_procedures p ON br.procedure_id = p.id 
                    ORDER BY br.id DESC";
            $res = $conn->query($sql);
            if($res) while($row = $res->fetch_assoc()) $data[] = $row;
        } elseif ($type === 'roles') {
            $res = $conn->query("SELECT id, role_name as name, is_active FROM ipd_setup_theatre_roles ORDER BY id DESC");
            if($res) while($row = $res->fetch_assoc()) $data[] = $row;
        } elseif ($type === 'categories') {
            $res = $conn->query("SELECT id, category_name as name, is_active FROM ipd_setup_surgery_categories ORDER BY id DESC");
            if($res) while($row = $res->fetch_assoc()) $data[] = $row;
        } elseif ($type === 'staff') {
            $res = $conn->query("SELECT t.id, t.staff_id, t.role_id, CONCAT(s.first_name, ' ', s.last_name) as staff_name, r.role_name, t.is_active FROM ipd_setup_theatre_staff t JOIN staff s ON t.staff_id = s.staff_id JOIN ipd_setup_theatre_roles r ON t.role_id = r.id ORDER BY t.id DESC");
            if($res) while($row = $res->fetch_assoc()) $data[] = $row;
        } elseif ($type === 'procedures') {
            $sql = "SELECT p.id, p.is_active, p.category_id, p.gdrg_code, p.procedure_name as name,
                           c.category_name, 
                           COALESCE(g.description, t.description, p.gdrg_code) as gdrg_desc,
                           s.id as service_id, s.department_id, d.department_name
                     FROM ipd_setup_surgical_procedures p 
                     LEFT JOIN service_catalog s ON p.service_id = s.id
                     LEFT JOIN departments d ON s.department_id = d.id
                     LEFT JOIN ipd_setup_surgery_categories c ON p.category_id = c.id
                     LEFT JOIN gdrg_dictionary g ON p.gdrg_code = g.code
                     LEFT JOIN nhis_gdrg_tariffs t ON p.gdrg_code = t.gdrg_code
                     ORDER BY p.id DESC";
            $res = $conn->query($sql);
            if($res) while($row = $res->fetch_assoc()) $data[] = $row;
        } elseif ($type === 'anesthesia') {
            $sql = "SELECT p.id, p.is_active, p.procedure_id,
                           sp.procedure_name as linked_procedure,
                           s.id as service_id, COALESCE(s.service_name, p.type_name) as name, s.target_age_group, s.applicable_gender,
                           s.cash_price_adult, s.cash_price_child, s.nhis_covered, s.corp_covered,
                           s.gdrg_adult_code as gdrg_code, s.tariff_adult, s.tariff_child, 
                           s.is_copay_required, s.nhis_copay_adult, s.nhis_copay_child
                     FROM ipd_setup_anesthesia_types p 
                     LEFT JOIN service_catalog s ON p.service_id = s.id
                     LEFT JOIN ipd_setup_surgical_procedures sp ON p.procedure_id = sp.id
                     ORDER BY p.id DESC";
            $res = $conn->query($sql);
            if($res) while($row = $res->fetch_assoc()) $data[] = $row;
        }

        foreach($data as &$row) {
            $row['status_badge'] = $row['is_active'] == 1 ? '<span class="badge bg-success shadow-sm">Active</span>' : '<span class="badge bg-danger shadow-sm">Disabled</span>';
        }

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

    if ($action === 'get_service_pricing') {
        $service_id = (int)$_POST['service_id'];
        $qSvc = $conn->query("SELECT * FROM service_catalog WHERE id = $service_id");
        $service = $qSvc->fetch_assoc();

        $corporate = [];
        $qCorp = $conn->query("SELECT * FROM service_corporate_tariffs WHERE service_id = $service_id");
        if($qCorp) {
            while($c = $qCorp->fetch_assoc()) {
                $corporate[$c['insurance_type_id']] = $c;
            }
        }

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

    // ==========================================
    // SAVE CONFIGURATION DATA
    // ==========================================
    if ($action === 'save_config') {
        $type = $_POST['config_type'];
        $id = !empty($_POST['id']) ? (int)$_POST['id'] : null;

        if ($type === 'rooms' || $type === 'roles' || $type === 'categories') {
            $table = 'ipd_setup_theatre_rooms'; $col = 'room_name';
            if ($type === 'roles') { $table = 'ipd_setup_theatre_roles'; $col = 'role_name'; }
            if ($type === 'categories') { $table = 'ipd_setup_surgery_categories'; $col = 'category_name'; }

            $name = trim($_POST['name']);
            if(empty($name)) throw new Exception("The name field is required.");

            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); 
            }
            $stmt->execute();
        } 
        elseif ($type === 'beds') {
            $name = trim($_POST['name']);
            $room_id = (int)$_POST['room_id'];
            if(empty($name) || !$room_id) throw new Exception("Bed name and its associated room are required.");

            if ($id) {
                $stmt = $conn->prepare("UPDATE ipd_setup_theatre_beds SET bed_name=?, room_id=? WHERE id=?");
                $stmt->bind_param("sii", $name, $room_id, $id);
            } else {
                $stmt = $conn->prepare("INSERT INTO ipd_setup_theatre_beds (bed_name, room_id) VALUES (?, ?)");
                $stmt->bind_param("si", $name, $room_id);
            }
            $stmt->execute();
        }
        elseif ($type === 'billing_rules') {
            $target_type = $_POST['rule_target_type'];
            $room_id = !empty($_POST['target_room_id']) ? (int)$_POST['target_room_id'] : null;
            $bed_id = !empty($_POST['target_bed_id']) ? (int)$_POST['target_bed_id'] : null;
            $proc_id = !empty($_POST['target_procedure_id']) ? (int)$_POST['target_procedure_id'] : null;
            $service_id = (int)$_POST['charge_service_id'];
            $frequency_id = !empty($_POST['charge_frequency_id']) ? (int)$_POST['charge_frequency_id'] : null;

            if(!$service_id) throw new Exception("Charge service is strictly required.");

            if ($id) {
                $stmt = $conn->prepare("UPDATE ipd_theatre_billing_rules SET rule_target_type=?, room_id=?, bed_id=?, procedure_id=?, service_id=?, frequency_id=? WHERE id=?");
                $stmt->bind_param("siiiiii", $target_type, $room_id, $bed_id, $proc_id, $service_id, $frequency_id, $id);
            } else {
                $stmt = $conn->prepare("INSERT INTO ipd_theatre_billing_rules (rule_target_type, room_id, bed_id, procedure_id, service_id, frequency_id) VALUES (?, ?, ?, ?, ?, ?)");
                $stmt->bind_param("siiiii", $target_type, $room_id, $bed_id, $proc_id, $service_id, $frequency_id);
            }
            $stmt->execute();
        }
        elseif ($type === 'staff') {
            $staff = (int)$_POST['staff_id'];
            $role = (int)$_POST['role_id'];
            if(!$staff || !$role) throw new Exception("Staff and Role selections are required.");

            if ($id) { 
                $stmt = $conn->prepare("UPDATE ipd_setup_theatre_staff SET staff_id=?, role_id=? WHERE id=?"); 
                $stmt->bind_param("iii", $staff, $role, $id); 
            } else { 
                $stmt = $conn->prepare("INSERT INTO ipd_setup_theatre_staff (staff_id, role_id) VALUES (?, ?)"); 
                $stmt->bind_param("ii", $staff, $role); 
            }
            
            if (!$stmt->execute()) {
                if ($conn->errno === 1062) throw new Exception("This staff member is already mapped to this specific role.");
                throw new Exception("Database error while mapping staff.");
            }
        }
        elseif ($type === 'procedures') {
            $name = trim($_POST['name']);
            $dept_id = (int)$_POST['department_id'];
            $cat_id = (int)$_POST['category_id'];
            $gdrg_code = !empty($_POST['gdrg_code_proc']) ? $_POST['gdrg_code_proc'] : null;
            
            if(empty($name) || !$cat_id || !$dept_id || empty($gdrg_code)) throw new Exception("All procedure mapping fields must be filled.");

            $conn->begin_transaction();

            $t_adult = 0.00; $t_child = 0.00;
            $qT = $conn->query("SELECT adult_tariff, child_tariff FROM nhis_gdrg_tariffs WHERE gdrg_code = '".$conn->real_escape_string($gdrg_code)."' ORDER BY id DESC LIMIT 1");
            if($qT && $tRow = $qT->fetch_assoc()) {
                $t_adult = (float)$tRow['adult_tariff'];
                $t_child = (float)$tRow['child_tariff'];
            }

            if ($id) {
                $qSvc = $conn->query("SELECT service_id FROM ipd_setup_surgical_procedures WHERE id = $id");
                $svc_id = $qSvc->fetch_assoc()['service_id'] ?? null;

                if ($svc_id) {
                    $stmtSvc = $conn->prepare("UPDATE service_catalog SET service_name=?, department_id=?, gdrg_adult_code=?, gdrg_child_code=?, tariff_adult=?, tariff_child=?, cash_price_adult=?, cash_price_child=?, nhis_covered=1 WHERE id=?");
                    $stmtSvc->bind_param("sissddddi", $name, $dept_id, $gdrg_code, $gdrg_code, $t_adult, $t_child, $t_adult, $t_child, $svc_id);
                    $stmtSvc->execute();
                } else {
                    $stmtSvc = $conn->prepare("INSERT INTO service_catalog (department_id, service_name, service_type, target_age_group, applicable_gender, nhis_covered, gdrg_adult_code, gdrg_child_code, tariff_adult, tariff_child, cash_price_adult, cash_price_child, is_active) VALUES (?, ?, 'Procedure', 'All Ages', 'Both', 1, ?, ?, ?, ?, ?, ?, 1)");
                    $stmtSvc->bind_param("isssdddd", $dept_id, $name, $gdrg_code, $gdrg_code, $t_adult, $t_child, $t_adult, $t_child);
                    $stmtSvc->execute();
                    $svc_id = $conn->insert_id;
                }

                $stmt = $conn->prepare("UPDATE ipd_setup_surgical_procedures SET procedure_name=?, category_id=?, gdrg_code=?, service_id=? WHERE id=?");
                $stmt->bind_param("sisii", $name, $cat_id, $gdrg_code, $svc_id, $id);
                $stmt->execute();

            } else {
                $stmtSvc = $conn->prepare("INSERT INTO service_catalog (department_id, service_name, service_type, target_age_group, applicable_gender, nhis_covered, gdrg_adult_code, gdrg_child_code, tariff_adult, tariff_child, cash_price_adult, cash_price_child, is_active) VALUES (?, ?, 'Procedure', 'All Ages', 'Both', 1, ?, ?, ?, ?, ?, ?, 1)");
                $stmtSvc->bind_param("isssdddd", $dept_id, $name, $gdrg_code, $gdrg_code, $t_adult, $t_child, $t_adult, $t_child);
                $stmtSvc->execute();
                $svc_id = $conn->insert_id;

                $stmt = $conn->prepare("INSERT INTO ipd_setup_surgical_procedures (procedure_name, service_id, category_id, gdrg_code) VALUES (?, ?, ?, ?)");
                $stmt->bind_param("siis", $name, $svc_id, $cat_id, $gdrg_code);
                $stmt->execute();
            }
            $conn->commit();
        }
        elseif ($type === 'anesthesia') {
            $name = trim($_POST['name']);
            $proc_id = !empty($_POST['procedure_id']) ? (int)$_POST['procedure_id'] : null;
            $target_age = $_POST['target_age_group'] ?? 'All Ages';
            $gender = $_POST['applicable_gender'] ?? 'Both';

            $cash_adult = (float)($_POST['cash_price_adult'] ?? 0);
            $cash_child = (float)($_POST['cash_price_child'] ?? 0);

            $nhis_covered = isset($_POST['nhis_covered']) ? 1 : 0;
            $tariff_adult = (float)($_POST['tariff_adult'] ?? 0);
            $tariff_child = (float)($_POST['tariff_child'] ?? 0);
            
            $is_copay = isset($_POST['is_copay_required']) ? 1 : 0;
            $copay_adult = (float)($_POST['nhis_copay_adult'] ?? 0);
            $copay_child = (float)($_POST['nhis_copay_child'] ?? 0);

            $corp_covered = isset($_POST['corp_covered']) ? 1 : 0;

            if(empty($name)) throw new Exception("The Anesthesia Name is required.");

            $conn->begin_transaction();

            $dept_id = 16; 
            $gdrg_code = null;
            if ($proc_id) {
                $qP = $conn->query("SELECT s.department_id, p.gdrg_code FROM ipd_setup_surgical_procedures p LEFT JOIN service_catalog s ON p.service_id = s.id WHERE p.id = $proc_id");
                if($qP && $pRow = $qP->fetch_assoc()) {
                    $dept_id = $pRow['department_id'] ?: 16;
                    $gdrg_code = $pRow['gdrg_code'];
                }
            }

            if ($id) {
                $qSvc = $conn->query("SELECT service_id FROM ipd_setup_anesthesia_types WHERE id = $id");
                $svc_id = $qSvc->fetch_assoc()['service_id'];

                if ($svc_id) {
                    $stmtSvc = $conn->prepare("UPDATE service_catalog SET department_id=?, service_name=?, target_age_group=?, applicable_gender=?, nhis_covered=?, corp_covered=?, cash_price_adult=?, cash_price_child=?, gdrg_adult_code=?, gdrg_child_code=?, tariff_adult=?, tariff_child=?, is_copay_required=?, nhis_copay_adult=?, nhis_copay_child=? WHERE id=?");
                    $stmtSvc->bind_param("isssiiddssddiddi", $dept_id, $name, $target_age, $gender, $nhis_covered, $corp_covered, $cash_adult, $cash_child, $gdrg_code, $gdrg_code, $tariff_adult, $tariff_child, $is_copay, $copay_adult, $copay_child, $svc_id);
                    $stmtSvc->execute();
                } else {
                    $stmtSvc = $conn->prepare("INSERT INTO service_catalog (department_id, service_name, service_type, target_age_group, applicable_gender, nhis_covered, corp_covered, cash_price_adult, cash_price_child, gdrg_adult_code, gdrg_child_code, tariff_adult, tariff_child, is_copay_required, nhis_copay_adult, nhis_copay_child, is_active) VALUES (?, ?, 'Service', ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, 1)");
                    $stmtSvc->bind_param("isssiiddssddidd", $dept_id, $name, $target_age, $gender, $nhis_covered, $corp_covered, $cash_adult, $cash_child, $gdrg_code, $gdrg_code, $tariff_adult, $tariff_child, $is_copay, $copay_adult, $copay_child);
                    $stmtSvc->execute();
                    $svc_id = $conn->insert_id;
                }

                $pid_val = $proc_id ? $proc_id : "NULL";
                $conn->query("UPDATE ipd_setup_anesthesia_types SET procedure_id = $pid_val, type_name = '".$conn->real_escape_string($name)."', service_id = $svc_id WHERE id = $id");

            } else {
                $stmtSvc = $conn->prepare("INSERT INTO service_catalog (department_id, service_name, service_type, target_age_group, applicable_gender, nhis_covered, corp_covered, cash_price_adult, cash_price_child, gdrg_adult_code, gdrg_child_code, tariff_adult, tariff_child, is_copay_required, nhis_copay_adult, nhis_copay_child, is_active) VALUES (?, ?, 'Service', ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, 1)");
                $stmtSvc->bind_param("isssiiddssddidd", $dept_id, $name, $target_age, $gender, $nhis_covered, $corp_covered, $cash_adult, $cash_child, $gdrg_code, $gdrg_code, $tariff_adult, $tariff_child, $is_copay, $copay_adult, $copay_child);
                $stmtSvc->execute();
                $svc_id = $conn->insert_id;

                $pid_val = $proc_id ? $proc_id : "NULL";
                $conn->query("INSERT INTO ipd_setup_anesthesia_types (type_name, procedure_id, service_id) VALUES ('".$conn->real_escape_string($name)."', $pid_val, $svc_id)");
            }

            if ($corp_covered && isset($_POST['corp_insurance_id'])) {
                $stmtCorp = $conn->prepare("INSERT INTO service_corporate_tariffs (service_id, insurance_type_id, tariff_amount_adult, tariff_amount_child, is_copay_required, copay_amount_adult, copay_amount_child) VALUES (?, ?, ?, ?, ?, ?, ?) ON DUPLICATE KEY UPDATE tariff_amount_adult=VALUES(tariff_amount_adult), tariff_amount_child=VALUES(tariff_amount_child), is_copay_required=VALUES(is_copay_required), copay_amount_adult=VALUES(copay_amount_adult), copay_amount_child=VALUES(copay_amount_child)");
                
                foreach ($_POST['corp_insurance_id'] as $idx => $ins_id) {
                    $ins_id = (int)$ins_id;
                    $c_adult = (float)($_POST['corp_tariff_adult'][$idx] ?? 0);
                    $c_child = (float)($_POST['corp_tariff_child'][$idx] ?? 0);
                    $c_req = isset($_POST['corp_is_copay'][$idx]) ? 1 : 0;
                    $c_copay_adult = (float)($_POST['corp_copay_adult'][$idx] ?? 0);
                    $c_copay_child = (float)($_POST['corp_copay_child'][$idx] ?? 0);

                    if ($c_adult > 0 || $c_child > 0) {
                        $stmtCorp->bind_param("iiddidd", $svc_id, $ins_id, $c_adult, $c_child, $c_req, $c_copay_adult, $c_copay_child);
                        $stmtCorp->execute();
                    } else {
                        $conn->query("DELETE FROM service_corporate_tariffs WHERE service_id = $svc_id AND insurance_type_id = $ins_id");
                    }
                }
            } else {
                if(isset($svc_id)) $conn->query("DELETE FROM service_corporate_tariffs WHERE service_id = $svc_id");
            }

            $conn->commit();
        }

        ob_end_clean(); echo json_encode(['status' => 'success', 'message' => 'Configuration saved & mapped successfully.']); exit;
    }

    if ($action === 'toggle_status') {
        $type = $_POST['config_type'];
        $id = (int)$_POST['id'];
        $new_status = (int)$_POST['new_status'];
        
        $table_map = ['rooms' => 'ipd_setup_theatre_rooms', 'beds' => 'ipd_setup_theatre_beds', 'billing_rules' => 'ipd_theatre_billing_rules', 'anesthesia' => 'ipd_setup_anesthesia_types', 'roles' => 'ipd_setup_theatre_roles', 'categories' => 'ipd_setup_surgery_categories', 'staff' => 'ipd_setup_theatre_staff', 'procedures' => 'ipd_setup_surgical_procedures'];
        $table = $table_map[$type];

        $stmt = $conn->prepare("UPDATE `$table` SET is_active = ? WHERE id = ?");
        $stmt->bind_param("ii", $new_status, $id);
        $stmt->execute();
        
        if($type === 'procedures' || $type === 'anesthesia') {
            $q = $conn->query("SELECT service_id FROM `$table` WHERE id = $id");
            if($q && $row = $q->fetch_assoc()) {
                $svc_id = $row['service_id'];
                if($svc_id) $conn->query("UPDATE service_catalog SET is_active = $new_status WHERE id = $svc_id");
            }
        }

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

    if ($action === 'delete_config') {
        $type = $_POST['config_type'];
        $id = (int)$_POST['id'];
        
        $table_map = ['rooms' => 'ipd_setup_theatre_rooms', 'beds' => 'ipd_setup_theatre_beds', 'billing_rules' => 'ipd_theatre_billing_rules', 'anesthesia' => 'ipd_setup_anesthesia_types', 'roles' => 'ipd_setup_theatre_roles', 'categories' => 'ipd_setup_surgery_categories', 'staff' => 'ipd_setup_theatre_staff', 'procedures' => 'ipd_setup_surgical_procedures'];
        $table = $table_map[$type];

        $stmt = $conn->prepare("DELETE FROM `$table` WHERE id = ?");
        $stmt->bind_param("i", $id);
        if ($stmt->execute()) {
            ob_end_clean(); echo json_encode(['status' => 'success', 'message' => 'Record successfully deleted.']);
        } else {
            if ($conn->errno === 1451) throw new Exception("Cannot delete this record because it is currently linked to existing clinical data. Please disable it instead.");
            throw new Exception("Database error: Unable to delete record.");
        }
        exit;
    }

} catch (Exception $e) {
    if(isset($conn) && $conn->connect_errno === 0) $conn->rollback();
    ob_end_clean(); echo json_encode(['status' => 'error', 'message' => $e->getMessage()]); exit;
}
?>