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

$error = '';

if (isset($_GET['logout'])) {
    session_destroy();
    header('Location: index.php');
    exit;
}

if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['password'])) {
    $pw = $_POST['password'];
    if ($pw === ADMIN_PASSWORD) {
        $_SESSION['auth'] = 'admin';
        header('Location: index.php');
        exit;
    } elseif ($pw === CLIENT_PASSWORD) {
        $_SESSION['auth'] = 'client';
        header('Location: index.php');
        exit;
    } else {
        $error = 'パスワードが正しくありません。';
    }
}

$authenticated = isClientAuthenticated();

$works = [];
$dataFile = __DIR__ . '/data/works.json';
if (file_exists($dataFile)) {
    $works = json_decode(file_get_contents($dataFile), true) ?: [];
    $works = array_reverse($works); // 新しいものを上に
}

$categories = [];
foreach ($works as $w) {
    if (!empty($w['category']) && !in_array($w['category'], $categories)) {
        $categories[] = $w['category'];
    }
}

function getCategoryColor(string $cat): string {
    $map = [
        '動画制作' => '#e53e3e',
        'Web・SNS' => '#6b46c1',
        'デザイン' => '#dd6b20',
        'イベント企画' => '#1a1a1a',
        'PR・広報' => '#276749',
        '広告運用' => '#b7791f',
    ];
    return $map[$cat] ?? '#718096';
}

function getTagColor(string $tag): string {
    $map = [
        'PLANNING' => '#3182ce',
        'WEB' => '#6b46c1',
        'PR' => '#d53f8c',
        'DESIGN' => '#dd6b20',
        'EVENT' => '#1a1a1a',
        'MOVIE' => '#e53e3e',
    ];
    return $map[$tag] ?? '#718096';
}

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/style.css">
</head>
<body>

<header class="site-header">
  <div class="header-inner">
    <div class="logo">Beethoven inc. <span class="logo-sep">|</span> <span class="logo-sub">PLAYING COMPANY</span></div>
    <?php if ($authenticated): ?>
    <nav class="header-nav">
      <?php if (isAdminAuthenticated()): ?>
      <a href="admin.php" class="btn-admin">管理</a>
      <?php endif; ?>
      <a href="?logout=1" class="btn-logout">ログアウト</a>
    </nav>
    <?php endif; ?>
  </div>
</header>

<?php if (!$authenticated): ?>
<div class="auth-wrap">
  <div class="auth-card">
    <div class="auth-logo">
      <span>Beethoven inc.</span>
      <span class="logo-sep">|</span>
      <span class="logo-sub">PLAYING COMPANY</span>
    </div>
    <div class="auth-title">Works Gallery</div>
    <div class="auth-subtitle">アクセスパスワードを入力してください</div>
    <?php if ($error): ?>
    <div class="auth-error"><?= h($error) ?></div>
    <?php endif; ?>
    <form method="post" class="auth-form">
      <div class="auth-field">
        <label for="password">パスワード</label>
        <input type="password" id="password" name="password" placeholder="Password" required autofocus autocomplete="off">
      </div>
      <button type="submit" class="auth-btn">アクセスする</button>
    </form>
  </div>
</div>

<?php else: ?>
<div class="gallery-wrap">
  <div class="page-title-wrap">
    <div class="watermark">WORKS</div>
    <h1 class="page-title">制作実績</h1>
    <p class="page-en">CASE STUDIES</p>
    <div class="underline"></div>
  </div>

  <div class="filter-bar">
    <button class="filter-btn active" data-category="all">すべて</button>
    <?php foreach ($categories as $cat): ?>
    <button class="filter-btn" data-category="<?= h($cat) ?>"><?= h($cat) ?></button>
    <?php endforeach; ?>
  </div>

  <div class="card-grid" id="cardGrid">
    <?php foreach ($works as $work): ?>
    <?php
      $id       = $work['id'] ?? '';
      $title    = $work['title'] ?? '';
      $category = $work['category'] ?? '';
      $tags     = $work['tags'] ?? [];
      $photos   = $work['photos'] ?? [];
      $catColor = getCategoryColor($category);
      $workJson = htmlspecialchars(json_encode($work, JSON_UNESCAPED_UNICODE), ENT_QUOTES, 'UTF-8');
    ?>
    <div class="work-card" data-category="<?= h($category) ?>" onclick="openModal(<?= $workJson ?>)">
      <div class="card-image-wrap">
        <?php if (!empty($photos)): ?>
        <img src="uploads/<?= h(basename($photos[0])) ?>" alt="<?= h($title) ?>" class="card-image" loading="lazy">
        <?php else: ?>
        <div class="card-image-placeholder"><span><?= h(mb_substr($title, 0, 2)) ?></span></div>
        <?php endif; ?>
        <?php if (!empty($tags)): ?>
        <div class="card-tags">
          <?php foreach ($tags as $tag): ?>
          <span class="tag-badge" style="background:<?= getTagColor($tag) ?>"><?= h($tag) ?></span>
          <?php endforeach; ?>
        </div>
        <?php endif; ?>
      </div>
      <div class="card-body">
        <?php if ($category): ?>
        <span class="category-badge" style="background:<?= $catColor ?>"><?= h($category) ?></span>
        <?php endif; ?>
        <h3 class="card-title"><?= h($title) ?></h3>
        <?php if (!empty($work['industry'])): ?>
        <p class="card-industry"><?= h($work['industry']) ?></p>
        <?php endif; ?>
        <p class="card-date"><?= h($work['date'] ?? '') ?><?= !empty($work['staff']) ? ' · ' . h($work['staff']) : '' ?></p>
        <?php if (!empty($work['description'])): ?>
        <p class="card-desc"><?= h($work['description']) ?></p>
        <?php endif; ?>
        <?php if (!empty($work['result'])): ?>
        <div class="card-result">
          <div class="card-result-label">RESULT / SCOPE</div>
          <div class="card-result-value"><?= h($work['result']) ?></div>
        </div>
        <?php endif; ?>
      </div>
    </div>
    <?php endforeach; ?>
    <?php if (empty($works)): ?>
    <div class="empty-state"><p>まだ実績が登録されていません。</p></div>
    <?php endif; ?>
  </div>
</div>

<div class="modal-overlay" id="modalOverlay" onclick="closeModal()"></div>
<div class="modal" id="modal">
  <button class="modal-close" onclick="closeModal()">✕</button>
  <div class="modal-inner" id="modalInner"></div>
</div>

<script>
function getCategoryColor(cat) {
  const map = {'動画制作':'#e53e3e','Web・SNS':'#6b46c1','デザイン':'#dd6b20','イベント企画':'#1a1a1a','PR・広報':'#276749'};
  return map[cat] || '#718096';
}
function getTagColor(tag) {
  const map = {'PLANNING':'#3182ce','WEB':'#6b46c1','PR':'#d53f8c','DESIGN':'#dd6b20','EVENT':'#1a1a1a','MOVIE':'#e53e3e'};
  return map[tag] || '#718096';
}
function esc(str) {
  if (!str) return '';
  return String(str).replace(/&/g,'&amp;').replace(/</g,'&lt;').replace(/>/g,'&gt;').replace(/"/g,'&quot;').replace(/'/g,'&#39;');
}
function extractYouTubeId(url) {
  const m = url.match(/(?:youtube\.com\/(?:watch\?v=|embed\/)|youtu\.be\/)([a-zA-Z0-9_-]{11})/);
  return m ? m[1] : null;
}
function openModal(work) {
  const inner = document.getElementById('modalInner');
  let html = '';
  const catColor = getCategoryColor(work.category || '');
  html += `<div class="modal-header">`;
  if (work.category) html += `<span class="category-badge" style="background:${catColor}">${esc(work.category)}</span>`;
  html += `<h2 class="modal-title">${esc(work.title || '')}</h2>`;
  if (work.industry) html += `<p class="modal-industry">${esc(work.industry)}</p>`;
  html += `</div>`;
  if (work.youtubeUrl) {
    const vid = extractYouTubeId(work.youtubeUrl);
    if (vid) html += `<div class="modal-youtube"><iframe src="https://www.youtube.com/embed/${esc(vid)}" frameborder="0" allowfullscreen allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture"></iframe></div>`;
  } else if (work.photos && work.photos.length > 0) {
    html += `<div class="modal-photos">`;
    work.photos.forEach(p => { html += `<img src="uploads/${esc(p.replace(/^.*[\/\\]/, ''))}" alt="" class="modal-photo" loading="lazy">`; });
    html += `</div>`;
  }
  if (work.description) html += `<p class="modal-description">${esc(work.description)}</p>`;
  if (work.result || work.resultDetail) {
    html += `<div class="result-box"><div class="result-label">RESULT</div>`;
    if (work.result) html += `<div class="result-main">${esc(work.result)}</div>`;
    if (work.resultDetail) html += `<div class="result-detail">${esc(work.resultDetail)}</div>`;
    html += `</div>`;
  }
  if (work.scope) html += `<div class="result-box"><div class="result-label">SCOPE</div><div class="result-detail">${esc(work.scope)}</div></div>`;
  if (work.tags && work.tags.length > 0) {
    html += `<div class="modal-tags">`;
    work.tags.forEach(tag => { html += `<span class="tag-badge" style="background:${getTagColor(tag)}">${esc(tag)}</span>`; });
    html += `</div>`;
  }
  html += `<div class="modal-meta">`;
  if (work.staff) html += `<span>担当: ${esc(work.staff)}</span>`;
  if (work.date) html += `<span>実施日: ${esc(work.date)}</span>`;
  html += `</div>`;
  if (work.websiteUrl) html += `<a href="${esc(work.websiteUrl)}" target="_blank" rel="noopener" class="btn-website">🔗 Webサイトを見る →</a>`;
  inner.innerHTML = html;
  document.getElementById('modal').classList.add('open');
  document.getElementById('modalOverlay').classList.add('open');
  document.body.style.overflow = 'hidden';
}
function closeModal() {
  document.getElementById('modal').classList.remove('open');
  document.getElementById('modalOverlay').classList.remove('open');
  document.body.style.overflow = '';
}
document.querySelectorAll('.filter-btn').forEach(btn => {
  btn.addEventListener('click', function() {
    document.querySelectorAll('.filter-btn').forEach(b => b.classList.remove('active'));
    this.classList.add('active');
    const cat = this.dataset.category;
    document.querySelectorAll('.work-card').forEach(card => {
      card.style.display = (cat === 'all' || card.dataset.category === cat) ? '' : 'none';
    });
  });
});
document.addEventListener('keydown', e => { if (e.key === 'Escape') closeModal(); });
</script>
<?php endif; ?>
</body>
</html>
