<?php
require_once 'config.php';

// 处理状态更新 - 必须在header.php之前
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['action'])) {
    if ($_POST['action'] === 'toggle') {
        $id = (int)$_POST['id'];
        $completed = (int)$_POST['completed'];
        $stmt = $pdo->prepare("UPDATE wedding_checklist SET is_completed = ?, completed_date = ? WHERE id = ?");
        $completedDate = $completed ? date('Y-m-d') : null;
        $stmt->execute([$completed, $completedDate, $id]);
        header('Content-Type: application/json');
        echo json_encode(['success' => true]);
        exit;
    }
}

$pageTitle = '婚礼清单';
require_once 'header.php';

// 获取清单数据
try {
    $stmt = $pdo->query("SELECT * FROM wedding_checklist ORDER BY FIELD(priority, '高', '中', '低'), deadline ASC, sort_order ASC");
    $tasks = $stmt->fetchAll(PDO::FETCH_ASSOC);
    
    $categories = [];
    $completedCount = 0;
    $totalCount = count($tasks);
    
    foreach ($tasks as $task) {
        $cat = $task['category'];
        if (!isset($categories[$cat])) {
            $categories[$cat] = [];
        }
        $categories[$cat][] = $task;
        if ($task['is_completed']) {
            $completedCount++;
        }
    }
    
    $progress = $totalCount > 0 ? round(($completedCount / $totalCount) * 100) : 0;
    
} catch (PDOException $e) {
    $tasks = [];
    $categories = [];
    $completedCount = 0;
    $totalCount = 0;
    $progress = 0;
}
?>

<main class="site-main">
    <div class="container">
        <!-- 进度概览 -->
        <section class="checklist-overview">
            <div class="section-header">
                <h2>📋 婚礼筹备清单</h2>
                <div class="section-actions">
                    <a href="downloads.php?action=download&type=checklist" class="btn-download-inline">
                        <i class="fas fa-download"></i> 下载Excel清单
                    </a>
                    <a href="downloads.php?action=download&type=checklist_pdf" class="btn-download-inline btn-pdf">
                        <i class="fas fa-file-pdf"></i> 下载PDF版
                    </a>
                </div>
            </div>
            <div class="progress-section">
                <div class="progress-info">
                    <span>完成进度: <?php echo $completedCount; ?>/<?php echo $totalCount; ?></span>
                    <span><?php echo $progress; ?>%</span>
                </div>
                <div class="progress-bar">
                    <div class="progress-fill" style="width:<?php echo $progress; ?>%;"></div>
                </div>
            </div>
        </section>

        <!-- 清单 - Tab切换 -->
        <section class="checklist-content">
            <div class="checklist-tabs">
                <button class="tab-btn active" data-period="half-year">提前半年</button>
                <button class="tab-btn" data-period="three-months">提前3个月</button>
                <button class="tab-btn" data-period="one-month">提前1个月</button>
                <button class="tab-btn" data-period="one-week">提前1周</button>
            </div>

            <div class="checklist-progress" style="margin-bottom:15px;">
                <div class="progress-bar">
                    <div class="progress-fill" id="progressFill" style="width:0;"></div>
                </div>
                <span id="progressPercent">0%</span>
            </div>

            <ul class="checklist-items" id="checklistItems">
                <!-- JS动态加载 -->
            </ul>
        </section>

        <?php if (count($categories) > 0): ?>
        <!-- 完整数据库清单 -->
        <section class="full-checklist">
            <h3>全部任务列表</h3>
            <?php foreach ($categories as $catName => $catTasks): ?>
            <div class="checklist-category">
                <h4><?php echo htmlspecialchars($catName); ?></h4>
                <ul class="checklist-items">
                    <?php foreach ($catTasks as $task): ?>
                    <li class="checklist-item">
                        <input type="checkbox" <?php echo $task['is_completed'] ? 'checked' : ''; ?> 
                               onchange="toggleTask(<?php echo $task['id']; ?>, this.checked)">
                        <span style="<?php echo $task['is_completed'] ? 'text-decoration:line-through;color:#999;' : ''; ?>">
                            <?php echo htmlspecialchars($task['task_name']); ?>
                        </span>
                        <span class="task-priority <?php echo $task['priority'] === '高' ? 'urgent' : ($task['priority'] === '中' ? 'important' : ''); ?>">
                            <?php echo htmlspecialchars($task['priority']); ?>
                        </span>
                        <?php if ($task['deadline']): ?>
                        <small class="deadline">截止: <?php echo $task['deadline']; ?></small>
                        <?php endif; ?>
                    </li>
                    <?php endforeach; ?>
                </ul>
            </div>
            <?php endforeach; ?>
        </section>
        <?php endif; ?>
    </div>
</main>

<script>
function toggleTask(id, completed) {
    fetch('checklist.php', {
        method: 'POST',
        headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
        body: 'action=toggle&id=' + id + '&completed=' + (completed ? 1 : 0)
    }).then(function() {
        location.reload();
    });
}
</script>

<?php require_once 'footer.php'; ?>