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

$error = '';
$success = '';

// ログアウト
if (isset($_GET['logout'])) {
    session_destroy();
    header('Location: admin.php');
    exit;
}

// ログイン処理
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['password']) && !isset($_POST['title'])) {
    $pw = $_POST['password'];
    if ($pw === ADMIN_PASSWORD) {
        $_SESSION['auth'] = 'admin';
        header('Location: admin.php');
        exit;
    } else {
        $error = 'パスワードが正しくありません。';
    }
}

$authenticated = isAdminAuthenticated();

// メッセージ
if (isset($_GET['success'])) $success = '実績を登録しました。';
if (isset($_GET['deleted'])) $success = '実績を削除しました。';
if (isset($_GET['error'])) $error = 'エラーが発生しました。';

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

// 最近5件（新しい順）
$recent = array_slice(array_reverse($works), 0, 10);

function h(string $s): string {
    return htmlspecialchars($s, ENT_QUOTES, 'UTF-8');
}

function getCategoryColor(string $cat): string {
    $map = [
        '動画制作' => '#e53e3e',
        'Web・SNS' => '#6b46c1',
        'デザイン' => '#dd6b20',
        'イベント企画' => '#1a1a1a',
        'PR・広報' => '#276749',
    ];
    return $map[$cat] ?? '#718096';
}
?>
<!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">
</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>
    <?php if ($authenticated): ?>
    <nav class="header-nav">
      <a href="index.php" class="btn-view">ギャラリーを見る</a>
      <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">Staff Admin</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="admin-wrap">
  <?php if ($success): ?>
  <div class="alert alert-success"><?= h($success) ?></div>
  <?php endif; ?>
  <?php if ($error): ?>
  <div class="alert alert-error"><?= h($error) ?></div>
  <?php endif; ?>

  <div class="admin-grid">
    <!-- 投稿フォーム -->
    <div class="admin-form-wrap">
      <h2 class="section-title">新規実績を追加</h2>
      <form method="post" action="upload.php" enctype="multipart/form-data" class="admin-form">
        <div class="form-row">
          <label for="title">案件名 <span class="required">*</span></label>
          <input type="text" id="title" name="title" required placeholder="例: 〇〇社 Webサイトリニューアル">
        </div>

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

        <div class="form-row form-row-half">
          <div>
            <label for="staff">担当者</label>
            <input type="text" id="staff" name="staff" placeholder="担当者名">
          </div>
          <div>
            <label for="date">実施日</label>
            <input type="date" id="date" name="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 placeholder="例: 株式会社〇〇">
          </div>
          <div>
            <label for="sponsor">Sponsor（スポンサー）</label>
            <input type="text" id="sponsor" name="sponsor" placeholder="任意">
          </div>
        </div>

        <div class="form-row">
          <label class="checkbox-label" style="font-weight:600;">
            <input type="checkbox" name="publishToCorporate" value="1">
            <span>コーポレートサイトに公開する</span>
          </label>
        </div>

        <div class="form-row">
          <label for="description">説明文</label>
          <textarea id="description" name="description" rows="4" placeholder="案件の概要・内容を記入"></textarea>
        </div>

        <div class="form-row">
          <label>タグ（複数選択可）</label>
          <div class="checkbox-group">
            <?php foreach (['PLANNING', 'WEB', 'PR', 'DESIGN', 'EVENT', 'MOVIE'] as $tag): ?>
            <label class="checkbox-label">
              <input type="checkbox" name="tags[]" value="<?= h($tag) ?>">
              <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" placeholder="https://example.com">
          </div>
          <div>
            <label for="youtubeUrl">YouTube URL</label>
            <input type="url" id="youtubeUrl" name="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" placeholder="例: ユーザー数2.6倍、PV 1.7倍">
        </div>

        <div class="form-row">
          <label for="resultDetail">Result 詳細</label>
          <textarea id="resultDetail" name="resultDetail" rows="3" placeholder="成果の詳細を記入"></textarea>
        </div>

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

        <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">
          <button type="submit" class="btn-submit">登録する</button>
        </div>
      </form>
    </div>

    <!-- 最近の投稿一覧 -->
    <div class="recent-wrap">
      <h2 class="section-title">最近の投稿</h2>
      <?php if (empty($recent)): ?>
      <p class="empty-note">まだ実績がありません。</p>
      <?php else: ?>
      <div class="recent-list">
        <?php foreach ($recent as $w): ?>
        <?php $catColor = getCategoryColor($w['category'] ?? ''); ?>
        <div class="recent-item">
          <div class="recent-item-info">
            <span class="category-badge" style="background:<?= $catColor ?>"><?= h($w['category'] ?? '') ?></span>
            <span class="recent-title"><?= h($w['title'] ?? '') ?></span>
            <span class="recent-date"><?= h($w['date'] ?? '') ?></span>
          </div>
          <div class="recent-item-actions">
            <a href="edit.php?id=<?= h($w['id'] ?? '') ?>" class="btn-edit">編集</a>
            <form method="post" action="delete.php" class="delete-form"
                  onsubmit="return confirm('「<?= h(addslashes($w['title'] ?? '')) ?>」を削除しますか？')">
              <input type="hidden" name="id" value="<?= h($w['id'] ?? '') ?>">
              <button type="submit" class="btn-delete">削除</button>
            </form>
          </div>
        </div>
        <?php endforeach; ?>
      </div>
      <?php endif; ?>
    </div>
  </div>
</div>

<?php endif; ?>
</body>
</html>
