<?php
/**
 * 芋头CMS
 * ============================================================================
 * 版权所有 2016-2028 沅陵县乌托邦网络服务有限公司，并保留所有权利。
 * 网站地址: http://www.yutoucms.cn
 * ----------------------------------------------------------------------------
 * 如果商业用途务必到官方购买正版授权, 以免引起不必要的法律纠纷.
 * ============================================================================
 * Author: 芋头 <mxgsf@qq.com>
 * Date: 2026-5-20
 */
if (!defined('ROOT_PATH')) {
    define('ROOT_PATH', dirname(dirname(__DIR__)) . '/');
}
define('CORE_PATH', ROOT_PATH . 'core/');
require_once CORE_PATH . 'db/db.php';

$db = \Core\Db\DB::getInstance();
$memberId = isset($_SESSION['member_id']) ? intval($_SESSION['member_id']) : 0;

if ($memberId <= 0) {
    header('Location: /member/login.php');
    exit;
}

$addressList = $db->fetchAll(
    "SELECT * FROM {$db->table('address')} WHERE member_id = ? ORDER BY is_default DESC, create_time DESC",
    [$memberId]
);
?>
<div class="page-header" style="padding:20px 20px 0;">
    <h1 class="page-title">
        <svg style="width:20px;height:20px;" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
            <path d="M21 10c0 7-9 13-9 13s-9-6-9-13a9 9 0 0 1 18 0z"></path>
            <circle cx="12" cy="10" r="3"></circle>
        </svg>
        收货地址
    </h1>
</div>

<div style="padding:20px;">
    <div style="display:flex;justify-content:flex-end;margin-bottom:20px;">
        <button class="btn btn-primary" onclick="showAddModal()">+ 添加新地址</button>
    </div>

    <?php if (empty($addressList)): ?>
    <div style="text-align:center;padding:60px 0;color:#999;">
        <p>暂无收货地址</p>
        <button class="btn btn-primary" onclick="showAddModal()">添加第一个地址</button>
    </div>
    <?php else: ?>
    <div style="display:grid;grid-template-columns:repeat(auto-fill,minmax(280px,1fr));gap:16px;">
        <?php foreach ($addressList as $addr): ?>
        <div class="addr-card<?php echo $addr['is_default'] == 1 ? ' default' : ''; ?>" data-id="<?php echo $addr['id']; ?>" style="position:relative;border:1px solid #e5e7eb;border-radius:12px;padding:20px;background:#fff;transition:all .2s;<?php echo $addr['is_default'] == 1 ? 'border-color:#5a8f3e;background:#f0f7ec;' : ''; ?>">
            <?php if ($addr['is_default'] == 1): ?>
            <span style="position:absolute;top:12px;right:12px;background:#5a8f3e;color:#fff;font-size:11px;padding:2px 8px;border-radius:10px;">默认</span>
            <?php endif; ?>
            <div style="font-weight:600;font-size:16px;color:#1e293b;margin-bottom:6px;"><?php echo htmlspecialchars($addr['name']); ?></div>
            <div style="font-size:13px;color:#64748b;margin-bottom:6px;"><?php echo htmlspecialchars($addr['mobile']); ?></div>
            <div style="font-size:13px;color:#374151;line-height:1.5;margin-bottom:16px;"><?php echo htmlspecialchars(trim($addr['province'] . ' ' . $addr['city'] . ' ' . $addr['district'] . ' ' . $addr['address'])); ?></div>
            <div style="display:flex;gap:12px;align-items:center;">
                <button onclick="editAddr(<?php echo $addr['id']; ?>)" style="font-size:13px;color:#5a8f3e;background:none;border:none;cursor:pointer;padding:0;">编辑</button>
                <?php if ($addr['is_default'] != 1): ?>
                <button onclick="setDefault(<?php echo $addr['id']; ?>)" style="font-size:13px;color:#f5a623;background:none;border:none;cursor:pointer;padding:0;">设为默认</button>
                <?php endif; ?>
                <button onclick="delAddr(<?php echo $addr['id']; ?>)" style="font-size:13px;color:#EF4444;background:none;border:none;cursor:pointer;padding:0;">删除</button>
            </div>
        </div>
        <?php endforeach; ?>
    </div>
    <?php endif; ?>
</div>

<div id="addrModal" style="display:none;position:fixed;top:0;left:0;right:0;bottom:0;background:rgba(0,0,0,.5);z-index:1000;align-items:center;justify-content:center;" onclick="closeModal(event)">
    <div style="background:#fff;border-radius:12px;width:100%;max-width:520px;overflow:hidden;" onclick="event.stopPropagation()">
        <div style="display:flex;justify-content:space-between;align-items:center;padding:16px 20px;border-bottom:1px solid #e5e7eb;">
            <h3 id="addrModalTitle" style="margin:0;font-size:16px;font-weight:600;color:#1e293b;">添加收货地址</h3>
            <button type="button" onclick="closeModal()" style="width:32px;height:32px;border-radius:50%;border:none;background:#f1f5f9;color:#64748b;cursor:pointer;font-size:18px;display:flex;align-items:center;justify-content:center;">×</button>
        </div>
        <form id="addrForm" style="padding:20px;">
            <input type="hidden" name="id" id="addrId" value="">
            <div style="margin-bottom:15px;">
                <label style="display:block;font-size:13px;color:#374151;margin-bottom:6px;font-weight:500;">收货人 <span style="color:#ef4444;">*</span></label>
                <input type="text" name="consignee" id="addrConsignee" style="border:1px solid #d1d5db;border-radius:8px;padding:10px 14px;font-size:14px;width:100%;box-sizing:border-box;" required placeholder="请输入收货人姓名">
            </div>
            <div style="margin-bottom:15px;">
                <label style="display:block;font-size:13px;color:#374151;margin-bottom:6px;font-weight:500;">手机号 <span style="color:#ef4444;">*</span></label>
                <input type="tel" name="mobile" id="addrMobile" style="border:1px solid #d1d5db;border-radius:8px;padding:10px 14px;font-size:14px;width:100%;box-sizing:border-box;" required placeholder="请输入手机号">
            </div>
            <div style="margin-bottom:15px;">
                <label style="display:block;font-size:13px;color:#374151;margin-bottom:6px;font-weight:500;">省份 <span style="color:#ef4444;">*</span></label>
                <input type="text" name="province" id="addrProvince" style="border:1px solid #d1d5db;border-radius:8px;padding:10px 14px;font-size:14px;width:100%;box-sizing:border-box;" required placeholder="如：广东省">
            </div>
            <div style="display:flex;gap:12px;margin-bottom:15px;">
                <div style="flex:1;">
                    <label style="display:block;font-size:13px;color:#374151;margin-bottom:6px;font-weight:500;">城市 <span style="color:#ef4444;">*</span></label>
                    <input type="text" name="city" id="addrCity" style="border:1px solid #d1d5db;border-radius:8px;padding:10px 14px;font-size:14px;width:100%;box-sizing:border-box;" required placeholder="如：深圳市">
                </div>
                <div style="flex:1;">
                    <label style="display:block;font-size:13px;color:#374151;margin-bottom:6px;font-weight:500;">区县 <span style="color:#ef4444;">*</span></label>
                    <input type="text" name="district" id="addrDistrict" style="border:1px solid #d1d5db;border-radius:8px;padding:10px 14px;font-size:14px;width:100%;box-sizing:border-box;" required placeholder="如：南山区">
                </div>
            </div>
            <div style="margin-bottom:15px;">
                <label style="display:block;font-size:13px;color:#374151;margin-bottom:6px;font-weight:500;">详细地址 <span style="color:#ef4444;">*</span></label>
                <input type="text" name="address" id="addrAddress" style="border:1px solid #d1d5db;border-radius:8px;padding:10px 14px;font-size:14px;width:100%;box-sizing:border-box;" required placeholder="街道、门牌号等">
            </div>
            <div style="margin-bottom:20px;">
                <label style="display:flex;align-items:center;gap:8px;cursor:pointer;">
                    <input type="checkbox" name="is_default" id="addrDefault" value="1">
                    <span style="font-size:13px;color:#374151;">设为默认收货地址</span>
                </label>
            </div>
            <div style="display:flex;gap:12px;">
                <button type="submit" class="btn btn-primary" style="flex:1;padding:12px;border-radius:8px;font-size:14px;cursor:pointer;border:none;background:#5a8f3e;color:#fff;">保存</button>
                <button type="button" onclick="closeModal()" style="flex:1;padding:12px;border-radius:8px;font-size:14px;cursor:pointer;border:1px solid #e2e8f0;background:#f1f5f9;color:#475569;">取消</button>
            </div>
        </form>
    </div>
</div>

<script>
var modal = document.getElementById('addrModal');
var form = document.getElementById('addrForm');
var addressApiUrl = '/api/address.php';
var memberCsrfToken = <?php echo json_encode(getMemberCsrfToken(), JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES); ?>;

function showAddModal() {
    document.getElementById('addrModalTitle').textContent = '添加收货地址';
    document.getElementById('addrId').value = '';
    form.reset();
    modal.style.display = 'flex';
}

function closeModal(event) {
    if (!event || event.target === modal) {
        modal.style.display = 'none';
    }
}

function parseAddressResponse(xhr, fallbackMessage) {
    try {
        return JSON.parse(xhr.responseText);
    } catch (e) {
        alert(fallbackMessage + '，接口返回异常：' + xhr.responseText);
        return null;
    }
}

function editAddr(id) {
    var xhr = new XMLHttpRequest();
    xhr.open('GET', addressApiUrl + '?action=detail&id=' + encodeURIComponent(id), true);
    xhr.onload = function() {
        var res = parseAddressResponse(xhr, '加载失败');
        if (!res) return;
        if (res.code != 200 || !res.data) {
            alert(res.msg || '加载失败');
            return;
        }
        var addr = res.data;
        document.getElementById('addrModalTitle').textContent = '编辑收货地址';
        document.getElementById('addrId').value = id;
        document.getElementById('addrConsignee').value = addr.name || '';
        document.getElementById('addrMobile').value = addr.mobile || '';
        document.getElementById('addrProvince').value = addr.province || '';
        document.getElementById('addrCity').value = addr.city || '';
        document.getElementById('addrDistrict').value = addr.district || '';
        document.getElementById('addrAddress').value = addr.address || '';
        document.getElementById('addrDefault').checked = addr.is_default == 1;
        modal.style.display = 'flex';
    };
    xhr.onerror = function() {
        alert('网络错误');
    };
    xhr.send();
}

function setDefault(id) {
    if (!confirm('确定设为默认地址吗？')) return;
    var xhr = new XMLHttpRequest();
    xhr.open('POST', addressApiUrl, true);
    xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
    xhr.setRequestHeader('X-CSRF-Token', memberCsrfToken);
    xhr.onload = function() {
        var res = parseAddressResponse(xhr, '操作失败');
        if (!res) return;
        alert(res.msg || '操作失败');
        if (res.code == 200) {
            location.reload();
        }
    };
    xhr.onerror = function() {
        alert('网络错误');
    };
    xhr.send('action=set_default&id=' + encodeURIComponent(id) + '&csrf_token=' + encodeURIComponent(memberCsrfToken));
}

function delAddr(id) {
    if (!confirm('确定删除这个地址吗？')) return;
    var xhr = new XMLHttpRequest();
    xhr.open('POST', addressApiUrl, true);
    xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
    xhr.setRequestHeader('X-CSRF-Token', memberCsrfToken);
    xhr.onload = function() {
        var res = parseAddressResponse(xhr, '删除失败');
        if (!res) return;
        alert(res.msg || '删除失败');
        if (res.code == 200) {
            location.reload();
        }
    };
    xhr.onerror = function() {
        alert('网络错误');
    };
    xhr.send('action=delete&id=' + encodeURIComponent(id) + '&csrf_token=' + encodeURIComponent(memberCsrfToken));
}

form.onsubmit = function(e) {
    e.preventDefault();
    var id = document.getElementById('addrId').value;
    var action = id ? 'edit' : 'add';
    var fd = new FormData();

    fd.append('action', action);
    fd.append('csrf_token', memberCsrfToken);
    if (id) {
        fd.append('id', id);
    }
    fd.append('name', document.getElementById('addrConsignee').value);
    fd.append('mobile', document.getElementById('addrMobile').value);
    fd.append('province', document.getElementById('addrProvince').value);
    fd.append('city', document.getElementById('addrCity').value);
    fd.append('district', document.getElementById('addrDistrict').value);
    fd.append('address', document.getElementById('addrAddress').value);
    if (document.getElementById('addrDefault').checked) {
        fd.append('is_default', '1');
    }

    var xhr = new XMLHttpRequest();
    xhr.open('POST', addressApiUrl, true);
    xhr.onload = function() {
        var res = parseAddressResponse(xhr, '保存失败');
        if (!res) return;
        alert(res.msg || '保存失败');
        if (res.code == 200) {
            location.reload();
        }
    };
    xhr.onerror = function() {
        alert('网络错误');
    };
    xhr.send(fd);
};
</script>
