<?php
if (!defined('ROOT_PATH')) {
    define('ROOT_PATH', dirname(dirname(__DIR__)) . '/');
}

define('CORE_PATH', ROOT_PATH . 'core/');
define('PUBLIC_PATH', ROOT_PATH . 'public/');

require_once CORE_PATH . 'lib/session.php';
cmsStartSession();
require_once CORE_PATH . 'db/db.php';
$db = \Core\Db\DB::getInstance();
require_once CORE_PATH . 'lib/common.php';
require_once CORE_PATH . 'lib/license.php';
require_once CORE_PATH . 'lib/template_loader.php';

$configs = $db->fetchAll("SELECT config_key, config_value FROM {$db->table('config')}");
$siteConfig = [];
foreach ($configs as $cfg) {
    $siteConfig[$cfg['config_key']] = $cfg['config_value'];
}

$urlMode = isset($siteConfig['url_mode']) ? $siteConfig['url_mode'] : 'dynamic';
$license = new \Core\Lib\License();
$templateLoader = new \Core\Lib\TemplateLoader($license);
$activeTemplateKey = $templateLoader->resolveUsableTemplate($siteConfig['site_template'] ?? 'default', $db);

$site = $siteConfig;
$site['template_dir'] = '/template/' . $activeTemplateKey . '/';
$site['template_path'] = ROOT_PATH . 'template/' . $activeTemplateKey . '/';
$site['public_dir'] = '/public/';
$site['url_mode'] = $urlMode;

if ($urlMode === 'dynamic') {
    $module = isset($_GET['m']) ? trim($_GET['m']) : 'index';
    $action = isset($_GET['a']) ? trim($_GET['a']) : 'index';
    $id = isset($_GET['id']) ? intval($_GET['id']) : 0;
} else {
    $path = isset($_SERVER['REQUEST_URI']) ? parse_url($_SERVER['REQUEST_URI'], PHP_URL_PATH) : '/';
    $path = trim($path, '/');
    if (strpos($path, 'public/') === 0) $path = substr($path, 7);
    $routes = [];
    if (!empty($path)) {
        $routes = explode('/', $path);
        foreach ($routes as $k => $v) {
            $routes[$k] = preg_replace('/[^a-z0-9_\-\.]/i', '', $v);
        }
    }
    $module = isset($routes[0]) ? $routes[0] : '';
    $action = isset($routes[1]) ? $routes[1] : '';
    $id = isset($routes[1]) && is_numeric($routes[1]) ? intval($routes[1]) : 0;
}

function getUrl($type, $id = 0, $dir = '') {
    global $urlMode, $siteConfig;
    $base = rtrim(isset($siteConfig['site_url']) ? $siteConfig['site_url'] : 'http://' . $_SERVER['HTTP_HOST'], '/');
    if (!cmsRewriteModeEnabled()) {
        switch ($type) {
            case 'home': return '/public/index.php?m=index';
            case 'channel': return '/public/index.php?m=channel&id=' . $id;
            case 'article': return '/public/index.php?m=article&id=' . $id;
            case 'product': return '/public/index.php?m=product&id=' . $id;
            default: return '/public/index.php';
        }
    } else {
        switch ($type) {
            case 'home': return '/';
            case 'channel': return $dir ? '/' . $dir . '/' : '/channel/' . $id . '/';
            case 'product': return '/product/' . $id . '.html';
            default: return '/';
        }
    }
}

if (isset($_GET['ajax']) && $_GET['ajax'] === 'cart') {
    header('Content-Type: application/json');
    $memberId = intval($_SESSION['member_id'] ?? 0);
    if ($memberId <= 0) {
        http_response_code(401);
        echo json_encode(['code' => 401, 'msg' => '请先登录'], JSON_UNESCAPED_UNICODE);
        exit;
    }
    if ($_SERVER['REQUEST_METHOD'] === 'POST') {
        requireMemberCsrfToken(true);
        $act = isset($_POST['action']) ? $_POST['action'] : '';
        if ($act === 'update') {
            $cartId = intval(isset($_POST['cart_id']) ? $_POST['cart_id'] : 0);
            $quantity = max(1, min(999, intval(isset($_POST['quantity']) ? $_POST['quantity'] : 1)));
            $db->update('cart', ['quantity' => $quantity], 'id = ? AND member_id = ?', [$cartId, $memberId]);
            echo json_encode(['code' => 200, 'msg' => '更新成功']);
            exit;
        }
        if ($act === 'remove') {
            $cartId = intval(isset($_POST['cart_id']) ? $_POST['cart_id'] : 0);
            $db->delete('cart', 'id = ? AND member_id = ?', [$cartId, $memberId]);
            echo json_encode(['code' => 200, 'msg' => '已移除']);
            exit;
        }
        if ($act === 'clear') {
            $db->delete('cart', 'member_id = ?', [$memberId]);
            echo json_encode(['code' => 200, 'msg' => '已清空']);
            exit;
        }
    }
    exit;
}

if (!isset($_SESSION['member_id']) || $_SESSION['member_id'] <= 0) {
    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'];
}
?>
<!DOCTYPE html>
<html lang="zh-CN">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>购物车 - <?php echo $siteConfig['site_name']; ?></title>
<link rel="stylesheet" href="<?php echo $site['template_dir']; ?>css/reset.css">
<link rel="stylesheet" href="<?php echo $site['template_dir']; ?>css/style.css">
<link rel="stylesheet" href="<?php echo $site['template_dir']; ?>css/shop.css">
<script src="https://cdn.jsdelivr.net/npm/jquery@3.6.0/dist/jquery.min.js"></script>
<style>
.cart-empty { text-align: center; padding: 80px 0; color: #999; }
.cart-empty svg { width: 60px; height: 60px; margin-bottom: 15px; opacity: 0.5; }
.cart-empty h3 { font-size: 18px; margin-bottom: 10px; color: #3d4a3e; }
</style>
</head>
<body>
<div class="wrapper">
    <header class="header">
        <div class="container">
            <div class="logo">
                <a href="<?php echo getUrl('home'); ?>"><?php echo $siteConfig['site_name']; ?></a>
            </div>
            <nav class="nav">
                <ul>
                    <li><a href="<?php echo getUrl('home'); ?>">首页</a></li>
                </ul>
            </nav>
            <div class="top-right">
                <a href="/member/index.php">会员中心</a>
                <a href="/member/logout.php">退出</a>
            </div>
        </div>
    </header>
    <main class="main">
        <div class="container" style="margin: 30px auto;">
            <div class="breadcrumb">
                <a href="<?php echo getUrl('home'); ?>">首页</a> > <span>购物车</span>
            </div>

            <h1 class="page-title" style="margin-bottom: 25px;">我的购物车<span style="font-size: 14px; color: #6b7280; font-weight: normal; margin-left: 15px;">共 <?php echo count($list); ?> 件商品</span></h1>

            <?php if (!empty($list)): ?>
            <div style="background: #fff; border: 1px solid #d4c9a8; border-radius: 8px; padding: 25px; margin-bottom: 20px;">
                <table class="cart-table">
                    <thead>
                        <tr>
                            <th style="width: 50px;"><input type="checkbox" id="checkAll" checked style="accent-color:#5a8f3e;width:18px;height:18px;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="cart-item">
                                    <div class="cart-item-img">
                                        <img src="<?php echo htmlspecialchars($item['litpic'] ?: $site['template_dir'] . 'images/no-product.jpg'); ?>" alt="<?php echo htmlspecialchars($item['title']); ?>">
                                    </div>
                                    <div class="cart-item-info">
                                        <h4><?php echo htmlspecialchars($item['title']); ?></h4>
                                        <p>库存：<?php echo intval($item['stock']); ?>件</p>
                                    </div>
                                </div>
                            </td>
                            <td style="font-weight:600;color:#f5a623;">¥<?php echo number_format($item['product_price'], 2); ?></td>
                            <td>
                                <div class="quantity-control">
                                    <button class="minus" onclick="updateQuantity(<?php echo $item['id']; ?>, -1)">-</button>
                                    <input type="text" value="<?php echo $item['quantity']; ?>" id="qty_<?php echo $item['id']; ?>" class="qty-input" style="width:40px;text-align:center;border:none;height:30px;">
                                    <button class="plus" onclick="updateQuantity(<?php echo $item['id']; ?>, 1)">+</button>
                                </div>
                            </td>
                            <td class="cart-subtotal" style="font-weight:600;color:#f5a623;">¥<?php echo number_format($item['total_price'], 2); ?></td>
                            <td>
                                <a href="javascript:removeItem(<?php echo $item['id']; ?>);" class="cart-remove">删除</a>
                            </td>
                        </tr>
                        <?php endforeach; ?>
                    </tbody>
                </table>

                <div class="cart-footer">
                    <div class="cart-total">
                        <div>
                            <label style="display:flex;align-items:center;gap:8px;cursor:pointer;">
                                <input type="checkbox" id="checkAll2" checked style="accent-color:#5a8f3e;width:16px;height:16px;cursor:pointer;"> 全选
                            </label>
                        </div>
                        <div class="total-text">已选<span id="selectedCount"><?php echo count($list); ?></span> 件</div>
                        <div>合计：<span class="total-price" id="totalPrice">¥<?php echo number_format($totalPrice, 2); ?></span></div>
                    </div>
                    <div class="cart-actions">
                        <button class="btn btn-secondary" onclick="clearCart()">清空购物车</button>
                        <button class="btn btn-primary" onclick="checkout()" style="padding:12px 40px;font-size:16px;">去结算</button>
                    </div>
                </div>
            </div>
            <?php else: ?>
            <div class="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 style="color:#6b7280;margin-bottom:20px;">快去挑选心仪的商品吧</p>
                <a href="<?php echo getUrl('home'); ?>" class="btn btn-primary">去首页看看</a>
            </div>
            <?php endif; ?>
        </div>
    </main>
    <footer class="footer">
        <div class="container">
            <div class="copyright">&copy; <?php echo date('Y'); ?> <?php echo $siteConfig['site_name']; ?> 版权所有</div>
        </div>
    </footer>
</div>

<script>
var cartCsrfToken = <?php echo json_encode(getMemberCsrfToken()); ?>;
function updateQuantity(cartId, delta) {
    var input = document.getElementById('qty_' + cartId);
    var val = parseInt(input.value) + delta;
    if (val < 1) val = 1;
    input.value = val;
    var xhr = new XMLHttpRequest();
    xhr.open('POST', '/api/cart.php', true);
    xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
    xhr.send('action=update&cart_id=' + cartId + '&quantity=' + val + '&csrf_token=' + encodeURIComponent(cartCsrfToken));
    var row = document.querySelector('tr[data-id="' + cartId + '"]');
    var price = parseFloat(row.querySelector('td:nth-child(3)').textContent.replace(/[^\d.]/g, ''));
    row.querySelector('.cart-subtotal').textContent = '¥' + (price * val).toFixed(2);
    updateTotal();
}

function removeItem(cartId) {
    if (!confirm('确认移除该商品？')) return;
    var xhr = new XMLHttpRequest();
    xhr.open('POST', '/api/cart.php', true);
    xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
    xhr.onload = function() {
        try { JSON.parse(xhr.responseText); } catch(e) {}
        var row = document.querySelector('tr[data-id="' + cartId + '"]');
        if (row) row.remove();
        updateTotal();
        var remaining = document.querySelectorAll('tr[data-id]').length;
        if (remaining === 0) location.reload();
    };
    xhr.send('action=remove&cart_id=' + cartId + '&csrf_token=' + encodeURIComponent(cartCsrfToken));
}

function clearCart() {
    if (!confirm('确认清空购物车？')) return;
    var xhr = new XMLHttpRequest();
    xhr.open('POST', '/api/cart.php', true);
    xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
    xhr.onload = function() { location.reload(); };
    xhr.send('action=clear&csrf_token=' + encodeURIComponent(cartCsrfToken));
}

function checkout() {
    var selectedIds = [];
    document.querySelectorAll('.item-check:checked').forEach(function(cb) {
        var row = cb.closest('tr[data-id]');
        if (row) selectedIds.push(row.getAttribute('data-id'));
    });
    if (selectedIds.length === 0) {
        alert('请选择商品');
        return;
    }
    window.location.href = '/public/order/confirm.php?cart_ids=' + selectedIds.join(',');
}

document.getElementById('checkAll').addEventListener('change', function() {
    document.querySelectorAll('.item-check').forEach(cb => cb.checked = this.checked);
    document.getElementById('checkAll2').checked = this.checked;
    updateTotal();
});
document.getElementById('checkAll2').addEventListener('change', function() {
    document.querySelectorAll('.item-check').forEach(cb => cb.checked = this.checked);
    document.getElementById('checkAll').checked = this.checked;
    updateTotal();
});

function updateTotal() {
    var total = 0;
    var count = 0;
    document.querySelectorAll('.item-check:checked').forEach(function(cb) {
        var row = cb.closest('tr');
        total += parseFloat(row.querySelector('.cart-subtotal').textContent.replace(/[^\d.]/g, ''));
        count++;
    });
    document.getElementById('selectedCount').textContent = count;
    document.getElementById('totalPrice').textContent = '¥' + total.toFixed(2);
}
</script>
</body>
</html>
