<?php
/**
 * 问卷管理 API：按题套保存标题、启用状态和题目列表。
 * 作者: @ccfork
 */
header('Content-Type: application/json; charset=utf-8');
header('Access-Control-Allow-Origin: *');

$data_dir = dirname(__DIR__, 2) . '/data/';
$sets_file = $data_dir . 'questionnaire_sets.json';
$questions_file = $data_dir . 'questions.json';
$config_file = $data_dir . 'questionnaire_config.json';

if (!file_exists($data_dir)) mkdir($data_dir, 0777, true);

function respond_json($payload) {
    echo json_encode($payload, JSON_UNESCAPED_UNICODE);
    exit;
}

function read_json_file($file, $fallback = []) {
    if (!file_exists($file)) return $fallback;
    $data = json_decode(file_get_contents($file), true);
    return is_array($data) ? $data : $fallback;
}

function write_json_file($file, $data) {
    file_put_contents($file, json_encode($data, JSON_UNESCAPED_UNICODE | JSON_PRETTY_PRINT));
}

function default_questions() {
    $questions_path = dirname(__DIR__, 2) . '/questions.php';
    ob_start();
    include $questions_path;
    $json = ob_get_clean();
    $questions = json_decode($json, true);
    return is_array($questions) ? $questions : [];
}

function load_questions($questions_file) {
    $questions = read_json_file($questions_file, null);
    return is_array($questions) ? $questions : default_questions();
}

function normalize_title($title) {
    $title = trim($title ?? '');
    if ($title === '') return '小问卷';
    return mb_substr($title, 0, 60);
}

function new_set_id() {
    return 'set_' . date('YmdHis') . '_' . substr(bin2hex(random_bytes(4)), 0, 8);
}

function legacy_store($questions_file, $config_file) {
    $legacy_config = read_json_file($config_file, []);
    $title = normalize_title($legacy_config['title'] ?? '少女心笔记本');
    $enabled = array_key_exists('enabled', $legacy_config) ? !empty($legacy_config['enabled']) : true;
    $now = time();
    $set = [
        'id' => 'default',
        'title' => $title,
        'enabled' => $enabled,
        'questions' => load_questions($questions_file),
        'created' => intval($legacy_config['created'] ?? $now),
        'updated' => intval($legacy_config['updated'] ?? $now)
    ];
    return ['active_set_id' => 'default', 'sets' => [$set]];
}

function normalize_question_set($set, $fallback_index = 0) {
    $now = time();
    $id = preg_replace('/[^A-Za-z0-9_-]/', '', $set['id'] ?? '');
    if ($id === '') $id = $fallback_index === 0 ? 'default' : new_set_id();
    return [
        'id' => $id,
        'title' => normalize_title($set['title'] ?? '小问卷'),
        'enabled' => array_key_exists('enabled', $set) ? !empty($set['enabled']) : true,
        'questions' => is_array($set['questions'] ?? null) ? array_values($set['questions']) : [],
        'created' => intval($set['created'] ?? $now),
        'updated' => intval($set['updated'] ?? $now)
    ];
}

function load_store($sets_file, $questions_file, $config_file) {
    $store = read_json_file($sets_file, null);
    if (!is_array($store) || !is_array($store['sets'] ?? null)) {
        return legacy_store($questions_file, $config_file);
    }
    $sets = [];
    foreach ($store['sets'] as $index => $set) {
        if (is_array($set)) $sets[] = normalize_question_set($set, $index);
    }
    if (!$sets) return legacy_store($questions_file, $config_file);
    $active_id = preg_replace('/[^A-Za-z0-9_-]/', '', $store['active_set_id'] ?? '');
    $ids = array_column($sets, 'id');
    if ($active_id === '' || !in_array($active_id, $ids, true)) $active_id = $sets[0]['id'];
    return ['active_set_id' => $active_id, 'sets' => $sets];
}

function save_store($sets_file, $store) {
    write_json_file($sets_file, [
        'active_set_id' => $store['active_set_id'],
        'sets' => array_values($store['sets'])
    ]);
}

function active_set_index($store) {
    foreach ($store['sets'] as $index => $set) {
        if (($set['id'] ?? '') === ($store['active_set_id'] ?? '')) return $index;
    }
    return 0;
}

function active_set($store) {
    $index = active_set_index($store);
    return $store['sets'][$index] ?? normalize_question_set([]);
}

function set_summaries($sets) {
    return array_map(function($set) {
        return [
            'id' => $set['id'],
            'title' => $set['title'],
            'enabled' => !empty($set['enabled']),
            'question_count' => count($set['questions'] ?? []),
            'updated' => intval($set['updated'] ?? 0)
        ];
    }, array_values($sets));
}

function respond_store($store) {
    $active = active_set($store);
    respond_json([
        'success' => true,
        'active_set_id' => $active['id'],
        'active_set' => $active,
        'sets' => set_summaries($store['sets']),
        'config' => [
            'set_id' => $active['id'],
            'title' => $active['title'],
            'enabled' => !empty($active['enabled'])
        ],
        'questions' => $active['questions'] ?? []
    ]);
}

$raw_input = file_get_contents('php://input');
$json_input = json_decode($raw_input, true);
if (!is_array($json_input)) $json_input = [];
$action = $_GET['action'] ?? ($json_input['action'] ?? 'get');

$store = load_store($sets_file, $questions_file, $config_file);

if ($action === 'get') {
    respond_store($store);
}

if ($action === 'set_active_set') {
    $set_id = preg_replace('/[^A-Za-z0-9_-]/', '', $json_input['set_id'] ?? '');
    foreach ($store['sets'] as $set) {
        if (($set['id'] ?? '') === $set_id) {
            $store['active_set_id'] = $set_id;
            save_store($sets_file, $store);
            respond_store($store);
        }
    }
    respond_json(['success' => false, 'error' => '题套不存在']);
}

if ($action === 'create_set') {
    $now = time();
    $copy_current = !empty($json_input['copy_current']);
    $current = active_set($store);
    $store['sets'][] = [
        'id' => new_set_id(),
        'title' => normalize_title($json_input['title'] ?? '新问卷'),
        'enabled' => $copy_current,
        'questions' => $copy_current ? array_values($current['questions'] ?? []) : [],
        'created' => $now,
        'updated' => $now
    ];
    $store['active_set_id'] = $store['sets'][count($store['sets']) - 1]['id'];
    save_store($sets_file, $store);
    respond_store($store);
}

if ($action === 'delete_set') {
    if (count($store['sets']) <= 1) respond_json(['success' => false, 'error' => '至少保留一个题套']);
    $set_id = preg_replace('/[^A-Za-z0-9_-]/', '', $json_input['set_id'] ?? $store['active_set_id']);
    $store['sets'] = array_values(array_filter($store['sets'], function($set) use ($set_id) {
        return ($set['id'] ?? '') !== $set_id;
    }));
    if (!$store['sets']) respond_json(['success' => false, 'error' => '至少保留一个题套']);
    if ($store['active_set_id'] === $set_id) $store['active_set_id'] = $store['sets'][0]['id'];
    save_store($sets_file, $store);
    respond_store($store);
}

if ($action === 'set_enabled') {
    $active_index = active_set_index($store);
    $store['sets'][$active_index]['enabled'] = !empty($json_input['enabled']);
    $store['sets'][$active_index]['updated'] = time();
    save_store($sets_file, $store);
    respond_store($store);
}

if ($action === 'set_title') {
    $active_index = active_set_index($store);
    $store['sets'][$active_index]['title'] = normalize_title($json_input['title'] ?? '');
    $store['sets'][$active_index]['updated'] = time();
    save_store($sets_file, $store);
    respond_store($store);
}

if ($action === 'add_question') {
    $active_index = active_set_index($store);
    $questions = array_values($store['sets'][$active_index]['questions'] ?? []);
    $text = trim($json_input['text'] ?? '');
    $options = $json_input['options'] ?? [];
    if ($text === '') respond_json(['success' => false, 'error' => '题目不能为空']);
    if (!is_array($options)) $options = [];
    $option_rows = [];
    foreach ($options as $option_index => $label) {
        $label = trim($label);
        if ($label === '') continue;
        $option_rows[] = ['label' => $label, 'value' => $option_index + 1, 'next' => null];
    }
    $max_id = -1;
    foreach ($questions as $question) $max_id = max($max_id, intval($question['id'] ?? -1));
    $questions[] = [
        'id' => $max_id + 1,
        'text' => $text,
        'type' => 'single',
        'options' => $option_rows,
        'explain_page' => null
    ];
    $store['sets'][$active_index]['questions'] = $questions;
    $store['sets'][$active_index]['updated'] = time();
    save_store($sets_file, $store);
    respond_store($store);
}

if ($action === 'delete_question') {
    $active_index = active_set_index($store);
    $questions = array_values($store['sets'][$active_index]['questions'] ?? []);
    $id = intval($json_input['id'] ?? -1);
    $questions = array_values(array_filter($questions, function($question) use ($id) {
        return intval($question['id'] ?? -1) !== $id;
    }));
    $store['sets'][$active_index]['questions'] = $questions;
    $store['sets'][$active_index]['updated'] = time();
    save_store($sets_file, $store);
    respond_store($store);
}

if ($action === 'update_question') {
    $active_index = active_set_index($store);
    $questions = array_values($store['sets'][$active_index]['questions'] ?? []);
    $id = intval($json_input['id'] ?? -1);
    $text = trim($json_input['text'] ?? '');
    $type = ($json_input['type'] ?? 'single') === 'multi' ? 'multi' : 'single';
    $options = $json_input['options'] ?? [];
    if ($id < 0) respond_json(['success' => false, 'error' => '参数错误']);
    if ($text === '') respond_json(['success' => false, 'error' => '题目不能为空']);
    if (!is_array($options)) $options = [];
    $option_rows = [];
    foreach ($options as $option_index => $option) {
        if (is_array($option)) {
            $label = trim($option['label'] ?? '');
            $value = $option['value'] ?? ($option_index + 1);
            $next = $option['next'] ?? null;
            $is_dont_know = !empty($option['is_dont_know']);
            $is_skip = !empty($option['is_skip']);
        } else {
            $label = trim($option);
            $value = $option_index + 1;
            $next = null;
            $is_dont_know = false;
            $is_skip = false;
        }
        if ($label === '') continue;
        $row = ['label' => $label, 'value' => $value, 'next' => $next];
        if ($is_dont_know) $row['is_dont_know'] = true;
        if ($is_skip) $row['is_skip'] = true;
        $option_rows[] = $row;
    }
    foreach ($questions as $index => $question) {
        if (intval($question['id'] ?? -1) !== $id) continue;
        $questions[$index]['text'] = $text;
        $questions[$index]['type'] = $type;
        $questions[$index]['options'] = $option_rows;
        if (!isset($questions[$index]['explain_page'])) $questions[$index]['explain_page'] = null;
        $store['sets'][$active_index]['questions'] = $questions;
        $store['sets'][$active_index]['updated'] = time();
        save_store($sets_file, $store);
        respond_store($store);
    }
    respond_json(['success' => false, 'error' => '题目不存在']);
}

respond_json(['success' => false, 'error' => '未知操作']);
?>
