<?php
/**
 * 2026企业CMS - 后台自定义表单管理
 */

require_once __DIR__ . '/../includes/functions.php';
require_once __DIR__ . '/../includes/auth.php';

if (session_status() !== PHP_SESSION_ACTIVE) {
    session_start();
}

// ===== AJAX POST 请求处理（必须在任何HTML输出之前） =====
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['action'])) {
    if (!isset($_SESSION['admin_id']) || !$_SESSION['admin_id']) {
        header('Content-Type: application/json; charset=utf-8');
        echo json_encode(['success' => false, 'message' => '请先登录']);
        exit;
    }

    check_permission('editor');

    header('Content-Type: application/json; charset=utf-8');

    $action = $_POST['action'];
    $id = intval($_POST['id'] ?? 0);
    $name = trim($_POST['name'] ?? '');
    $slug = trim($_POST['slug'] ?? '');
    $description = trim($_POST['description'] ?? '');
    $type = $_POST['type'] ?? 'contact';
    $fields = $_POST['fields'] ?? '';
    $settings = $_POST['settings'] ?? '{}';
    $success_message = trim($_POST['success_message'] ?? '');
    $notification_email = trim($_POST['notification_email'] ?? '');

    if ($action === 'save') {
        if (empty($name)) {
            echo json_encode(['success' => false, 'message' => '表单名称不能为空']);
            exit;
        }
        if (empty($slug)) {
            $slug = generate_slug($name);
        }
        if (!empty($fields)) {
            json_decode($fields);
            if (json_last_error() !== JSON_ERROR_NONE) {
                echo json_encode(['success' => false, 'message' => '字段JSON格式错误']);
                exit;
            }
        }

        if ($id > 0) {
            $sql = "UPDATE forms SET name=?, slug=?, description=?, type=?, fields=?, settings=?, success_message=?, notification_email=? WHERE id=?";
            $stmt = $pdo->prepare($sql);
            $result = $stmt->execute([$name, $slug, $description, $type, $fields, $settings, $success_message, $notification_email, $id]);
        } else {
            $sql = "INSERT INTO forms (name, slug, description, type, fields, settings, success_message, notification_email) VALUES (?,?,?,?,?,?,?,?)";
            $stmt = $pdo->prepare($sql);
            $result = $stmt->execute([$name, $slug, $description, $type, $fields, $settings, $success_message, $notification_email]);
        }
        echo json_encode($result ? ['success' => true, 'message' => '保存成功'] : ['success' => false, 'message' => '保存失败']);
        exit;
    }

    if ($action === 'delete') {
        $id = intval($_POST['id'] ?? 0);
        $sql = "DELETE FROM forms WHERE id=?";
        $stmt = $pdo->prepare($sql);
        $result = $stmt->execute([$id]);
        echo json_encode($result ? ['success' => true, 'message' => '删除成功'] : ['success' => false, 'message' => '删除失败']);
        exit;
    }

    if ($action === 'get') {
        $id = intval($_POST['id'] ?? 0);
        $stmt = $pdo->prepare("SELECT * FROM forms WHERE id=?");
        $stmt->execute([$id]);
        $form = $stmt->fetch(PDO::FETCH_ASSOC);
        echo json_encode($form ? ['success' => true, 'data' => $form] : ['success' => false, 'message' => '表单不存在']);
        exit;
    }
}

// ===== GET 请求：渲染页面 =====
$admin = current_admin();
$pageTitle = '自定义表单';

ob_start();
require_once __DIR__ . '/header.php';

$forms = db_query("SELECT f.*, (SELECT COUNT(*) FROM form_submissions WHERE form_id=f.id) as submission_count FROM forms f ORDER BY created_at DESC");
?>
<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>自定义表单 - 2026企业CMS</title>
    <link rel="stylesheet" href="style.css">
    <style>
        .table-wrapper { margin: 20px 0; }
        table { width: 100%; border-collapse: collapse; background: #fff; }
        th, td { padding: 12px 15px; text-align: left; border-bottom: 1px solid #dee2e6; }
        th { background: #f8f9fa; font-weight: 600; }
        .modal { display: none; position: fixed; top:0;left:0; width:100%;height:100%; background:rgba(0,0,0,0.5); z-index:1000; }
        .modal.active { display: flex; align-items: center; justify-content: center; }
        .modal-content { background: white; padding:30px; border-radius:8px; width:90%; max-width:700px; max-height:90vh; overflow-y:auto; }
        .form-group { margin-bottom: 15px; }
        .form-group label { display:block; margin-bottom:5px; font-weight:500; }
        .form-group input,.form-group select,.form-group textarea { width:100%; padding:8px 12px; border:1px solid #ddd; border-radius:4px; font-size:14px; }
        .form-group textarea { min-height:80px; resize:vertical; }
        .btn-group { display:flex; gap:10px; justify-content:flex-end; margin-top:20px; }
    </style>
</head>
<body>
    <div class="container">
        <?php include 'sidebar.php'; ?>

        <main class="admin-content">
            <div class="page-header">
                <h1>自定义表单</h1>
                <button class="btn btn-primary" onclick="openModal()">新建表单</button>
            </div>

            <div class="table-wrapper">
                <table>
                    <thead>
                        <tr>
                            <th>ID</th>
                            <th>名称</th>
                            <th>标识</th>
                            <th>类型</th>
                            <th>提交数</th>
                            <th>创建时间</th>
                            <th>操作</th>
                        </tr>
                    </thead>
                    <tbody>
                        <?php foreach ($forms as $form): ?>
                        <tr>
                            <td><?php echo $form['id']; ?></td>
                            <td><?php echo xss_clean($form['name']); ?></td>
                            <td><code><?php echo xss_clean($form['slug']); ?></code></td>
                            <td><?php echo xss_clean($form['type']); ?></td>
                            <td><?php echo intval($form['submission_count']); ?></td>
                            <td><?php echo $form['created_at']; ?></td>
                            <td>
                                <button class="btn btn-sm btn-secondary" onclick="editForm(<?php echo $form['id']; ?>)">编辑</button>
                                <button class="btn btn-sm btn-danger" onclick="deleteForm(<?php echo $form['id']; ?>, '<?php echo htmlspecialchars($form['name'], ENT_QUOTES); ?>')">删除</button>
                            </td>
                        </tr>
                        <?php endforeach; ?>
                    </tbody>
                </table>
            </div>
        </main>
    </div>

    <div id="formModal" class="modal">
        <div class="modal-content">
            <h2 id="modalTitle">新建表单</h2>
            <form id="formForm">
                <input type="hidden" id="formId" name="id" value="0">
                <div class="form-group">
                    <label>表单名称</label>
                    <input type="text" id="formName" name="name" class="form-control" required>
                </div>
                <div class="form-group">
                    <label>标识(slug)</label>
                    <input type="text" id="formSlug" name="slug" class="form-control" placeholder="留空自动生成">
                </div>
                <div class="form-group">
                    <label>描述</label>
                    <textarea id="formDescription" name="description" class="form-control" rows="2"></textarea>
                </div>
                <div class="form-group">
                    <label>类型</label>
                    <select id="formType" name="type" class="form-control">
                        <option value="contact">联系表单</option>
                        <option value="registration">报名表单</option>
                        <option value="survey">调查问卷</option>
                        <option value="custom">自定义</option>
                    </select>
                </div>
                <div class="form-group">
                    <label>字段定义(JSON)</label>
                    <textarea id="formFields" name="fields" class="form-control" rows="4" placeholder="[]"></textarea>
                </div>
                <div class="form-group">
                    <label>成功提示语</label>
                    <input type="text" id="formSuccessMessage" name="success_message" class="form-control" value="提交成功，感谢您的参与！">
                </div>
                <div class="form-group">
                    <label>通知邮箱</label>
                    <input type="email" id="formNotificationEmail" name="notification_email" class="form-control">
                </div>
                <div class="btn-group">
                    <button type="button" class="btn btn-secondary" onclick="closeModal()">取消</button>
                    <button type="submit" class="btn btn-primary">保存</button>
                </div>
            </form>
        </div>
    </div>

    <script>
    function openModal() {
        document.getElementById('formModal').classList.add('active');
    }
    function closeModal() {
        document.getElementById('formModal').classList.remove('active');
        ['formId','formName','formSlug','formDescription','formFields','formSuccessMessage','formNotificationEmail'].forEach(function(id){
            document.getElementById(id).value = '';
        });
        document.getElementById('formFields').value = '[]';
        document.getElementById('formSuccessMessage').value = '提交成功，感谢您的参与！';
    }
    function editForm(id) {
        var fd = new FormData();
        fd.append('action', 'get'); fd.append('id', id);
        fetch('', {method:'POST', body:fd}).then(function(r){return r.json();}).then(function(data){
            if (data.success) {
                document.getElementById('modalTitle').textContent = '编辑表单';
                document.getElementById('formId').value = data.data.id;
                document.getElementById('formName').value = data.data.name;
                document.getElementById('formSlug').value = data.data.slug;
                document.getElementById('formDescription').value = data.data.description || '';
                document.getElementById('formType').value = data.data.type || 'contact';
                document.getElementById('formFields').value = data.data.fields || '[]';
                document.getElementById('formSuccessMessage').value = data.data.success_message || '提交成功，感谢您的参与！';
                document.getElementById('formNotificationEmail').value = data.data.notification_email || '';
                openModal();
            } else { alert(data.message); }
        });
    }
    function deleteForm(id, name) {
        if (!confirm('确定删除表单「'+name+'」吗？')) return;
        var fd = new FormData(); fd.append('action','delete'); fd.append('id',id);
        fetch('',{method:'POST',body:fd}).then(function(r){return r.json();}).then(function(d){
            if(d.success){alert(d.message);location.reload();}else{alert(d.message);}
        });
    }
    function showToast(msg, type) {
        type = type || 'success';
        var colors = {'success':'#28a745','error':'#dc3545','warning':'#ffc107','info':'#17a2b8'};
        var el = document.createElement('div');
        el.style.cssText = 'position:fixed;top:20px;right:20px;padding:12px 24px;background:'+colors[type]+';color:#fff;border-radius:4px;z-index:9999;font-size:14px;transition:all 0.3s;';
        el.textContent = msg;
        document.body.appendChild(el);
        setTimeout(function(){el.style.opacity=0;setTimeout(function(){el.remove();},300);},2000);
    }
    document.getElementById('formForm').addEventListener('submit', function(e){
        e.preventDefault();
        var fd = new FormData(this);
        fd.append('action', 'save');
        if (document.getElementById('formId').value > 0) { fd.set('action', 'save'); }
        fetch('', {method:'POST', body:new URLSearchParams(fd)})
            .then(function(r){return r.json();})
            .then(function(data){
                if(data.success){
                    showToast(data.message, 'success');
                    setTimeout(function(){location.reload();},1500);
                } else { alert(data.message||'操作失败'); }
            })
            .catch(function(err){ console.error(err); alert('网络错误，请重试'); });
    });
    document.getElementById('formModal').addEventListener('click', function(e){
        if(e.target===this){closeModal();}
    });
    </script>
</body>
</html>
<?php require_once __DIR__ . '/footer.php'; ?>
