<?php
declare(strict_types=1);
require_once __DIR__ . '/db.php';
start_session();
$config = app_config();
$lang = strtolower((string)($_GET['lang'] ?? $_SESSION['survey_lang'] ?? 'zh'));
$lang = $lang === 'en' ? 'en' : 'zh';
$_SESSION['survey_lang'] = $lang;
$error = $_SESSION['form_error'] ?? '';
$success = $_SESSION['form_success'] ?? '';
unset($_SESSION['form_error'], $_SESSION['form_success']);
$isEn = $lang === 'en';
$txt = [
    'tag' => $isEn ? 'Survey · Manual review · Reward delivery' : '填写问卷 · 人工审核 · 奖励发放',
    'title' => $isEn ? 'Service Experience Survey' : ($config['app_name'] ?? '服务体验调查'),
    'intro' => $isEn ? 'After submission, your response will enter manual review. Each email can receive a reward only once. Review is usually completed within 24 hours; if there is no result within 24 hours, click customer service in the bottom-right corner.' : '提交后进入人工审核，每个邮箱仅限领取一次。审核时间通常为 24h 之内；24h 内无结果请点击右下角联系客服。',
    'query_title' => $isEn ? 'Check review result' : '查询审核结果',
    'query_desc' => $isEn ? 'Enter the email used for submission. If approved, the prize level and card code will be shown. If rejected, there is no reward.' : '已提交用户可在这里输入邮箱查询。审核通过后会显示获得的一/二/三等奖和对应卡密；审核失败无奖励。',
    'email_placeholder' => $isEn ? 'Enter the email used for submission' : '请输入提交时填写的邮箱',
    'query_btn' => $isEn ? 'Check result' : '查询结果',
    'email_label' => $isEn ? 'Email address' : '邮箱地址',
    'email_hint' => $isEn ? 'Each email can submit and receive a reward only once. Please make sure it is correct.' : '每个邮箱仅限提交一次，请确保邮箱填写正确。',
    'email_form_placeholder' => $isEn ? 'Used for review and result lookup' : '用于审核和查询结果',
    'q1' => $isEn ? '1. Which applications do you mainly use this service with?' : '1. 您主要在哪些应用使用本服务？',
    'other_placeholder' => $isEn ? 'Other application name, optional' : '其他应用，可填写名称',
    'q1_hint' => $isEn ? 'Please select at least one option, or fill in Other.' : '请至少选择一个选项，或填写“其他”。',
    'q2' => $isEn ? '2. What problems did you encounter while using the service?' : '2. 使用过程中，您遇到了哪些问题？',
    'q2_placeholder' => $isEn ? 'Minimum length: 10 characters.' : '字数要求：至少 10 字。',
    'q2_hint' => $isEn ? 'Requirement: at least 10 characters.' : '要求：10 字以上。',
    'q3' => $isEn ? '3. What do you think needs the most improvement?' : '3. 您认为本服务最需要改进的地方是什么？',
    'q3_placeholder' => $isEn ? 'Minimum length: 10 characters.' : '字数要求：至少 10 字。',
    'q3_hint' => $isEn ? 'Requirement: at least 10 characters.' : '要求：10 字以上。',
    'q4' => $isEn ? '4. What is your overall rating of this product?' : '4. 您对本产品的总体评价如何？',
    'rating_placeholder' => $isEn ? 'Minimum length: 20 characters.' : '字数要求：至少 20 字。',
    'rating_hint' => $isEn ? 'A comment or suggestion is required. Requirement: at least 20 characters.' : '必须填写评价或建议，要求：20 字以上。',
    'submit' => $isEn ? 'Submit survey for manual review' : '提交问卷，等待人工审核',
    'contact' => $isEn ? 'Contact support' : '联系客服',
    'contact_alert' => $isEn ? 'Please use the customer service entry in the bottom-right corner, or contact the administrator.' : '请点击页面右下角客服入口，或联系管理员处理。',
    'lang_switch' => $isEn ? '中文' : 'English',
    'lang_url' => $isEn ? 'index.php?lang=zh' : 'index.php?lang=en',
    'length_fail' => $isEn ? 'Submission failed: minimum length not met.' : '填写失败：未满足字数要求。',
];
$ratingLabels = $isEn ? [1=>'Very poor',2=>'Poor',3=>'Average',4=>'Satisfied',5=>'Very satisfied'] : [1=>'很差',2=>'较差',3=>'一般',4=>'满意',5=>'非常满意'];
?>
<!doctype html><html lang="<?= $isEn ? 'en' : 'zh-CN' ?>"><head><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1"><title><?= e($txt['title']) ?></title><link rel="stylesheet" href="assets/style.css"></head><body>
<div class="container">
<div class="language-bar"><a class="btn secondary" href="<?= e($txt['lang_url']) ?>"><?= e($txt['lang_switch']) ?></a></div>
<div class="hero"><span class="tag"><?= e($txt['tag']) ?></span><h1><?= e($txt['title']) ?></h1><p><?= e($txt['intro']) ?></p></div>
<div class="panel query-panel"><h2><?= e($txt['query_title']) ?></h2><p class="muted"><?= e($txt['query_desc']) ?></p><form method="get" action="query.php" class="query-form"><input type="hidden" name="lang" value="<?= e($lang) ?>"><input type="email" name="email" placeholder="<?= e($txt['email_placeholder']) ?>" required><button type="submit"><?= e($txt['query_btn']) ?></button></form></div>
<div class="panel"><?php if ($error): ?><div class="alert error"><?= e($error) ?></div><?php endif; ?><?php if ($success): ?><div class="alert success"><?= e($success) ?></div><?php endif; ?>
<form method="post" action="submit.php" id="surveyForm" novalidate><input type="hidden" name="csrf_token" value="<?= e(csrf_token()) ?>"><input type="hidden" name="lang" value="<?= e($lang) ?>">
<div class="question"><label class="title" for="email"><?= e($txt['email_label']) ?> <span>*</span></label><input id="email" type="email" name="email" placeholder="<?= e($txt['email_form_placeholder']) ?>" required><small><?= e($txt['email_hint']) ?></small></div>
<div class="question"><div class="title"><?= e($txt['q1']) ?> <span>*</span></div><div class="options multi">
<?php foreach(['Codex CLI','Claude Code','Factory Droid CLI'] as $option): ?><label><input type="checkbox" name="applications[]" value="<?= e($option) ?>"> <?= e($option) ?></label><?php endforeach; ?></div><input name="app_other" placeholder="<?= e($txt['other_placeholder']) ?>"><small><?= e($txt['q1_hint']) ?></small></div>
<div class="question"><label class="title" for="problems"><?= e($txt['q2']) ?> <span>*</span></label><textarea id="problems" name="problems" rows="4" maxlength="2000" placeholder="<?= e($txt['q2_placeholder']) ?>" required data-minchars="10" data-error-target="problems-error"></textarea><small><?= e($txt['q2_hint']) ?></small><div id="problems-error" class="field-error" aria-live="polite"></div></div>
<div class="question"><label class="title" for="improvement"><?= e($txt['q3']) ?> <span>*</span></label><textarea id="improvement" name="improvement" rows="4" maxlength="2000" placeholder="<?= e($txt['q3_placeholder']) ?>" required data-minchars="10" data-error-target="improvement-error"></textarea><small><?= e($txt['q3_hint']) ?></small><div id="improvement-error" class="field-error" aria-live="polite"></div></div>
<div class="question"><div class="title"><?= e($txt['q4']) ?> <span>*</span></div><div class="score-row"><?php foreach($ratingLabels as $score=>$label): ?><label><input type="radio" name="rating_score" value="<?= $score ?>" required><b><?= $score ?></b><small><?= e($label) ?></small></label><?php endforeach; ?></div><textarea name="rating_comment" rows="4" maxlength="3000" placeholder="<?= e($txt['rating_placeholder']) ?>" required data-minchars="20" data-error-target="rating-error"></textarea><small><?= e($txt['rating_hint']) ?></small><div id="rating-error" class="field-error" aria-live="polite"></div></div>
<button type="submit" class="submit-btn"><?= e($txt['submit']) ?></button><p class="center muted"><?= e($txt['intro']) ?></p></form></div></div><a class="contact-float" href="https://dengtaai.cc/" target="_blank" rel="noopener noreferrer"><?= e($txt['contact']) ?></a>
<script>
(function(){
  const form = document.getElementById('surveyForm');
  const lengthFail = <?= json_encode($txt['length_fail'], JSON_UNESCAPED_UNICODE) ?>;
  const minText = <?= json_encode($isEn ? 'Minimum length not met. Required: {min} characters.' : '未满足字数要求，至少需要填写 {min} 字。', JSON_UNESCAPED_UNICODE) ?>;
  function countChars(value){ return Array.from((value || '').trim()).length; }
  function showError(field, message){
    const target = field.dataset.errorTarget ? document.getElementById(field.dataset.errorTarget) : null;
    if (target) target.textContent = message;
    field.classList.add('invalid-field');
  }
  function clearError(field){
    const target = field.dataset.errorTarget ? document.getElementById(field.dataset.errorTarget) : null;
    if (target) target.textContent = '';
    field.classList.remove('invalid-field');
  }
  document.querySelectorAll('[data-minchars]').forEach(field => field.addEventListener('input', () => clearError(field)));
  form.addEventListener('submit', function(e){
    let firstInvalid = null;
    document.querySelectorAll('[data-minchars]').forEach(function(field){
      const min = parseInt(field.dataset.minchars || '0', 10);
      if (countChars(field.value) < min) {
        showError(field, minText.replace('{min}', String(min)));
        firstInvalid = firstInvalid || field;
      } else {
        clearError(field);
      }
    });
    if (firstInvalid) {
      e.preventDefault();
      alert(lengthFail);
      firstInvalid.focus();
    }
  });
})();
</script></body></html>
