<?php
/**
 * Sanag耳机库存 - 首页风格版（动态读取5.md）
 */
$pageTitle = '🎧 耳机库存';
include 'header.php';
include 'ts_helper.php';

// ===== 解析 5.md =====
date_default_timezone_set('Asia/Shanghai');
$mdFile = __DIR__ . '/5.md';

$inventoryRows = [];
$soldRows = [];
$currentSection = 'none';

if (file_exists($mdFile)) {
    $lines = file($mdFile, FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES);
    
    foreach ($lines as $line) {
        $trimmed = trim($line);
        
        // 检测区域标记
        if (strpos($trimmed, '<!-- inventory -->') === 0) {
            $currentSection = 'inventory';
            continue;
        }
        if (strpos($trimmed, '<!-- end inventory -->') === 0) {
            $currentSection = 'none';
            continue;
        }
        if (strpos($trimmed, '<!-- sold -->') === 0) {
            $currentSection = 'sold';
            continue;
        }
        if (strpos($trimmed, '<!-- end sold -->') === 0) {
            $currentSection = 'none';
            continue;
        }
        
        if ($currentSection === 'none') continue;
        
        // 只处理表格行（以 | 开头和结尾）
        if (!preg_match('/^\|.*\|$/', $trimmed)) continue;
        
        // 跳过表头行（含"序号"和"型号"等）
        if (preg_match('/序号/', $trimmed) && preg_match('/型号/', $trimmed)) continue;
        
        // 跳过分隔行
        if (preg_match('/^\|?\s*-{2,}\s*\|/', $trimmed)) continue;
        
        // 解析行数据
        $trimmed = ltrim($trimmed, '|');
        $trimmed = rtrim($trimmed, '|');
        $cols = array_map('trim', explode('|', $trimmed));
        
        if (count($cols) < 7) continue;
        
        if ($currentSection === 'inventory' && count($cols) >= 8) {
            // 库存表: 序号|型号|颜色|序列号|渠道价|指导价|入库时间|备注
            $inventoryRows[] = [
                'seq' => (int)$cols[0],
                'model' => $cols[1],
                'color' => $cols[2],
                'sn' => $cols[3],
                'cost' => (int)$cols[4],
                'retail' => (int)$cols[5],
                'date' => $cols[6],
                'note' => $cols[7] ?? ''
            ];
        } elseif ($currentSection === 'sold' && count($cols) >= 7) {
            // 已售表: 序号|型号|颜色|序列号|售出价|买家|状态
            $soldRows[] = [
                'seq' => (int)$cols[0],
                'model' => $cols[1],
                'color' => $cols[2],
                'sn' => $cols[3],
                'price' => (int)$cols[4],
                'buyer' => $cols[5],
                'status' => $cols[6] ?? ''
            ];
        }
    }
    
    // 按序号升序
    usort($inventoryRows, fn($a, $b) => $a['seq'] - $b['seq']);
    usort($soldRows, fn($a, $b) => $a['seq'] - $b['seq']);
}

$lastUpdate = file_exists($mdFile) ? date('Y-m-d', filemtime($mdFile)) : date('Y-m-d');
$totalInventory = count($inventoryRows);
$totalSold = count($soldRows);
?>
<div class="page-header text-center mb-8 max-w-3xl mx-auto reveal">
    <p class="text-cta font-medium tracking-widest mb-2 uppercase text-sm">Headphones</p>
    <h1 class="font-heading text-3xl md:text-4xl font-bold mb-2"><span class="emoji-natural">🎧</span> <span class="gradient-text">耳机库存</span></h1>
</div>
    <p class="text-gray-400 text-sm">更新时间：<?= htmlspecialchars($lastUpdate) ?></p>


<div class="reveal glass rounded-2xl p-5 flex items-center gap-3 mb-6" style="transition-delay: 0.1s;">
    <svg xmlns="http://www.w3.org/2000/svg" width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="#22C55E" stroke-width="2">
        <path d="M4 16v1a3 3 0 003 3h10a3 3 0 003-3v-1m-4-4l-4 4m0 0l-4-4m4 4V4"/>
    </svg>
    <span class="text-gray-400 text-sm">下载源文件：</span>
</div>
    <a href="5.md" target="_blank" class="text-sm text-cta hover:text-light transition-smooth">📄 耳机库存.md</a>



    
        <table>
            <thead>
                <tr>
                    <th>序号</th><th>型号</th><th>颜色</th><th>序列号(S/N)</th><th>渠道价</th><th>指导价</th><th>利润空间</th><th>入库时间</th><th>备注</th>
                </tr>
            </thead>
            <tbody>
<?php foreach ($inventoryRows as $row):
    $profit = $row['retail'] - $row['cost'];
?>
                <tr>
                    <td><?= $row['seq'] ?></td>
                    <td><strong><?= htmlspecialchars($row['model']) ?></strong></td>
                    <td><?= htmlspecialchars($row['color']) ?></td>
                    <td><?= htmlspecialchars($row['sn']) ?></td>
                    <td class="price-highlight">¥<?= $row['cost'] ?></td>
                    <td class="price-strike">¥<?= $row['retail'] ?></td>
                    <td class="price-profit">¥<?= $profit ?></td>
                    <td><?= htmlspecialchars($row['date']) ?></td>
                    <td><?= htmlspecialchars($row['note']) ?></td>
                </tr>
<?php endforeach; ?>
            </tbody>
        </table>
    



    <h2 class="text-xl font-bold mb-4">📋 已售清单</h2>
    
        <table>
            <thead>
                <tr>
                    <th>序号</th><th>型号</th><th>颜色</th><th>序列号(S/N)</th><th>售出价</th><th>买家</th><th>状态</th>
                </tr>
            </thead>
            <tbody>
<?php foreach ($soldRows as $row):
    $statusClass = '';
    if (strpos($row['status'], '已结') !== false || strpos($row['status'], '✔') !== false) {
        $statusClass = 'text-green-400';
    }
?>
                <tr>
                    <td><?= $row['seq'] ?></td>
                    <td><strong><?= htmlspecialchars($row['model']) ?></strong></td>
                    <td><?= htmlspecialchars($row['color']) ?></td>
                    <td><?= htmlspecialchars($row['sn']) ?></td>
                    <td class="price-highlight">¥<?= $row['price'] ?></td>
                    <td><?= htmlspecialchars($row['buyer']) ?></td>
                    <td class="<?= $statusClass ?>"><span style="color:#10b981"><?= htmlspecialchars($row['status']) ?></span></td>
                </tr>
<?php endforeach; ?>
            </tbody>
        </table>
    


</body>
</html>
