<%- include('../partials/admin-header') %>
<h1>产品管理</h1>

<div class="form-card">
  <h2>添加产品</h2>
  <form method="POST" action="/admin/products">
    <div class="form-row">
      <label>商家
        <select name="merchant_id" required>
          <option value="">选择商家</option>
          <% merchants.forEach(m => { %>
          <option value="<%= m.id %>"><%= m.name %></option>
          <% }) %>
        </select>
      </label>
      <label>产品名 <input name="name" required placeholder="HKG.Pulse.Mini"></label>
      <label>地区 <input name="location" placeholder="🇭🇰 HKG / 🇯🇵 JPN"></label>
      <label>产品页 URL <input name="url" placeholder="https://...（商家产品页）"></label>
    </div>
    <div class="form-row">
      <label style="flex:2">购买链接 <input name="buy_url" id="add_buy_url" placeholder="https://...（基础购买链接 或 含aff的链接）" onchange="autoParseUrl(this)"></label>
      <label>Aff 参数名 <input name="aff_param" id="add_aff_param" value="aff" placeholder="aff" style="width:80px"></label>
      <label>Aff 值 <input name="aff_code" id="add_aff_code" placeholder="如 5" oninput="previewAffUrl()"></label>
      <label>商家 PID <input name="provider_pid" id="add_provider_pid" placeholder="自动识别"></label>
    </div>
    <div id="add_aff_preview" style="display:none;padding:4px 12px;margin:-4px 0 8px;background:#e8f5e9;border-radius:4px;font-size:13px;word-break:break-all">
      <strong>生成的 Aff 链接：</strong><span id="add_aff_preview_url"></span>
    </div>
    <div class="form-row">
      <label>价格 <input name="price" placeholder="$49/月"></label>
      <label>年付价 <input name="annual_price" placeholder="$470.4/年"></label>
      <label>配置摘要 <input name="spec_summary" placeholder="2C / 4G / 40G｜1Gbps"></label>
      <label>流量 <input name="traffic" placeholder="1000G 单向"></label>
      <label>计费说明 <input name="billing_cycle" placeholder="年付 8 折"></label>
    </div>
    <div class="form-row">
      <label>优惠码 <input name="coupon_code" placeholder="gomami365"></label>
      <label>标签 <input name="tags" placeholder="gomami,pulse,香港"></label>
      <label>SKU <input name="sku"></label>
      <label style="flex:1">推送开头
        <input name="push_intro" placeholder="🔥 推荐产品">
      </label>
    </div>
    <div class="form-row">
      <label>Slug <input name="slug" placeholder="自动生成"></label>
    </div>
    <div class="form-row">
      <label>检测模式
        <select name="check_mode">
          <option value="keyword">keyword</option>
          <option value="manual">manual</option>
        </select>
      </label>
      <label style="flex:1">有货关键词
        <input name="in_stock_keywords" placeholder="Add to Cart,立即购买">
      </label>
      <label style="flex:1">缺货关键词
        <input name="out_of_stock_keywords" placeholder="Out of Stock,缺货,售罄">
      </label>
    </div>
    <div class="form-row">
      <label>
        <input type="checkbox" name="is_public" value="1" checked> 前台展示
      </label>
      <label>
        <input type="checkbox" name="is_featured" value="1"> 推荐
      </label>
      <label>排序值 <input name="sort_order" type="number" value="100" style="width:80px"></label>
      <label style="flex:1">备注 <input name="notes" placeholder="备注"></label>
      <button type="submit" class="btn btn-primary" style="align-self:end">添加</button>
    </div>
  </form>
</div>

<table>
  <thead><tr><th>系统PID</th><th>商家</th><th>产品</th><th>商家PID</th><th>Aff</th><th>价格</th><th>库存</th><th>前台</th><th>操作</th></tr></thead>
  <tbody>
    <% products.forEach(p => { %>
    <tr>
      <td><code style="font-size:11px;color:#6c757d"><%= p.internal_pid || '-' %></code></td>
      <td><%= p.merchant_name || '-' %></td>
      <td>
        <div><strong><%= p.location ? p.location + '｜' : '' %><%= p.name %></strong></div>
        <% if (p.spec_summary) { %><div class="muted"><%= p.spec_summary %></div><% } %>
        <% if (p.slug) { %><div class="muted" style="font-size:11px">/<%= p.slug %></div><% } %>
      </td>
      <td><%= p.provider_pid || '-' %></td>
      <td style="max-width:180px">
        <% if (p.aff_code) { %>
          <span class="badge" style="background:#d4edda;color:#155724;font-size:11px"><%= p.aff_param || 'aff' %>=<%= p.aff_code %></span>
          <% if (p.generated_aff_url) { %>
          <div class="muted" style="font-size:11px;margin-top:2px;word-break:break-all;max-width:180px;overflow:hidden;text-overflow:ellipsis;white-space:nowrap" title="<%= p.generated_aff_url %>">
            <a href="<%= p.generated_aff_url %>" target="_blank">🔗 aff链接</a>
            <% if (p.product_aff_url) { %><span style="color:#28a745">✓推送用</span><% } %>
          </div>
          <% } %>
        <% } else { %>-<% } %>
      </td>
      <td>
        <div><%= p.price || '-' %></div>
        <% if (p.annual_price) { %><div class="muted"><%= p.billing_cycle || '年付' %>：<%= p.annual_price %></div><% } %>
      </td>
      <td>
        <% if (p.in_stock === 1) { %><span class="badge badge-on">有货</span>
        <% } else if (p.in_stock === 2) { %><span class="badge badge-off">缺货</span>
        <% } else { %>未知<% } %>
      </td>
      <td><%= p.is_public ? '✅' : '❌' %></td>
      <td style="white-space:nowrap">
        <a href="/admin/products/<%= p.id %>/edit" class="btn btn-sm" style="background:#17a2b8;color:#fff">编辑</a>
        <form class="inline" method="POST" action="/admin/products/<%= p.id %>/delete" onsubmit="return confirm('确定删除?')">
          <button class="btn btn-danger btn-sm">删除</button>
        </form>
      </td>
    </tr>
    <% }) %>
  </tbody>
</table>

<script>
function autoParseUrl(input) {
  var url = input.value.trim();
  if (!url) return;
  fetch('/admin/products/api/parse-pid?url=' + encodeURIComponent(url))
    .then(function(r) { return r.json(); })
    .then(function(data) {
      if (data.provider_pid) {
        var el = document.getElementById('add_provider_pid');
        if (el && !el.value) { el.value = data.provider_pid; flashGreen(el); }
      }
      if (data.aff_code) {
        var el2 = document.getElementById('add_aff_code');
        if (el2 && !el2.value) { el2.value = data.aff_code; flashGreen(el2); }
      }
      if (data.aff_param) {
        var el3 = document.getElementById('add_aff_param');
        if (el3) { el3.value = data.aff_param; }
      }
      previewAffUrl();
    })
    .catch(function() {});
}

function previewAffUrl() {
  var buyUrl = document.getElementById('add_buy_url').value.trim();
  var affCode = document.getElementById('add_aff_code').value.trim();
  var affParam = document.getElementById('add_aff_param').value.trim() || 'aff';
  var preview = document.getElementById('add_aff_preview');
  var previewUrl = document.getElementById('add_aff_preview_url');

  if (buyUrl && affCode) {
    fetch('/admin/products/api/build-aff-url?base_url=' + encodeURIComponent(buyUrl) + '&aff_code=' + encodeURIComponent(affCode) + '&aff_param=' + encodeURIComponent(affParam))
      .then(function(r) { return r.json(); })
      .then(function(data) {
        if (data.aff_url) {
          previewUrl.textContent = data.aff_url;
          preview.style.display = 'block';
        }
      })
      .catch(function() {});
  } else {
    preview.style.display = 'none';
  }
}

function flashGreen(el) {
  el.style.borderColor = '#28a745';
  setTimeout(function() { el.style.borderColor = ''; }, 2000);
}
</script>
<%- include('../partials/footer') %>
