<?php
require_once __DIR__ . '/../../config/database.php';
require_once __DIR__ . '/../../includes/header.php';
$user = currentUser(); $db = (new Database())->getConnection();
$db->exec("CREATE TABLE IF NOT EXISTS mkt_content_pipeline (content_id INT AUTO_INCREMENT PRIMARY KEY, campaign_id INT, content_type ENUM('블로그','SNS','영상','배너','이메일','보도자료','기타') DEFAULT 'SNS', title VARCHAR(200) NOT NULL, channel VARCHAR(50), scheduled_date DATE, publish_date DATE, status ENUM('기획','제작','검토','발행','완료') DEFAULT '기획', staff_id INT, notes TEXT, created_at DATETIME DEFAULT CURRENT_TIMESTAMP)");
$db->exec("CREATE TABLE IF NOT EXISTS mkt_campaign (campaign_id INT AUTO_INCREMENT PRIMARY KEY, campaign_name VARCHAR(100), campaign_type VARCHAR(20), channel VARCHAR(50), start_date DATE, end_date DATE, budget DECIMAL(15,0) DEFAULT 0, status VARCHAR(10) DEFAULT '기획', staff_id INT, description TEXT, created_at DATETIME DEFAULT CURRENT_TIMESTAMP, updated_at DATETIME DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP)");

if ($_SERVER['REQUEST_METHOD']==='POST' && $_POST['action']==='add') {
    $db->prepare("INSERT INTO mkt_content_pipeline (campaign_id,content_type,title,channel,scheduled_date,status,staff_id,notes) VALUES(?,?,?,?,?,?,?,?)")
       ->execute([$_POST['campaign_id']?:null,$_POST['type'],$_POST['title'],$_POST['channel'],$_POST['sched_date'],'기획',$user['staff_id'],$_POST['notes']]);
} elseif ($_SERVER['REQUEST_METHOD']==='POST' && $_POST['action']==='update_status') {
    $pubDate = $_POST['status']==='발행' ? date('Y-m-d') : null;
    $db->prepare("UPDATE mkt_content_pipeline SET status=?, publish_date=COALESCE(?,publish_date) WHERE content_id=?")->execute([$_POST['status'],$pubDate,$_POST['cid']]);
}

$campaigns = $db->query("SELECT campaign_id, campaign_name FROM mkt_campaign ORDER BY campaign_name")->fetchAll();
$contents = $db->query("SELECT cp.*, c.campaign_name, s.name AS staff_name FROM mkt_content_pipeline cp LEFT JOIN mkt_campaign c ON cp.campaign_id=c.campaign_id LEFT JOIN staff s ON cp.staff_id=s.staff_id ORDER BY cp.scheduled_date DESC, cp.created_at DESC LIMIT 50")->fetchAll();
?>
<div class="page-header"><h2>📝 콘텐츠 파이프라인</h2><div class="breadcrumb">마케팅 &gt; 콘텐츠 파이프라인</div></div>

<div class="card" style="margin-bottom:1.25rem;">
    <div class="card-header"><h3>콘텐츠 등록</h3></div>
    <form method="POST"><input type="hidden" name="action" value="add">
        <div style="display:grid;grid-template-columns:repeat(auto-fit,minmax(10rem,1fr));gap:0.75rem;">
            <div class="form-group"><label>제목</label><input type="text" name="title" required placeholder="콘텐츠 제목"></div>
            <div class="form-group"><label>유형</label><select name="type"><option>블로그</option><option>SNS</option><option>영상</option><option>배너</option><option>이메일</option><option>보도자료</option><option>기타</option></select></div>
            <div class="form-group"><label>캠페인</label><select name="campaign_id"><option value="">없음</option><?php foreach($campaigns as $c): ?><option value="<?= $c['campaign_id'] ?>"><?= htmlspecialchars($c['campaign_name']) ?></option><?php endforeach; ?></select></div>
            <div class="form-group"><label>채널</label><input type="text" name="channel" placeholder="인스타, 블로그 등"></div>
            <div class="form-group"><label>예정일</label><input type="date" name="sched_date"></div>
        </div>
        <div class="form-group"><label>메모</label><textarea name="notes" rows="2" placeholder="비고"></textarea></div>
        <button type="submit" class="btn btn-primary">등록</button>
    </form>
</div>

<div class="card">
    <div class="card-header"><h3>콘텐츠 현황</h3></div>
    <div style="overflow-x:auto;">
    <table class="data-table">
        <thead><tr><th>제목</th><th>유형</th><th>캠페인</th><th>채널</th><th>예정일</th><th>발행일</th><th>담당</th><th>상태</th><th>변경</th></tr></thead>
        <tbody>
        <?php foreach($contents as $ct): ?>
        <tr>
            <td><strong><?= htmlspecialchars($ct['title']) ?></strong></td>
            <td><span class="badge badge-info"><?= $ct['content_type'] ?></span></td>
            <td style="font-size:var(--fs-xs);"><?= htmlspecialchars($ct['campaign_name']??'-') ?></td>
            <td><?= htmlspecialchars($ct['channel']??'-') ?></td>
            <td><?= $ct['scheduled_date']??'-' ?></td>
            <td><?= $ct['publish_date']??'-' ?></td>
            <td><?= htmlspecialchars($ct['staff_name']??'-') ?></td>
            <td><span class="badge <?= ['기획'=>'badge-gray','제작'=>'badge-warning','검토'=>'badge-info','발행'=>'badge-success','완료'=>'badge-success'][$ct['status']] ?>"><?= $ct['status'] ?></span></td>
            <td><form method="POST" style="display:flex;gap:0.25rem;"><input type="hidden" name="action" value="update_status"><input type="hidden" name="cid" value="<?= $ct['content_id'] ?>"><select name="status" style="font-size:var(--fs-xs);padding:0.25rem;"><option>기획</option><option>제작</option><option>검토</option><option>발행</option><option>완료</option></select><button type="submit" class="btn btn-outline" style="font-size:var(--fs-xs);padding:0.2rem 0.5rem;">변경</button></form></td>
        </tr>
        <?php endforeach; ?>
        <?php if(!$contents): ?><tr><td colspan="9" style="text-align:center;color:var(--text-tertiary);">등록된 콘텐츠가 없습니다</td></tr><?php endif; ?>
        </tbody>
    </table>
    </div>
</div>
<?php require_once __DIR__ . '/../../includes/footer.php'; ?>
