<?php
require_once __DIR__ . '/config.php';
requireLogin();
$pageTitle = '订单结算';
$pdo  = getDB();

$is_post = ($_SERVER['REQUEST_METHOD'] === 'POST');
if ($is_post) {
    $type = trim($_POST['order_type'] ?? $_GET['type'] ?? 'esim');
    $id   = intval($_POST['package_id'] ?? $_GET['id'] ?? 0);
    $device_ids_raw = array_merge((array)($_POST['device_ids'] ?? []), (array)($_POST['addon_devices'] ?? []));
    $multi_pkg_ids = array_values(array_unique(array_filter(array_map('intval', (array)($_POST['package_ids'] ?? [])))));
} else {
    $type = trim($_GET['type'] ?? 'esim');
    $id   = intval($_GET['id'] ?? 0);
    $device_ids_raw = [];
    $multi_pkg_ids = [];
}

$item = null;
$devices = [];
$addon_devices = [];
$multi_pkgs = [];
$id_arr = [];
$amount = 0.0;
$shipping_fee = 0.0;
$error = '';
$discountAmount = 0.0;
$promoCode = trim($_POST['promo_code'] ?? $_GET['promo_code'] ?? '');
$promoData = null;
$promoApplicable = false;
$promoVisible = false;
$applyMode = 'first_purchase';
if (in_array($type, ['phone_renew','phone_recharge'], true)) {
    $applyMode = $type === 'phone_renew' ? 'renewal' : 'topup';
}

if ($type === 'esim' && $id > 0) {
    $stmt = $pdo->prepare("SELECT * FROM packages WHERE id = ?");
    $stmt->execute([$id]);
    $item = $stmt->fetch();
    if (!$item) { header('Location: /esim-packages.php'); exit; }
    $amount = (float)$item['sale_price'];
} elseif ($type === 'phone' && $id > 0) {
    $stmt = $pdo->prepare("SELECT * FROM phone_packages WHERE id = ?");
    $stmt->execute([$id]);
    $item = $stmt->fetch();
    if (!$item) { header('Location: /phone-packages.php'); exit; }
    $amount = (float)$item['price'];
} elseif ($type === 'phone_multi' && !empty($multi_pkg_ids)) {
    $ph = implode(',', array_fill(0, count($multi_pkg_ids), '?'));
    $stmt_multi = $pdo->prepare("SELECT * FROM phone_packages WHERE id IN ($ph)");
    $stmt_multi->execute($multi_pkg_ids);
    $multi_pkgs = $stmt_multi->fetchAll();
    if (empty($multi_pkgs)) { header('Location: /phone-packages.php'); exit; }
    foreach ($multi_pkgs as $mp) { $amount += (float)$mp['price']; }
} elseif ($type === 'device') {
    $raw_ids = trim($_GET['ids'] ?? '');
    if ($raw_ids) $device_ids_raw = array_merge($device_ids_raw, array_filter(array_map('intval', explode(',', $raw_ids))));
} else {
    header('Location: /esim-packages.php'); exit;
}

$id_arr = array_values(array_unique(array_filter(array_map('intval', $device_ids_raw))));
if (!empty($id_arr)) {
    $ph = implode(',', array_fill(0, count($id_arr), '?'));
    $stmt = $pdo->prepare("SELECT * FROM devices WHERE id IN ($ph)");
    $stmt->execute($id_arr);
    $addon_devices = $stmt->fetchAll();
    foreach ($addon_devices as $d) { $amount += (float)$d['price']; }
    $shipping_fee = (float)(getSetting('shipping_fee_default') ?? getSetting('shipping_fee') ?? 3.50);
}
if ($type === 'device') {
    $devices = $addon_devices;
    if (empty($devices)) { header('Location: /devices.php'); exit; }
}

$productScope = $type === 'esim' ? 'esim' : (($type === 'device') ? 'device' : 'phone');
try {
    $promoStmt = $pdo->prepare("SELECT * FROM promo_codes WHERE is_active = 1 AND show_input_frontend = 1 AND (product_scope = 'all' OR product_scope = ?) AND (apply_mode = 'all' OR apply_mode = ?) ORDER BY id DESC");
    $promoStmt->execute([$productScope, $applyMode]);
    $promoVisible = (bool)$promoStmt->fetch();
} catch (Throwable $e) { $promoVisible = false; }

if ($promoCode !== '') {
    try {
        $stmt = $pdo->prepare("SELECT * FROM promo_codes WHERE code = ? AND is_active = 1 LIMIT 1");
        $stmt->execute([strtoupper($promoCode)]);
        $promoData = $stmt->fetch();
        if ($promoData) {
            $scopeOk = in_array($promoData['product_scope'], ['all', $productScope], true);
            $modeOk  = in_array($promoData['apply_mode'], ['all', $applyMode], true);
            $dateOk  = (empty($promoData['starts_at']) || strtotime($promoData['starts_at']) <= time()) && (empty($promoData['expires_at']) || strtotime($promoData['expires_at']) >= time());
            $limitOk = ($promoData['usage_limit'] === null) || ((int)$promoData['used_count'] < (int)$promoData['usage_limit']);
            $minOk   = ($promoData['minimum_amount'] === null) || ($amount >= (float)$promoData['minimum_amount']);
            if ($scopeOk && $modeOk && $dateOk && $limitOk && $minOk) {
                $promoApplicable = true;
                if ($promoData['discount_type'] === 'percent') {
                    $discountAmount = round($amount * ((float)$promoData['discount_value'] / 100), 2);
                } else {
                    $discountAmount = min($amount, (float)$promoData['discount_value']);
                }
            }
        }
    } catch (Throwable $e) {}
}

$total = max(0, $amount - $discountAmount) + $shipping_fee;
$need_shipping = ($type === 'device') || !empty($addon_devices);

$availableMethods = [];
if ((getSetting('gateway_usdt_enabled') ?? '1') === '1') $availableMethods['usdt'] = ['title' => 'USDT支付', 'desc' => 'TRC20 链自动入账', 'icon' => '<i class="fab fa-bitcoin fa-2x text-warning mb-2 d-block"></i>'];
if ((getSetting('gateway_wechat_enabled') ?? '1') === '1') $availableMethods['wechat'] = ['title' => '微信支付', 'desc' => 'Stripe WeChat Pay', 'icon' => '<img src="https://linuxword.com/wp-content/uploads/2026/02/wechatpaypng.png" alt="微信" style="height:40px;" class="mb-2 d-block mx-auto">'];
if ((getSetting('gateway_card_enabled') ?? '1') === '1') $availableMethods['card'] = ['title' => '银行卡支付', 'desc' => 'Apple Pay / VISA / MASTER', 'icon' => '<img src="https://linuxword.com/wp-content/uploads/2026/02/credit-card.png" alt="银行卡" style="height:40px;" class="mb-2 d-block mx-auto">'];
if ((getSetting('gateway_alipay_enabled') ?? '0') === '1') $availableMethods['alipay'] = ['title' => 'Stripe支付宝', 'desc' => 'Alipay via Stripe', 'icon' => '<i class="fas fa-wallet fa-2x text-info mb-2 d-block"></i>'];
if (empty($availableMethods)) $availableMethods['usdt'] = ['title' => 'USDT支付', 'desc' => 'TRC20 链自动入账', 'icon' => '<i class="fab fa-bitcoin fa-2x text-warning mb-2 d-block"></i>'];

if ($is_post) {
    $payment_method = trim($_POST['payment_method'] ?? '');
    if (!isset($availableMethods[$payment_method])) {
        $error = '请选择有效支付方式';
        goto render;
    }

    $uid = (int)$_SESSION['user_id'];
    $chk_user = $pdo->prepare("SELECT id FROM users WHERE id = ?");
    $chk_user->execute([$uid]);
    if (!$chk_user->fetch()) {
        session_unset(); session_destroy();
        header('Location: /login.php?err=session_expired'); exit;
    }

    $order_number = generateOrderNumber(strtoupper($type));

    if ($type === 'esim') {
        $euicc_id = null;
        $raw_euicc = intval($_POST['euicc_id'] ?? 0);
        if ($raw_euicc > 0) {
            $eu_chk = $pdo->prepare("SELECT id FROM euniccs WHERE id = ? AND user_id = ?");
            $eu_chk->execute([$raw_euicc, $uid]);
            if ($eu_chk->fetch()) $euicc_id = $raw_euicc;
        }
        $stmt = $pdo->prepare("INSERT INTO orders (user_id, package_id, order_number, amount, status, payment_method, euicc_id, created_at) VALUES (?, ?, ?, ?, 'pending', ?, ?, NOW())");
        $stmt->execute([$uid, $id, $order_number, $total, $payment_method, $euicc_id]);
    } elseif ($type === 'phone') {
        $stmt = $pdo->prepare("INSERT INTO phone_orders (user_id, package_id, order_number, amount, status, payment_method, created_at) VALUES (?, ?, ?, ?, 'pending', ?, NOW())");
        $stmt->execute([$uid, $id, $order_number, $total, $payment_method]);
    } elseif ($type === 'phone_multi') {
        foreach ($multi_pkgs as $mp) {
            $sub_order = generateOrderNumber('PHN');
            $stmt_mp = $pdo->prepare("INSERT INTO phone_orders (user_id, package_id, order_number, amount, status, payment_method, created_at) VALUES (?, ?, ?, ?, 'pending', ?, NOW())");
            $stmt_mp->execute([$uid, $mp['id'], $sub_order, (float)$mp['price'], $payment_method]);
        }
        $order_number = generateOrderNumber('PHN');
    } elseif ($type === 'device') {
        $use_saved = intval($_POST['use_saved_address'] ?? 0);
        if ($use_saved) {
            $u_row = getCurrentUser();
            $ship_name = $u_row['real_name'] ?? $u_row['email'] ?? ''; $ship_phone = $u_row['phone'] ?? '';
            $ship_province = $u_row['province'] ?? ''; $ship_city = $u_row['city'] ?? '';
            $ship_zip = $u_row['zip'] ?? ''; $ship_address = $u_row['address'] ?? '';
        } else {
            $ship_name = trim($_POST['ship_name'] ?? ''); $ship_phone = trim($_POST['ship_phone'] ?? '');
            $ship_province = trim($_POST['ship_province'] ?? ''); $ship_city = trim($_POST['ship_city'] ?? '');
            $ship_zip = trim($_POST['ship_zip'] ?? ''); $ship_address = trim($_POST['ship_address'] ?? '');
        }
        if (!$ship_name || !$ship_address) { $error = '请填写完整的收货地址信息（姓名、地址为必填）'; goto render; }
        $dev_amount = max(0, $amount - $shipping_fee - $discountAmount);
        $stmt = $pdo->prepare("INSERT INTO device_orders (user_id, order_number, amount, shipping_fee, total_amount, status, payment_method, ship_name, ship_phone, ship_province, ship_city, ship_zip, ship_address, created_at) VALUES (?, ?, ?, ?, ?, 'pending', ?, ?, ?, ?, ?, ?, ?, NOW())");
        $stmt->execute([$uid, $order_number, $dev_amount, $shipping_fee, $total, $payment_method, $ship_name, $ship_phone, $ship_province, $ship_city, $ship_zip, $ship_address]);
        $order_id = (int)$pdo->lastInsertId();
        foreach ($devices as $d) {
            $ins = $pdo->prepare("INSERT INTO device_order_items (device_order_id, device_id, quantity, price) VALUES (?, ?, 1, ?)");
            $ins->execute([$order_id, $d['id'], $d['price']]);
        }
    }

    try {
        $pdo->exec("CREATE TABLE IF NOT EXISTS billing_invoices (
            id INT AUTO_INCREMENT PRIMARY KEY,
            user_id INT NOT NULL,
            invoice_number VARCHAR(50) NOT NULL,
            related_type VARCHAR(30) DEFAULT NULL,
            related_id INT DEFAULT NULL,
            order_number VARCHAR(50) DEFAULT NULL,
            title VARCHAR(255) NOT NULL,
            subtotal DECIMAL(10,2) NOT NULL DEFAULT 0.00,
            discount_amount DECIMAL(10,2) NOT NULL DEFAULT 0.00,
            tax_amount DECIMAL(10,2) NOT NULL DEFAULT 0.00,
            total_amount DECIMAL(10,2) NOT NULL DEFAULT 0.00,
            paid_amount DECIMAL(10,2) NOT NULL DEFAULT 0.00,
            payment_method VARCHAR(30) DEFAULT NULL,
            status VARCHAR(30) NOT NULL DEFAULT 'unpaid',
            due_date DATETIME DEFAULT NULL,
            paid_at DATETIME DEFAULT NULL,
            created_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
            updated_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
            UNIQUE KEY uniq_invoice_number (invoice_number)
        ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4");
        $invoiceStmt = $pdo->prepare("INSERT INTO billing_invoices (user_id, invoice_number, related_type, order_number, title, subtotal, discount_amount, total_amount, payment_method, status, due_date, created_at, updated_at) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, 'unpaid', DATE_ADD(NOW(), INTERVAL 1 DAY), NOW(), NOW())");
        $invoiceStmt->execute([$uid, generateOrderNumber('INV'), $type, $order_number, '订单结算 - ' . $type, $amount + $shipping_fee, $discountAmount, $total, $payment_method]);
    } catch (Throwable $e) {}

    if ($promoApplicable && $promoData) {
        try {
            $pdo->prepare("UPDATE promo_codes SET used_count = used_count + 1 WHERE id = ?")->execute([$promoData['id']]);
        } catch (Throwable $e) {}
    }

    try {
        $user = getCurrentUser();
        sendTemplateMail('order_placed', $user['email'], [
            'order_number' => $order_number,
            'amount'       => '$' . number_format($total, 2) . ' USD',
            'username'     => $user['email'],
        ], true);
    } catch (Exception $e) {}

    if ($payment_method === 'usdt') header("Location: /pay-usdt.php?order=" . urlencode($order_number) . "&type=" . urlencode($type));
    elseif ($payment_method === 'wechat') header("Location: /stripe-paywechat.php?order=" . urlencode($order_number) . "&type=" . urlencode($type));
    elseif ($payment_method === 'card') header("Location: /stripe-paycard.php?order=" . urlencode($order_number) . "&type=" . urlencode($type));
    elseif ($payment_method === 'alipay') header("Location: /stripe-payalipay.php?order=" . urlencode($order_number) . "&type=" . urlencode($type));
    else header("Location: /user/esim-orders.php");
    exit;
}

render:
$u = getCurrentUser();
require_once __DIR__ . '/includes/header.php';
?>
<style>
.checkout-wrap { max-width: 860px; margin: 0 auto; padding: 40px 16px; }
.checkout-card { background: #fff; border-radius: 16px; box-shadow: 0 2px 16px rgba(0,0,0,.07); margin-bottom: 24px; overflow: hidden; }
.checkout-card-header { padding: 16px 24px; border-bottom: 1px solid #f0f0f0; font-weight: 700; font-size: .95rem; display: flex; align-items: center; gap: 8px; }
.checkout-card-body { padding: 24px; }
.pay-method { border: 2px solid #e9ecef; border-radius: 14px; padding: 18px 12px; text-align: center; cursor: pointer; transition: .2s; height:100%; }
.pay-method:hover { border-color: #0d6efd; background: rgba(13,110,253,.03); }
.pay-method.active { border-color: #0d6efd; background: rgba(13,110,253,.06); }
.total-row { display: flex; justify-content: space-between; align-items: center; font-size: 1.2rem; font-weight: 700; }
.summary-kv{display:flex;justify-content:space-between;margin-bottom:10px;color:#64748b}
.discount-box{background:#ecfdf5;border:1px solid #bbf7d0;color:#166534;padding:10px 14px;border-radius:12px;margin-top:14px}
</style>
<div class="checkout-wrap">
    <h3 class="fw-bold mb-4"><i class="fas fa-shopping-cart me-2 text-primary"></i>订单结算</h3>
    <?php if ($error): ?><div class="alert alert-danger"><i class="fas fa-exclamation-circle me-2"></i><?php echo e($error); ?></div><?php endif; ?>
    <div class="checkout-card">
        <div class="checkout-card-header"><i class="fas fa-receipt text-primary"></i>订单详情</div>
        <div class="checkout-card-body">
            <?php if ($type === 'esim' && $item): ?>
                <div class="d-flex justify-content-between align-items-start mb-2"><div><div class="fw-semibold"><?php echo e($item['name']); ?></div><div class="text-muted small mt-1"><?php echo formatMB($item['data_mb']); ?> · <?php echo getDays($item['days'], $item['name']); ?> 天</div><?php if (!empty($item['countries'])): ?><div class="mt-1 small text-muted"><i class="fas fa-globe me-1 text-primary"></i><?php echo e($item['countries']); ?></div><?php endif; ?></div><span class="fw-bold text-primary fs-5 ms-3">$<?php echo number_format($item['sale_price'], 2); ?></span></div>
            <?php elseif ($type === 'phone' && $item): ?>
                <div class="d-flex justify-content-between align-items-start mb-2"><div><div class="fw-semibold"><?php echo e($item['name']); ?></div><?php if (!empty($item['description'])): ?><div class="text-muted small mt-1"><?php echo e($item['description']); ?></div><?php endif; ?></div><span class="fw-bold text-primary fs-5 ms-3">$<?php echo number_format($item['price'], 2); ?></span></div>
            <?php elseif ($type === 'device' && !empty($devices)): ?>
                <?php foreach ($devices as $d): ?><div class="d-flex justify-content-between mb-2"><span><i class="fas fa-sim-card me-2 text-muted"></i><?php echo e($d['product_name'] ?? $d['name'] ?? '设备'); ?></span><span class="fw-semibold"><?php echo $d['price'] > 0 ? '$' . number_format($d['price'], 2) : '<span class="text-success">免费</span>'; ?></span></div><?php endforeach; ?>
            <?php endif; ?>
            <?php if (!empty($addon_devices) && $type !== 'device'): ?><hr class="my-2"><div class="text-muted small fw-semibold mb-1"><i class="fas fa-plus-circle me-1 text-success"></i>搭配设备</div><?php foreach ($addon_devices as $d): ?><div class="d-flex justify-content-between mb-1 text-muted small"><span><?php echo e($d['product_name'] ?? $d['name'] ?? '设备'); ?></span><span><?php echo $d['price'] > 0 ? '$' . number_format($d['price'], 2) : '免费'; ?></span></div><?php endforeach; ?><?php endif; ?>
            <hr class="my-3">
            <div class="summary-kv"><span>商品小计</span><span>$<?php echo number_format($amount, 2); ?></span></div>
            <div class="summary-kv"><span>快递费</span><span>$<?php echo number_format($shipping_fee, 2); ?></span></div>
            <?php if ($discountAmount > 0): ?><div class="summary-kv"><span>促销优惠</span><span class="text-success">- $<?php echo number_format($discountAmount, 2); ?></span></div><div class="discount-box"><i class="fas fa-badge-percent me-2"></i>已应用促销码：<strong><?php echo e(strtoupper($promoCode)); ?></strong></div><?php endif; ?>
            <div class="total-row mt-3"><span>应付合计</span><span class="text-primary">$<?php echo number_format($total, 2); ?> USD</span></div>
        </div>
    </div>

    <?php if ($need_shipping): ?>
    <div class="checkout-card"><div class="checkout-card-header"><i class="fas fa-map-marker-alt text-danger"></i>收货地址</div><div class="checkout-card-body"><?php $hasSaved = !empty($u['address']); ?><?php if ($hasSaved): ?><div class="alert alert-light border mb-3 py-2 px-3"><div class="small fw-semibold mb-1"><i class="fas fa-map-marker-alt text-danger me-1"></i>已保存地址</div><div class="text-muted small"><?php echo e(trim(($u['province'] ?? '') . ' ' . ($u['city'] ?? '') . ' ' . ($u['address'] ?? ''))); ?></div><div class="mt-2 d-flex gap-3"><div class="form-check form-check-inline"><input class="form-check-input" type="radio" name="addr_choice" id="useSaved" value="saved" checked onchange="toggleAddr(this.value)"><label class="form-check-label small" for="useSaved">使用此地址</label></div><div class="form-check form-check-inline"><input class="form-check-input" type="radio" name="addr_choice" id="useNew" value="new" onchange="toggleAddr(this.value)"><label class="form-check-label small" for="useNew">填写新地址</label></div></div></div><?php endif; ?><div id="new-addr-form" <?php echo $hasSaved ? 'style="display:none"' : ''; ?>><div class="row g-3"><div class="col-md-6"><label class="form-label small fw-semibold">收件人姓名 <span class="text-danger">*</span></label><input type="text" class="form-control" id="f_ship_name" placeholder="真实姓名"></div><div class="col-md-6"><label class="form-label small fw-semibold">联系电话 <span class="text-danger">*</span></label><input type="text" class="form-control" id="f_ship_phone" placeholder="手机号码"></div><div class="col-md-4"><label class="form-label small fw-semibold">省份/州</label><input type="text" class="form-control" id="f_ship_province" placeholder="省份/州"></div><div class="col-md-4"><label class="form-label small fw-semibold">城市</label><input type="text" class="form-control" id="f_ship_city" placeholder="城市"></div><div class="col-md-4"><label class="form-label small fw-semibold">邮政编码</label><input type="text" class="form-control" id="f_ship_zip" placeholder="邮编"></div><div class="col-12"><label class="form-label small fw-semibold">详细地址 <span class="text-danger">*</span></label><input type="text" class="form-control" id="f_ship_address" placeholder="街道、门牌号等"></div></div></div></div></div>
    <?php endif; ?>

    <div class="checkout-card">
        <div class="checkout-card-header"><i class="fas fa-credit-card text-primary"></i>选择支付方式</div>
        <div class="checkout-card-body">
            <form method="POST" action="/checkout.php" id="checkout-form">
                <input type="hidden" name="order_type" value="<?php echo htmlspecialchars($type); ?>">
                <?php if ($id > 0): ?><input type="hidden" name="package_id" value="<?php echo $id; ?>"><?php endif; ?>
                <?php foreach ($id_arr as $did): ?><input type="hidden" name="device_ids[]" value="<?php echo (int)$did; ?>"><?php endforeach; ?>
                <?php if ($need_shipping): ?><input type="hidden" name="use_saved_address" id="h_use_saved" value="<?php echo (!empty($u['address'])) ? '1' : '0'; ?>"><input type="hidden" name="ship_name" id="h_ship_name" value=""><input type="hidden" name="ship_phone" id="h_ship_phone" value=""><input type="hidden" name="ship_province" id="h_ship_province" value=""><input type="hidden" name="ship_city" id="h_ship_city" value=""><input type="hidden" name="ship_zip" id="h_ship_zip" value=""><input type="hidden" name="ship_address" id="h_ship_address" value=""><?php endif; ?>
                <input type="hidden" name="payment_method" id="payment_method" value="">
                <?php if ($promoVisible): ?>
                <div class="mb-4">
                    <label class="form-label fw-semibold">促销码</label>
                    <div class="input-group"><input type="text" name="promo_code" class="form-control" placeholder="请输入促销码" value="<?php echo e($promoCode); ?>"><button type="submit" class="btn btn-outline-primary">应用</button></div>
                    <div class="form-text">是否展示促销码输入框由后台促销码策略控制，默认关闭，仅活动期间启用。</div>
                </div>
                <?php endif; ?>
                <div class="row g-3 mb-4">
                    <?php foreach ($availableMethods as $methodKey => $method): ?>
                    <div class="col-md-3"><div class="pay-method" data-method="<?php echo e($methodKey); ?>"><?php echo $method['icon']; ?><div class="fw-bold"><?php echo e($method['title']); ?></div><small class="text-muted"><?php echo e($method['desc']); ?></small></div></div>
                    <?php endforeach; ?>
                </div>
                <button type="button" class="btn btn-primary btn-lg w-100" id="submit-btn" style="opacity:.45;" onclick="doSubmit()"><i class="fas fa-lock me-2"></i>确认支付 $<?php echo number_format($total, 2); ?> USD</button>
            </form>
        </div>
    </div>
</div>
<script>
function selectPayMethod(el){document.querySelectorAll('.pay-method').forEach(function(c){c.classList.remove('active');c.style.borderColor='';c.style.background='';});el.classList.add('active');el.style.borderColor='#0d6efd';el.style.background='rgba(13,110,253,.06)';document.getElementById('payment_method').value=el.getAttribute('data-method');var btn=document.getElementById('submit-btn');btn.style.opacity='1';btn.style.cursor='pointer';}
function toggleAddr(val){var nf=document.getElementById('new-addr-form');var hs=document.getElementById('h_use_saved');if(val==='new'){nf.style.display='';if(hs) hs.value='0';} else {nf.style.display='none';if(hs) hs.value='1';}}
function doSubmit(){var method=document.getElementById('payment_method').value;if(!method){alert('请先选择支付方式');return;}<?php if ($need_shipping): ?>var useSavedEl=document.getElementById('useSaved');var useSaved=useSavedEl?useSavedEl.checked:false;if(useSaved){document.getElementById('h_use_saved').value='1';document.getElementById('h_ship_name').value='<?php echo addslashes($u['real_name'] ?? $u['email'] ?? ''); ?>';document.getElementById('h_ship_phone').value='<?php echo addslashes($u['phone'] ?? ''); ?>';document.getElementById('h_ship_province').value='<?php echo addslashes($u['province'] ?? ''); ?>';document.getElementById('h_ship_city').value='<?php echo addslashes($u['city'] ?? ''); ?>';document.getElementById('h_ship_zip').value='<?php echo addslashes($u['zip'] ?? ''); ?>';document.getElementById('h_ship_address').value='<?php echo addslashes($u['address'] ?? ''); ?>';} else {document.getElementById('h_use_saved').value='0';var n=document.getElementById('f_ship_name')?document.getElementById('f_ship_name').value.trim():'';var p=document.getElementById('f_ship_phone')?document.getElementById('f_ship_phone').value.trim():'';var a=document.getElementById('f_ship_address')?document.getElementById('f_ship_address').value.trim():'';if(!n||!a){alert('请填写收件人姓名和详细地址');return;}document.getElementById('h_ship_name').value=n;document.getElementById('h_ship_phone').value=p;document.getElementById('h_ship_province').value=document.getElementById('f_ship_province').value;document.getElementById('h_ship_city').value=document.getElementById('f_ship_city').value;document.getElementById('h_ship_zip').value=document.getElementById('f_ship_zip').value;document.getElementById('h_ship_address').value=a;}<?php endif; ?>document.getElementById('checkout-form').submit();}
(function bindPayCards(){var cards=document.querySelectorAll('.pay-method');if(cards.length===0){setTimeout(bindPayCards,50);return;}cards.forEach(function(card){card.onclick=function(){selectPayMethod(this);};});})();
</script>
<?php require_once __DIR__ . '/includes/footer.php'; ?>
