<?php
/**
 * 会员中心购物车页
 * 作为独立页面嵌入会员中心布局
 */

// 登录检查
if (!isset($_SESSION['member_id'])) {
    header('Location: /member/login.php?redirect=' . urlencode($_SERVER['REQUEST_URI']));
    exit;
}

$memberId = $_SESSION['member_id'];
$list = $db->fetchAll("SELECT c.*, p.id as pid, p.title, p.litpic, p.stock, p.price as product_price FROM {$db->table('cart')} c LEFT JOIN {$db->table('product')} p ON c.product_id = p.id WHERE c.member_id = ? ORDER BY c.create_time DESC", [$memberId]);

$totalPrice = 0;
$totalQuantity = 0;
foreach ($list as &$item) {
    $item['total_price'] = $item['price'] * $item['quantity'];
    $totalPrice += $item['total_price'];
    $totalQuantity += $item['quantity'];
}
?>
<style>
.mc-cart-wrapper { padding: 0; }
.mc-cart-empty { text-align:center; padding:60px 0; }
.mc-cart-empty svg { width:60px;height:60px;margin-bottom:15px;opacity:0.4; }
.mc-cart-empty h3 { font-size:18px;color:#3d4a3e;margin-bottom:8px; }
.mc-cart-empty p { color:#6b7280;font-size:14px;margin-bottom:20px; }
.mc-cart-table { width:100%;border-collapse:collapse; }
.mc-cart-table thead tr { background:#f9fafb; }
.mc-cart-table th { padding:12px 16px;text-align:left;font-size:13px;color:#6b7280;font-weight:500;border-bottom:2px solid #e5e7eb; }
.mc-cart-table td { padding:14px 16px;border-bottom:1px solid #f0f0f0;vertical-align:middle; }
.mc-cart-table tbody tr:hover { background:#fafafa; }
.mc-cart-item { display:flex;align-items:center;gap:12px; }
.mc-cart-item img { width:56px;height:56px;object-fit:cover;border-radius:6px;border:1px solid #e5e7eb; }
.mc-cart-item h4 { font-size:14px;color:#1a1a1a;display:-webkit-box;-webkit-line-clamp:2;-webkit-box-orient:vertical;overflow:hidden;line-height:1.4; }
.mc-cart-item p { font-size:12px;color:#6b7280;margin-top:4px; }
.mc-cart-price { font-weight:600;color:#f5a623;font-size:15px; }
.mc-qty-control { display:flex;align-items:center;gap:0;border:1px solid #d1d5db;border-radius:8px;overflow:hidden;width:fit-content; }
.mc-qty-control button { width:30px;height:30px;border:none;background:#f3f4f6;cursor:pointer;font-size:16px;color:#374151; }
.mc-qty-control button:hover { background:#e5e7eb; }
.mc-qty-control input { width:40px;height:30px;text-align:center;border:none;border-left:1px solid #d1d5db;border-right:1px solid #d1d5db;font-size:14px; }
.mc-cart-subtotal { font-weight:600;color:#f5a623;font-size:15px; }
.mc-cart-remove { color:#ef4444;font-size:13px;text-decoration:none; }
.mc-cart-remove:hover { text-decoration:underline; }
.mc-cart-footer { display:flex;justify-content:space-between;align-items:center;padding:16px 20px;background:#fff;border:1px solid #e5e7eb;border-radius:12px;margin-top:16px; }
.mc-cart-footer-left { display:flex;align-items:center;gap:16px; }
.mc-cart-footer-total { font-size:18px;font-weight:600;color:#1a1a1a; }
.mc-cart-footer-total span { color:#f5a623;font-size:22px; }
.mc-cart-footer-right { display:flex;gap:12px; }
.mc-btn-secondary { padding:10px 24px;border:1px solid #d1d5db;border-radius:8px;background:#fff;color:#374151;font-size:14px;cursor:pointer; }
.mc-btn-secondary:hover { background:#f3f4f6; }
.mc-btn-primary { padding:10px 32px;background:#5a8f3e;color:#fff;border:none;border-radius:8px;font-size:15px;cursor:pointer; }
.mc-btn-primary:hover { background:#4a7a32; }
</style>

<?php if (empty($list)): ?>
<div class="mc-cart-empty">
    <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
        <circle cx="9" cy="21" r="1"/><circle cx="20" cy="21" r="1"/>
        <path d="M1 1h4l2.68 13.39a2 2 0 0 0 2 1.61h9.72a2 2 0 0 0 2-1.61L23 6H6"/>
    </svg>
    <h3>购物车是空的</h3>
    <p>快去挑选心仪的商品吧</p>
    <a href="/public/index.php" class="mc-btn-primary">去首页看看</a>
</div>
<?php else: ?>
<div style="background:#fff;border:1px solid #e5e7eb;border-radius:12px;overflow:hidden;">
    <table class="mc-cart-table">
        <thead>
            <tr>
                <th style="width:50px;">
                    <input type="checkbox" id="checkAll" checked style="accent-color:#5a8f3e;width:16px;height:16px;cursor:pointer;">
                </th>
                <th>商品信息</th>
                <th style="width:120px;">单价</th>
                <th style="width:150px;">数量</th>
                <th style="width:120px;">小计</th>
                <th style="width:100px;">操作</th>
            </tr>
        </thead>
        <tbody>
            <?php foreach ($list as $item): ?>
            <tr data-id="<?php echo $item['id']; ?>">
                <td>
                    <input type="checkbox" class="item-check" checked style="accent-color:#5a8f3e;width:16px;height:16px;cursor:pointer;">
                </td>
                <td>
                    <div class="mc-cart-item">
                        <img src="<?php echo htmlspecialchars($item['litpic'] ?: '/template/agrismart/images/no-product.jpg'); ?>" alt="">
                        <div>
                            <h4><?php echo htmlspecialchars($item['title']); ?></h4>
                            <p>库存：<?php echo intval($item['stock']); ?>件</p>
                        </div>
                    </div>
                </td>
                <td class="mc-cart-price">¥<?php echo number_format($item['product_price'], 2); ?></td>
                <td>
                    <div class="mc-qty-control">
                        <button onclick="mcUpdateQty(<?php echo $item['id']; ?>, -1)">-</button>
                        <input type="text" value="<?php echo $item['quantity']; ?>" id="qty_<?php echo $item['id']; ?>" onchange="mcUpdateQtyDirect(<?php echo $item['id']; ?>, this.value)">
                        <button onclick="mcUpdateQty(<?php echo $item['id']; ?>, 1)">+</button>
                    </div>
                </td>
                <td class="mc-cart-subtotal">¥<?php echo number_format($item['total_price'], 2); ?></td>
                <td>
                    <a href="javascript:mcRemoveItem(<?php echo $item['id']; ?>);" class="mc-cart-remove">删除</a>
                </td>
            </tr>
            <?php endforeach; ?>
        </tbody>
    </table>

    <div class="mc-cart-footer">
        <div class="mc-cart-footer-left">
            <input type="checkbox" id="checkAll2" checked style="accent-color:#5a8f3e;width:16px;height:16px;cursor:pointer;">
            <span style="font-size:14px;color:#6b7280;">全选</span>
            <span class="mc-cart-footer-total">已选 <span id="selectedCount"><?php echo count($list); ?></span> 件，合计：<span>¥<span id="totalPrice"><?php echo number_format($totalPrice, 2); ?></span></span></span>
        </div>
        <div class="mc-cart-footer-right">
            <button class="mc-btn-secondary" onclick="mcClearCart()">清空购物车</button>
            <button class="mc-btn-primary" onclick="mcCheckout()">去结算</button>
        </div>
    </div>
</div>

<script>
function mcUpdateQty(cartId, delta) {
    var input = document.getElementById('qty_' + cartId);
    var val = parseInt(input.value) + delta;
    if (val < 1) val = 1;
    input.value = val;
    mcUpdateCartAjax(cartId, val);
    var row = document.querySelector('tr[data-id="' + cartId + '"]');
    var price = parseFloat(row.querySelector('.mc-cart-price').textContent.replace(/[^\d.]/g, ''));
    row.querySelector('.mc-cart-subtotal').textContent = '¥' + (price * val).toFixed(2);
    mcUpdateTotal();
}
function mcUpdateQtyDirect(cartId, val) {
    val = parseInt(val) || 1;
    if (val < 1) val = 1;
    document.getElementById('qty_' + cartId).value = val;
    mcUpdateCartAjax(cartId, val);
    var row = document.querySelector('tr[data-id="' + cartId + '"]');
    var price = parseFloat(row.querySelector('.mc-cart-price').textContent.replace(/[^\d.]/g, ''));
    row.querySelector('.mc-cart-subtotal').textContent = '¥' + (price * val).toFixed(2);
    mcUpdateTotal();
}
function mcUpdateCartAjax(cartId, quantity) {
    var xhr = new XMLHttpRequest();
    xhr.open('POST', '/api/cart.php?action=update', true);
    xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
    xhr.send('cart_id=' + cartId + '&quantity=' + quantity);
}
function mcRemoveItem(cartId) {
    if (!confirm('确认移除该商品？')) return;
    var xhr = new XMLHttpRequest();
    xhr.open('POST', '/api/cart.php?action=remove', true);
    xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
    xhr.onload = function() {
        var row = document.querySelector('tr[data-id="' + cartId + '"]');
        if (row) row.remove();
        mcUpdateTotal();
        var remaining = document.querySelectorAll('tr[data-id]').length;
        if (remaining === 0) location.reload();
    };
    xhr.send('cart_id=' + cartId);
}
function mcClearCart() {
    if (!confirm('确认清空购物车？')) return;
    var xhr = new XMLHttpRequest();
    xhr.open('POST', '/api/cart.php?action=clear', true);
    xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
    xhr.onload = function() { location.reload(); };
    xhr.send();
}
function mcCheckout() {
    window.location.href = '/public/order/confirm.php';
}
document.getElementById('checkAll').addEventListener('change', function() {
    document.querySelectorAll('.item-check').forEach(cb => cb.checked = this.checked);
    document.getElementById('checkAll2').checked = this.checked;
    mcUpdateTotal();
});
document.getElementById('checkAll2').addEventListener('change', function() {
    document.querySelectorAll('.item-check').forEach(cb => cb.checked = this.checked);
    document.getElementById('checkAll').checked = this.checked;
    mcUpdateTotal();
});
function mcUpdateTotal() {
    var total = 0;
    var count = 0;
    document.querySelectorAll('.item-check:checked').forEach(function(cb) {
        var row = cb.closest('tr');
        total += parseFloat(row.querySelector('.mc-cart-subtotal').textContent.replace(/[^\d.]/g, ''));
        count++;
    });
    document.getElementById('selectedCount').textContent = count;
    document.getElementById('totalPrice').textContent = total.toFixed(2);
}
</script>
<?php endif; ?>