<?php
require_once 'auth.php';
requireAdminAuth();

$dataFile = __DIR__ . '/data/works.json';
$uploadsDir = __DIR__ . '/uploads/';

// IDパラメータ取得
$targetId = trim($_GET['id'] ?? '');
if (empty($targetId)) {
    header('Location: admin.php?error=1');
    exit;
}

// works.json読み込み
$works = [];
if (file_exists($dataFile)) {
    $json = file_get_contents($dataFile);
    $works = json_decode($json, true) ?: [];
}

// 対象のworkを探す
$work = null;
foreach ($works as $w) {
    if ((string)($w['id'] ?? '') === $targetId) {
        $work = $w;
        break;
    }
}

if ($work === null) {
    header('Location: admin.php?error=1');
    exit;
}

function h(string $s): string {
    return htmlspecialchars($s, ENT_QUOTES, 'UTF-8');
}
?>
<!DOCTYPE html>
<html lang="ja">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>実績を編集 | Beethoven inc.</title>
<link rel="stylesheet" href="assets/admin.css">
<style>
.photo-thumb-list {
    display: flex;
    flex-wrap: wrap;
    gap: 12px;
    margin-top: 8px;
}
.photo-thumb-item {
    position: relative;
    display: inline-flex;
    flex-direction: column;
    align-items: center;
    gap: 4px;
}
.photo-thumb-item img {
    width: 100px;
    height: 80px;
    object-fit: cover;
    border-radius: 4px;
    border: 1px solid #e2e8f0;
}
.photo-thumb-item label {
    display: flex;
    align-items: center;
    gap: 4px;
    font-size: 0.75rem;
    color: #e53e3e;
    cursor: pointer;
}
.photo-thumb-item input[type="checkbox"] {
    accent-color: #e53e3e;
    cursor: pointer;
}
</style>
</head>
<body>

<header class="site-header">
  <div class="header-inner">
    <div class="logo">Beethoven inc. <span class="logo-sep">|</span> <span class="logo-sub">ADMIN</span></div>
    <nav class="header-nav">
      <a href="admin.php" class="btn-view">管理画面に戻る</a>
      <a href="admin.php?logout=1" class="btn-logout">ログアウト</a>
    </nav>
  </div>
</header>

<div class="admin-wrap">
  <div class="admin-form-wrap" style="max-width: 800px;">
    <h2 class="section-title">実績を編集</h2>
    <form method="post" action="edit_save.php" enctype="multipart/form-data" class="admin-form">
      <input type="hidden" name="id" value="<?= h($work['id']) ?>">

      <div class="form-row">
        <label for="title">案件名 <span class="required">*</span></label>
        <input type="text" id="title" name="title" required
               value="<?= h($work['title'] ?? '') ?>"
               placeholder="例: 〇〇社 Webサイトリニューアル">
      </div>

      <div class="form-row form-row-half">
        <div>
          <label>カテゴリ <span class="required">*</span></label>
          <div class="checkbox-group">
            <?php
            $currentCats = $work['categories'] ?? (isset($work['category']) ? [$work['category']] : []);
            foreach (['動画制作','Web・SNS','デザイン','イベント企画','PR・広報','広告運用'] as $cat): ?>
            <label class="checkbox-label">
              <input type="checkbox" name="categories[]" value="<?= h($cat) ?>"<?= in_array($cat, $currentCats) ? ' checked' : '' ?>>
              <span><?= h($cat) ?></span>
            </label>
            <?php endforeach; ?>
          </div>
        </div>
        <div>
          <label for="industry">業種</label>
          <select id="industry" name="industry">
            <option value="">選択してください</option>
            <?php foreach (['官公庁・自治体','教育','医療・福祉','人材・就労支援','食品・飲食','小売・流通','メーカー','住宅・不動産','環境・サステナビリティ','IT・テクノロジー','金融・保険','交通・インフラ','観光・文化','メディア・広告','団体・協会','その他'] as $ind): ?>
            <option value="<?= h($ind) ?>"<?= ($work['industry'] ?? '') === $ind ? ' selected' : '' ?>><?= h($ind) ?></option>
            <?php endforeach; ?>
          </select>
        </div>
      </div>

      <div class="form-row form-row-half">
        <div>
          <label for="staff">担当者</label>
          <input type="text" id="staff" name="staff"
                 value="<?= h($work['staff'] ?? '') ?>"
                 placeholder="担当者名">
        </div>
        <div>
          <label for="date">実施日</label>
          <input type="date" id="date" name="date"
                 value="<?= h($work['date'] ?? '') ?>">
        </div>
      </div>

      <div class="form-row form-row-half">
        <div>
          <label for="client">Client（クライアント名）<span class="required">*</span></label>
          <input type="text" id="client" name="client" required
                 value="<?= h($work['client'] ?? '') ?>"
                 placeholder="例: 株式会社〇〇">
        </div>
        <div>
          <label for="sponsor">Sponsor（スポンサー）</label>
          <input type="text" id="sponsor" name="sponsor"
                 value="<?= h($work['sponsor'] ?? '') ?>"
                 placeholder="任意">
        </div>
      </div>

      <div class="form-row">
        <label class="checkbox-label" style="font-weight:600;">
          <input type="checkbox" name="publishToCorporate" value="1"<?= !empty($work['publishToCorporate']) ? ' checked' : '' ?>>
          <span>コーポレートサイトに公開する</span>
        </label>
      </div>

      <div class="form-row">
        <label for="description">説明文</label>
        <textarea id="description" name="description" rows="4"
                  placeholder="案件の概要・内容を記入"><?= h($work['description'] ?? '') ?></textarea>
      </div>

      <div class="form-row">
        <label>タグ（複数選択可）</label>
        <div class="checkbox-group">
          <?php
          $currentTags = $work['tags'] ?? [];
          foreach (['PLANNING', 'WEB', 'PR', 'DESIGN', 'EVENT', 'MOVIE'] as $tag):
          ?>
          <label class="checkbox-label">
            <input type="checkbox" name="tags[]" value="<?= h($tag) ?>"<?= in_array($tag, $currentTags) ? ' checked' : '' ?>>
            <span><?= h($tag) ?></span>
          </label>
          <?php endforeach; ?>
        </div>
      </div>

      <div class="form-row form-row-half">
        <div>
          <label for="websiteUrl">WebサイトURL</label>
          <input type="url" id="websiteUrl" name="websiteUrl"
                 value="<?= h($work['websiteUrl'] ?? '') ?>"
                 placeholder="https://example.com">
        </div>
        <div>
          <label for="youtubeUrl">YouTube URL</label>
          <input type="url" id="youtubeUrl" name="youtubeUrl"
                 value="<?= h($work['youtubeUrl'] ?? '') ?>"
                 placeholder="https://youtube.com/watch?v=...">
        </div>
      </div>

      <div class="form-row">
        <label for="result">Result（数値成果）</label>
        <input type="text" id="result" name="result"
               value="<?= h($work['result'] ?? '') ?>"
               placeholder="例: ユーザー数2.6倍、PV 1.7倍">
      </div>

      <div class="form-row">
        <label for="resultDetail">Result 詳細</label>
        <textarea id="resultDetail" name="resultDetail" rows="3"
                  placeholder="成果の詳細を記入"><?= h($work['resultDetail'] ?? '') ?></textarea>
      </div>

      <div class="form-row">
        <label>Scope（対応範囲・複数選択可）</label>
        <div class="checkbox-group checkbox-group-wrap">
          <?php
          $currentScopes = $work['scopes'] ?? [];
          foreach (['戦略・企画','Webサイト制作・運用','SNS運用','動画制作','グラフィックデザイン','広報・PR','広告','イベント運営','ブース制作','コンテンツ制作'] as $sc): ?>
          <label class="checkbox-label">
            <input type="checkbox" name="scopes[]" value="<?= h($sc) ?>"<?= in_array($sc, $currentScopes) ? ' checked' : '' ?>>
            <span><?= h($sc) ?></span>
          </label>
          <?php endforeach; ?>
        </div>
      </div>

      <!-- 既存写真サムネイル -->
      <?php if (!empty($work['photos'])): ?>
      <div class="form-row">
        <label>現在の写真（削除する場合はチェックを入れてください）</label>
        <div class="photo-thumb-list">
          <?php foreach ($work['photos'] as $photo): ?>
          <?php $safeName = basename($photo); ?>
          <div class="photo-thumb-item">
            <img src="uploads/<?= h($safeName) ?>" alt="<?= h($safeName) ?>">
            <label>
              <input type="checkbox" name="delete_photos[]" value="<?= h($safeName) ?>">
              削除
            </label>
          </div>
          <?php endforeach; ?>
        </div>
      </div>
      <?php endif; ?>

      <!-- 写真追加 -->
      <div class="form-row">
        <label for="photos">写真を追加（複数枚可）</label>
        <input type="file" id="photos" name="photos[]" multiple accept="image/jpeg,image/png,image/gif,image/webp">
        <p class="field-note">JPEG / PNG / GIF / WebP、各ファイル10MB以下</p>
      </div>

      <div class="form-actions">
        <a href="admin.php" class="btn-cancel" style="margin-right: 12px; text-decoration: none; color: #718096;">キャンセル</a>
        <button type="submit" class="btn-submit">更新する</button>
      </div>
    </form>
  </div>
</div>

</body>
</html>
