<?php
session_start();
error_reporting(0); 
ob_start(); 

require_once dirname(__DIR__, 2) . '/includes/db.php';
if (!isset($conn) && isset($db)) { $conn = $db; }

ob_clean();
header('Content-Type: application/json');

if (!isset($conn) || !$conn) {
    echo json_encode(['status' => 'error', 'message' => 'Fatal Error: Database connection failed.']);
    exit;
}

$action = $_REQUEST['action'] ?? '';

try {
    if ($action === 'fetch') {
        $fields = [];
        $qFields = "
            SELECT c.*, COALESCE(d.department_name, 'Global (All Departments)') AS mapped_department
            FROM consultation_form_setup c
            LEFT JOIN departments d ON c.department_id = d.id
            ORDER BY c.department_id ASC, c.display_order ASC
        ";
        $resFields = $conn->query($qFields);
        if ($resFields) {
            while ($r = $resFields->fetch_assoc()) {
                $fields[] = $r;
            }
        }
        echo json_encode(['data' => $fields]);
        exit;
    }

    if ($action === 'add' || $action === 'edit') {
        $id = !empty($_POST['field_id']) ? (int)$_POST['field_id'] : null;
        $department_id = !empty($_POST['department_id']) ? (int)$_POST['department_id'] : null;
        
        $section_name = trim($_POST['section_name'] ?? ''); 
        $field_label = trim($_POST['field_label'] ?? '');
        
        $field_name = strtolower(preg_replace('/[^a-zA-Z0-9]+/', '_', trim($_POST['field_name'] ?? $field_label)));
        $field_name = trim($field_name, '_');
        
        $field_type = $_POST['field_type'] ?? 'text'; 
        $field_options = trim($_POST['field_options'] ?? '');
        
        $is_required = isset($_POST['is_required']) ? 1 : 0;
        $display_order = (int)($_POST['display_order'] ?? 0);
        $is_active = isset($_POST['is_active']) ? 1 : 0;

        if (empty($section_name) || empty($field_label) || empty($field_name)) {
            echo json_encode(['status' => 'error', 'message' => 'Please fill in the Clinical Phase, Field Label, and JSON Key.']);
            exit;
        }

        if ($action === 'add') {
            $check = $conn->prepare("SELECT id FROM consultation_form_setup WHERE field_name = ? AND (department_id = ? OR department_id IS NULL)");
            $check->bind_param("si", $field_name, $department_id);
            $check->execute();
            if ($check->get_result()->num_rows > 0) {
                echo json_encode(['status' => 'error', 'message' => 'This exact field identifier already exists for this department.']);
                exit;
            }
            $check->close();

            $stmt = $conn->prepare("INSERT INTO consultation_form_setup (department_id, section_name, field_label, field_name, field_type, field_options, is_required, display_order, is_active) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)");
            $stmt->bind_param("isssssiii", $department_id, $section_name, $field_label, $field_name, $field_type, $field_options, $is_required, $display_order, $is_active);
            
            if ($stmt->execute()) {
                echo json_encode(['status' => 'success', 'message' => 'Field mapped successfully.']);
            } else {
                echo json_encode(['status' => 'error', 'message' => 'Database error: ' . $stmt->error]);
            }
            $stmt->close();
        } 
        
        elseif ($action === 'edit' && $id) {
            $stmt = $conn->prepare("UPDATE consultation_form_setup SET department_id=?, section_name=?, field_label=?, field_name=?, field_type=?, field_options=?, is_required=?, display_order=?, is_active=? WHERE id=?");
            $stmt->bind_param("isssssiiii", $department_id, $section_name, $field_label, $field_name, $field_type, $field_options, $is_required, $display_order, $is_active, $id);
            
            if ($stmt->execute()) {
                echo json_encode(['status' => 'success', 'message' => 'Field mapping updated successfully.']);
            } else {
                echo json_encode(['status' => 'error', 'message' => 'Database error: ' . $stmt->error]);
            }
            $stmt->close();
        }
    }

    if ($action === 'delete') {
        $id = (int)($_POST['delete_id'] ?? 0);
        if ($id) {
            $stmt = $conn->prepare("DELETE FROM consultation_form_setup WHERE id = ?");
            $stmt->bind_param("i", $id);
            if ($stmt->execute()) {
                echo json_encode(['status' => 'success', 'message' => 'Field permanently deleted.']);
            } else {
                echo json_encode(['status' => 'error', 'message' => 'Error removing field: ' . $stmt->error]);
            }
            $stmt->close();
        } else {
            echo json_encode(['status' => 'error', 'message' => 'Invalid ID provided.']);
        }
    }

} catch (Exception $e) {
    echo json_encode(['status' => 'error', 'message' => 'Server Error: ' . $e->getMessage()]);
}
?>