<?php
/**
 * 芋头CMS - 会员收货地址页面
 */
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;
}

// 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']) : '';
    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;
    }
    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]);
?>
<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"/><circle cx="12" cy="10" r="3"/></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($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 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');

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 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;
            modal.style.display = 'flex';
        } catch(e) { alert('加载失败'); }
    };
    xhr.onerror = function() { alert('网络错误'); };
    xhr.send('action=list');
}

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

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);
    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);
};
</script>