<?php
/**
 * /www/list.php  —  상품목록 (DB 연동) · 실제 kpoppoca 스키마 기준
 * ------------------------------------------------------------------
 * 필터:  ?type=photocard|goods|accessory|gacha
 *        ?artist=<slug>          (artists.slug)
 *        ?view=best | new        (best=is_featured / new=최근30일)
 *        ?q=<검색어>             (상품명 / 아티스트명)
 *        ?sort=new|price_asc|price_desc|name
 *        ?page=N                 (20개씩)
 *
 * products 에서 읽는 컬럼:
 *   id, artist_id, type, name, price, sale_price, thumbnail,
 *   is_active, is_featured, created_at
 * product_skus 에서 집계:
 *   price_delta, is_soldout, is_active   (최저가/품절 계산)
 * ------------------------------------------------------------------
 */

require_once __DIR__ . '/includes/config.php';        // $pdo, 세션, 공통함수(won/e/...)
require_once __DIR__ . '/includes/product_card.php';  // render_product_card()
require_once __DIR__ . '/includes/page_head.php';     // kp_page_head() 공통 제목

/* ---------------- 입력 파라미터 ---------------- */
$allowedTypes = ['photocard','goods','accessory','gacha'];
$type       = (isset($_GET['type']) && in_array($_GET['type'], $allowedTypes, true)) ? $_GET['type'] : '';
$artistSlug = isset($_GET['artist']) ? trim($_GET['artist']) : '';
$view       = in_array(($_GET['view'] ?? ''), ['best','new'], true) ? $_GET['view'] : '';
$q          = isset($_GET['q']) ? trim($_GET['q']) : '';
$sort       = in_array(($_GET['sort'] ?? ''), ['new','price_asc','price_desc'], true) ? $_GET['sort'] : 'new';
$page       = max(1, (int)($_GET['page'] ?? 1));
$perPage    = 20;
$offset     = ($page - 1) * $perPage;

/* ---------------- 아티스트 해석 ---------------- */
$artist = null;
$artistDisp = '';
if ($artistSlug !== '') {
    $st = $pdo->prepare("SELECT id, name, name_en FROM artists WHERE slug = ? AND is_active = 1");
    $st->execute([$artistSlug]);
    $artist = $st->fetch();
    if ($artist) {
        $artistDisp = (trim((string)($artist['name_en'] ?? '')) !== '') ? $artist['name_en'] : $artist['name'];
    }
}

/* ---------------- 진입 맥락 (아티스트 vs 타입) ----------------
   - 아티스트로 진입  → 카테고리 탭(전체/POCA/GOODS/ACCESSORIES) + '전체 아티스트 목록' 버튼
   - 타입으로 진입    → 아티스트 칩 스트립(전체 + 28팀)   ※ GACHA 제외(아티스트 무관)
   둘 다 지정된 URL이면 ctx 파라미터로 어느 줄을 보일지 구분(없으면 아티스트 우선). */
$ctxIn = in_array(($_GET['ctx'] ?? ''), ['artist','type'], true) ? $_GET['ctx'] : '';
if      ($ctxIn !== '')            { $ctx = $ctxIn; }
elseif  ($artist && $type === '') { $ctx = 'artist'; }
elseif  ($type !== '' && !$artist){ $ctx = 'type'; }
elseif  ($artist && $type !== '') { $ctx = 'artist'; }
else                              { $ctx = ''; }

/* 타입 맥락(가챠 제외)에서만 아티스트 칩 목록을 읽는다 */
$artistChips = [];
if ($ctx === 'type' && $type !== '' && $type !== 'gacha') {
    $ast = $pdo->query("SELECT name, name_en, slug FROM artists WHERE is_active = 1 ORDER BY sort_order, name");
    $artistChips = $ast->fetchAll();
}

/* ---------------- 가챠 소분류 (미니/대형/컬러링) ----------------
   가챠 페이지 서브탭. products.subcat 컬럼이 있을 때만 실제 필터(없으면 '전체'처럼 동작).
   subcat 값: mini / large / coloring  (어드민에서 가챠 상품 등록 시 지정) */
$gk = in_array(($_GET['gk'] ?? ''), ['mini','large','coloring'], true) ? $_GET['gk'] : '';
$hasSubcat = false;
if ($type === 'gacha') {
    try { $hasSubcat = (bool)$pdo->query("SHOW COLUMNS FROM products LIKE 'subcat'")->fetch(); } catch (Throwable $e) {}
}

/* ---------------- WHERE 빌드 ---------------- */
$where  = ['p.is_active = 1'];
$params = [];
if ($type !== '')    { $where[] = 'p.type = ?';      $params[] = $type; }
if ($artist)         { $where[] = 'p.artist_id = ?'; $params[] = $artist['id']; }
if ($view === 'best'){ $where[] = 'p.is_featured = 1'; }
if ($view === 'new') { $where[] = 'p.is_new = 1'; }
if ($q !== '')       { $where[] = '(p.name LIKE ? OR a.name LIKE ?)'; $params[] = "%$q%"; $params[] = "%$q%"; }
if ($type === 'gacha' && $gk !== '' && $hasSubcat) { $where[] = 'p.subcat = ?'; $params[] = $gk; }
$whereSql = implode(' AND ', $where);

/* ---------------- 정렬 ---------------- */
$orderMap = [
    'new'        => 'p.created_at DESC, p.id DESC',
    'price_asc'  => 'disp_price ASC',
    'price_desc' => 'disp_price DESC',
];
$orderSql = $orderMap[$sort];

/* ---------------- 총 개수 ---------------- */
$cst = $pdo->prepare("SELECT COUNT(*) FROM products p LEFT JOIN artists a ON a.id = p.artist_id WHERE $whereSql");
$cst->execute($params);
$total = (int)$cst->fetchColumn();
$totalPages = max(1, (int)ceil($total / $perPage));

/* ---------------- 목록 조회 (세일가/최저가/품절 집계) ----------------
   기본가 = sale_price 있으면 sale_price, 없으면 price
   표시가 = 기본가 + (재고 있는 SKU 중 최저 price_delta)
   품절   = 활성 SKU가 있는데 그중 재고(미품절)가 0개                       */
$sql = "
SELECT
    p.id, p.name, p.type, p.thumbnail, p.is_featured, p.price, p.sale_price,
    p.is_new AS is_new_calc,
    COALESCE(NULLIF(a.name_en,''), a.name) AS artist_name,
    (CASE WHEN p.sale_price IS NOT NULL AND p.sale_price > 0 THEN p.sale_price ELSE p.price END
       + COALESCE((SELECT MIN(s.price_delta) FROM product_skus s
                    WHERE s.product_id = p.id AND s.is_active = 1 AND s.is_soldout = 0), 0)) AS disp_price,
    (p.price
       + COALESCE((SELECT MIN(s.price_delta) FROM product_skus s
                    WHERE s.product_id = p.id AND s.is_active = 1 AND s.is_soldout = 0), 0)) AS list_disp,
    (SELECT COUNT(*) FROM product_skus s WHERE s.product_id = p.id AND s.is_active = 1)                     AS sku_total,
    (SELECT COUNT(*) FROM product_skus s WHERE s.product_id = p.id AND s.is_active = 1 AND s.is_soldout = 0) AS sku_instock
FROM products p
LEFT JOIN artists a ON a.id = p.artist_id
WHERE $whereSql
ORDER BY p.is_featured DESC, $orderSql
LIMIT $perPage OFFSET $offset
";
$st = $pdo->prepare($sql);
$st->execute($params);
$rows = $st->fetchAll();

/* ---------------- 제목 ---------------- */
$typeLabels = ['photocard'=>'포토카드','goods'=>'굿즈','accessory'=>'액세서리','gacha'=>'가챠'];
if ($q !== '') {
    $heading = '‘' . e($q) . '’ 검색결과';
} elseif ($artist && $type !== '') {
    $heading = e($artistDisp) . ' · ' . $typeLabels[$type];
} elseif ($artist) {
    $heading = e($artistDisp) . ' 전체상품';
} elseif ($view === 'best') {
    $heading = '베스트 상품';
} elseif ($view === 'new') {
    $heading = '신상품';
} elseif ($type !== '') {
    $heading = $typeLabels[$type];
} else {
    $heading = '전체 상품';
}

/* ---- 중앙 통일 제목(eyebrow / 영문 대제목 / 한글 보조) ---- */
$typeHead = [
    'photocard' => ['PHOTO CARD',     'POCA',        '최애의 공식 포토카드'],
    'goods'     => ['OFFICIAL GOODS', 'GOODS',       '아티스트 공식 굿즈'],
    'accessory' => ['ACCESSORIES',    'ACCESSORIES', '데일리 공식 액세서리'],
    'gacha'     => ['GACHA',          'GACHA',       '두근두근 랜덤 가챠'],
];
if ($q !== '') {
    $kphEye = 'SEARCH';    $kphTitle = '‘' . e($q) . '’';      $kphSub = '검색 결과';
} elseif ($artist) {
    $kphEye = 'ARTIST';    $kphTitle = e($artistDisp);
    $kphSub = ($type !== '' ? $typeLabels[$type] : '전체 상품');
} elseif ($view === 'best') {
    $kphEye = 'BEST';      $kphTitle = 'BEST';                  $kphSub = '많이 찾는 베스트 상품';
} elseif ($view === 'new') {
    $kphEye = 'NEW';       $kphTitle = 'NEW';                   $kphSub = '방금 들어온 신상품';
} elseif ($type !== '') {
    [$kphEye, $kphTitle, $kphSub] = $typeHead[$type];
} else {
    $kphEye = 'ALL ITEMS'; $kphTitle = 'ALL';                  $kphSub = '전체 상품';
}
$kphSub .= ' · <b>' . number_format($total) . '개 상품</b>';

/* ---------------- 쿼리스트링 헬퍼 (필터 유지) ---------------- */
function list_qs($overrides){
    $base = [
        'type'   => $_GET['type']   ?? null,
        'artist' => $_GET['artist'] ?? null,
        'q'      => $_GET['q']      ?? null,
        'view'   => $_GET['view']   ?? null,
        'sort'   => $_GET['sort']   ?? null,
        'ctx'    => $_GET['ctx']    ?? null,
        'gk'     => $_GET['gk']     ?? null,
        'page'   => null,
    ];
    $m = array_merge($base, $overrides);
    $m = array_filter($m, fn($v) => $v !== null && $v !== '');
    return '/list.php' . (empty($m) ? '' : '?' . http_build_query($m));
}

/* 헤더에 넘길 값 (header.php가 무시해도 무해) */
$page_title  = $heading . ' | KPOPPOCA';
$active_menu = $type !== '' ? $type : 'shop';

include __DIR__ . '/includes/header.php';
?>

<link rel="preconnect" href="https://fonts.googleapis.com">
<link href="https://fonts.googleapis.com/css2?family=Unbounded:wght@700;800&display=swap" rel="stylesheet">
<link rel="stylesheet" href="https://cdn.jsdelivr.net/gh/orioncactus/pretendard@v1.3.9/dist/web/static/pretendard.css">

<style>
.lst-wrap{ max-width:1200px; margin:0 auto; padding:18px 18px 70px; font-family:'Pretendard',sans-serif; }
.lst-head{ display:flex; align-items:baseline; gap:12px; flex-wrap:wrap; margin-bottom:18px; }
.lst-title{ font-family:'Unbounded',sans-serif; font-weight:800; font-size:26px; color:#141414; }
.lst-count{ font-size:14px; font-weight:600; color:#FF1488; }
.lst-tabs{ display:flex; gap:8px; flex-wrap:wrap; margin-bottom:14px; }
.lst-tab{ text-decoration:none; font-size:13px; font-weight:700; padding:9px 16px; border-radius:999px;
  background:#fff; color:#141414; border:1.5px solid #FFE3F0; transition:.15s; white-space:nowrap; }
.lst-tab:hover{ border-color:#FF1488; color:#FF1488; }
.lst-tab.on{ background:#FF1488; color:#fff; border-color:#FF1488; }

/* ── 진입 맥락별 필터 줄 ── */
.lst-catbar{ display:flex; flex-direction:column; align-items:center; gap:12px; margin-bottom:18px; }
.lst-catbar .lst-tabs{ margin-bottom:0; justify-content:center; }
.lst-allartists{ text-decoration:none; font-size:12.5px; font-weight:600; color:#9a9aa3; transition:.15s; }
.lst-allartists:hover{ color:#FF1488; }
.lst-artbar{ display:flex; align-items:center; gap:8px; margin-bottom:16px; }
.lst-arlabel{ flex:none; font-size:11px; font-weight:700; color:#b0b0b8; letter-spacing:.02em; margin-right:2px; }
.lst-arrow{ flex:none; width:32px; height:32px; border-radius:50%; border:none; cursor:pointer;
  background:#FF1488; color:#fff; font-size:19px; line-height:1; display:grid; place-items:center;
  box-shadow:0 5px 14px rgba(255,20,136,.28); transition:.15s; font-family:'Pretendard',sans-serif; }
.lst-arrow:hover{ filter:brightness(.95); }
.lst-arrow:disabled{ opacity:.28; cursor:default; box-shadow:none; }
.lst-artbar.no-overflow .lst-arrow{ display:none; }
.lst-artrack{ display:flex; gap:14px; overflow-x:auto; flex:1; padding:4px 2px 6px;
  -webkit-overflow-scrolling:touch; scrollbar-width:none; }
.lst-artrack::-webkit-scrollbar{ display:none; }
.lst-chip{ flex:none; width:58px; text-align:center; text-decoration:none; }
.lst-ava{ width:48px; height:48px; border-radius:50%; margin:0 auto; display:grid; place-items:center;
  background:linear-gradient(145deg,#FFE3F0,#FFF0F6); color:#FF1488;
  font-family:'Unbounded',sans-serif; font-weight:800; font-size:18px; border:2px solid transparent; transition:.15s; }
.lst-chip:hover .lst-ava{ border-color:#FF1488; }
.lst-chip.on .lst-ava{ background:linear-gradient(145deg,#FF1488,#FF5BA8); color:#fff; border-color:#FF1488; }
.lst-chip-all .lst-ava{ font-size:13px; font-family:'Pretendard',sans-serif; font-weight:800; }
.lst-chip-nm{ display:block; margin-top:5px; font-size:11px; color:#9a9aa3; white-space:nowrap; max-width:58px; overflow:hidden; text-overflow:ellipsis; }
.lst-chip.on .lst-chip-nm{ color:#FF1488; font-weight:700; }
@media(max-width:600px){
  .lst-arrow{ display:none; }
  .lst-ava{ width:44px; height:44px; font-size:16px; }
  .lst-chip{ width:54px; }
}
.lst-bar{ display:flex; justify-content:space-between; align-items:center; gap:10px;
  margin-bottom:18px; padding-bottom:14px; border-bottom:1.5px solid #FFE3F0; flex-wrap:wrap; }
.lst-sort{ display:flex; gap:14px; }
.lst-sort a{ text-decoration:none; font-size:13px; font-weight:600; color:#999; }
.lst-sort a.on{ color:#141414; font-weight:800; }
.lst-sort a:hover{ color:#FF1488; }
.lst-empty{ text-align:center; padding:80px 20px; color:#888; }
.lst-empty .em-emoji{ font-size:46px; }
.lst-empty .em-msg{ margin-top:14px; font-size:16px; font-weight:600; color:#555; }
.lst-empty a{ display:inline-block; margin-top:18px; text-decoration:none; font-weight:800;
  font-size:14px; color:#fff; background:#FF1488; padding:12px 22px; border-radius:999px; }
.lst-page{ display:flex; justify-content:center; align-items:center; gap:6px; margin-top:40px; }
.lst-page a, .lst-page span{ min-width:38px; height:38px; display:inline-flex; align-items:center; justify-content:center;
  border-radius:10px; font-size:14px; font-weight:700; text-decoration:none; }
.lst-page a{ background:#fff; color:#141414; border:1.5px solid #FFE3F0; }
.lst-page a:hover{ border-color:#FF1488; color:#FF1488; }
.lst-page .on{ background:#FF1488; color:#fff; }
.lst-page .off{ color:#ccc; }
</style>

<?php kp_page_head($kphEye, $kphTitle, $kphSub); ?>

<div class="lst-wrap">

  <?php if ($ctx === 'artist'): ?>
    <!-- 아티스트 진입: 카테고리 탭 + 전체 아티스트 목록 버튼 -->
    <div class="lst-catbar">
      <div class="lst-tabs">
        <a class="lst-tab <?= $type===''          ?'on':'' ?>" href="<?= list_qs(['type'=>null,        'ctx'=>'artist']) ?>">전체</a>
        <a class="lst-tab <?= $type==='photocard'  ?'on':'' ?>" href="<?= list_qs(['type'=>'photocard', 'ctx'=>'artist']) ?>">POCA</a>
        <a class="lst-tab <?= $type==='goods'      ?'on':'' ?>" href="<?= list_qs(['type'=>'goods',     'ctx'=>'artist']) ?>">GOODS</a>
        <a class="lst-tab <?= $type==='accessory'  ?'on':'' ?>" href="<?= list_qs(['type'=>'accessory', 'ctx'=>'artist']) ?>">ACCESSORIES</a>
      </div>
      <a class="lst-allartists" href="/artists.php">← 전체 아티스트 목록</a>
    </div>

  <?php elseif ($type === 'gacha'): ?>
    <!-- 가챠 진입: 소분류 탭 (미니/대형/컬러링) — 아티스트 카테고리 탭과 동일 스타일 -->
    <div class="lst-catbar">
      <div class="lst-tabs">
        <a class="lst-tab <?= $gk===''         ?'on':'' ?>" href="<?= list_qs(['gk'=>null]) ?>">전체</a>
        <a class="lst-tab <?= $gk==='mini'     ?'on':'' ?>" href="<?= list_qs(['gk'=>'mini']) ?>">미니 가챠머신</a>
        <a class="lst-tab <?= $gk==='large'    ?'on':'' ?>" href="<?= list_qs(['gk'=>'large']) ?>">대형 가챠머신</a>
        <a class="lst-tab <?= $gk==='coloring' ?'on':'' ?>" href="<?= list_qs(['gk'=>'coloring']) ?>">컬러링 에디션</a>
      </div>
    </div>

  <?php elseif ($ctx === 'type' && $artistChips): ?>
    <!-- 타입 진입: 아티스트 칩 스트립 -->
    <div class="lst-artbar">
      <span class="lst-arlabel">아티스트별</span>
      <button type="button" class="lst-arrow" data-dir="-1" aria-label="이전">‹</button>
      <div class="lst-artrack">
        <a class="lst-chip lst-chip-all <?= !$artist ? 'on':'' ?>" href="<?= list_qs(['artist'=>null,'ctx'=>'type']) ?>">
          <span class="lst-ava">전체</span>
        </a>
        <?php foreach ($artistChips as $c):
            $en   = trim((string)($c['name_en'] ?? ''));
            $kr   = trim((string)$c['name']);
            $sl   = trim((string)$c['slug']);
            $init = $en !== '' ? strtoupper($en[0])
                  : (function_exists('mb_substr') ? mb_substr($kr, 0, 1, 'UTF-8') : '♪');
        ?>
          <a class="lst-chip <?= $artistSlug === $sl ? 'on':'' ?>" href="<?= list_qs(['artist'=>$sl,'ctx'=>'type']) ?>">
            <span class="lst-ava"><?= e($init) ?></span>
            <span class="lst-chip-nm"><?= e($en !== '' ? $en : $kr) ?></span>
          </a>
        <?php endforeach; ?>
      </div>
      <button type="button" class="lst-arrow" data-dir="1" aria-label="다음">›</button>
    </div>
    <script>
    (function(){
      var bar = document.querySelector('.lst-artbar'); if(!bar) return;
      var track = bar.querySelector('.lst-artrack');
      var prev  = bar.querySelector('.lst-arrow[data-dir="-1"]');
      var next  = bar.querySelector('.lst-arrow[data-dir="1"]');
      function step(d){ track.scrollBy({ left: d * Math.max(track.clientWidth * 0.8, 160), behavior:'smooth' }); }
      if(prev) prev.onclick = function(){ step(-1); };
      if(next) next.onclick = function(){ step(1); };
      function upd(){
        var overflow = track.scrollWidth > track.clientWidth + 4;
        bar.classList.toggle('no-overflow', !overflow);
        if(!overflow) return;
        var max = track.scrollWidth - track.clientWidth - 2;
        if(prev) prev.disabled = track.scrollLeft <= 2;
        if(next) next.disabled = track.scrollLeft >= max;
      }
      track.addEventListener('scroll', upd);
      window.addEventListener('resize', upd);
      var onChip = track.querySelector('.lst-chip.on');
      if(onChip && onChip !== track.firstElementChild){
        var tR = track.getBoundingClientRect(), oR = onChip.getBoundingClientRect();
        track.scrollLeft += (oR.left - tR.left) - (track.clientWidth - onChip.offsetWidth)/2;
      }
      setTimeout(upd, 60);
    })();
    </script>
  <?php endif; ?>


  <div class="lst-bar">
    <div class="lst-sort">
      <a class="<?= $sort==='new'        ?'on':'' ?>" href="<?= list_qs(['sort'=>'new']) ?>">최신순</a>
      <a class="<?= $sort==='price_asc'  ?'on':'' ?>" href="<?= list_qs(['sort'=>'price_asc']) ?>">낮은가격순</a>
      <a class="<?= $sort==='price_desc' ?'on':'' ?>" href="<?= list_qs(['sort'=>'price_desc']) ?>">높은가격순</a>
    </div>
  </div>

  <?php if ($rows): ?>
    <div class="pc-grid">
      <?php foreach ($rows as $r):
          $card = [
              'id'          => $r['id'],
              'name'        => $r['name'],
              'type'        => $r['type'],
              'artist_name' => $r['artist_name'],
              'thumb'       => $r['thumbnail'],
              'price'       => (int)$r['disp_price'],
              'list_price'  => (($r['sale_price'] !== null && (int)$r['sale_price'] > 0 && (int)$r['sale_price'] < (int)$r['price']) ? (int)$r['list_disp'] : 0),
              'soldout'     => ((int)$r['sku_total'] > 0 && (int)$r['sku_instock'] === 0),
              'from'        => ((int)$r['sku_total'] > 0),
              'is_best'     => (int)$r['is_featured'] === 1,
              'is_new'      => (int)($r['is_new_calc'] ?? 0) === 1,
          ];
          render_product_card($card);
      endforeach; ?>
    </div>

    <?php if ($totalPages > 1): ?>
      <nav class="lst-page">
        <?php if ($page > 1): ?><a href="<?= list_qs(['page'=>$page-1]) ?>">‹</a>
        <?php else: ?><span class="off">‹</span><?php endif; ?>
        <?php
          $start = max(1, $page - 2);
          $end   = min($totalPages, $page + 2);
          if ($start > 1) echo '<a href="'.list_qs(['page'=>1]).'">1</a>'.($start>2?'<span class="off">…</span>':'');
          for ($i=$start; $i<=$end; $i++):
            if ($i == $page) echo '<span class="on">'.$i.'</span>';
            else echo '<a href="'.list_qs(['page'=>$i]).'">'.$i.'</a>';
          endfor;
          if ($end < $totalPages) echo ($end<$totalPages-1?'<span class="off">…</span>':'').'<a href="'.list_qs(['page'=>$totalPages]).'">'.$totalPages.'</a>';
        ?>
        <?php if ($page < $totalPages): ?><a href="<?= list_qs(['page'=>$page+1]) ?>">›</a>
        <?php else: ?><span class="off">›</span><?php endif; ?>
      </nav>
    <?php endif; ?>

  <?php else: ?>
    <div class="lst-empty">
      <div class="em-emoji">🔍</div>
      <div class="em-msg"><?= $q!=='' ? '‘'.e($q).'’ 에 대한 상품이 없어요.' : '해당 조건의 상품이 아직 없어요.' ?></div>
      <?php if ($artist): ?>
        <a href="/artists.php">← 아티스트 목록으로</a>
      <?php else: ?>
        <a href="/list.php">전체 상품 보기</a>
      <?php endif; ?>
    </div>
  <?php endif; ?>

</div>

<?php include __DIR__ . '/includes/footer.php'; ?>
