<?php
/**
 * 收货地址API接口
 */
require_once dirname(__DIR__) . '/core/lib/session.php';
cmsStartSession();
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';
require_once __DIR__ . '/../core/lib/common.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;
}

if (in_array($action, ['add', 'edit', 'delete', 'set_default'], true)) {
    if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
        http_response_code(405);
        echo json_encode(['code' => 405, 'msg' => '璇锋敹鍒板悎鍙厑璁?POST']);
        exit;
    }
    requireMemberCsrfToken(true);
}

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':
        $data = [
            'member_id' => $memberId,
            'name' => trim($_POST['name'] ?? ''),
            'mobile' => trim($_POST['mobile'] ?? ''),
            'province' => trim($_POST['province'] ?? ''),
            'city' => trim($_POST['city'] ?? ''),
            'district' => trim($_POST['district'] ?? ''),
            'address' => trim($_POST['address'] ?? ''),
            'is_default' => intval($_POST['is_default'] ?? 0),
            'create_time' => time(),
        ];
        if ($data['name'] === '' || $data['mobile'] === '' || $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]); }
        $id = $db->insert('address', $data);
        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; }
        $exists = $db->fetch("SELECT id FROM {$db->table('address')} WHERE id = ? AND member_id = ?", [$id, $memberId]);
        if (!$exists) { echo json_encode(['code' => 400, 'msg' => '地址不存在']); exit; }
        $data = [
            'name' => trim($_POST['name'] ?? ''),
            'mobile' => trim($_POST['mobile'] ?? ''),
            'province' => trim($_POST['province'] ?? ''),
            'city' => trim($_POST['city'] ?? ''),
            'district' => trim($_POST['district'] ?? ''),
            'address' => trim($_POST['address'] ?? ''),
            'is_default' => intval($_POST['is_default'] ?? 0),
        ];
        if ($data['name'] === '' || $data['mobile'] === '' || $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]); }
        $db->update('address', $data, 'id = ? AND member_id = ?', [$id, $memberId]);
        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]);
        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; }
        $exists = $db->fetch("SELECT id FROM {$db->table('address')} WHERE id = ? AND member_id = ?", [$id, $memberId]);
        if (!$exists) { echo json_encode(['code' => 400, 'msg' => '地址不存在']); exit; }
        $db->query("UPDATE {$db->table('address')} SET is_default = 0 WHERE member_id = ?", [$memberId]);
        $db->update('address', ['is_default' => 1], 'id = ? AND member_id = ?', [$id, $memberId]);
        echo json_encode(['code' => 200, 'msg' => '设置成功']);
        break;
    default:
        echo json_encode(['code' => 400, 'msg' => '未知操作', 'data' => []]);
        break;
}
