<?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: DYNAMIC FORM TABLES
    // ==========================================
    $conn->query("CREATE TABLE IF NOT EXISTS `ipd_setup_clinical_stages` (
        `id` int(11) NOT NULL AUTO_INCREMENT,
        `stage_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_form_sections` (
        `id` int(11) NOT NULL AUTO_INCREMENT,
        `section_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 `theatre_form_setup` (
        `id` int(11) UNSIGNED NOT NULL AUTO_INCREMENT,
        `target_departments` varchar(255) DEFAULT NULL COMMENT 'Comma separated dept IDs',
        `target_procedures` varchar(255) DEFAULT NULL COMMENT 'Comma separated procedure IDs',
        `stage_id` int(11) DEFAULT NULL,
        `section_id` int(11) DEFAULT NULL,
        `field_label` varchar(150) NOT NULL,
        `field_name` varchar(100) NOT NULL,
        `field_type` varchar(50) NOT NULL DEFAULT 'text',
        `dictionary_reference` varchar(150) DEFAULT NULL,
        `embedded_section_id` int(11) DEFAULT NULL COMMENT 'Used if linking a form inside a form',
        `field_options` text DEFAULT NULL,
        `is_required` tinyint(1) DEFAULT 0,
        `display_order` int(11) DEFAULT 0,
        `is_active` tinyint(1) DEFAULT 1,
        PRIMARY KEY (`id`)
    ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;");

    // Patch existing legacy table to support advanced mappings & nested forms
    $chk1 = $conn->query("SHOW COLUMNS FROM theatre_form_setup LIKE 'stage_id'");
    if($chk1 && $chk1->num_rows == 0) {
        $conn->query("ALTER TABLE `theatre_form_setup` ADD COLUMN `stage_id` INT(11) DEFAULT NULL AFTER `id`");
        $conn->query("ALTER TABLE `theatre_form_setup` ADD COLUMN `section_id` INT(11) DEFAULT NULL AFTER `stage_id`");
        $conn->query("ALTER TABLE `theatre_form_setup` ADD COLUMN `target_departments` VARCHAR(255) DEFAULT NULL AFTER `section_id`");
        $conn->query("ALTER TABLE `theatre_form_setup` ADD COLUMN `target_procedures` VARCHAR(255) DEFAULT NULL AFTER `target_departments`");
        $conn->query("ALTER TABLE `theatre_form_setup` ADD COLUMN `dictionary_reference` VARCHAR(150) DEFAULT NULL AFTER `field_type`");
        $conn->query("ALTER TABLE `theatre_form_setup` MODIFY COLUMN `field_type` VARCHAR(50) NOT NULL");
    }

    $chk2 = $conn->query("SHOW COLUMNS FROM theatre_form_setup LIKE 'embedded_section_id'");
    if($chk2 && $chk2->num_rows == 0) {
        $conn->query("ALTER TABLE `theatre_form_setup` ADD COLUMN `embedded_section_id` INT(11) DEFAULT NULL AFTER `dictionary_reference`");
    }

    // ==========================================
    // FETCH DROPDOWN DEPENDENCIES
    // ==========================================
    if ($action === 'fetch_dependencies') {
        $stages = []; $sections = []; $procedures = []; $depts = []; $dictionaries = [];
        
        $qStages = $conn->query("SELECT id, stage_name as name FROM ipd_setup_clinical_stages WHERE is_active=1 ORDER BY id ASC");
        if($qStages) while($r = $qStages->fetch_assoc()) $stages[] = $r;

        $qSec = $conn->query("SELECT id, section_name as name FROM ipd_setup_form_sections WHERE is_active=1 ORDER BY section_name ASC");
        if($qSec) while($r = $qSec->fetch_assoc()) $sections[] = $r;

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

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

        $qDict = $conn->query("SELECT dictionary_name as id, dictionary_name as name FROM system_dictionaries_registry WHERE is_active=1 ORDER BY dictionary_name ASC");
        if($qDict) while($r = $qDict->fetch_assoc()) $dictionaries[] = $r;

        ob_end_clean(); 
        echo json_encode(['status' => 'success', 'stages' => $stages, 'sections' => $sections, 'procedures' => $procedures, 'departments' => $depts, 'dictionaries' => $dictionaries]); 
        exit;
    }

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

        if ($type === 'stages') {
            $res = $conn->query("SELECT id, stage_name as name, is_active FROM ipd_setup_clinical_stages ORDER BY id ASC");
            if($res) while($row = $res->fetch_assoc()) $data[] = $row;
        } elseif ($type === 'sections') {
            $res = $conn->query("SELECT id, section_name as name, is_active FROM ipd_setup_form_sections ORDER BY id DESC");
            if($res) while($row = $res->fetch_assoc()) $data[] = $row;
        } elseif ($type === 'fields') {
            
            // Build Maps for Name Resolution
            $deptMap = []; $procMap = [];
            $resDept = $conn->query("SELECT id, department_name FROM departments");
            if($resDept) while($r = $resDept->fetch_assoc()) $deptMap[$r['id']] = $r['department_name'];

            $resProc = $conn->query("SELECT id, procedure_name FROM ipd_setup_surgical_procedures");
            if($resProc) while($r = $resProc->fetch_assoc()) $procMap[$r['id']] = $r['procedure_name'];

            $sql = "SELECT f.*, 
                           st.stage_name, 
                           sec.section_name
                    FROM theatre_form_setup f
                    LEFT JOIN ipd_setup_clinical_stages st ON f.stage_id = st.id
                    LEFT JOIN ipd_setup_form_sections sec ON f.section_id = sec.id
                    ORDER BY f.stage_id ASC, f.section_id ASC, f.display_order ASC";
            
            $res = $conn->query($sql);
            if($res) {
                while($row = $res->fetch_assoc()) {
                    
                    // Resolve Departments Array to Names
                    $d_names = [];
                    if(!empty($row['target_departments'])) {
                        $t_depts = explode(',', $row['target_departments']);
                        foreach($t_depts as $d) if(isset($deptMap[$d])) $d_names[] = $deptMap[$d];
                    }
                    $row['dept_targets'] = empty($d_names) ? '<span class="badge bg-secondary">Global (All Depts)</span>' : '<span class="badge bg-info text-dark">'.implode(', ', $d_names).'</span>';

                    // Resolve Procedures Array to Names
                    $p_names = [];
                    if(!empty($row['target_procedures'])) {
                        $t_procs = explode(',', $row['target_procedures']);
                        foreach($t_procs as $p) if(isset($procMap[$p])) $p_names[] = $procMap[$p];
                    }
                    $row['proc_targets'] = empty($p_names) ? '<span class="badge bg-secondary">Global (All Procs)</span>' : '<span class="badge bg-primary">'.implode(', ', $p_names).'</span>';

                    $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>';
            if($type === 'fields') {
                $row['req_badge'] = $row['is_required'] == 1 ? '<span class="text-danger fw-bold"><i class="fa fa-asterisk"></i> Yes</span>' : '<span class="text-muted">No</span>';
            }
        }

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

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

        if ($type === 'stages' || $type === 'sections') {
            $table = $type === 'stages' ? 'ipd_setup_clinical_stages' : 'ipd_setup_form_sections';
            $col = $type === 'stages' ? 'stage_name' : 'section_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 === 'fields') {
            $stage_id = (int)$_POST['stage_id'];
            $section_id = (int)$_POST['section_id'];
            
            // Implode array selections into comma separated strings
            $target_depts = !empty($_POST['target_departments']) ? implode(',', $_POST['target_departments']) : null;
            $target_procs = !empty($_POST['target_procedures']) ? implode(',', $_POST['target_procedures']) : null;
            
            $label = trim($_POST['field_label']);
            $f_type = $_POST['field_type'];
            
            // Intelligently route configuration based on field type
            $dict_ref = ($f_type === 'config_map') ? $_POST['dictionary_reference'] : null;
            $embed_id = ($f_type === 'embedded_form') ? (int)$_POST['embedded_section_id'] : null;
            
            $options = '';
            if (in_array($f_type, ['select', 'radio', 'checkbox'])) {
                $options = trim($_POST['field_options'] ?? '');
            } elseif ($f_type === 'richtext') {
                $options = trim($_POST['field_options_richtext'] ?? 'basic'); // basic, standard, advanced
            }
            
            $is_req = isset($_POST['is_required']) ? 1 : 0;
            $order = (int)($_POST['display_order'] ?? 0);

            if(!$stage_id || !$section_id || empty($label) || empty($f_type)) {
                throw new Exception("Stage, Section, Label, and Type are mandatory fields.");
            }

            // Clean JSON inputs to prevent DB injections (Snake Case generation)
            $field_name = strtolower(preg_replace('/[^a-zA-Z0-9]+/', '_', $label));

            if ($id) { 
                $stmt = $conn->prepare("UPDATE theatre_form_setup SET target_departments=?, target_procedures=?, stage_id=?, section_id=?, field_label=?, field_name=?, field_type=?, dictionary_reference=?, embedded_section_id=?, field_options=?, is_required=?, display_order=? WHERE id=?"); 
                // 13 params: ssiissssisiii
                $stmt->bind_param("ssiissssisiii", $target_depts, $target_procs, $stage_id, $section_id, $label, $field_name, $f_type, $dict_ref, $embed_id, $options, $is_req, $order, $id); 
            } else { 
                $stmt = $conn->prepare("INSERT INTO theatre_form_setup (target_departments, target_procedures, stage_id, section_id, field_label, field_name, field_type, dictionary_reference, embedded_section_id, field_options, is_required, display_order) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)"); 
                // 12 params: ssiissssisi
                $stmt->bind_param("ssiissssisii", $target_depts, $target_procs, $stage_id, $section_id, $label, $field_name, $f_type, $dict_ref, $embed_id, $options, $is_req, $order); 
            }
            $stmt->execute();
        }

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

    // ==========================================
    // TOGGLE & DELETE
    // ==========================================
    if ($action === 'toggle_status') {
        $type = $_POST['config_type'];
        $id = (int)$_POST['id'];
        $new_status = (int)$_POST['new_status'];
        
        $table = 'theatre_form_setup';
        if ($type === 'stages') $table = 'ipd_setup_clinical_stages';
        if ($type === 'sections') $table = 'ipd_setup_form_sections';

        $stmt = $conn->prepare("UPDATE `$table` SET is_active = ? WHERE id = ?");
        $stmt->bind_param("ii", $new_status, $id);
        $stmt->execute();

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

    if ($action === 'delete_config') {
        $type = $_POST['config_type'];
        $id = (int)$_POST['id'];
        
        $table = 'theatre_form_setup';
        if ($type === 'stages') $table = 'ipd_setup_clinical_stages';
        if ($type === 'sections') $table = 'ipd_setup_form_sections';

        $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 permanently deleted.']);
        } else {
            throw new Exception("Database error: Unable to delete record. It may be in use.");
        }
        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;
}
?>