<?php
// pages/promotion.php — 프로모션 관리
require_once __DIR__ . '/../config/database.php';
require_once __DIR__ . '/../includes/header.php';
$db = (new Database())->getConnection();

$db->exec("CREATE TABLE IF NOT EXISTS promotion (
    promo_id INT AUTO_INCREMENT PRIMARY KEY,
    promo_month VARCHAR(7) NOT NULL COMMENT '적용 월 YYYY-MM',
    title VARCHAR(200) NOT NULL,
    description TEXT,
    is_active TINYINT(1) DEFAULT 1,
    created_by INT,
    created_at DATETIME DEFAULT CURRENT_TIMESTAMP,
    updated_at DATETIME DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP
)");

$msg = '';
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $action = $_POST['action'] ?? '';
    if ($action === 'create') {
        $month = $_POST['promo_month'] ?? date('Y-m');
        $title = trim($_POST['title'] ?? '');
        $desc = trim($_POST['description'] ?? '');
        if ($title) {
            $db->prepare("INSERT INTO promotion (promo_month, title, description, created_by) VALUES(?,?,?,?)")
               ->execute([$month, $title, $desc, $_SESSION['user_id'] ?? 0]);
            $msg = '프로모션이 등록되었습니다.';
        }
    }
    if ($action === 'update') {
        $id = (int)$_POST['promo_id'];
        $db->prepare("UPDATE promotion SET promo_month=?, title=?, description=?, is_active=? WHERE promo_id=?")
           ->execute([$_POST['promo_month'], trim($_POST['title']), trim($_POST['description']), isset($_POST['is_active'])?1:0, $id]);
        $msg = '프로모션이 수정되었습니다.';
    }
    if ($action === 'delete') {
        $db->prepare("DELETE FROM promotion WHERE promo_id=?")->execute([(int)$_POST['promo_id']]);
        $msg = '프로모션이 삭제되었습니다.';
    }
}

$promos = $db->query("SELECT p.*, ua.login_id AS creator FROM promotion p LEFT JOIN user_account ua ON p.created_by=ua.user_id ORDER BY p.promo_month DESC, p.promo_id DESC")->fetchAll();
$activePromos = array_filter($promos, fn($p) => $p['is_active']);
?>

<div class="page-header"><h2>🎯 프로모션 관리</h2></div>
<?php if ($msg): ?><div class="alert alert-success" style="margin-bottom:1rem;">✓ <?= htmlspecialchars($msg) ?></div><?php endif; ?>

<!-- 등록 -->
<div class="card" style="margin-bottom:1.25rem;">
    <div class="card-header"><h3>➕ 프로모션 등록</h3></div>
    <form method="POST" style="display:grid;grid-template-columns:auto 1fr;gap:0.75rem;padding:0.5rem 0;align-items:end;">
        <input type="hidden" name="action" value="create">
        <div><label style="font-size:var(--fs-xs);color:var(--text-tertiary);">적용 월</label>
            <input type="month" name="promo_month" value="<?= date('Y-m') ?>" required style="font-size:var(--fs-sm);"></div>
        <div><label style="font-size:var(--fs-xs);color:var(--text-tertiary);">프로모션 제목</label>
            <input type="text" name="title" required placeholder="예: 2월 방송 스폰서십 20% 할인" style="font-size:var(--fs-sm);"></div>
        <div style="grid-column:1/3;"><label style="font-size:var(--fs-xs);color:var(--text-tertiary);">상세 설명</label>
            <textarea name="description" rows="2" placeholder="상세 내용 (선택)" style="font-size:var(--fs-sm);width:100%;"></textarea></div>
        <div style="grid-column:1/3;"><button type="submit" class="btn btn-primary">등록</button></div>
    </form>
</div>

<!-- 목록 -->
<div class="card">
    <div class="card-header"><h3>📋 프로모션 목록 (<?= count($promos) ?>)</h3></div>
    <table class="data-table">
        <thead><tr><th>적용 월</th><th>제목</th><th>상태</th><th>등록자</th><th>관리</th></tr></thead>
        <tbody>
        <?php foreach ($promos as $p): ?>
        <tr style="<?= !$p['is_active']?'opacity:0.5;':'' ?>">
            <td><span class="badge badge-info"><?= $p['promo_month'] ?></span></td>
            <td>
                <form method="POST" style="display:flex;gap:0.5rem;align-items:center;flex-wrap:wrap;">
                    <input type="hidden" name="action" value="update">
                    <input type="hidden" name="promo_id" value="<?= $p['promo_id'] ?>">
                    <input type="hidden" name="promo_month" value="<?= $p['promo_month'] ?>">
                    <input type="text" name="title" value="<?= htmlspecialchars($p['title']) ?>" style="font-size:var(--fs-xs);flex:1;min-width:12rem;">
                    <input type="text" name="description" value="<?= htmlspecialchars($p['description']??'') ?>" style="font-size:var(--fs-xs);flex:1;min-width:8rem;" placeholder="설명">
                    <label style="font-size:var(--fs-xs);"><input type="checkbox" name="is_active" <?= $p['is_active']?'checked':'' ?>> 활성</label>
                    <button type="submit" class="btn btn-sm btn-outline" style="font-size:var(--fs-xs);">저장</button>
                </form>
            </td>
            <td><span class="badge <?= $p['is_active']?'badge-success':'badge-gray' ?>"><?= $p['is_active']?'활성':'종료' ?></span></td>
            <td style="font-size:var(--fs-xs);color:var(--text-tertiary);"><?= htmlspecialchars($p['creator']??'-') ?></td>
            <td>
                <form method="POST" style="display:inline;" onsubmit="return confirm('삭제하시겠습니까?')">
                    <input type="hidden" name="action" value="delete"><input type="hidden" name="promo_id" value="<?= $p['promo_id'] ?>">
                    <button type="submit" class="btn btn-sm" style="color:var(--accent);font-size:var(--fs-xs);">🗑️</button>
                </form>
            </td>
        </tr>
        <?php endforeach; ?>
        <?php if (!$promos): ?><tr><td colspan="5" style="padding:1.5rem;color:var(--text-tertiary);">등록된 프로모션이 없습니다.</td></tr><?php endif; ?>
        </tbody>
    </table>
</div>

<?php require_once __DIR__ . '/../includes/footer.php'; ?>
