<?php
/**
 * 芋头CMS - 收货地址管理
 * ============================================================================
 * 版权所有 2016-2028 沅陵县乌托邦网络服务有限公司，并保留所有权利。
 * 网站地址: http://www.yutoucms.cn
 * ----------------------------------------------------------------------------
 * 如果商业用途务必到官方购买正版授权, 以免引起不必要的法律纠纷.
 * ============================================================================
 * Author: 芋头 <mxgsf@qq.com>
 * Date: 2026-5-30
 */

session_start();

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();
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;

function getUrl($type, $id = 0, $dir = '') {
    global $urlMode, $siteConfig;
    if ($urlMode === 'dynamic') {
        switch ($type) {
            case 'home': return '/public/index.php?m=index';
            default: return '/public/index.php';
        }
    }
    return '/';
}

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

$memberId = intval($_SESSION['member_id']);

// AJAX 地址操作
if (isset($_GET['ajax']) && $_GET['ajax'] === 'address') {
    header('Content-Type: application/json; charset=utf-8');
    
    if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
        echo json_encode(['code'=>405,'msg'=>'请求方法不允许']); exit;
    }
    
    $act = isset($_POST['action']) ? trim($_POST['action']) : '';
    
    // list 单独处理
    if ($act === 'list') {
        $addrs = $db->fetchAll("SELECT * FROM {$db->table('address')} WHERE member_id = ? ORDER BY is_default DESC, create_time DESC", [$memberId]);
        echo json_encode(['code'=>200,'data'=>$addrs]); exit;
    }
    
    // 必须有 member_id
    if ($memberId <= 0) {
        echo json_encode(['code'=>401,'msg'=>'未登录']); exit;
    }
    
    if ($act === 'add') {
        $data = [
            'member_id' => $memberId,
            'name' => isset($_POST['consignee']) ? trim($_POST['consignee']) : '',
            'mobile' => isset($_POST['mobile']) ? trim($_POST['mobile']) : '',
            'province' => isset($_POST['province']) ? trim($_POST['province']) : '',
            'city' => isset($_POST['city']) ? trim($_POST['city']) : '',
            'district' => isset($_POST['district']) ? trim($_POST['district']) : '',
            'address' => isset($_POST['address']) ? trim($_POST['address']) : '',
            'is_default' => isset($_POST['is_default']) ? 1 : 0,
            'create_time' => time(),
        ];
        if (empty($data['name']) || empty($data['mobile']) || empty($data['address'])) {
            echo json_encode(['code'=>400,'msg'=>'收货人、手机号、详细地址不能为空']); exit;
        }
        // 清除其它默认
        if ($data['is_default'] == 1) {
            $db->query("UPDATE {$db->table('address')} SET is_default = 0 WHERE member_id = ?", [$memberId]);
        }
        try {
            $db->insert('address', $data);
            echo json_encode(['code'=>200,'msg'=>'添加成功']);
        } catch (Exception $e) {
            echo json_encode(['code'=>500,'msg'=>'添加失败：'.$e->getMessage()]);
        }
        exit;
    }
    
    if ($act === 'edit') {
        $id = isset($_POST['id']) ? intval($_POST['id']) : 0;
        if ($id <= 0) { echo json_encode(['code'=>400,'msg'=>'无效ID']); exit; }
        $data = [
            'name' => isset($_POST['consignee']) ? trim($_POST['consignee']) : '',
            'mobile' => isset($_POST['mobile']) ? trim($_POST['mobile']) : '',
            'province' => isset($_POST['province']) ? trim($_POST['province']) : '',
            'city' => isset($_POST['city']) ? trim($_POST['city']) : '',
            'district' => isset($_POST['district']) ? trim($_POST['district']) : '',
            'address' => isset($_POST['address']) ? trim($_POST['address']) : '',
            'is_default' => isset($_POST['is_default']) ? 1 : 0,
        ];
        if (empty($data['name']) || empty($data['mobile']) || empty($data['address'])) {
            echo json_encode(['code'=>400,'msg'=>'收货人、手机号、详细地址不能为空']); exit;
        }
        if ($data['is_default'] == 1) {
            $db->query("UPDATE {$db->table('address')} SET is_default = 0 WHERE member_id = ?", [$memberId]);
        }
        try {
            $db->update('address', $data, 'id = ? AND member_id = ?', [$id, $memberId]);
            echo json_encode(['code'=>200,'msg'=>'修改成功']);
        } catch (Exception $e) {
            echo json_encode(['code'=>500,'msg'=>'修改失败：'.$e->getMessage()]);
        }
        exit;
    }
    
    if ($act === 'delete') {
        $id = isset($_POST['id']) ? intval($_POST['id']) : 0;
        if ($id <= 0) { echo json_encode(['code'=>400,'msg'=>'无效ID']); exit; }
        try {
            $db->query("DELETE FROM {$db->table('address')} WHERE id = ? AND member_id = ?", [$id, $memberId]);
            echo json_encode(['code'=>200,'msg'=>'删除成功']);
        } catch (Exception $e) {
            echo json_encode(['code'=>500,'msg'=>'删除失败：'.$e->getMessage()]);
        }
        exit;
    }
    
    if ($act === 'setDefault') {
        $id = isset($_POST['id']) ? intval($_POST['id']) : 0;
        if ($id <= 0) { echo json_encode(['code'=>400,'msg'=>'无效ID']); exit; }
        try {
            $db->query("UPDATE {$db->table('address')} SET is_default = 0 WHERE member_id = ?", [$memberId]);
            $db->query("UPDATE {$db->table('address')} SET is_default = 1 WHERE id = ? AND member_id = ?", [$id, $memberId]);
            echo json_encode(['code'=>200,'msg'=>'设置成功']);
        } catch (Exception $e) {
            echo json_encode(['code'=>500,'msg'=>'设置失败：'.$e->getMessage()]);
        }
        exit;
    }
    
    echo json_encode(['code'=>404,'msg'=>'未知操作']); exit;
}

// 收货地址列表
$addressList = $db->fetchAll("SELECT * FROM {$db->table('address')} WHERE member_id = ? ORDER BY is_default DESC, create_time DESC", [$memberId]);
?>
<!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 htmlspecialchars(isset($siteConfig['site_name']) ? $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>
</head>
<body>
<div class="wrapper">
    <header class="header">
        <div class="container">
            <div class="logo"><a href="<?php echo getUrl('home'); ?>"><?php echo htmlspecialchars(isset($siteConfig['site_name']) ? $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> &gt; <a href="/member/index.php">会员中心</a> &gt; <span>收货地址</span></div>
            
            <div style="display:flex;justify-content:space-between;align-items:center;margin-bottom:20px;">
                <h1 class="page-title" style="margin:0;">收货地址</h1>
                <button onclick="showAddrModal()" class="btn btn-primary">+ 添加新地址</button>
            </div>

            <?php if (empty($addressList)): ?>
            <div class="content-card" style="padding:60px 0;text-align:center;color:#999;">
                <p style="margin-bottom:20px;">暂无收货地址</p>
                <button onclick="showAddrModal()" class="btn btn-primary">添加第一个地址</button>
            </div>
            <?php else: ?>
            <div class="address-list-grid">
                <?php foreach ($addressList as $addr): ?>
                <div class="address-card<?php echo $addr['is_default'] == 1 ? ' default' : ''; ?>" data-id="<?php echo $addr['id']; ?>">
                    <?php if ($addr['is_default'] == 1): ?><span class="default-tag">默认</span><?php endif; ?>
                    <div class="addr-consignee"><?php echo htmlspecialchars($addr['name']); ?></div>
                    <div class="addr-mobile"><?php echo htmlspecialchars($addr['mobile']); ?></div>
                    <div class="addr-detail"><?php echo htmlspecialchars($addr['province'] . ' ' . $addr['city'] . ' ' . $addr['district'] . ' ' . $addr['address']); ?></div>
                    <div class="addr-actions">
                        <a href="javascript:editAddr(<?php echo $addr['id']; ?>);" class="btn-edit">编辑</a>
                        <?php if ($addr['is_default'] != 1): ?>
                        <a href="javascript:setDefault(<?php echo $addr['id']; ?>);" class="btn-setdefault">设为默认</a>
                        <?php endif; ?>
                        <a href="javascript:delAddr(<?php echo $addr['id']; ?>);" class="btn-del">删除</a>
                    </div>
                </div>
                <?php endforeach; ?>
            </div>
            <?php endif; ?>
        </div>
    </main>
    <footer class="footer">
        <div class="container"><div class="copyright">&copy; <?php echo date('Y'); ?> <?php echo htmlspecialchars(isset($siteConfig['site_name']) ? $siteConfig['site_name'] : ''); ?></div></div>
    </footer>
</div>

<!-- 添加/编辑地址弹窗 -->
<div id="addrModal" class="modal" style="display:none;">
    <div class="modal-content" style="max-width:520px;">
        <div class="modal-header"><h3 id="addrModalTitle">添加收货地址</h3><button onclick="closeAddrModal()" class="modal-close">×</button></div>
        <form id="addrForm" style="padding:20px;">
            <input type="hidden" name="action" value="add">
            <input type="hidden" name="id" id="addrId" value="">
            <div class="form-group" 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" class="form-control" style="width:100%;padding:10px 14px;border:1px solid #d1d5db;border-radius:8px;box-sizing:border-box;" placeholder="请输入收货人姓名" required>
            </div>
            <div class="form-group" 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" class="form-control" style="width:100%;padding:10px 14px;border:1px solid #d1d5db;border-radius:8px;box-sizing:border-box;" placeholder="请输入手机号码" required>
            </div>
            <div class="form-group" 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" class="form-control" style="width:100%;padding:10px 14px;border:1px solid #d1d5db;border-radius:8px;box-sizing:border-box;" placeholder="如：广东省" required>
            </div>
            <div class="form-row" style="display:flex;gap:12px;margin-bottom:15px;">
                <div class="form-group" 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" class="form-control" style="width:100%;padding:10px 14px;border:1px solid #d1d5db;border-radius:8px;box-sizing:border-box;" placeholder="如：深圳市" required>
                </div>
                <div class="form-group" 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" class="form-control" style="width:100%;padding:10px 14px;border:1px solid #d1d5db;border-radius:8px;box-sizing:border-box;" placeholder="如：南山区" required>
                </div>
            </div>
            <div class="form-group" 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" class="form-control" style="width:100%;padding:10px 14px;border:1px solid #d1d5db;border-radius:8px;box-sizing:border-box;" placeholder="街道、门牌号等" required>
            </div>
            <div class="form-group" style="margin-bottom:15px;">
                <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;">保存</button>
                <button type="button" onclick="closeAddrModal()" class="btn btn-secondary" style="flex:1;padding:12px;border-radius:8px;font-size:14px;cursor:pointer;background:#f1f5f9;color:#475569;border:1px solid #e2e8f0;">取消</button>
            </div>
        </form>
    </div>
</div>

<style>
.address-list-grid{display:grid;grid-template-columns:repeat(auto-fill,minmax(280px,1fr));gap:16px;}
.address-card{position:relative;border:1px solid #e5e7eb;border-radius:12px;padding:20px;background:#fff;transition:all .2s;}
.address-card:hover{border-color:#5a8f3e;box-shadow:0 4px 12px rgba(90,143,62,.1);}
.address-card.default{border-color:#5a8f3e;background:#f0f7ec;}
.default-tag{position:absolute;top:12px;right:12px;background:#5a8f3e;color:#fff;font-size:11px;padding:2px 8px;border-radius:10px;}
.addr-consignee{font-weight:600;font-size:16px;color:#1e293b;margin-bottom:8px;}
.addr-mobile{font-size:13px;color:#64748b;margin-bottom:8px;}
.addr-detail{font-size:13px;color:#374151;line-height:1.5;margin-bottom:16px;}
.addr-actions{display:flex;gap:12px;align-items:center;}
.btn-edit{font-size:13px;color:#5a8f3e;text-decoration:none;}
.btn-edit:hover{text-decoration:underline;}
.btn-setdefault{font-size:13px;color:#f5a623;text-decoration:none;}
.btn-setdefault:hover{text-decoration:underline;}
.btn-del{font-size:13px;color:#EF4444;text-decoration:none;}
.btn-del:hover{text-decoration:underline;}
.modal{position:fixed;top:0;left:0;right:0;bottom:0;background:rgba(0,0,0,.5);z-index:1000;display:flex;align-items:center;justify-content:center;}
.modal-content{background:#fff;border-radius:12px;width:100%;max-width:520px;overflow:hidden;}
.modal-header{display:flex;justify-content:space-between;align-items:center;padding:16px 20px;border-bottom:1px solid #e5e7eb;}
.modal-header h3{margin:0;font-size:16px;font-weight:600;color:#1e293b;}
.modal-close{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;}
.modal-close:hover{background:#e2e8f0;}
</style>

<script>
var addrModal = document.getElementById('addrModal');
var addrForm = document.getElementById('addrForm');

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

function editAddr(id) {
    var xhr = new XMLHttpRequest();
    xhr.open('POST', '?ajax=address', true);
    xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
    xhr.onload = function() {
        try {
            var res = JSON.parse(xhr.responseText);
            var addrs = res.data || [];
            var addr = null;
            for (var i = 0; i < addrs.length; i++) {
                if (addrs[i].id == id) { addr = addrs[i]; break; }
            }
            if (!addr) { alert('地址不存在'); return; }
            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;
            addrModal.style.display = 'flex';
        } catch(e) { alert('加载失败'); }
    };
    xhr.onerror = function() { alert('网络错误'); };
    xhr.send('action=list');
}

function closeAddrModal() {
    addrModal.style.display = 'none';
}

function setDefault(id) {
    if (!confirm('确定设为默认地址？')) return;
    var xhr = new XMLHttpRequest();
    xhr.open('POST', '?ajax=address', true);
    xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
    xhr.onload = function() {
        try { var d = JSON.parse(xhr.responseText); alert(d.msg); if(d.code==200) location.reload(); } catch(e) { alert('操作失败'); }
    };
    xhr.send('action=setDefault&id=' + id);
}

function delAddr(id) {
    if (!confirm('确定删除此地址？')) return;
    var xhr = new XMLHttpRequest();
    xhr.open('POST', '?ajax=address', true);
    xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
    xhr.onload = function() {
        try { var d = JSON.parse(xhr.responseText); alert(d.msg); if(d.code==200) location.reload(); } catch(e) { alert('删除失败'); }
    };
    xhr.send('action=delete&id=' + id);
}

addrForm.onsubmit = function(e) {
    e.preventDefault();
    var id = document.getElementById('addrId').value;
    var action = id ? 'edit' : 'add';
    var fd = new FormData();
    fd.append('action', action);
    if (id) fd.append('id', id);
    fd.append('consignee', 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', '?ajax=address', true);
    xhr.onload = function() {
        try { var d = JSON.parse(xhr.responseText); alert(d.msg); if(d.code==200) location.reload(); } catch(e) { alert('保存失败: ' + xhr.responseText); }
    };
    xhr.onerror = function() { alert('网络错误'); };
    xhr.send(fd);
};

addrModal.addEventListener('click', function(e) {
    if (e.target === addrModal) closeAddrModal();
});
</script>
</body>
</html>
