<?php
/**
 * 2026企业CMS - 表单提交处理
 */

// 引入核心文件
require_once __DIR__ . '/includes/functions.php';

// 只处理POST请求
if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
    header('Location: /');
    exit;
}

// 验证CSRF令牌
if (!isset($_POST['csrf_token']) || $_POST['csrf_token'] !== ($_SESSION['csrf_token'] ?? '')) {
    die('安全令牌错误，请刷新页面后重试。');
}

// 获取表单ID
$form_id = intval($_POST['form_id'] ?? 0);
if ($form_id === 0) {
    die('表单不存在。');
}

// 获取表单定义
$form = db_query_one("SELECT * FROM `forms` WHERE `id`=? AND `status`=1", [$form_id]);
if (!$form) {
    die('表单不存在或已禁用。');
}

// 解析表单字段
$fields = json_decode($form['fields'], true);
if (!$fields) {
    die('表单配置错误。');
}

// 处理提交数据
$submission_data = [];
$errors = [];

foreach ($fields as $field) {
    $name = $field['name'] ?? '';
    $label = $field['label'] ?? '';
    $type = $field['type'] ?? 'text';
    $required = $field['required'] ?? false;
    
    // 获取字段值
    if ($type === 'file') {
        // 文件上传
        if (isset($_FILES['fields']['name'][$name])) {
            $file = [
                'name' => $_FILES['fields']['name'][$name],
                'type' => $_FILES['fields']['type'][$name],
                'tmp_name' => $_FILES['fields']['tmp_name'][$name],
                'error' => $_FILES['fields']['error'][$name],
                'size' => $_FILES['fields']['size'][$name]
            ];
            
            if ($required && $file['error'] === UPLOAD_ERR_NO_FILE) {
                $errors[] = $label . ' 必须上传';
            }
            
            if ($file['error'] === UPLOAD_ERR_OK) {
                $upload_result = handle_upload($file, 'file');
                if (isset($upload_result['error'])) {
                    $errors[] = $upload_result['error'];
                } else {
                    $submission_data[$name] = $upload_result['path'];
                }
            }
        }
    } else {
        // 普通字段
        $value = $_POST['fields'][$name] ?? '';
        
        // 必填验证
        if ($required && empty($value)) {
            $errors[] = $label . ' 不能为空';
        }
        
        // 邮箱验证
        if ($type === 'email' && !empty($value) && !filter_var($value, FILTER_VALIDATE_EMAIL)) {
            $errors[] = $label . ' 格式不正确';
        }
        
        // 电话验证（简单验证）
        if ($type === 'tel' && !empty($value) && !preg_match('/^1[3-9]\d{9}$/', $value)) {
            $errors[] = $label . ' 格式不正确';
        }
        
        $submission_data[$name] = is_array($value) ? json_encode($value) : $value;
    }
}

// 如果有错误，显示错误
if (!empty($errors)) {
    echo '<!DOCTYPE html>
    <html lang="zh-CN">
    <head>
        <meta charset="UTF-8">
        <title>表单提交错误</title>
        <style>
            body { font-family: Arial, sans-serif; padding: 40px; text-align: center; }
            .error-box { max-width: 500px; margin: 0 auto; padding: 30px; background: #f8d7da; border-radius: 8px; }
            .error-box h2 { color: #721c24; }
            .error-box ul { text-align: left; margin-top: 15px; }
            .back-btn { margin-top: 20px; padding: 10px 20px; background: #2c82e0; color: white; border: none; border-radius: 4px; cursor: pointer; }
        </style>
    </head>
    <body>
        <div class="error-box">
            <h2>表单提交失败</h2>
            <ul>
                ' . implode('', array_map(function($error) { return '<li>' . htmlspecialchars($error) . '</li>'; }, $errors)) . '
            </ul>
            <button class="back-btn" onclick="history.back()">返回修改</button>
        </div>
    </body>
    </html>';
    exit;
}

// 保存提交数据
$data_json = json_encode($submission_data, JSON_UNESCAPED_UNICODE);
$ip = $_SERVER['REMOTE_ADDR'] ?? '';
$user_agent = $_SERVER['HTTP_USER_AGENT'] ?? '';

db_exec(
    "INSERT INTO `form_submissions` (`form_id`, `data`, `ip`, `user_agent`) VALUES (?, ?, ?, ?)",
    [$form_id, $data_json, $ip, $user_agent]
);

// 发送邮件通知
if (!empty($form['notification_email'])) {
    $subject = '表单提交通知 - ' . SITE_NAME;
    $body = '<h3>您收到了新的表单提交</h3>';
    $body .= '<p><strong>表单名称：</strong>' . htmlspecialchars($form['name']) . '</p>';
    $body .= '<p><strong>提交时间：</strong>' . date('Y-m-d H:i:s') . '</p>';
    $body .= '<p><strong>提交数据：</strong></p>';
    $body .= '<ul>';
    
    foreach ($submission_data as $key => $value) {
        $body .= '<li><strong>' . htmlspecialchars($key) . '：</strong> ' . htmlspecialchars($value) . '</li>';
    }
    
    $body .= '</ul>';
    
    send_mail($form['notification_email'], $subject, $body);
}

// 显示成功页面
$success_message = $form['success_message'] ?: '提交成功！';
?>
<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>提交成功 - <?php echo SITE_NAME; ?></title>
    <style>
        body {
            font-family: 'Microsoft YaHei', Arial, sans-serif;
            padding: 40px;
            text-align: center;
            background: #f5f5f5;
        }
        .success-box {
            max-width: 500px;
            margin: 50px auto;
            padding: 40px;
            background: white;
            border-radius: 8px;
            box-shadow: 0 2px 10px rgba(0,0,0,0.1);
        }
        .success-icon {
            font-size: 64px;
            color: #28a745;
            margin-bottom: 20px;
        }
        .success-box h2 {
            color: #28a745;
            margin-bottom: 15px;
        }
        .success-box p {
            color: #666;
            line-height: 1.8;
        }
        .back-btn {
            margin-top: 30px;
            padding: 12px 30px;
            background: #2c82e0;
            color: white;
            border: none;
            border-radius: 4px;
            font-size: 16px;
            cursor: pointer;
            text-decoration: none;
            display: inline-block;
        }
    </style>
</head>
<body>
    <div class="success-box">
        <div class="success-icon">✓</div>
        <h2>提交成功！</h2>
        <p><?php echo htmlspecialchars($success_message); ?></p>
        <a href="/" class="back-btn">返回首页</a>
    </div>
</body>
</html>
