<?php
// ============================================
// 嘉品仪器 - 服务工单中心（报修 / 保养 / 报价）
// 会员端：提交工单 + 我的工单列表
// ============================================
require_once __DIR__.'/includes/functions.php';
require_member();

$member = get_current_member();
$msg = $_GET['msg'] ?? '';
$msg_type = ($msg === 'created') ? 'success' : 'error';
$msg_text = [
    'created' => '工单提交成功，我们已收到您的请求',
    'fail' => '提交失败，请检查填写内容后重试',
][$msg] ?? '';

$tab = $_GET['tab'] ?? 'all';
$valid_tabs = ['all', 'repair', 'maintenance', 'quote', 'download'];
if (!in_array($tab, $valid_tabs, true)) $tab = 'all';

$type_labels = ['repair' => '报修', 'maintenance' => '保养', 'quote' => '报价', 'download' => '资料下载申请'];

// GET 预填（#1053：产品详情/知识库“保养申请/报价”按钮带入上下文）
$g_type = isset($_GET['type']) ? trim((string)$_GET['type']) : '';
if (!isset($type_labels[$g_type])) $g_type = 'maintenance';
// repair 走独立《维修申请单》，快速工单页仅保养/报价
if ($g_type === 'repair') $g_type = 'maintenance';
$g_title = trim((string)($_GET['title'] ?? ''));
if (mb_strlen($g_title) > 100) $g_title = mb_substr($g_title, 0, 100);
$g_desc = trim((string)($_GET['description'] ?? ''));
$g_phone = trim((string)($_GET['contact_phone'] ?? ''));

// ===== 提交工单 =====
if ($_SERVER['REQUEST_METHOD'] === 'POST' && ($_POST['action'] ?? '') === 'create') {
    $type = trim($_POST['type'] ?? '');
    $title = trim($_POST['title'] ?? '');
    $desc = trim($_POST['description'] ?? '');
    $phone = trim($_POST['contact_phone'] ?? '');
    $images_json = trim($_POST['images'] ?? '[]');
    $images = json_decode($images_json, true);
    if (!is_array($images)) $images = [];
    $images = array_values(array_filter($images, function ($u) {
        return is_string($u) && strpos($u, '/uploads/wo/') === 0 && strpos($u, '..') === false;
    }));

    // 报修统一走结构化维修申请单（repair-form.php）
    if ($type === 'repair') { header('Location: /repair-form.php'); exit; }
    if (!isset($type_labels[$type]) || mb_strlen($title) < 2 || mb_strlen($title) > 100 || mb_strlen($desc) > 3000 || count($images) > 9) {
        header('Location: /service.php?msg=fail#submit'); exit;
    }

    try {
        $pdo->beginTransaction();
        $stmt = $pdo->prepare("INSERT INTO wo_orders (wo_no, type, member_id, title, description, images, contact_name, contact_phone, status, created_at, updated_at)
            VALUES (?, ?, ?, ?, ?, ?, ?, ?, 'pending', NOW(), NOW())");
        $contact_name = trim((string)($member['real_name'] ?? '')) ?: (string)$member['username'];
        $stmt->execute(['', $type, (int)$member['id'], $title, $desc, json_encode($images, JSON_UNESCAPED_UNICODE), $contact_name, $phone]);
        $oid = (int)$pdo->lastInsertId();
        $wo_no = 'WO' . date('Ymd') . '-' . str_pad((string)$oid, 4, '0', STR_PAD_LEFT);
        $pdo->prepare("UPDATE wo_orders SET wo_no = ? WHERE id = ?")->execute([$wo_no, $oid]);
        $log = $pdo->prepare("INSERT INTO wo_logs (order_id, action, note, operator_type, operator_id, operator_name, created_at)
            VALUES (?, 'created', ?, 'member', ?, ?, NOW())");
        $log->execute([$oid, '提交' . $type_labels[$type] . '工单', (int)$member['id'], $contact_name]);
        $pdo->commit();
        header('Location: /service-order.php?id=' . $oid); exit;
    } catch (Exception $e) {
        if ($pdo->inTransaction()) $pdo->rollBack();
        header('Location: /service.php?msg=fail#submit'); exit;
    }
}

// ===== 我的工单列表 =====
$where = ['member_id = ?'];
$params = [(int)$member['id']];
if ($tab !== 'all') { $where[] = 'type = ?'; $params[] = $tab; }
$stmt = $pdo->prepare("SELECT * FROM wo_orders WHERE " . implode(' AND ', $where) . " ORDER BY id DESC LIMIT 100");
$stmt->execute($params);
$orders = $stmt->fetchAll();

// 各类型计数角标
$cnt = ['all' => 0, 'repair' => 0, 'maintenance' => 0, 'quote' => 0, 'download' => 0];
$stmt2 = $pdo->prepare("SELECT type, COUNT(*) c FROM wo_orders WHERE member_id = ? GROUP BY type");
$stmt2->execute([(int)$member['id']]);
foreach ($stmt2->fetchAll() as $r) { $cnt[$r['type']] = (int)$r['c']; $cnt['all'] += (int)$r['c']; }

$status_labels = [
    'draft' => '草稿', 'pending' => '待处理', 'accepted' => '已接单', 'processing' => '处理中', 'quoting' => '报价中',
    'quoted' => '已报价', 'verifying' => '待审核返验', 'completed' => '已完成', 'closed' => '已关闭',
];
$status_colors = [
    'draft' => '#64748b', 'pending' => '#d97706', 'accepted' => '#B99168', 'processing' => '#B99168', 'quoting' => '#7c3aed',
    'quoted' => '#b45309', 'verifying' => '#db2777', 'completed' => '#16a34a', 'closed' => '#64748b',
];
$status_bg = [
    'draft' => '#f1f5f9', 'pending' => '#fef3c7', 'accepted' => '#EDE3D0', 'processing' => '#EDE3D0', 'quoting' => '#ede9fe',
    'quoted' => '#fef3c7', 'verifying' => '#fce7f3', 'completed' => '#dcfce7', 'closed' => '#f1f5f9',
];

$page_title = '客服中心 - 报修·保养·报价 - 嘉品仪器';
ob_start();
?>
<link rel="stylesheet" href="/assets/css/service.css?v=1.3">
<div class="page-header" style="background:linear-gradient(135deg,#A67C52,#B99168)">
  <div class="container">
    <h1>🛠 客服中心</h1>
    <p style="color:rgba(255,255,255,.85);margin-top:8px">仪器报修 · 定期保养 · 采购报价，提交后可随时查看处理进度</p>
  </div>
</div>

<div class="container">
  <?php if ($msg_text): ?><div class="wo-msg wo-msg-<?=htmlspecialchars($msg_type)?>"><?=htmlspecialchars($msg_text)?></div><?php endif; ?>

  <div class="wo-layout">
    <!-- 左：提交工单 -->
    <div class="wo-submit-card" id="submit">
      <h2 class="wo-card-title">📝 提交服务工单</h2>
      <form method="post" action="/service.php" enctype="multipart/form-data">
        <input type="hidden" name="action" value="create">
        <input type="hidden" name="images" id="woImages" value="[]">
        <div class="wo-type-row" role="tablist">
          <a class="wo-type-item wo-type-link" href="/repair-form.php">
            <span class="wo-type-chip wo-chip-repair">
              🔧 报修
              <small>结构化维修申请单 →</small>
            </span>
          </a>
          <?php foreach (['maintenance' => '保养', 'quote' => '报价', 'download' => '资料下载申请'] as $tk => $tv): ?>
          <label class="wo-type-item">
            <input type="radio" name="type" value="<?=htmlspecialchars($tk)?>" <?= $tk === $g_type ? 'checked' : '' ?>>
            <span class="wo-type-chip">
              <?= $tk === 'maintenance' ? '🧰 保养' : ($tk === 'quote' ? '💰 报价' : '📄 资料下载申请') ?>
              <small><?= $tk === 'maintenance' ? '定期维护保养' : ($tk === 'quote' ? '采购询价报价' : '申请下载保存本地') ?></small>
            </span>
          </label>
          <?php endforeach; ?>
        </div>
        <div class="wo-repair-hint">🔧 报修请填写<a href="/repair-form.php">《维修申请单》</a>——含设备信息、故障描述与附件，处理更快，支持保存草稿</div>
        <div class="wo-field">
          <label>标题 <i>*</i></label>
          <input type="text" name="title" maxlength="100" required placeholder="如：PA323 功率计无法开机" value="<?=htmlspecialchars($g_title)?>">
        </div>
        <div class="wo-field">
          <label>问题描述</label>
          <textarea name="description" rows="4" maxlength="3000" placeholder="请描述设备情况、故障现象或需求详情（型号、序列号、购买时间等有助于加快处理）"><?=htmlspecialchars($g_desc)?></textarea>
        </div>
        <div class="wo-field">
          <label>联系电话</label>
          <input type="text" name="contact_phone" maxlength="30" value="<?=htmlspecialchars($g_phone !== '' ? $g_phone : (string)($member['phone'] ?? ''))?>" placeholder="方便工程师与您联系">
        </div>
        <div class="wo-field">
          <label>图片上传 <small>（可选，最多 9 张）</small></label>
          <div class="wo-upload-area">
            <input type="file" id="woFile" accept="image/jpeg,image/png,image/gif,image/webp" multiple hidden>
            <button type="button" class="wo-upload-btn" onclick="document.getElementById('woFile').click()">＋ 上传图片</button>
            <div class="wo-thumbs" id="woThumbs"></div>
          </div>
        </div>
        <button type="submit" class="wo-submit-btn">提交工单</button>
      </form>
    </div>

    <!-- 右：我的工单 -->
    <div class="wo-list-card">
      <h2 class="wo-card-title">📋 我的工单</h2>
      <div class="wo-tabs">
        <?php foreach (['all' => '全部', 'repair' => '报修', 'maintenance' => '保养', 'quote' => '报价', 'download' => '资料下载申请'] as $tk => $tv): ?>
        <a class="wo-tab <?= $tab === $tk ? 'active' : '' ?>" href="/service.php?tab=<?=htmlspecialchars($tk)?>"><?=htmlspecialchars($tv)?> <b><?=$cnt[$tk]?></b></a>
        <?php endforeach; ?>
      </div>
      <?php if (!$orders): ?>
      <div class="wo-empty">暂无工单，左侧提交第一个服务工单吧</div>
      <?php else: ?>
      <div class="wo-list">
        <?php foreach ($orders as $o): ?>
        <a class="wo-item" href="<?= $o['status'] === 'draft' && $o['type'] === 'repair' ? '/repair-form.php?id=' . (int)$o['id'] : '/service-order.php?id=' . (int)$o['id'] ?>">
          <div class="wo-item-head">
            <span class="wo-item-no"><?=htmlspecialchars($o['wo_no'])?></span>
            <span class="wo-badge" style="color:<?=$status_colors[$o['status']]?>;background:<?=$status_bg[$o['status']]?>"><?=$status_labels[$o['status']] ?? $o['status']?></span>
          </div>
          <div class="wo-item-title">【<?=htmlspecialchars($type_labels[$o['type']] ?? $o['type'])?>】<?=htmlspecialchars($o['title'])?></div>
          <div class="wo-item-time"><?=date('Y-m-d H:i', strtotime($o['created_at']))?></div>
        </a>
        <?php endforeach; ?>
      </div>
      <?php endif; ?>
    </div>
  </div>
</div>

<script>
(function () {
  var imgs = [];
  var box = document.getElementById('woThumbs');
  var hidden = document.getElementById('woImages');
  var file = document.getElementById('woFile');
  function sync() { hidden.value = JSON.stringify(imgs); }
  function render() {
    box.innerHTML = '';
    imgs.forEach(function (u, i) {
      var d = document.createElement('div');
      d.className = 'wo-thumb';
      d.innerHTML = '<img src="' + u + '"><i data-i="' + i + '">✕</i>';
      box.appendChild(d);
    });
    sync();
  }
  box.addEventListener('click', function (e) {
    if (e.target.tagName === 'I') { imgs.splice(+e.target.getAttribute('data-i'), 1); render(); }
  });
  file.addEventListener('change', function () {
    var fs = Array.prototype.slice.call(file.files || []);
    if (!fs.length) return;
    if (imgs.length + fs.length > 9) { alert('最多上传 9 张图片'); file.value = ''; return; }
    fs.forEach(function (f) {
      var fd = new FormData();
      fd.append('file', f);
      fetch('/api-service-upload.php', { method: 'POST', body: fd })
        .then(function (r) { return r.json(); })
        .then(function (j) {
          if (j.location) { imgs.push(j.location); render(); }
          else if (j.error) { alert(j.error); }
        })
        .catch(function () { alert('图片上传失败，请重试'); });
    });
    file.value = '';
  });
})();
</script>
<?php
$content = ob_get_clean();
require __DIR__.'/includes/header.php';
echo $content;
require __DIR__.'/includes/footer.php';
