<?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_campaign (campaign_id INT AUTO_INCREMENT PRIMARY KEY, campaign_name VARCHAR(100) NOT NULL, campaign_type ENUM('디지털','오프라인','SNS','브랜드','프로모션','기타') DEFAULT '디지털', channel VARCHAR(50), start_date DATE, end_date DATE, budget DECIMAL(15,0) DEFAULT 0, status ENUM('기획','진행','완료','중단') 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' && isset($_POST['action'])) {
    if ($_POST['action']==='add') {
        $db->prepare("INSERT INTO mkt_campaign (campaign_name,campaign_type,channel,start_date,end_date,budget,status,staff_id,description) VALUES(?,?,?,?,?,?,?,?,?)")
           ->execute([$_POST['name'],$_POST['type'],$_POST['channel'],$_POST['start_date'],$_POST['end_date'],$_POST['budget']?:0,'기획',$user['staff_id'],$_POST['desc']]);
    } elseif ($_POST['action']==='update_status') {
        $db->prepare("UPDATE mkt_campaign SET status=? WHERE campaign_id=?")->execute([$_POST['status'],$_POST['campaign_id']]);
    }
}

$campaigns = $db->query("SELECT c.*, s.name AS staff_name FROM mkt_campaign c LEFT JOIN staff s ON c.staff_id=s.staff_id ORDER BY c.created_at DESC")->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(12rem,1fr));gap:0.75rem;">
            <div class="form-group"><label>캠페인명</label><input type="text" name="name" required placeholder="캠페인명 입력"></div>
            <div class="form-group"><label>유형</label><select name="type"><option>디지털</option><option>오프라인</option><option>SNS</option><option>브랜드</option><option>프로모션</option><option>기타</option></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="start_date"></div>
            <div class="form-group"><label>종료일</label><input type="date" name="end_date"></div>
            <div class="form-group"><label>예산 (원)</label><input type="number" name="budget" placeholder="0"></div>
        </div>
        <div class="form-group"><label>설명</label><textarea name="desc" rows="2" placeholder="캠페인 설명"></textarea></div>
        <button type="submit" class="btn btn-primary">등록</button>
    </form>
</div>

<div class="card">
    <div class="card-header"><h3>캠페인 목록 (<?= count($campaigns) ?>건)</h3></div>
    <div style="overflow-x:auto;">
    <table class="data-table">
        <thead><tr><th>ID</th><th>캠페인명</th><th>유형</th><th>채널</th><th>기간</th><th>예산</th><th>담당</th><th>상태</th><th>변경</th></tr></thead>
        <tbody>
        <?php foreach ($campaigns as $c): ?>
        <tr>
            <td><?= $c['campaign_id'] ?></td>
            <td><strong><?= htmlspecialchars($c['campaign_name']) ?></strong></td>
            <td><span class="badge badge-info"><?= $c['campaign_type'] ?></span></td>
            <td><?= htmlspecialchars($c['channel']??'-') ?></td>
            <td style="font-size:var(--fs-xs);"><?= $c['start_date'] ?> ~ <?= $c['end_date']??'' ?></td>
            <td style="text-align:right;"><?= number_format($c['budget']) ?></td>
            <td><?= htmlspecialchars($c['staff_name']??'-') ?></td>
            <td><span class="badge <?= ['기획'=>'badge-gray','진행'=>'badge-info','완료'=>'badge-success','중단'=>'badge-danger'][$c['status']]??'badge-gray' ?>"><?= $c['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="campaign_id" value="<?= $c['campaign_id'] ?>">
                    <select name="status" style="font-size:var(--fs-xs);padding:0.25rem;"><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(!$campaigns): ?><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'; ?>
