<?php
/**
 * 收货地址API接口
 */
session_start();
header('Content-Type: application/json; charset=utf-8');
header('Access-Control-Allow-Origin: *');
header('Access-Control-Allow-Methods: POST, GET, OPTIONS');

require_once __DIR__ . '/../core/db/db.php';
$db = Core\Db\DB::getInstance();

$action = $_POST['action'] ?? $_GET['action'] ?? '';
$memberId = $_SESSION['member_id'] ?? 0;

// 未登录拦截
if ($memberId <= 0) {
    echo json_encode([
        'code' => 401,
        'msg' => '请先登录',
        'data' => []
    ]);
    exit;
}

switch ($action) {
    // 地址列表
    case 'list':
        $list = $db->fetchAll("SELECT * FROM {$db->table('address')} WHERE member_id = ? ORDER BY is_default DESC, create_time DESC", [$memberId]);
        echo json_encode([
            'code' => 200,
            'msg' => '获取成功',
            'data' => $list
        ]);
        break;

    // 地址详情
    case 'detail':
        $id = intval($_GET['id'] ?? 0);
        if ($id <= 0) {
            echo json_encode(['code' => 400, 'msg' => '参数错误']);
            exit;
        }

        $address = $db->fetch("SELECT * FROM {$db->table('address')} WHERE id = ? AND member_id = ?", [$id, $memberId]);
        if (!$address) {
            echo json_encode(['code' => 400, 'msg' => '地址不存在']);
            exit;
        }

        echo json_encode([
            'code' => 200,
            'msg' => '获取成功',
            'data' => $address
        ]);
        break;

    // 新增地址
    case 'add':
        $name = trim($_POST['name'] ?? '');
        $mobile = trim($_POST['mobile'] ?? '');
        $province = trim($_POST['province'] ?? '');
        $city = trim($_POST['city'] ?? '');
        $district = trim($_POST['district'] ?? '');
        $address = trim($_POST['address'] ?? '');
        $isDefault = intval($_POST['is_default'] ?? 0);

        if (empty($name) || empty($mobile) || empty($province) || empty($city) || empty($district) || empty($address)) {
            echo json_encode(['code' => 400, 'msg' => '请填写完整信息']);
            exit;
        }

        if (!preg_match('/^1[3-9]\d{9}$/', $mobile)) {
            echo json_encode(['code' => 400, 'msg' => '请输入正确的手机号']);
            exit;
        }

        // 如果是默认地址，先取消其他默认
        if ($isDefault == 1) {
            $db->update('address', ['is_default' => 0], 'member_id = ?', [$memberId]);
        } else {
            // 如果是第一个地址，自动设为默认
            $count = $db->fetch("SELECT COUNT(*) as cnt FROM {$db->table('address')} WHERE member_id = ?", [$memberId])['cnt'] ?? 0;
            if ($count == 0) {
                $isDefault = 1;
            }
        }

        $data = [
            'member_id' => $memberId,
            'name' => $name,
            'mobile' => $mobile,
            'province' => $province,
            'city' => $city,
            'district' => $district,
            'address' => $address,
            'is_default' => $isDefault,
            'create_time' => time()
        ];

        $db->insert('address', $data);
        $id = $db->lastInsertId();

        echo json_encode([
            'code' => 200,
            'msg' => '添加成功',
            'data' => [
                'id' => $id
            ]
        ]);
        break;

    // 编辑地址
    case 'edit':
        $id = intval($_POST['id'] ?? 0);
        if ($id <= 0) {
            echo json_encode(['code' => 400, 'msg' => '参数错误']);
            exit;
        }

        // 检查地址是否存在
        $exist = $db->fetch("SELECT id FROM {$db->table('address')} WHERE id = ? AND member_id = ?", [$id, $memberId]);
        if (!$exist) {
            echo json_encode(['code' => 400, 'msg' => '地址不存在']);
            exit;
        }

        $name = trim($_POST['name'] ?? '');
        $mobile = trim($_POST['mobile'] ?? '');
        $province = trim($_POST['province'] ?? '');
        $city = trim($_POST['city'] ?? '');
        $district = trim($_POST['district'] ?? '');
        $address = trim($_POST['address'] ?? '');
        $isDefault = intval($_POST['is_default'] ?? 0);

        if (empty($name) || empty($mobile) || empty($province) || empty($city) || empty($district) || empty($address)) {
            echo json_encode(['code' => 400, 'msg' => '请填写完整信息']);
            exit;
        }

        if (!preg_match('/^1[3-9]\d{9}$/', $mobile)) {
            echo json_encode(['code' => 400, 'msg' => '请输入正确的手机号']);
            exit;
        }

        // 如果是默认地址，先取消其他默认
        if ($isDefault == 1) {
            $db->update('address', ['is_default' => 0], 'member_id = ?', [$memberId]);
        }

        $data = [
            'name' => $name,
            'mobile' => $mobile,
            'province' => $province,
            'city' => $city,
            'district' => $district,
            'address' => $address,
            'is_default' => $isDefault,
            'update_time' => time()
        ];

        $db->update('address', $data, 'id = ?', [$id]);

        echo json_encode([
            'code' => 200,
            'msg' => '修改成功'
        ]);
        break;

    // 删除地址
    case 'delete':
        $id = intval($_POST['id'] ?? 0);
        if ($id <= 0) {
            echo json_encode(['code' => 400, 'msg' => '参数错误']);
            exit;
        }

        $db->query("DELETE FROM {$db->table('address')} WHERE id = ? AND member_id = ?", [$id, $memberId]);

        // 如果删除的是默认地址，把最新的设为默认
        $exist = $db->fetch("SELECT id FROM {$db->table('address')} WHERE member_id = ? AND is_default = 1", [$memberId]);
        if (!$exist) {
            $newDefault = $db->fetch("SELECT id FROM {$db->table('address')} WHERE member_id = ? ORDER BY create_time DESC LIMIT 1", [$memberId]);
            if ($newDefault) {
                $db->update('address', ['is_default' => 1], 'id = ?', [$newDefault['id']]);
            }
        }

        echo json_encode(['code' => 200, 'msg' => '删除成功']);
        break;

    // 设置默认地址
    case 'set_default':
        $id = intval($_POST['id'] ?? 0);
        if ($id <= 0) {
            echo json_encode(['code' => 400, 'msg' => '参数错误']);
            exit;
        }

        // 检查地址是否存在
        $exist = $db->fetch("SELECT id FROM {$db->table('address')} WHERE id = ? AND member_id = ?", [$id, $memberId]);
        if (!$exist) {
            echo json_encode(['code' => 400, 'msg' => '地址不存在']);
            exit;
        }

        // 先取消其他默认
        $db->update('address', ['is_default' => 0], 'member_id = ?', [$memberId]);
        // 设置新默认
        $db->update('address', ['is_default' => 1], 'id = ?', [$id]);

        echo json_encode([
            'code' => 200,
            'msg' => '设置成功'
        ]);
        break;

    default:
        echo json_encode(['code' => 400, 'msg' => '未知操作']);
        break;
}
