<?php
// CRITICAL: Suppress warnings from breaking JSON headers
error_reporting(0);
ini_set('display_errors', 0);

ob_start();
if (session_status() === PHP_SESSION_NONE) {
    session_start();
}

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

try {
    // =====================================
    // 1. AUTO-HEALING DATABASE PROTOCOL
    // =====================================
    
    // Ensure Special Columns exist
    $chkPrio = $conn->query("SHOW COLUMNS FROM `ipd_setup_admission_priorities` LIKE 'color_code'");
    if($chkPrio && $chkPrio->num_rows == 0) $conn->query("ALTER TABLE `ipd_setup_admission_priorities` ADD COLUMN `color_code` varchar(20) DEFAULT '#0d6efd' AFTER `priority_level`");

    $chkOut = $conn->query("SHOW COLUMNS FROM `ipd_setup_round_outcomes` LIKE 'triggers_action'");
    if($chkOut && $chkOut->num_rows == 0) $conn->query("ALTER TABLE `ipd_setup_round_outcomes` ADD COLUMN `triggers_action` varchar(50) DEFAULT NULL AFTER `outcome_name`");

    // Unified Configuration Map for Standard Tables
    $config_map = [
        'adm_source'    => ['table' => 'ipd_setup_admission_sources', 'col' => 'source_name'],
        'adm_reason'    => ['table' => 'ipd_setup_admission_reasons', 'col' => 'reason_name'],
        'adm_status'    => ['table' => 'ipd_setup_admission_statuses', 'col' => 'status_name'],
        'trans_type'    => ['table' => 'ipd_setup_transfer_types', 'col' => 'type_name'],
        'trans_reason'  => ['table' => 'ipd_setup_transfer_reasons', 'col' => 'reason_name'],
        'round_type'    => ['table' => 'ipd_setup_round_types', 'col' => 'round_name'],
        'med_status'    => ['table' => 'ipd_setup_med_admin_status', 'col' => 'status_name'],
        'med_missed'    => ['table' => 'ipd_setup_missed_dose_reasons', 'col' => 'reason_name'],
        'med_alert'     => ['table' => 'ipd_setup_high_alert_categories', 'col' => 'category_name'],
        'iv_cannula'    => ['table' => 'ipd_setup_iv_cannula_types', 'col' => 'type_name'],
        'iv_site'       => ['table' => 'ipd_setup_iv_sites', 'col' => 'site_name'],
        'iv_status'     => ['table' => 'ipd_setup_iv_status', 'col' => 'status_name'],
        'iv_comp'       => ['table' => 'ipd_setup_iv_complications', 'col' => 'complication_name'],
        'bb_prior'      => ['table' => 'ipd_setup_blood_req_priorities', 'col' => 'priority_name'],
        'bb_compat'     => ['table' => 'ipd_setup_blood_compat_results', 'col' => 'result_name'],
        'bb_react'      => ['table' => 'ipd_setup_transfusion_reactions', 'col' => 'reaction_name'],
        'bb_sever'      => ['table' => 'ipd_setup_reaction_severity', 'col' => 'severity_name'],
        'dis_type'      => ['table' => 'ipd_setup_discharge_types', 'col' => 'type_name'],
        'dis_dest'      => ['table' => 'ipd_setup_discharge_destinations', 'col' => 'destination_name'],
        'dis_cond'      => ['table' => 'ipd_setup_discharge_conditions', 'col' => 'condition_name'],
        'mort_cat'      => ['table' => 'ipd_setup_death_categories', 'col' => 'category_name'],
        'cons_type'     => ['table' => 'ipd_setup_consultation_types', 'col' => 'type_name'],
        'cons_out'      => ['table' => 'ipd_setup_consult_outcomes', 'col' => 'outcome_name'],
        'alert_type'    => ['table' => 'ipd_setup_alert_types', 'col' => 'type_name'],
        'alert_sev'     => ['table' => 'ipd_setup_alert_severity', 'col' => 'severity_name'],
        'score_sys'     => ['table' => 'ipd_setup_scoring_systems', 'col' => 'system_name']
    ];

    // Auto-create all standard tables silently if they don't exist
    foreach ($config_map as $key => $schema) {
        $tbl = $schema['table']; $col = $schema['col'];
        $conn->query("CREATE TABLE IF NOT EXISTS `$tbl` ( `id` int(11) NOT NULL AUTO_INCREMENT, `$col` varchar(150) NOT NULL, `is_active` tinyint(1) DEFAULT 1, PRIMARY KEY (`id`) ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;");
    }

    if ($_SERVER['REQUEST_METHOD'] == 'POST') {
        $action = $_POST['action'] ?? '';

        // =====================================
        // DATATABLES FETCH ENGINE
        // =====================================
        if ($action === 'fetch_dictionaries') {
            $type = $_POST['dict_type'] ?? '';
            $data = [];
            
            // Special Cases
            if ($type === 'adm_priority') $res = $conn->query("SELECT id, priority_level as name, color_code, is_active FROM ipd_setup_admission_priorities ORDER BY id DESC");
            elseif ($type === 'round_outcome') $res = $conn->query("SELECT id, outcome_name as name, triggers_action, is_active FROM ipd_setup_round_outcomes ORDER BY id DESC");
            // Dynamic Standard Cases
            elseif (isset($config_map[$type])) {
                $tbl = $config_map[$type]['table']; $col = $config_map[$type]['col'];
                $res = $conn->query("SELECT id, $col as name, is_active FROM $tbl ORDER BY id DESC");
            }
            
            if(isset($res) && $res) {
                while ($row = $res->fetch_assoc()) { $data[] = $row; }
            }
            if (ob_get_length()) ob_clean(); echo json_encode(['data' => $data]); exit;
        }

        // =====================================
        // GET SINGLE RECORD FOR EDITING
        // =====================================
        if ($action === 'get_record') {
            $table = $_POST['table']; $id = (int)$_POST['id'];
            
            // Verify table is authorized
            $is_auth = false;
            if($table === 'ipd_setup_admission_priorities' || $table === 'ipd_setup_round_outcomes') $is_auth = true;
            foreach($config_map as $schema) { if($schema['table'] === $table) $is_auth = true; }
            
            if(!$is_auth) { if (ob_get_length()) ob_clean(); echo json_encode(['status' => 'error', 'message' => 'Unauthorized Table']); exit; }
            
            $stmt = $conn->prepare("SELECT * FROM $table WHERE id = ?"); $stmt->bind_param("i", $id); $stmt->execute();
            $record = $stmt->get_result()->fetch_assoc();
            if (ob_get_length()) ob_clean(); echo json_encode(['status' => 'success', 'data' => $record]); exit;
        }

        // =====================================
        // UNIFIED SAVING ENGINE
        // =====================================
        if ($action === 'save_dictionary') {
            $id = !empty($_POST['id']) ? (int)$_POST['id'] : null;
            $type = $_POST['dict_type'];
            $name = trim($_POST['dict_name']);
            
            // Handle Special Cases
            if ($type === 'adm_priority') {
                $color = trim($_POST['color_code'] ?? '#0d6efd');
                if($id) { $stmt = $conn->prepare("UPDATE ipd_setup_admission_priorities SET priority_level=?, color_code=? WHERE id=?"); $stmt->bind_param("ssi", $name, $color, $id); } 
                else { $stmt = $conn->prepare("INSERT INTO ipd_setup_admission_priorities (priority_level, color_code) VALUES (?, ?)"); $stmt->bind_param("ss", $name, $color); }
            } 
            elseif ($type === 'round_outcome') {
                $trigger = trim($_POST['triggers_action'] ?? '');
                if($id) { $stmt = $conn->prepare("UPDATE ipd_setup_round_outcomes SET outcome_name=?, triggers_action=? WHERE id=?"); $stmt->bind_param("ssi", $name, $trigger, $id); } 
                else { $stmt = $conn->prepare("INSERT INTO ipd_setup_round_outcomes (outcome_name, triggers_action) VALUES (?, ?)"); $stmt->bind_param("ss", $name, $trigger); }
            }
            // Handle All 26 Standard Cases Dynamically
            elseif(isset($config_map[$type])) {
                $table = $config_map[$type]['table']; $col = $config_map[$type]['col'];
                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); }
            } else {
                if (ob_get_length()) ob_clean(); echo json_encode(['status' => 'error']); exit;
            }

            if (ob_get_length()) ob_clean(); echo json_encode(['status' => $stmt->execute() ? 'success' : 'error']); exit;
        }

        // =====================================
        // GLOBAL TOGGLE & DELETE ENGINE
        // =====================================
        if ($action === 'delete_record' || $action === 'toggle_status') {
            $table = $_POST['table']; $id = (int)$_POST['id'];
            
            $is_auth = false;
            if($table === 'ipd_setup_admission_priorities' || $table === 'ipd_setup_round_outcomes') $is_auth = true;
            foreach($config_map as $schema) { if($schema['table'] === $table) $is_auth = true; }
            
            if($is_auth) {
                if ($action === 'delete_record') {
                    $conn->query("DELETE FROM $table WHERE id = $id");
                } else {
                    $status = (int)$_POST['status'];
                    $conn->query("UPDATE $table SET is_active = $status WHERE id = $id");
                }
            }
            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' => $e->getMessage()]);
    exit;
}
?>