<?php
// 处理删除 - POST方式
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['action']) && $_POST['action'] === 'delete') {
    require_once 'config.php';
    $stmt = $pdo->prepare("DELETE FROM budget_items WHERE id = ?");
    $stmt->execute([(int)$_POST['id']]);
    header('Location: budget.php');
    exit;
}

$pageTitle = '预算管理';
require_once 'header.php';
require_once 'config.php';

// 获取预算数据
try {
    $stmt = $pdo->query("SELECT * FROM budget_items ORDER BY category, priority DESC");
    $items = $stmt->fetchAll(PDO::FETCH_ASSOC);
    
    $categories = [];
    $totalEstimated = 0;
    $totalActual = 0;
    $totalPaid = 0;
    
    foreach ($items as $item) {
        $cat = $item['category'];
        if (!isset($categories[$cat])) {
            $categories[$cat] = [
                'items' => [],
                'estimated' => 0,
                'actual' => 0,
                'paid' => 0,
                'count' => 0
            ];
        }
        $categories[$cat]['items'][] = $item;
        $categories[$cat]['estimated'] += $item['estimated_amount'];
        $categories[$cat]['actual'] += $item['actual_amount'];
        $categories[$cat]['paid'] += $item['paid_amount'];
        $categories[$cat]['count']++;
        
        $totalEstimated += $item['estimated_amount'];
        $totalActual += $item['actual_amount'];
        $totalPaid += $item['paid_amount'];
    }
    
    $remaining = $totalEstimated - $totalPaid;
    
} catch (PDOException $e) {
    $items = [];
    $categories = [];
    $totalEstimated = 0;
    $totalActual = 0;
    $totalPaid = 0;
    $remaining = 0;
}

// 参考预算汇总
$referenceBudget = [
    '婚宴酒席' => ['low' => 28000, 'mid' => 36000],
    '婚庆布置' => ['low' => 10000, 'mid' => 20000],
    '四大金刚' => ['low' => 7500,  'mid' => 12500],
    '婚纱礼服' => ['low' => 4300,  'mid' => 8300],
    '婚纱照'   => ['low' => 3500,  'mid' => 6000],
    '婚车车队' => ['low' => 3800,  'mid' => 6300],
    '其他杂项' => ['low' => 5800,  'mid' => 9500],
];
$refLowTotal = array_sum(array_column($referenceBudget, 'low'));
$refMidTotal = array_sum(array_column($referenceBudget, 'mid'));
?>

<main class="site-main">
    <div class="container">
        <!-- 预算概览 -->
        <section class="budget-overview">
            <h2>💰 预算概览</h2>
            <div class="budget-stats">
                <div class="stat-card">
                    <h3>预算总额</h3>
                    <p class="amount">¥<?php echo number_format($totalEstimated, 2); ?></p>
                </div>
                <div class="stat-card">
                    <h3>已花费</h3>
                    <p class="amount paid">¥<?php echo number_format($totalPaid, 2); ?></p>
                </div>
                <div class="stat-card">
                    <h3>剩余预算</h3>
                    <p class="amount <?php echo $remaining < 0 ? 'danger' : 'success'; ?>">¥<?php echo number_format($remaining, 2); ?></p>
                </div>
            </div>
        </section>

        <!-- 添加预算项目 -->
        <section class="budget-form-section">
            <h3>添加预算项目</h3>
            <form method="POST" action="budget_save.php" class="budget-form">
                <div class="form-row">
                    <select name="category" required>
                        <option value="">选择分类</option>
                        <option value="婚宴酒席">婚宴酒席</option>
                        <option value="婚庆布置">婚庆布置</option>
                        <option value="四大金刚">四大金刚</option>
                        <option value="婚纱礼服">婚纱礼服</option>
                        <option value="婚纱照">婚纱照</option>
                        <option value="婚车车队">婚车车队</option>
                        <option value="其他杂项">其他杂项</option>
                    </select>
                    <input type="text" name="item_name" placeholder="项目名称" required>
                    <input type="number" name="estimated_amount" placeholder="预算金额" step="0.01" required>
                    <input type="number" name="actual_amount" placeholder="实际花费" step="0.01">
                    <label class="checkbox-label">
                        <input type="checkbox" name="is_essential"> 必需项
                    </label>
                    <button type="submit" class="btn-primary">添加</button>
                </div>
            </form>
        </section>

        <!-- 预算列表 -->
        <section class="budget-list">
            <?php if (!empty($categories)): ?>
                <?php foreach ($categories as $catName => $catData): ?>
                <div class="budget-category">
                    <div class="category-header">
                        <h3><?php echo htmlspecialchars($catName); ?></h3>
                        <span><?php echo $catData['count']; ?>项 | 预算: ¥<?php echo number_format($catData['estimated'], 2); ?> | 已花: ¥<?php echo number_format($catData['paid'], 2); ?></span>
                    </div>
                    <div class="budget-items">
                        <?php foreach ($catData['items'] as $item): ?>
                        <div class="budget-item">
                            <span class="item-name">
                                <?php if ($item['is_essential']): ?><span class="essential-tag">必需</span><?php endif; ?>
                                <?php echo htmlspecialchars($item['item_name']); ?>
                            </span>
                            <span class="item-amount">预算: ¥<?php echo number_format($item['estimated_amount'], 2); ?></span>
                            <span class="item-actual">实际: ¥<?php echo number_format($item['actual_amount'], 2); ?></span>
                            <span class="item-paid">已付: ¥<?php echo number_format($item['paid_amount'], 2); ?></span>
                            <form method="POST" style="display:inline;" onsubmit="return confirm('确定删除?')">
                                <input type="hidden" name="action" value="delete">
                                <input type="hidden" name="id" value="<?php echo (int)$item['id']; ?>">
                                <button type="submit" class="btn-delete">删除</button>
                            </form>
                        </div>
                        <?php endforeach; ?>
                    </div>
                </div>
                <?php endforeach; ?>
            <?php else: ?>
                <p class="empty-state">暂无预算项目，请添加。</p>
            <?php endif; ?>
        </section>

        <!-- 阳泉婚礼费用参考汇总表 -->
        <section class="budget-reference">
            <h2>📊 阳泉婚礼费用参考（20桌）</h2>
            <p class="reference-intro">以下为阳泉市区中等规模婚礼参考预算，供新人规划时参考。实际费用因酒店档次、婚庆公司、个人选择等因素有所浮动。</p>
            <div class="reference-table-wrapper">
                <table class="reference-table">
                    <thead>
                        <tr>
                            <th>序号</th>
                            <th>费用大类</th>
                            <th>低配（元）</th>
                            <th>中配（元）</th>
                            <th>主要包含项目</th>
                        </tr>
                    </thead>
                    <tbody>
                        <?php $i = 1; foreach ($referenceBudget as $cat => $range): ?>
                        <tr>
                            <td class="ref-num"><?php echo $i++; ?></td>
                            <td class="ref-cat"><?php echo htmlspecialchars($cat); ?></td>
                            <td class="ref-amount low">¥<?php echo number_format($range['low']); ?></td>
                            <td class="ref-amount mid">¥<?php echo number_format($range['mid']); ?></td>
                            <td class="ref-detail"><?php
                                $details = [
                                    '婚宴酒席' => '菜品、酒水、香烟、备桌、场地服务费',
                                    '婚庆布置' => '舞台背景、T台、鲜花、灯光音响、策划',
                                    '四大金刚' => '主持人、摄影、摄像、化妆跟妆、妈妈妆',
                                    '婚纱礼服' => '新娘婚纱、新郎西装、伴娘伴郎服',
                                    '婚纱照'   => '影楼套餐、精修、相册升级',
                                    '婚车车队' => '头车、跟车5辆、婚车装饰',
                                    '其他杂项' => '喜糖伴手礼、请柬、红包、烟酒糖茶、婚房布置',
                                ];
                                echo htmlspecialchars($details[$cat] ?? '');
                            ?></td>
                        </tr>
                        <?php endforeach; ?>
                    </tbody>
                    <tfoot>
                        <tr>
                            <td colspan="2" class="ref-total-label">总计</td>
                            <td class="ref-total low-total">¥<?php echo number_format($refLowTotal); ?></td>
                            <td class="ref-total mid-total">¥<?php echo number_format($refMidTotal); ?></td>
                            <td class="ref-total-label">实际费用以合同为准</td>
                        </tr>
                    </tfoot>
                </table>
            </div>
        </section>
    </div>
</main>

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