<?php
/**
 * /www/promotion.php  —  기획전 · 이벤트 (헤더 EVENT 도착지)
 * ------------------------------------------------------------------
 *  기획전 DB 연동 전 단계.
 *  - 배너: 자리(추후 이미지 등록)
 *  - 특가 상품: 실제 할인상품(sale_price < price). 없으면 featured/recent 폴백
 * ------------------------------------------------------------------
 */

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() 공통 제목

$cardCols = "
    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
";
function promo_card($r){
    $disc = ($r['sale_price'] !== null && (int)$r['sale_price'] > 0 && (int)$r['sale_price'] < (int)$r['price']);
    return [
        'id'=>$r['id'],'name'=>$r['name'],'type'=>$r['type'],'artist_name'=>$r['artist_name'],
        'thumb'=>$r['thumbnail'],'price'=>(int)$r['disp_price'],
        'list_price'=>$disc ? (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, 'badge'=>($disc?'SALE':''),
    ];
}

/* 특가 상품: 실제 할인 상품 우선 */
$st = $pdo->query("SELECT $cardCols FROM products p LEFT JOIN artists a ON a.id=p.artist_id
    WHERE p.is_active=1 AND p.sale_price IS NOT NULL AND p.sale_price > 0 AND p.sale_price < p.price
    ORDER BY p.is_featured DESC, p.created_at DESC LIMIT 20");
$saleRows = $st->fetchAll();
$isFallback = false;
if (!$saleRows) {  // 할인상품 없으면 추천으로 폴백
    $isFallback = true;
    $saleRows = $pdo->query("SELECT $cardCols FROM products p LEFT JOIN artists a ON a.id=p.artist_id
        WHERE p.is_active=1 ORDER BY p.is_featured DESC, p.created_at DESC LIMIT 10")->fetchAll();
}

/* 샘플 기획전 메타 (promotions 없을 때 폴백) */
$promo = [
    'label'   => 'SPECIAL',
    'title'   => '✦ KPOPPOCA 특가 기획전',
    'period'  => '상시 진행 · 재고 소진 시 종료',
    'benefits'=> ['신규가입 즉시 5,000원 적립금 + 웰컴 포카 증정', '3만원 이상 무료배송', '정품 인증 · 안전결제'],
    'notice'  => '특가 상품은 수량 한정으로, 조기 품절될 수 있습니다.',
    'banner'  => '', 'link' => '',
];
$othersSample = [
    ['🆕 신상 드롭', '매주 새로 올라온 신상', '/list.php?view=new'],
    ['🏆 베스트 모음', '가장 많이 찾는 인기 상품', '/list.php?view=best'],
    ['🎁 가챠 위크', '랜덤 포카·캡슐 가챠', '/list.php?type=gacha'],
];

/* 기획전: promotions(placement=promotion, 진행중) DB 연동 → 첫 번째=메인 배너, 나머지=다른 기획전 */
$promoRows = [];
try {
    $now = date('Y-m-d H:i:s');
    /* placement 컬럼이 있으면 기획전만, 없으면(구버전) 전체 */
    $hasPlacement = false;
    try { $pdo->query("SELECT placement FROM promotions LIMIT 1"); $hasPlacement = true; }
    catch (Throwable $ex) { $hasPlacement = false; }
    $plClause = $hasPlacement ? " AND placement='promotion'" : "";
    $pst = $pdo->prepare("SELECT * FROM promotions WHERE is_visible=1" . $plClause . "
        AND (starts_at IS NULL OR starts_at<=?) AND (ends_at IS NULL OR ends_at>=?)
        ORDER BY sort_order ASC, created_at DESC, id DESC LIMIT 20");
    $pst->execute([$now, $now]);
    $promoRows = $pst->fetchAll();
} catch (Throwable $ex) {}

if (!empty($promoRows)) {
    $m = $promoRows[0];
    $promo['label']  = 'EVENT';
    $promo['title']  = $m['title'];
    $promo['period'] = ($m['starts_at'] ? substr((string)$m['starts_at'],0,10) : '상시') . ' ~ ' . ($m['ends_at'] ? substr((string)$m['ends_at'],0,10) : '');
    $promo['banner'] = $m['banner_image'] ?? '';
    $promo['link']   = $m['link_url'] ?? '';
    // 혜택 칩: 이 배너에 관리자가 입력한 값(한 줄에 하나)으로 대체.
    // (예전처럼 부제/subtitle을 칩으로 끼워넣지 않음 → "TEST" 사라짐)
    if (array_key_exists('benefits', $m)) {
        $benLines = preg_split('/\r\n|\r|\n/', (string)($m['benefits'] ?? ''));
        $benLines = array_values(array_filter(array_map('trim', $benLines), fn($x) => $x !== ''));
        $promo['benefits'] = $benLines;   // 비어 있으면 칩 없음
    }
    // benefits 컬럼이 아직 없으면(구버전) 기존 샘플 칩 유지 (TEST만 빠짐)
}

$others = [];
foreach (array_slice($promoRows, 1) as $p) {
    $others[] = [ $p['title'], ($p['subtitle'] ?: '자세히 보기'), ($p['link_url'] ?: '#') ];
}
if (!$others) $others = $othersSample;

$page_title  = '기획전 · 이벤트 | KPOPPOCA';
$active_menu = 'event';
include __DIR__ . '/includes/header.php';
?>

<link rel="preconnect" href="https://fonts.googleapis.com">
<link href="https://fonts.googleapis.com/css2?family=Unbounded:wght@600;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>
.pr-wrap{ max-width:1120px; margin:0 auto; padding:24px 18px 90px; font-family:'Pretendard',sans-serif; color:#141414; word-break:keep-all; }

/* 배너 (제목 아래 · 핑크 · 세로 300 · 추후 이미지) */
.pr-banner{ aspect-ratio:1200/300; display:grid; place-items:center; text-align:center; color:#fff;
  border-radius:20px; overflow:hidden; margin:18px 0 20px;
  background:
    repeating-linear-gradient(45deg,rgba(255,255,255,.06) 0 14px,transparent 14px 28px),
    linear-gradient(135deg,#FF1488,#FF5BA8 55%,#FFB0D4); }
.pr-banner .ph{ font-size:13px; opacity:.9; padding:0 16px; }
.pr-info{ text-align:center; }
.pr-benefits{ display:flex; flex-wrap:wrap; gap:8px; justify-content:center; }
.pr-benefits span{ font-size:12.5px; font-weight:700; color:#D6006F; background:#FFF0F6; padding:7px 13px; border-radius:999px; }
.pr-notice{ margin-top:14px; font-size:12.5px; color:#aaa; }

.pr-sec-h{ display:flex; align-items:baseline; gap:10px; margin:34px 0 16px; }
.pr-sec-h .t{ font-family:'Unbounded',sans-serif; font-weight:800; font-size:19px; }
.pr-sec-h .c{ font-size:13px; font-weight:700; color:#FF1488; }
.pr-fallback{ font-size:12.5px; color:#aaa; margin:-8px 0 14px; }

/* 다른 기획전 */
.pr-others{ display:grid; grid-template-columns:repeat(auto-fill,minmax(min(100%,240px),1fr)); gap:12px; margin-top:18px; }
.pr-other{ display:block; text-decoration:none; color:inherit; border:1.5px solid #f0eef2; border-radius:14px; padding:18px; transition:.16s; background:#fff; }
.pr-other:hover{ border-color:#FF1488; transform:translateY(-3px); box-shadow:0 12px 26px rgba(255,20,136,.12); }
.pr-other .ot-t{ font-weight:800; font-size:15px; } .pr-other .ot-s{ font-size:12.5px; color:#999; margin-top:4px; }
.pr-all{ display:inline-block; margin-top:16px; font-size:13.5px; font-weight:800; color:#FF1488; text-decoration:none; }
</style>

<!-- 제목 (위 · 가운데 · 다른 페이지와 통일 · 고정 제목) -->
<style>.pr-sub-br{display:none}.pr-sub-sp{display:inline}@media(max-width:768px){.pr-sub-br{display:inline}.pr-sub-sp{display:none}}</style>
<?php
  // 페이지 제목은 다른 페이지와 통일된 고정값 (관리자 배너 제목/기간은 H1·부제로 쓰지 않음)
  // 부제: PC 한 줄 / 모바일 두 줄
  kp_page_head('SPECIAL', 'EVENT', '놓치면 아쉬운<span class="pr-sub-sp"> </span><br class="pr-sub-br">지금 이 순간만의 혜택', false);
?>

<div class="pr-wrap">

  <!-- 배너 (등록된 기획전 이미지 · 없으면 자리표시) -->
  <?php if (!empty($promo['banner'])): ?>
    <?php if (!empty($promo['link'])): ?><a href="<?= e($promo['link']) ?>" style="display:block;text-decoration:none;"><?php endif; ?>
    <div class="pr-banner" style="padding:0;background:#f4f4f7;">
      <img src="<?= e($promo['banner']) ?>" alt="<?= e($promo['title']) ?>" style="width:100%;height:100%;object-fit:cover;">
    </div>
    <?php if (!empty($promo['link'])): ?></a><?php endif; ?>
  <?php else: ?>
    <div class="pr-banner">
      <div class="ph">🗓️ 기획전 배너 이미지가 들어갈 자리 · 권장 1200×300 · 추후 등록</div>
    </div>
  <?php endif; ?>

  <!-- 혜택 + 공지 (가운데) -->
  <div class="pr-info">
    <div class="pr-benefits">
      <?php foreach ($promo['benefits'] as $b): ?><span>✓ <?= e($b) ?></span><?php endforeach; ?>
    </div>
    <div class="pr-notice"><?= e($promo['notice']) ?></div>
  </div>

  <!-- 특가 상품 -->
  <div class="pr-sec-h">
    <span class="t"><?= $isFallback ? '추천 상품' : '특가 상품' ?></span>
    <span class="c"><?= count($saleRows) ?>개</span>
  </div>
  <?php if ($isFallback): ?><div class="pr-fallback">현재 진행 중인 할인 상품이 없어, 인기·신상 상품을 보여드려요.</div><?php endif; ?>
  <div class="pc-grid">
    <?php foreach ($saleRows as $r) render_product_card(promo_card($r)); ?>
  </div>

  <!-- 다른 기획전 -->
  <div class="pr-sec-h"><span class="t">다른 기획전</span></div>
  <div class="pr-others">
    <?php foreach ($others as $o): ?>
      <a class="pr-other" href="<?= e($o[2]) ?>"><div class="ot-t"><?= e($o[0]) ?></div><div class="ot-s"><?= e($o[1]) ?></div></a>
    <?php endforeach; ?>
  </div>
  <a class="pr-all" href="/list.php">전체 상품 보기 ›</a>
</div>

<?php include __DIR__ . '/includes/footer.php'; ?>
