<?php
declare(strict_types=1);

require_once __DIR__ . '/../auth.php';
require_once __DIR__ . '/../db.php';

if (!function_exists('is_logged_in') || !is_logged_in()) {
  header('Location: /login.php');
  exit;
}
if (empty($_SESSION['role']) || $_SESSION['role'] !== 'admin') {
  http_response_code(403);
  echo '403 Forbidden';
  exit;
}

$csrf = function_exists('csrf_token') ? csrf_token() : '';

?>
<!doctype html>
<html lang="ja">
<head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width,initial-scale=1">
  <title>顧客管理</title>
  <style>
    body{font-family:system-ui,-apple-system,"Segoe UI","Hiragino Kaku Gothic ProN","Meiryo",sans-serif;margin:0;background:#f6f7fb;color:#111;}
    .wrap{max-width:1100px;margin:0 auto;padding:16px;}
    .top{display:flex;gap:10px;align-items:center;flex-wrap:wrap;margin-bottom:12px;}
    .btn{border:1px solid #cfd6e4;background:#fff;border-radius:10px;padding:10px 12px;cursor:pointer}
    .btn.primary{background:#1e66d0;border-color:#1e66d0;color:#fff}
    .card{background:#fff;border:1px solid #e3e8f3;border-radius:14px;padding:14px;margin:12px 0}
    table{width:100%;border-collapse:collapse}
    th,td{padding:10px;border-bottom:1px solid #eef1f7;text-align:left;font-size:14px}
    th{background:#fafbfe}
    input,textarea,select{width:100%;box-sizing:border-box;border:1px solid #cfd6e4;border-radius:10px;padding:10px}
    textarea{min-height:90px}
    .grid{display:grid;grid-template-columns:1fr 1fr;gap:12px}
    .muted{color:#6b7280;font-size:13px}
    .row{display:flex;gap:10px;align-items:center;flex-wrap:wrap}
    .pill{display:inline-block;border:1px solid #e3e8f3;background:#fafbfe;padding:4px 10px;border-radius:999px;font-size:12px;color:#374151}
  </style>
</head>
<body>
  <div class="wrap">
    <div class="top">
      <div class="pill">管理者</div>
      <a class="btn" href="/board.php">← Boardへ戻る</a>
      <button class="btn" id="reloadBtn">更新</button>
    </div>

    <div class="card">
      <h2 style="margin:0 0 8px;">顧客一覧</h2>
      <div class="muted" id="listMsg"></div>
      <div style="overflow:auto;">
        <table>
          <thead>
            <tr>
              <th style="width:70px;">ID</th>
              <th>顧客名</th>
              <th>担当者</th>
              <th>電話</th>
              <th>Email</th>
              <th style="width:90px;">有効</th>
              <th style="width:90px;">操作</th>
            </tr>
          </thead>
          <tbody id="customersTbody"></tbody>
        </table>
      </div>
    </div>

    <div class="card">
      <h2 style="margin:0 0 8px;">顧客 追加/編集</h2>
      <div class="muted" id="formMsg"></div>

      <form id="customerForm">
        <input type="hidden" name="csrf_token" value="<?= htmlspecialchars($csrf) ?>">
        <input type="hidden" name="id" id="custId" value="">

        <div class="grid">
          <div>
            <label>顧客名（必須）</label>
            <input type="text" name="name" id="custName" required>
          </div>
          <div>
            <label>担当者名</label>
            <input type="text" name="contact_name" id="custContactName">
          </div>
          <div>
            <label>電話</label>
            <input type="text" name="phone" id="custPhone">
          </div>
          <div>
            <label>Email</label>
            <input type="email" name="email" id="custEmail">
          </div>
        </div>

        <div style="margin-top:12px;">
          <label>住所</label>
          <input type="text" name="address" id="custAddress">
        </div>

        <div style="margin-top:12px;">
          <label>メモ</label>
          <textarea name="note" id="custNote"></textarea>
        </div>

        <div class="row" style="margin-top:12px;">
          <label style="display:flex;gap:8px;align-items:center;">
            <input type="checkbox" id="custActive" checked>
            有効
          </label>

          <button type="submit" class="btn primary">保存</button>
          <button type="button" class="btn" id="newBtn">新規入力</button>
        </div>
      </form>
    </div>
  </div>

<script>
const $ = (s)=>document.querySelector(s);

async function apiGet(url){
  const r = await fetch(url, {credentials:'same-origin'});
  const j = await r.json().catch(()=>null);
  if(!r.ok) throw new Error((j && j.error) ? j.error : ('HTTP_'+r.status));
  return j;
}
async function apiPost(url, form){
  const fd = new FormData(form);
  // checkboxは値として送る
  fd.set('is_active', $('#custActive').checked ? '1' : '0');
  const r = await fetch(url, {method:'POST', body:fd, credentials:'same-origin'});
  const j = await r.json().catch(()=>null);
  if(!r.ok) throw new Error((j && j.error) ? j.error : ('HTTP_'+r.status));
  return j;
}

function fillForm(c){
  $('#custId').value = c.id ?? '';
  $('#custName').value = c.name ?? '';
  $('#custContactName').value = c.contact_name ?? '';
  $('#custPhone').value = c.phone ?? '';
  $('#custEmail').value = c.email ?? '';
  $('#custAddress').value = c.address ?? '';
  $('#custNote').value = c.note ?? '';
  $('#custActive').checked = String(c.is_active ?? 1) === '1';
}

function clearForm(){
  fillForm({id:'',name:'',contact_name:'',phone:'',email:'',address:'',note:'',is_active:1});
  $('#formMsg').textContent = '新規入力モード';
}

async function loadCustomers(){
  $('#listMsg').textContent = '読み込み中...';
  const j = await apiGet('/api/customers_list.php');
  const items = j.items || j.customers || [];
  const tb = $('#customersTbody');
  tb.innerHTML = '';
  items.forEach(c=>{
    const tr = document.createElement('tr');
    tr.innerHTML = `
      <td>${c.id}</td>
      <td>${escapeHtml(c.name ?? '')}</td>
      <td>${escapeHtml(c.contact_name ?? '')}</td>
      <td>${escapeHtml(c.phone ?? '')}</td>
      <td>${escapeHtml(c.email ?? '')}</td>
      <td>${String(c.is_active ?? 1) === '1' ? '1' : '0'}</td>
      <td><button class="btn" data-edit="${c.id}">編集</button></td>
    `;
    tb.appendChild(tr);
  });
  $('#listMsg').textContent = `件数: ${items.length}`;
}

function escapeHtml(s){
  return String(s).replace(/[&<>"']/g, m => ({'&':'&amp;','<':'&lt;','>':'&gt;','"':'&quot;',"'":'&#39;'}[m]));
}

document.addEventListener('click', async (e)=>{
  const btn = e.target.closest('button[data-edit]');
  if(!btn) return;
  const id = btn.getAttribute('data-edit');
  try{
    $('#formMsg').textContent = '読み込み中...';
    const j = await apiGet('/api/customers_get.php?id=' + encodeURIComponent(id));
    fillForm(j.customer);
    $('#formMsg').textContent = `編集モード: ID=${id}`;
    window.scrollTo({top: document.body.scrollHeight, behavior:'smooth'});
  }catch(err){
    $('#formMsg').textContent = '取得失敗: ' + err.message;
  }
});

$('#customerForm').addEventListener('submit', async (e)=>{
  e.preventDefault();
  const id = $('#custId').value;
  if(!id){
    // 追加は既存customers_create.phpを使う（nameのみ確実に動く前提）
    // まず作成 → 直後に update で詳細を入れる（二段階）
    try{
      $('#formMsg').textContent = '作成中...';
      const fd = new FormData(e.target);
      const r1 = await fetch('/api/customers_create.php', {method:'POST', body:fd, credentials:'same-origin'});
      const j1 = await r1.json().catch(()=>null);
      if(!r1.ok) throw new Error((j1 && j1.error) ? j1.error : ('HTTP_'+r1.status));
      const newId = j1.customer_id;
      $('#custId').value = String(newId);
      $('#formMsg').textContent = '詳細保存中...';
      await apiPost('/api/customers_update.php', e.target);
      $('#formMsg').textContent = '保存しました';
      await loadCustomers();
    }catch(err){
      $('#formMsg').textContent = '保存失敗: ' + err.message;
    }
    return;
  }

  // 編集保存
  try{
    $('#formMsg').textContent = '保存中...';
    await apiPost('/api/customers_update.php', e.target);
    $('#formMsg').textContent = '保存しました';
    await loadCustomers();
  }catch(err){
    $('#formMsg').textContent = '保存失敗: ' + err.message;
  }
});

$('#newBtn').addEventListener('click', clearForm);
$('#reloadBtn').addEventListener('click', async ()=>{ await loadCustomers(); });

(async ()=>{
  clearForm();
  await loadCustomers();
})();
</script>

</body>
</html>
