<?php
/**
 * 巴黎香平台发货系统 - index.php
 * 核心功能：会员查询、优惠券发放、系统日志（自动保留30天）
 * 安全特性：权限控制、Session安全、CSRF防护、密码加密校验
 * 日志规则：自动清理30天前日志
 */

// ==================== 全局配置区 ====================
$isLoggedIn = false;
$loginError = '';
$SESSION_STARTED = false;

// 用户权限配置（最小权限原则）
$userPermissions = [
    'admin' => ['canSeeLog' => true],  // 管理员可查看日志
    'fahuo' => ['canSeeLog' => false] // 发货员不可查看日志
];

// 银豹接口配置
$config = [
    "host" => "https://area41-win.pospal.cn:443",
    "appID" => "2DD9C4426ED00E4D3338CEB8AD24CCA3",
    "appKey" => "647593296341423454",
    "apiVersion" => "v1"
];

// 业务变量初始化
$activeTab = 'query';          // 默认激活查询标签
$phone = '';                   // 通用手机号
$customerUidCache = '';        // 会员UID缓存
$operateResult = null;         // 操作结果
$queryResult = null;           // 会员查询结果
$bindQueryResult = null;       // 会员绑定查询结果
$couponRuleName = '';          // 优惠券规则名称
$couponRulesResult = null;     // 优惠券规则查询结果
$memberCouponsResult = null;    // 会员优惠券查询结果
$rechargeResult = null;         // 会员充值记录查询结果

// 日志查询变量（仅管理员可见，默认30天）
$logResult = null;
$logStartDate = date('Y-m-d', strtotime('-30 days'));
$logEndDate = date('Y-m-d');
$logType = '';
$logPage = 1;

// ==================== 核心工具函数 ====================
/**
 * 初始化Session（安全配置）
 */
function initSession() {
    global $SESSION_STARTED;
    if (!$SESSION_STARTED && session_status() === PHP_SESSION_NONE) {
        // Session安全配置
        ini_set('session.cookie_httponly', 1);    // 禁止JS读取（防XSS）
        ini_set('session.cookie_samesite', 'Lax'); // 防CSRF
        ini_set('session.gc_maxlifetime', 3600);   // 有效期1小时
        ini_set('session.use_strict_mode', 1);     // 拒绝无效Session ID
        
        session_start();
        
        // 登录时重置Session ID（防固定攻击）
        if (isset($_POST['login_action']) && $_POST['login_action'] === 'login') {
            session_regenerate_id(true);
        }
        
        $SESSION_STARTED = true;
    }
}

/**
 * 生成CSRF令牌（防跨站请求伪造）
 */
function generateCsrfToken() {
    if (!isset($_SESSION['csrf_token'])) {
        $_SESSION['csrf_token'] = bin2hex(random_bytes(32));
    }
    return $_SESSION['csrf_token'];
}

/**
 * 校验CSRF令牌
 */
function verifyCsrfToken($token) {
    return isset($_SESSION['csrf_token']) && hash_equals($_SESSION['csrf_token'], $token);
}

/**
 * 权限校验函数
 */
function checkPermission($requiredPermission, $currentPermissions) {
    $allowedPermissions = ['canSeeLog'];
    if (!in_array($requiredPermission, $allowedPermissions)) {
        writeSystemLog('error', "非法权限校验：{$requiredPermission}", $_SESSION['username'] ?? '未知');
        return false;
    }
    return isset($currentPermissions[$requiredPermission]) && $currentPermissions[$requiredPermission] === true;
}

/**
 * 空值处理函数
 */
function getValue($var, $default = '') {
    return isset($var) && $var !== null ? $var : $default;
}

// ==================== 日志管理核心函数 ====================
/**
 * 自动清理指定天数前的旧日志
 * @param int $keepDays 保留天数（默认30天）
 */
function autoClearOldLogs($keepDays = 30) {
    $logDir = __DIR__ . '/system_logs/';
    if (!is_dir($logDir)) return;

    // 计算保留起始时间（30天前0点）
    $keepTimestamp = strtotime("-{$keepDays} days", strtotime(date('Y-m-d')));
    
    // 遍历日志文件并清理
    $files = glob($logDir . 'sys_log_*.log');
    foreach ($files as $file) {
        preg_match('/sys_log_(\d{8})\.log/', $file, $matches);
        if (isset($matches[1])) {
            $fileTimestamp = strtotime($matches[1]);
            if ($fileTimestamp < $keepTimestamp) {
                unlink($file);
            }
        }
    }
}

/**
 * 记录系统日志（自动清理30天前日志）
 * @param string $type 日志类型
 * @param string $content 日志内容
 * @param string $username 操作人
 */
function writeSystemLog($type, $content, $username = '') {
    // 自动清理30天前日志
    autoClearOldLogs(30);

    $logDir = __DIR__ . '/system_logs/';
    if (!is_dir($logDir)) {
        mkdir($logDir, 0755, true);
    }

    $logFile = $logDir . 'sys_log_' . date('Ymd') . '.log';
    $username = empty($username) ? ($_SESSION['username'] ?? '未知用户') : $username;
    $clientIp = $_SERVER['REMOTE_ADDR'] ?? '未知IP';
    
    if (isset($_SERVER['HTTP_X_FORWARDED_FOR']) && !empty($_SERVER['HTTP_X_FORWARDED_FOR'])) {
        $clientIp = $_SERVER['HTTP_X_FORWARDED_FOR'];
    }

    $logLine = date('Y-m-d H:i:s') . '|' . $username . '|' . $clientIp . '|' . $type . '|' . $content . PHP_EOL;
    file_put_contents($logFile, $logLine, FILE_APPEND | LOCK_EX);
}

/**
 * 读取系统日志（默认30天）
 * @param string $startDate 开始日期
 * @param string $endDate 结束日期
 * @param string $logType 日志类型
 * @param int $page 页码
 * @param int $pageSize 每页条数
 * @return array 日志数据
 */
function readSystemLogs($startDate = '', $endDate = '', $logType = '', $page = 1, $pageSize = 20) {
    $logDir = __DIR__ . '/system_logs/';
    $allLogs = [];

    // 默认30天范围
    if (empty($startDate)) $startDate = date('Y-m-d', strtotime('-30 days'));
    if (empty($endDate)) $endDate = date('Y-m-d');

    // 遍历日期范围日志
    $currentDate = $startDate;
    while (strtotime($currentDate) <= strtotime($endDate)) {
        $logFile = $logDir . 'sys_log_' . str_replace('-', '', $currentDate) . '.log';
        if (file_exists($logFile)) {
            $lines = explode(PHP_EOL, file_get_contents($logFile));
            foreach ($lines as $line) {
                $line = trim($line);
                if (empty($line)) continue;

                $logParts = explode('|', $line, 5);
                if (count($logParts) < 5) continue;

                // 类型筛选
                if (!empty($logType) && $logParts[3] != $logType) continue;

                $allLogs[] = [
                    'time' => $logParts[0],
                    'user' => $logParts[1],
                    'ip' => $logParts[2],
                    'type' => $logParts[3],
                    'content' => $logParts[4]
                ];
            }
        }
        $currentDate = date('Y-m-d', strtotime($currentDate . ' +1 day'));
    }

    // 倒序排序+分页
    usort($allLogs, function($a, $b) {
        return strtotime($b['time']) - strtotime($a['time']);
    });

    $total = count($allLogs);
    $totalPages = ceil($total / $pageSize);
    $page = max(1, min($page, $totalPages));
    $offset = ($page - 1) * $pageSize;
    $pageLogs = array_slice($allLogs, $offset, $pageSize);

    return [
        'logs' => $pageLogs,
        'total' => $total,
        'page' => $page,
        'pageSize' => $pageSize,
        'totalPages' => $totalPages
    ];
}

// ==================== 银豹接口核心函数 ====================
/**
 * 生成签名
 */
function generateSignature($appKey, $requestBody) {
    return strtoupper(md5($appKey . $requestBody));
}

/**
 * GZIP解压兼容函数
 */
function gzipDecodeCompat($data) {
    if (function_exists('gzdecode')) return gzdecode($data);
    
    $flags = ord(substr($data, 3, 1));
    $headerlen = 10;
    if ($flags & 4) {
        $unpack = unpack('v', substr($data, 10, 2));
        $extralen = $unpack[1];
        $headerlen += 2 + $extralen;
    }
    if ($flags & 8) $headerlen = strpos(substr($data, $headerlen), chr(0)) + $headerlen + 1;
    if ($flags & 16) $headerlen = strpos($data, chr(0), $headerlen) + 1;
    if ($flags & 2) $headerlen += 2;
    
    $uncompressed = gzinflate(substr($data, $headerlen));
    return $uncompressed === false ? $data : $uncompressed;
}

/**
 * 通用POST请求函数
 */
function sendPostRequest($url, $requestBody, $config) {
    $timestampMs = strval(round(microtime(true) * 1000));
    $dataSignature = generateSignature($config['appKey'], $requestBody);

    if (!defined('CURLINFO_CONTENT_ENCODING')) {
        define('CURLINFO_CONTENT_ENCODING', 104);
    }

    $ch = curl_init();
    curl_setopt_array($ch, [
        CURLOPT_URL => $url,
        CURLOPT_RETURNTRANSFER => true,
        CURLOPT_POST => true,
        CURLOPT_POSTFIELDS => $requestBody,
        CURLOPT_FOLLOWLOCATION => true,
        CURLOPT_TIMEOUT => 30,
        CURLOPT_SSL_VERIFYPEER => false,
        CURLOPT_SSL_VERIFYHOST => false,
        CURLOPT_HTTPHEADER => [
            'User-Agent: openApi',
            'Content-Type: application/json; charset=utf-8',
            'accept-encoding: gzip,deflate',
            "time-stamp: {$timestampMs}",
            "data-signature: {$dataSignature}"
        ]
    ]);

    $response = curl_exec($ch);
    $httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
    $contentEncoding = curl_getinfo($ch, CURLINFO_CONTENT_ENCODING);
    $curlError = curl_error($ch);
    curl_close($ch);

    if ($curlError) {
        $username = $_SESSION['username'] ?? '未知用户';
        writeSystemLog('error', "CURL错误：{$curlError} | URL：{$url}", $username);
        return ['status' => 'error', 'msg' => "请求错误: {$curlError}", 'raw' => ''];
    }

    // 解压GZIP响应
    $uncompressedResponse = $response;
    if (!empty($response)) {
        $isGzip = (strtolower($contentEncoding) === 'gzip') || (substr($response, 0, 2) === "\x1f\x8b");
        if ($isGzip) {
            $uncompressedResponse = gzipDecodeCompat($response);
        }
    }

    // 解析JSON
    $result = json_decode($uncompressedResponse, true);
    if (json_last_error() !== JSON_ERROR_NONE) {
        $username = $_SESSION['username'] ?? '未知用户';
        writeSystemLog('error', "JSON解析失败：" . json_last_error_msg() . " | 原始数据：" . substr($uncompressedResponse, 0, 200), $username);
        return ['status' => 'error', 'msg' => "解析失败: " . json_last_error_msg(), 'raw' => $uncompressedResponse];
    }

    return ['status' => 'success', 'data' => $result, 'httpCode' => $httpCode, 'raw' => $uncompressedResponse];
}

/**
 * 查询会员（带缓存）
 */
function queryMemberByPhone($phone, $config, &$customerUidCache) {
    $postData = ["appId" => $config["appID"], "customerTel" => $phone];
    $requestBody = json_encode($postData, JSON_UNESCAPED_UNICODE);
    $url = $config['host'] . "/pospal-api2/openapi/{$config['apiVersion']}/customerOpenapi/queryBytel";
    
    $result = sendPostRequest($url, $requestBody, $config);
    $username = $_SESSION['username'] ?? '未知用户';

    if ($result['status'] === 'success' && getValue($result['data']['status']) === 'success') {
        $members = getValue($result['data']['data'], []);
        if (!empty($members)) {
            $customerUidCache = getValue($members[0]['customerUid'], '');
            writeSystemLog('query', "查询会员成功：手机号={$phone} | UID={$customerUidCache}", $username);
            return [
                'success' => true,
                'data' => $members,
                'uid' => $customerUidCache,
                'msg' => "查询会员成功"
            ];
        } else {
            $customerUidCache = '';
            writeSystemLog('query', "查询会员无结果：手机号={$phone}", $username);
            return [
                'success' => false,
                'data' => [],
                'uid' => '',
                'msg' => "手机号 {$phone} 未绑定会员"
            ];
        }
    }

    $errorMsg = getValue($result['msg'], '接口异常');
    $customerUidCache = '';
    writeSystemLog('error', "查询会员失败：手机号={$phone} | 错误：{$errorMsg}", $username);
    return [
        'success' => false,
        'data' => [],
        'uid' => '',
        'msg' => "查询失败: {$errorMsg}"
    ];
}

/**
 * 根据会员号查询会员
 * @param string $customerNum 会员号
 * @param array $config 银豹接口配置
 * @param string &$customerUidCache 会员UID缓存（引用传递）
 * @return array 查询结果，包含success、data、uid、msg字段
 */
function queryMemberByNumber($customerNum, $config, &$customerUidCache) {
    // 构建请求参数
    $postData = ["appId" => $config["appID"], "customerNum" => $customerNum];
    $requestBody = json_encode($postData, JSON_UNESCAPED_UNICODE);
    $url = $config['host'] . "/pospal-api2/openapi/{$config['apiVersion']}/customerOpenapi/queryByNumber";
    
    // 发送API请求
    $result = sendPostRequest($url, $requestBody, $config);
    $username = $_SESSION['username'] ?? '未知用户';

    // 处理API响应
    if ($result['status'] === 'success' && getValue($result['data']['status']) === 'success') {
        $member = getValue($result['data']['data'], []);
        if (!empty($member)) {
            // 缓存会员UID
            $customerUidCache = getValue($member['customerUid'], '');
            // 记录日志
            writeSystemLog('query', "查询会员成功：会员号={$customerNum} | UID={$customerUidCache}", $username);
            // 返回成功结果
            return [
                'success' => true,
                'data' => [$member], // 保持与queryMemberByPhone函数返回格式一致
                'uid' => $customerUidCache,
                'msg' => "查询会员成功"
            ];
        } else {
            // 会员不存在
            $customerUidCache = '';
            writeSystemLog('query', "查询会员无结果：会员号={$customerNum}", $username);
            return [
                'success' => false,
                'data' => [],
                'uid' => '',
                'msg' => "会员号 {$customerNum} 不存在"
            ];
        }
    }

    // API请求失败
    $errorMsg = getValue($result['msg'], '接口异常');
    $customerUidCache = '';
    writeSystemLog('error', "查询会员失败：会员号={$customerNum} | 错误：{$errorMsg}", $username);
    return [
        'success' => false,
        'data' => [],
        'uid' => '',
        'msg' => "查询失败: {$errorMsg}"
    ];
}

/**
 * 修改会员手机号
 * @param string $customerUid 会员在银豹系统的唯一标识
 * @param string $newPhone 新手机号
 * @param array $config 银豹接口配置
 * @return array 修改结果，包含success和msg字段
 */
function updateMemberPhone($customerUid, $newPhone, $config) {
    // 构建会员信息数据
    $memberData = [
        "customerUid" => $customerUid,
        "phone" => $newPhone
    ];

    // 构建请求参数
    $postData = ["appId" => $config["appID"], "customerInfo" => $memberData];
    $requestBody = json_encode($postData, JSON_UNESCAPED_UNICODE);
    $url = $config['host'] . "/pospal-api2/openapi/{$config['apiVersion']}/customerOpenapi/updateBaseInfo";

    // 发送API请求
    $result = sendPostRequest($url, $requestBody, $config);
    $username = $_SESSION['username'] ?? '未知用户';

    // 处理API响应
    if ($result['status'] === 'success' && getValue($result['data']['status']) === 'success') {
        // 修改成功
        writeSystemLog('update', "修改会员手机号成功：UID={$customerUid} | 新手机号={$newPhone}", $username);
        return [
            'success' => true,
            'msg' => "修改手机号成功"
        ];
    } else {
        // 修改失败
        $errorMsg = getValue($result['msg'], getValue($result['data']['messages'][0] ?? '未知错误'));
        writeSystemLog('error', "修改会员手机号失败：UID={$customerUid} | 新手机号={$newPhone} | 错误：{$errorMsg}", $username);
        return [
            'success' => false,
            'msg' => "修改失败: {$errorMsg}"
        ];
    }
}

/**
 * 修改会员状态（启用/禁用）
 * @param string $customerUid 会员在银豹系统的唯一标识
 * @param int $status 状态值，1为启用，0为禁用
 * @param array $config 银豹接口配置
 * @return array 修改结果，包含success和msg字段
 */
function updateMemberStatus($customerUid, $status, $config) {
    // 构建会员信息数据
    $memberData = [
        "customerUid" => $customerUid,
        "enable" => $status
    ];

    // 构建请求参数
    $postData = ["appId" => $config["appID"], "customerInfo" => $memberData];
    $requestBody = json_encode($postData, JSON_UNESCAPED_UNICODE);
    $url = $config['host'] . "/pospal-api2/openapi/{$config['apiVersion']}/customerOpenapi/updateBaseInfo";

    // 发送API请求
    $result = sendPostRequest($url, $requestBody, $config);
    $username = $_SESSION['username'] ?? '未知用户';

    // 处理API响应
    if ($result['status'] === 'success' && getValue($result['data']['status']) === 'success') {
        // 修改成功
        $statusText = $status == 1 ? '启用' : '禁用';
        writeSystemLog('update', "修改会员状态成功：UID={$customerUid} | 状态={$statusText}", $username);
        return [
            'success' => true,
            'msg' => "会员{$statusText}成功"
        ];
    } else {
        // 修改失败
        $errorMsg = getValue($result['msg'], getValue($result['data']['messages'][0] ?? '未知错误'));
        $statusText = $status == 1 ? '启用' : '禁用';
        writeSystemLog('error', "修改会员状态失败：UID={$customerUid} | 状态={$statusText} | 错误：{$errorMsg}", $username);
        return [
            'success' => false,
            'msg' => "修改失败: {$errorMsg}"
        ];
    }
}

/**
 * 查询优惠券规则
 */
function getCouponRuleUid($ruleName, $config) {
    $postData = ["appId" => $config["appID"]];
    $requestBody = json_encode($postData, JSON_UNESCAPED_UNICODE);
    $url = $config['host'] . "/pospal-api2/openapi/{$config['apiVersion']}/promotionOpenApi/queryCouponPromotions";

    $result = sendPostRequest($url, $requestBody, $config);

    if ($result['status'] === 'success') {
        $responseData = getValue($result['data'], []);
        if (getValue($responseData['status']) === 'success') {
            $couponRules = getValue($responseData['data'], []);
            $ruleNames = [];
            foreach ($couponRules as $rule) {
                $ruleNameTmp = getValue($rule['name'], '');
                $ruleNames[] = $ruleNameTmp;
                if (stripos($ruleNameTmp, $ruleName) !== false) {
                    $couponUid = getValue($rule['promotionCouponUid'], '');
                    $validEndDate = getValue($rule['endDate'], '未知');
                    return [
                        'success' => true,
                        'uid' => $couponUid,
                        'msg' => "找到规则：{$ruleNameTmp}（UID：{$couponUid}）",
                        'validEndDate' => !empty($validEndDate) ? substr($validEndDate, 0, 10) : '未知'
                    ];
                }
            }
            $ruleNameStr = implode(',', $ruleNames);
            return [
                'success' => false,
                'uid' => '',
                'msg' => "未找到「{$ruleName}」相关规则，可用规则：{$ruleNameStr}"
            ];
        } else {
            $errorMsg = !empty($responseData['messages'][0]) ? $responseData['messages'][0] : '接口错误';
            return ['success' => false, 'uid' => '', 'msg' => "查询失败: {$errorMsg}"];
        }
    }

    $errorMsg = getValue($result['msg'], '网络异常');
    return ['success' => false, 'uid' => '', 'msg' => "查询失败: {$errorMsg}"];
}

/**
 * 查询可用优惠券规则（支持关键字模糊匹配）
 */
function getAllCouponRules($config, $keyword = '') {
    $postData = ["appId" => $config["appID"]];
    $requestBody = json_encode($postData, JSON_UNESCAPED_UNICODE);
    $url = $config['host'] . "/pospal-api2/openapi/{$config['apiVersion']}/promotionOpenApi/queryCouponPromotions";

    $result = sendPostRequest($url, $requestBody, $config);
    $username = $_SESSION['username'] ?? '未知用户';

    if ($result['status'] === 'success') {
        $responseData = getValue($result['data'], []);
        if (getValue($responseData['status']) === 'success') {
            $couponRules = getValue($responseData['data'], []);
            // 过滤出可用的优惠券规则
            $availableRules = array_filter($couponRules, function($rule) {
                return getValue($rule['enable'], 0) === 1;
            });
            
            // 如果有关键字，进行模糊匹配
            if (!empty($keyword)) {
                $availableRules = array_filter($availableRules, function($rule) use ($keyword) {
                    $ruleName = getValue($rule['name'], '');
                    return stripos($ruleName, $keyword) !== false;
                });
            }
            
            $ruleCount = count($availableRules);
            $logMsg = !empty($keyword) ? "根据关键字 '{$keyword}' 查询可用优惠券规则成功，共找到 {$ruleCount} 条规则" : "查询所有可用优惠券规则成功，共找到 {$ruleCount} 条规则";
            writeSystemLog('query', $logMsg, $username);
            
            $msg = !empty($keyword) ? "查询成功，共找到 {$ruleCount} 条与 '{$keyword}' 相关的可用优惠券规则" : "查询成功，共找到 {$ruleCount} 条可用优惠券规则";
            return [
                'success' => true,
                'data' => $availableRules,
                'msg' => $msg
            ];
        } else {
            $errorMsg = !empty($responseData['messages'][0]) ? $responseData['messages'][0] : '接口错误';
            writeSystemLog('error', "查询优惠券规则失败：{$errorMsg}", $username);
            return ['success' => false, 'data' => [], 'msg' => "查询失败: {$errorMsg}"];
        }
    }

    $errorMsg = getValue($result['msg'], '网络异常');
    writeSystemLog('error', "查询优惠券规则失败：{$errorMsg}", $username);
    return ['success' => false, 'data' => [], 'msg' => "查询失败: {$errorMsg}"];
}

/**
 * 检查是否在30秒内已经发送过优惠券
 */
function checkCouponSendLimit($phone) {
    $limitFile = __DIR__ . '/coupon_send_limit.json';
    $limits = [];
    
    if (file_exists($limitFile)) {
        $content = file_get_contents($limitFile);
        if (!empty($content)) {
            $limits = json_decode($content, true);
        }
    }
    
    $currentTime = time();
    $phoneKey = 'phone_' . $phone;
    
    if (isset($limits[$phoneKey])) {
        $lastSendTime = $limits[$phoneKey];
        if ($currentTime - $lastSendTime < 30) {
            return false; // 30秒内已发送过
        }
    }
    
    return true; // 可以发送
}

/**
 * 记录优惠券发送时间
 */
function recordCouponSendTime($phone) {
    $limitFile = __DIR__ . '/coupon_send_limit.json';
    $limits = [];
    
    if (file_exists($limitFile)) {
        $content = file_get_contents($limitFile);
        if (!empty($content)) {
            $limits = json_decode($content, true);
        }
    }
    
    $currentTime = time();
    $phoneKey = 'phone_' . $phone;
    $limits[$phoneKey] = $currentTime;
    
    // 清理过期记录（超过1小时的记录）
    foreach ($limits as $key => $time) {
        if (time() - $time > 3600) {
            unset($limits[$key]);
        }
    }
    
    file_put_contents($limitFile, json_encode($limits));
}

/**
 * 生成唯一优惠券码
 */
function generateUniqueCouponCode() {
    return 'COUP' . date('YmdHis') . rand(100000, 999999);
}

/**
 * 发放优惠券
 */
function sendCouponToMember($customerUid, $couponRuleUid, $config, $ruleEndDate = '未知') {
    $couponCode = generateUniqueCouponCode();
    $postData = [
        "appId" => $config["appID"],
        "promotionCouponUid" => $couponRuleUid,
        "code" => $couponCode,
        "customerUid" => $customerUid
    ];
    $requestBody = json_encode($postData, JSON_UNESCAPED_UNICODE);
    $url = $config['host'] . "/pospal-api/api/auth/openapi/promotion/addCouponcode/";

    $result = sendPostRequest($url, $requestBody, $config);

    if ($result['status'] === 'success') {
        $responseData = getValue($result['data'], []);
        if (getValue($responseData['status']) === 'success') {
            $expiredDate = getValue($responseData['data']['codeExpiredDate'], '');
            $finalExpiredDate = !empty($expiredDate) ? substr($expiredDate, 0, 10) : $ruleEndDate;
            return [
                'success' => true,
                'code' => $couponCode,
                'expiredDate' => $finalExpiredDate,
                'msg' => "发放成功！\n券码：{$couponCode}\n有效期至：{$finalExpiredDate}"
            ];
        } else {
            $errorMsg = !empty($responseData['messages'][0]) ? $responseData['messages'][0] : '接口错误';
            return ['success' => false, 'code' => '', 'expiredDate' => '', 'msg' => "发放失败: {$errorMsg}"];
        }
    }

    $errorMsg = getValue($result['msg'], '网络异常');
    return ['success' => false, 'code' => '', 'expiredDate' => '', 'msg' => "发放失败: {$errorMsg}"];
}

/**
 * 查询会员优惠券
 */
function queryMemberCoupons($phone, $config, &$customerUidCache, $page = 1, $pageSize = 20) {
    // 先查询会员UID
    $memberResult = queryMemberByPhone($phone, $config, $customerUidCache);
    if (!$memberResult['success']) {
        return [
            'success' => false,
            'data' => [],
            'msg' => $memberResult['msg']
        ];
    }
    
    $customerUid = $customerUidCache;
    $username = $_SESSION['username'] ?? '未知用户';
    
    // 调用查询会员优惠券API
    $postData = [
        "appId" => $config["appID"],
        "customerUid" => $customerUid,
        "page" => $page,
        "pageSize" => $pageSize
    ];
    $requestBody = json_encode($postData, JSON_UNESCAPED_UNICODE);
    $url = $config['host'] . "/pospal-api2/openapi/{$config['apiVersion']}/promotionOpenApi/queryCustomerCouponCodePage";

    $result = sendPostRequest($url, $requestBody, $config);

    if ($result['status'] === 'success') {
        $responseData = getValue($result['data'], []);
        // 记录详细的响应数据
        writeSystemLog('query', "查询会员优惠券API响应：手机号={$phone} | 响应数据：" . json_encode($responseData), $username);
        
        if (getValue($responseData['status']) === 'success') {
            // 优惠券数据在 result 字段中
            $coupons = getValue($responseData['data']['result'], []);
            $totalCount = count($coupons);
            $totalPages = ceil($totalCount / $pageSize);
            
            // 检查优惠券数据
            if (empty($coupons)) {
                writeSystemLog('info', "查询会员优惠券为空：手机号={$phone}", $username);
            } else {
                writeSystemLog('info', "查询会员优惠券成功：手机号={$phone} | UID={$customerUid} | 共找到 {$totalCount} 张优惠券", $username);
            }
            
            return [
                'success' => true,
                'data' => $coupons,
                'total' => $totalCount,
                'page' => $page,
                'pageSize' => $pageSize,
                'totalPages' => $totalPages,
                'msg' => "查询成功，共找到 {$totalCount} 张优惠券"
            ];
        } else {
            $errorMsg = !empty($responseData['messages'][0]) ? $responseData['messages'][0] : '接口错误';
            writeSystemLog('error', "查询会员优惠券失败：手机号={$phone} | UID={$customerUid} | 错误：{$errorMsg}", $username);
            return ['success' => false, 'data' => [], 'msg' => "查询失败: {$errorMsg}"];
        }
    }

    $errorMsg = getValue($result['msg'], '网络异常');
    writeSystemLog('error', "查询会员优惠券失败：手机号={$phone} | 错误：{$errorMsg} | 原始响应：" . $result['raw'], $username);
    return ['success' => false, 'data' => [], 'msg' => "查询失败: {$errorMsg}"];
}

/**
 * 查询会员通用金额充值记录
 * @param string $phone 会员手机号
 * @param array $config 银豹接口配置
 * @param string &$customerUidCache 会员UID缓存（引用传递）
 * @param int $page 页码
 * @param int $pageSize 每页条数
 * @return array 查询结果，包含success、data、total、page、pageSize、totalPages、msg字段
 */
function queryMemberRechargeRecords($phone, $config, &$customerUidCache, $page = 1, $pageSize = 20) {
    // 先查询会员UID
    $memberResult = queryMemberByPhone($phone, $config, $customerUidCache);
    if (!$memberResult['success']) {
        return [
            'success' => false,
            'data' => [],
            'msg' => $memberResult['msg']
        ];
    }
    
    $customerUid = $customerUidCache;
    $username = $_SESSION['username'] ?? '未知用户';
    
    // 调用查询会员充值日志API（使用专门的会员充值日志接口）
    $postData = [
        "appId" => $config["appID"],
        "customerUid" => $customerUid
    ];
    
    // 调试：打印请求参数
    $username = $_SESSION['username'] ?? '未知用户';
    writeSystemLog('debug', "充值记录查询请求参数：" . json_encode($postData), $username);
    
    $requestBody = json_encode($postData, JSON_UNESCAPED_UNICODE);
    $url = $config['host'] . "/pospal-api2/openapi/{$config['apiVersion']}/customerOpenApi/queryCustomerRechargeLog";

    $result = sendPostRequest($url, $requestBody, $config);

    if ($result['status'] === 'success') {
        $responseData = getValue($result['data'], []);
        // 记录详细的响应数据
        writeSystemLog('query', "查询会员充值记录API响应：手机号={$phone} | 响应数据：" . json_encode($responseData), $username);
        
        if (getValue($responseData['status']) === 'success') {
            // 获取充值记录数据（直接从data字段获取）
            $rechargeRecords = getValue($responseData['data'], []);
            
            // 映射字段名，确保与前端期望的格式一致
            $mappedRecords = [];
            foreach ($rechargeRecords as $record) {
                $mappedRecords[] = [
                    'amount' => $record['rechargeMoney'] ?? 0,
                    'createdDate' => $record['datetime'] ?? '',
                    'paymentMethod' => $record['payMethod'] ?? '',
                    'operator' => '系统', // API返回中没有操作人字段
                    'remarks' => "充值后余额：" . ($record['customerMoneyAfterRecharge'] ?? 0) . "元"
                ];
            }
            
            $rechargeRecords = $mappedRecords;
            $totalCount = count($rechargeRecords);
            $totalPages = ceil($totalCount / $pageSize);
            
            // 检查充值记录数据
            if (empty($rechargeRecords)) {
                writeSystemLog('info', "查询会员充值记录为空：手机号={$phone}", $username);
            } else {
                writeSystemLog('info', "查询会员充值记录成功：手机号={$phone} | UID={$customerUid} | 共找到 {$totalCount} 条记录", $username);
            }
            
            return [
                'success' => true,
                'data' => $rechargeRecords,
                'total' => $totalCount,
                'page' => $page,
                'pageSize' => $pageSize,
                'totalPages' => $totalPages,
                'msg' => "查询成功，共找到 {$totalCount} 条充值记录"
            ];
        } else {
            $errorMsg = !empty($responseData['messages'][0]) ? $responseData['messages'][0] : '接口错误';
            writeSystemLog('error', "查询会员充值记录失败：手机号={$phone} | UID={$customerUid} | 错误：{$errorMsg}", $username);
            return ['success' => false, 'data' => [], 'msg' => "查询失败: {$errorMsg}"];
        }
    }

    $errorMsg = getValue($result['msg'], '网络异常');
    writeSystemLog('error', "查询会员充值记录失败：手机号={$phone} | 错误：{$errorMsg} | 原始响应：" . $result['raw'], $username);
    return ['success' => false, 'data' => [], 'msg' => "查询失败: {$errorMsg}"];
}

// ==================== 业务逻辑处理 ====================
// 初始化Session
initSession();

// 登录验证
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['login_action']) && $_POST['login_action'] === 'login') {
    // CSRF校验
    if (!verifyCsrfToken($_POST['csrf_token'] ?? '')) {
        $loginError = '非法请求！';
    } else {
        $username = trim($_POST['username'] ?? '');
        $password = trim($_POST['password'] ?? '');

        // 账号密码配置（建议迁移到独立配置文件）
        $validUsers = [
            'admin' => password_hash('blx123456', PASSWORD_DEFAULT),
            'fahuo' => password_hash('blx123456', PASSWORD_DEFAULT)
        ];

        if (isset($validUsers[$username]) && password_verify($password, $validUsers[$username])) {
            $_SESSION['logged_in'] = true;
            $_SESSION['username'] = $username;
            $_SESSION['permissions'] = $userPermissions[$username] ?? ['canSeeLog' => false];
            $isLoggedIn = true;
            writeSystemLog('login', "登录成功", $username);
        } else {
            $loginError = '账号或密码错误！';
            $isLoggedIn = false;
            writeSystemLog('login_error', "登录失败：账号={$username}", $username);
        }
    }
}

// 检查登录状态
if (isset($_SESSION['logged_in']) && $_SESSION['logged_in'] === true) {
    $isLoggedIn = true;
}

// 获取当前用户信息
$currentUser = $_SESSION['username'] ?? '';
$currentPermissions = $_SESSION['permissions'] ?? ['canSeeLog' => false];
$canSeeLog = checkPermission('canSeeLog', $currentPermissions);

// 登出处理
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['login_action']) && $_POST['login_action'] === 'logout') {
    // CSRF校验
    if (verifyCsrfToken($_POST['csrf_token'] ?? '')) {
        $username = $_SESSION['username'] ?? '未知用户';
        writeSystemLog('logout', "登出成功", $username);

        $_SESSION = [];
        if (ini_get("session.use_cookies")) {
            $params = session_get_cookie_params();
            setcookie(session_name(), '', time() - 42000,
                $params["path"], $params["domain"],
                $params["secure"], $params["httponly"]
            );
        }
        session_destroy();
        $isLoggedIn = false;
        header("Location: " . $_SERVER['PHP_SELF']);
        exit;
    } else {
        $loginError = '非法请求！';
    }
}

// 登录后业务处理
if ($isLoggedIn && $_SERVER['REQUEST_METHOD'] === 'POST') {
    // CSRF校验
    if (!verifyCsrfToken($_POST['csrf_token'] ?? '')) {
        $operateResult = ['status' => 'error', 'msg' => '非法请求！'];
    } else {
        $phone = trim($_POST['phone'] ?? '');
        $activeTab = trim($_POST['active_tab'] ?? 'query');
        $username = $_SESSION['username'] ?? '未知用户';

        // 日志查询（仅管理员）
        if ($canSeeLog && isset($_POST['action']) && $_POST['action'] === 'query_log') {
            $logStartDate = trim($_POST['log_start_date'] ?? $logStartDate);
            $logEndDate = trim($_POST['log_end_date'] ?? $logEndDate);
            $logType = trim($_POST['log_type'] ?? '');
            $logPage = intval($_POST['log_page'] ?? 1);
            $logResult = readSystemLogs($logStartDate, $logEndDate, $logType, $logPage);
        }

        // ==================== 会员查询处理 ====================
        /**
         * 处理会员查询请求
         * 通过手机号查询会员信息
         */
        if (isset($_POST['action']) && $_POST['action'] === 'query') {
            $queryResult = queryMemberByPhone($phone, $config, $customerUidCache);
        }

        // ==================== 修改手机号处理 ====================
        /**
         * 处理修改手机号请求
         * 注意：此功能已迁移到会员绑定页面，此处保留代码仅为兼容历史操作
         */
        if (isset($_POST['action']) && $_POST['action'] === 'update_phone') {
            $newPhone = trim($_POST['new_phone'] ?? '');
            if (empty($newPhone)) {
                $operateResult = ['status' => 'error', 'msg' => '新手机号不能为空！'];
            } elseif (!preg_match('/^1[3-9]\d{9}$/', $newPhone)) {
                $operateResult = ['status' => 'error', 'msg' => '请输入有效11位手机号！'];
            } else {
                if (empty($customerUidCache)) {
                    $operateResult = ['status' => 'error', 'msg' => '请先查询会员信息！'];
                } else {
                    $updateResult = updateMemberPhone($customerUidCache, $newPhone, $config);
                    $operateResult = [
                        'status' => $updateResult['success'] ? 'success' : 'error',
                        'msg' => $updateResult['msg']
                    ];
                }
            }
        }

        // ==================== 会员绑定处理 ====================
        /**
         * 处理会员绑定 - 查询会员
         * 通过会员号查询会员信息，为后续修改手机号做准备
         */
        if (isset($_POST['action']) && $_POST['action'] === 'bind_query') {
            $customerNum = trim($_POST['customer_num'] ?? '');
            if (empty($customerNum)) {
                $operateResult = ['status' => 'error', 'msg' => '会员号不能为空！'];
            } else {
                $bindQueryResult = queryMemberByNumber($customerNum, $config, $customerUidCache);
                if (!$bindQueryResult['success']) {
                    $operateResult = ['status' => 'error', 'msg' => $bindQueryResult['msg']];
                }
            }
        }

        /**
         * 处理会员绑定 - 修改手机号
         * 在查询到会员信息后，修改会员的手机号
         */
        if (isset($_POST['action']) && $_POST['action'] === 'bind_update_phone') {
            $customerUid = trim($_POST['customer_uid'] ?? '');
            $newPhone = trim($_POST['new_phone'] ?? '');
            
            if (empty($customerUid)) {
                $operateResult = ['status' => 'error', 'msg' => '会员信息不存在，请先查询会员！'];
            } elseif (empty($newPhone)) {
                $operateResult = ['status' => 'error', 'msg' => '新手机号不能为空！'];
            } elseif (!preg_match('/^1[3-9]\d{9}$/', $newPhone)) {
                $operateResult = ['status' => 'error', 'msg' => '请输入有效11位手机号！'];
            } else {
                $updateResult = updateMemberPhone($customerUid, $newPhone, $config);
                $operateResult = [
                    'status' => $updateResult['success'] ? 'success' : 'error',
                    'msg' => $updateResult['msg']
                ];
            }
        }

        // 发放优惠券
        if (isset($_POST['action']) && $_POST['action'] === 'send_coupon') {
            $couponRuleName = trim($_POST['coupon_rule_name'] ?? '');
            if (empty($phone)) {
                $operateResult = ['status' => 'error', 'msg' => '手机号不能为空！'];
            } elseif (!preg_match('/^1[3-9]\d{9}$/', $phone)) {
                $operateResult = ['status' => 'error', 'msg' => '请输入有效11位手机号！'];
            } elseif (empty($couponRuleName)) {
                $operateResult = ['status' => 'error', 'msg' => '优惠券规则名称不能为空！'];
            } elseif (!checkCouponSendLimit($phone)) {
                $operateResult = ['status' => 'error', 'msg' => '30秒内已发送过优惠券，请稍后再试！'];
                writeSystemLog('error', "发券失败：手机号={$phone} | 错误：30秒内已发送过优惠券", $username);
            } else {
                if (empty($customerUidCache)) {
                    $checkResult = queryMemberByPhone($phone, $config, $customerUidCache);
                    if (!$checkResult['success']) {
                        $operateResult = ['status' => 'error', 'msg' => $checkResult['msg']];
                        $customerUidCache = '';
                    }
                }

                if (!empty($customerUidCache)) {
                    $couponRuleResult = getCouponRuleUid($couponRuleName, $config);
                    if (!$couponRuleResult['success']) {
                        $operateResult = ['status' => 'error', 'msg' => $couponRuleResult['msg']];
                        writeSystemLog('error', "发券失败：手机号={$phone} | 规则={$couponRuleName} | 错误：{$couponRuleResult['msg']}", $username);
                    } else {
                        $sendResult = sendCouponToMember(
                            $customerUidCache,
                            $couponRuleResult['uid'],
                            $config,
                            $couponRuleResult['validEndDate']
                        );
                        $operateResult = [
                            'status' => $sendResult['success'] ? 'success' : 'error',
                            'msg' => $sendResult['msg']
                        ];
                        if ($sendResult['success']) {
                            recordCouponSendTime($phone); // 记录发送时间
                            writeSystemLog('coupon', "发券成功：手机号={$phone} | UID={$customerUidCache} | 规则={$couponRuleName} | 券码={$sendResult['code']} | 有效期至={$sendResult['expiredDate']}", $username);
                        } else {
                            writeSystemLog('error', "发券失败：手机号={$phone} | UID={$customerUidCache} | 规则={$couponRuleName} | 错误：{$sendResult['msg']}", $username);
                        }
                    }
                } else {
                    $operateResult = ['status' => 'error', 'msg' => "手机号 {$phone} 会员不存在！"];
                    writeSystemLog('coupon', "发券失败：手机号={$phone}（不存在）", $username);
                }
            }
        }

        // 查询可用优惠券规则（支持关键字模糊匹配）
        if (isset($_POST['action']) && $_POST['action'] === 'query_coupon_rules') {
            $couponRuleKeyword = trim($_POST['coupon_rule_keyword'] ?? '');
            $couponRulesResult = getAllCouponRules($config, $couponRuleKeyword);
        }
        
        // 查询会员优惠券
        if (isset($_POST['action']) && $_POST['action'] === 'query_member_coupons') {
            $phone = trim($_POST['phone'] ?? '');
            $page = intval($_POST['page'] ?? 1);
            $pageSize = 20;
            if (empty($phone)) {
                $memberCouponsResult = ['status' => 'error', 'msg' => '手机号不能为空！'];
            } elseif (!preg_match('/^1[3-9]\d{9}$/', $phone)) {
                $memberCouponsResult = ['status' => 'error', 'msg' => '请输入有效11位手机号！'];
            } else {
                $memberCouponsResult = queryMemberCoupons($phone, $config, $customerUidCache, $page, $pageSize);
            }
        }

        // 查询会员充值记录
        if (isset($_POST['action']) && $_POST['action'] === 'query_member_recharge') {
            $phone = trim($_POST['phone'] ?? '');
            $page = intval($_POST['page'] ?? 1);
            $pageSize = 20;
            if (empty($phone)) {
                $rechargeResult = ['status' => 'error', 'msg' => '手机号不能为空！'];
            } elseif (!preg_match('/^1[3-9]\d{9}$/', $phone)) {
                $rechargeResult = ['status' => 'error', 'msg' => '请输入有效11位手机号！'];
            } else {
                $rechargeResult = queryMemberRechargeRecords($phone, $config, $customerUidCache, $page, $pageSize);
            }
        }

        // 切换会员状态（启用/禁用）
        if (isset($_POST['action']) && $_POST['action'] === 'toggle_status') {
            $customerUid = trim($_POST['customer_uid'] ?? '');
            $currentStatus = intval($_POST['current_status'] ?? 1);
            $phone = trim($_POST['phone'] ?? '');
            
            if (empty($customerUid)) {
                $operateResult = ['status' => 'error', 'msg' => '会员信息不存在！'];
            } else {
                // 计算新状态（1变0，0变1）
                $newStatus = $currentStatus == 1 ? 0 : 1;
                $updateResult = updateMemberStatus($customerUid, $newStatus, $config);
                $operateResult = [
                    'status' => $updateResult['success'] ? 'success' : 'error',
                    'msg' => $updateResult['msg']
                ];
                
                // 重新查询会员信息以更新界面
                if ($updateResult['success'] && !empty($phone)) {
                    $queryResult = queryMemberByPhone($phone, $config, $customerUidCache);
                }
            }
        }
    }
}

// 初始化日志查询（管理员默认显示30天）
if ($isLoggedIn && $canSeeLog && $activeTab === 'log' && $logResult === null) {
    $logResult = readSystemLogs($logStartDate, $logEndDate, $logType, $logPage);
}

// ==================== 前端页面渲染 ====================
?>
<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>巴黎香平台发货系统</title>
    <style>
        * {
            margin: 0;
            padding: 0;
            box-sizing: border-box;
            font-family: "微软雅黑", "Microsoft Yahei", Arial, sans-serif;
        }
        body {
            background-color: #f5f7fa;
            padding: 30px 0;
        }
        .container {
            width: 90%;
            max-width: 1000px;
            margin: 0 auto;
            background: white;
            border-radius: 12px;
            box-shadow: 0 2px 15px rgba(0,0,0,0.08);
            padding: 20px;
        }
        .header {
            text-align: center;
            margin-bottom: 20px;
            padding-bottom: 15px;
            border-bottom: 1px solid #eee;
        }
        .header h1 {
            font-size: 24px;
            color: #333;
        }
        .header .user-info {
            text-align: right;
            margin-bottom: 10px;
            color: #666;
            font-size: 14px;
        }
        .login-container {
            max-width: 400px;
            margin: 50px auto;
            padding: 30px;
            background: white;
            border-radius: 12px;
            box-shadow: 0 2px 15px rgba(0,0,0,0.08);
        }
        .login-title {
            text-align: center;
            margin-bottom: 20px;
            font-size: 20px;
            color: #333;
        }
        .login-form .form-group {
            margin-bottom: 20px;
        }
        .login-form label {
            display: block;
            margin-bottom: 8px;
            font-size: 14px;
            color: #666;
        }
        .login-form input {
            width: 100%;
            padding: 12px 15px;
            border: 1px solid #ddd;
            border-radius: 6px;
            font-size: 16px;
        }
        .login-btn {
            width: 100%;
            padding: 12px;
            background-color: #0088ff;
            color: white;
            border: none;
            border-radius: 6px;
            font-size: 16px;
            cursor: pointer;
        }
        .login-btn:hover {
            background-color: #0077dd;
        }
        .login-error {
            background-color: #fef0f0;
            border: 1px solid #fbc4c4;
            color: #f56c6c;
            padding: 10px;
            border-radius: 6px;
            margin-bottom: 20px;
            text-align: center;
        }
        .tabs {
            display: flex;
            flex-wrap: wrap;
            border-bottom: 1px solid #eee;
            margin-bottom: 20px;
            gap: 5px;
        }
        .tab {
            padding: 10px 20px;
            cursor: pointer;
            font-size: 16px;
            color: #666;
            border-bottom: 2px solid transparent;
        }
        .tab.active {
            color: #0088ff;
            border-bottom-color: #0088ff;
            font-weight: 500;
        }
        .form-section {
            display: none;
            padding: 10px 0;
        }
        .form-section.active {
            display: block !important;
        }
        .form-group {
            display: flex;
            flex-direction: column;
            margin-bottom: 15px;
        }
        .form-group label {
            font-size: 14px;
            color: #666;
            margin-bottom: 5px;
        }
        .form-group label span {
            color: red;
        }
        .form-group input,
        .form-group select {
            padding: 10px 15px;
            border: 1px solid #ddd;
            border-radius: 6px;
            font-size: 16px;
            width: 100%;
        }
        .query-form {
            display: flex;
            gap: 10px;
            margin-bottom: 20px;
        }
        .query-form input {
            flex: 1;
            padding: 10px 15px;
            border: 1px solid #ddd;
            border-radius: 6px;
            font-size: 16px;
        }
        .log-filter-form {
            display: flex;
            flex-wrap: wrap;
            gap: 10px;
            margin-bottom: 20px;
            align-items: flex-end;
        }
        .log-filter-form .form-group {
            flex: 1;
            min-width: 150px;
            margin-bottom: 0;
        }
        .btn {
            padding: 12px 20px;
            border: none;
            border-radius: 6px;
            cursor: pointer;
            font-size: 16px;
            width: 100%;
            background-color: #0088ff;
            color: white;
            margin-top: 10px;
        }
        .btn:hover {
            background-color: #0077dd;
        }
        .btn-small {
            padding: 8px 15px;
            font-size: 14px;
            width: auto;
        }
        .logout-btn {
            background-color: #f56c6c;
            margin-top: 10px;
        }
        .logout-btn:hover {
            background-color: #e65959;
        }
        .result {
            margin-top: 20px;
            padding: 15px;
            border-radius: 6px;
            font-size: 14px;
            line-height: 1.6;
        }
        .result.success {
            background-color: #f0f9ff;
            border: 1px solid #91d5ff;
            color: #1890ff;
        }
        .result.error {
            background-color: #fef0f0;
            border: 1px solid #fbc4c4;
            color: #f56c6c;
        }
        .log-table {
            width: 100%;
            border-collapse: collapse;
            margin-top: 20px;
            font-size: 14px;
        }
        .log-table th, .log-table td {
            padding: 12px 15px;
            border: 1px solid #eee;
            text-align: left;
        }
        .log-table th {
            background-color: #f8f9fa;
            font-weight: 500;
            color: #333;
        }
        .log-table tr:nth-child(even) {
            background-color: #fafafa;
        }
        .pagination {
            display: flex;
            justify-content: center;
            align-items: center;
            margin-top: 20px;
            gap: 10px;
        }
        .pagination-btn {
            padding: 8px 12px;
            border: 1px solid #ddd;
            border-radius: 4px;
            background-color: white;
            cursor: pointer;
            font-size: 14px;
        }
        .pagination-btn.active {
            background-color: #0088ff;
            color: white;
            border-color: #0088ff;
        }
        .pagination-btn:disabled {
            opacity: 0.5;
            cursor: not-allowed;
        }
        .hidden {
            display: none;
        }
        .member-cards {
            display: grid;
            grid-template-columns: repeat(auto-fill, minmax(300px, 1fr));
            gap: 20px;
            margin-top: 20px;
        }
        .member-card {
            background: #f8f9fa;
            border: 1px solid #e9ecef;
            border-radius: 8px;
            padding: 15px;
            box-shadow: 0 2px 4px rgba(0,0,0,0.05);
            transition: all 0.3s ease;
        }
        .member-card:hover {
            box-shadow: 0 4px 8px rgba(0,0,0,0.1);
            transform: translateY(-2px);
        }
        .member-card h3 {
            margin-bottom: 12px;
            color: #333;
            font-size: 16px;
            border-bottom: 1px solid #e9ecef;
            padding-bottom: 8px;
        }
        .member-info {
            line-height: 1.6;
        }
        .member-info p {
            margin: 5px 0;
            font-size: 14px;
        }
        .member-info .label {
            font-weight: 500;
            color: #666;
            display: inline-block;
            width: 80px;
        }
        .member-info .value {
            color: #333;
        }
        
        /* 响应式设计 */
        @media (max-width: 768px) {
            body {
                padding: 10px 0;
                font-size: 14px;
            }
            .container {
                width: 98%;
                padding: 12px;
                border-radius: 8px;
            }
            .header {
                margin-bottom: 12px;
                padding-bottom: 8px;
            }
            .header h1 {
                font-size: 18px;
            }
            .header .user-info {
                font-size: 12px;
                margin-bottom: 8px;
            }
            .tabs {
                margin-bottom: 12px;
                gap: 3px;
            }
            .tab {
                padding: 6px 10px;
                font-size: 12px;
            }
            .query-form {
                flex-direction: column;
                gap: 8px;
                margin-bottom: 15px;
            }
            .query-form input {
                width: 100%;
                padding: 12px;
                font-size: 16px;
            }
            .log-filter-form {
                flex-direction: column;
                align-items: stretch;
                gap: 8px;
                margin-bottom: 15px;
            }
            .log-filter-form .form-group {
                min-width: 100%;
            }
            .form-group {
                margin-bottom: 12px;
            }
            .form-group label {
                font-size: 13px;
                margin-bottom: 4px;
            }
            .form-group input,
            .form-group select {
                padding: 12px;
                font-size: 16px;
            }
            .btn {
                padding: 12px;
                font-size: 16px;
                margin-top: 8px;
            }
            .btn-small {
                width: 100%;
                padding: 10px;
                font-size: 14px;
            }
            .member-cards {
                grid-template-columns: 1fr;
                gap: 12px;
                margin-top: 15px;
            }
            .member-card {
                padding: 10px;
                border-radius: 6px;
            }
            .member-card h3 {
                font-size: 13px;
                margin-bottom: 8px;
                padding-bottom: 6px;
            }
            .member-info p {
                font-size: 12px;
                margin: 3px 0;
            }
            .member-info .label {
                width: 65px;
                font-size: 12px;
            }
            .log-table {
                font-size: 11px;
                margin-top: 12px;
            }
            .log-table th, .log-table td {
                padding: 6px 8px;
            }
            .pagination {
                gap: 4px;
                flex-wrap: wrap;
                margin-top: 12px;
            }
            .pagination-btn {
                padding: 5px 8px;
                font-size: 11px;
            }
            .result {
                margin-top: 12px;
                padding: 10px;
                font-size: 13px;
            }
            .login-container {
                max-width: 90%;
                margin: 20px auto;
                padding: 15px;
            }
            .login-title {
                font-size: 16px;
                margin-bottom: 15px;
            }
            .login-form .form-group {
                margin-bottom: 12px;
            }
            .login-form input {
                padding: 12px;
                font-size: 16px;
            }
            .login-btn {
                padding: 12px;
                font-size: 16px;
            }
            .login-error {
                margin-bottom: 12px;
                padding: 8px;
                font-size: 13px;
            }
        }
        
        /* 触摸设备优化 */
        @media (hover: none) and (pointer: coarse) {
            .tab {
                padding: 10px 15px;
            }
            .btn {
                padding: 14px 20px;
            }
            .form-group input,
            .form-group select {
                padding: 12px 15px;
            }
        }
    </style>
</head>
<body>
    <?php if (!$isLoggedIn): ?>
        <!-- 登录页面 -->
        <div class="login-container">
            <div class="login-title">巴黎香平台发货系统 - 登录</div>
            <?php if (!empty($loginError)): ?>
                <div class="login-error"><?php echo htmlspecialchars($loginError); ?></div>
            <?php endif; ?>
            <form class="login-form" method="POST" action="">
                <input type="hidden" name="login_action" value="login">
                <input type="hidden" name="csrf_token" value="<?php echo generateCsrfToken(); ?>">
                <div class="form-group">
                    <label for="username">用户名</label>
                    <input type="text" id="username" name="username" required placeholder="请输入用户名">
                </div>
                <div class="form-group">
                    <label for="password">密码</label>
                    <input type="password" id="password" name="password" required placeholder="请输入密码">
                </div>
                <button type="submit" class="login-btn">登录</button>
            </form>
        </div>
    <?php else: ?>
        <!-- 主系统页面 -->
        <div class="container">
            <div class="header">
                <div class="user-info">
                    当前登录：<?php echo htmlspecialchars($currentUser); ?> | 
                    <form method="POST" action="" style="display: inline;">
                        <input type="hidden" name="login_action" value="logout">
                        <input type="hidden" name="csrf_token" value="<?php echo generateCsrfToken(); ?>">
                        <button type="submit" class="btn-small logout-btn">退出登录</button>
                    </form>
                </div>
                <h1>巴黎香平台发货系统</h1>
            </div>

            <!-- 标签页导航 -->
            <div class="tabs">
                <div class="tab <?php echo $activeTab === 'query' ? 'active' : ''; ?>" data-tab="query">会员查询</div>
                <div class="tab <?php echo $activeTab === 'bind' ? 'active' : ''; ?>" data-tab="bind">会员绑定</div>
                <div class="tab <?php echo $activeTab === 'coupon' ? 'active' : ''; ?>" data-tab="coupon">发优惠券</div>
                <div class="tab <?php echo $activeTab === 'coupon_rules' ? 'active' : ''; ?>" data-tab="coupon_rules">优惠券规则</div>
                <div class="tab <?php echo $activeTab === 'member_coupons' ? 'active' : ''; ?>" data-tab="member_coupons">会员优惠券</div>
                <div class="tab <?php echo $activeTab === 'recharge' ? 'active' : ''; ?>" data-tab="recharge">充值记录</div>
                <?php if ($canSeeLog): ?>
                    <div class="tab <?php echo $activeTab === 'log' ? 'active' : ''; ?>" data-tab="log">系统日志</div>
                <?php endif; ?>
            </div>

            <!-- 会员查询表单 -->
            <div class="form-section <?php echo $activeTab === 'query' ? 'active' : ''; ?>" id="query-section">
                <form method="POST" action="" class="query-form" onsubmit="showLoading('query-loading');">
                    <input type="hidden" name="active_tab" value="query">
                    <input type="hidden" name="action" value="query">
                    <input type="hidden" name="csrf_token" value="<?php echo generateCsrfToken(); ?>">
                    <input type="tel" name="phone" value="<?php echo htmlspecialchars($phone); ?>" placeholder="请输入会员手机号" required pattern="^1[3-9]\d{9}$">
                    <button type="submit" class="btn btn-small">查询</button>
                </form>
                <div id="query-loading" class="result hidden" style="margin-top: 10px;">正在查询，请稍候...</div>

                <?php if ($operateResult && $activeTab === 'query'): ?>
                    <div class="result <?php echo $operateResult['status']; ?>">
                        <?php echo htmlspecialchars($operateResult['msg']); ?>
                    </div>
                <?php endif; ?>

                <?php if ($queryResult): ?>
                    <div class="result <?php echo $queryResult['success'] ? 'success' : 'error'; ?>">
                        <?php echo htmlspecialchars($queryResult['msg']); ?>
                        <?php if ($queryResult['success'] && !empty($queryResult['data'])): ?>
                            <br>
                            <?php $memberCount = count($queryResult['data']); ?>
                            <strong>共找到 <?php echo $memberCount; ?> 个会员：</strong>
                            <div class="member-cards">
                                <?php foreach ($queryResult['data'] as $index => $member): ?>
                                    <div class="member-card">
                                        <h3>会员 <?php echo $index + 1; ?></h3>
                                        <div class="member-info">
                                            <p><span class="label">会员UID：</span><span class="value"><?php echo htmlspecialchars($member['customerUid'] ?? ''); ?></span></p>
                                            <p><span class="label">会员号：</span><span class="value"><?php echo htmlspecialchars($member['number'] ?? ''); ?></span></p>
                                            <p><span class="label">姓名：</span><span class="value"><?php echo htmlspecialchars($member['name'] ?? ''); ?></span></p>
                                            <p><span class="label">手机号：</span><span class="value"><?php echo htmlspecialchars($member['phone'] ?? ''); ?></span></p>
                                            <p><span class="label">余额：</span><span class="value"><?php echo htmlspecialchars($member['balance'] ?? 0); ?> 元</span></p>
                                            <p><span class="label">积分：</span><span class="value"><?php echo htmlspecialchars($member['point'] ?? 0); ?></span></p>
                                            <p><span class="label">等级：</span><span class="value"><?php echo htmlspecialchars($member['categoryName'] ?? ''); ?></span></p>
                                            <p><span class="label">状态：</span><span class="value"><?php echo $member['enable'] == 1 ? '启用' : ($member['enable'] == 0 ? '禁用' : '删除'); ?></span></p>
                                            <p><span class="label">生日：</span><span class="value"><?php echo htmlspecialchars($member['birthday'] ?? ''); ?></span></p>
                                            <p><span class="label">QQ：</span><span class="value"><?php echo htmlspecialchars($member['qq'] ?? ''); ?></span></p>
                                            <p><span class="label">邮箱：</span><span class="value"><?php echo htmlspecialchars($member['email'] ?? ''); ?></span></p>
                                            <p><span class="label">地址：</span><span class="value"><?php echo htmlspecialchars($member['address'] ?? ''); ?></span></p>
                                            <p><span class="label">备注：</span><span class="value"><?php echo htmlspecialchars($member['remarks'] ?? ''); ?></span></p>
                                            <p><span class="label">创建日期：</span><span class="value"><?php echo htmlspecialchars($member['createdDate'] ?? ''); ?></span></p>
                                            <p><span class="label">是否赊账：</span><span class="value"><?php echo $member['onAccount'] == 1 ? '是' : '否'; ?></span></p>
                                            <p><span class="label">到期日期：</span><span class="value"><?php echo htmlspecialchars($member['expiryDate'] ?? ''); ?></span></p>
                                            <p><span class="label">开卡门店：</span><span class="value"><?php echo htmlspecialchars($member['createStoreAppIdOrAccount'] ?? ''); ?></span></p>
                                            <p><span class="label">部门：</span><span class="value"><?php echo htmlspecialchars($member['department'] ?? ''); ?></span></p>
                                            
                                            <?php if (!empty($member['extInfo'])): ?>
                                                <div style="margin-top: 10px; padding-top: 10px; border-top: 1px dashed #ddd;">
                                                    <strong>扩展信息：</strong>
                                                    <p><span class="label">性别：</span><span class="value"><?php echo isset($member['extInfo']['sex']) ? ($member['extInfo']['sex'] == 1 ? '男' : ($member['extInfo']['sex'] == 2 ? '女' : '未知')) : '未知'; ?></span></p>
                                                    <p><span class="label">农历生日：</span><span class="value"><?php echo htmlspecialchars($member['extInfo']['lunarBirthday'] ?? ''); ?></span></p>
                                                    <p><span class="label">总积分：</span><span class="value"><?php echo htmlspecialchars($member['extInfo']['totalPoint'] ?? 0); ?></span></p>
                                                    <p><span class="label">信用额度：</span><span class="value"><?php echo htmlspecialchars($member['extInfo']['creditLimit'] ?? 0); ?> 元</span></p>
                                                    <p><span class="label">信用期限：</span><span class="value"><?php echo htmlspecialchars($member['extInfo']['creditPeriod'] ?? 0); ?> 天</span></p>
                                                    <p><span class="label">昵称：</span><span class="value"><?php echo htmlspecialchars($member['extInfo']['nickName'] ?? ''); ?></span></p>
                                                    <p><span class="label">补贴金额：</span><span class="value"><?php echo htmlspecialchars($member['extInfo']['subsidyAmount'] ?? 0); ?> 元</span></p>
                                                </div>
                                            <?php endif; ?>
                                            
                                            <?php if (!empty($member['weixinOpenIds'])): ?>
                                                <div style="margin-top: 10px; padding-top: 10px; border-top: 1px dashed #ddd;">
                                                    <strong>微信信息：</strong>
                                                    <?php foreach ($member['weixinOpenIds'] as $openIdInfo): ?>
                                                        <p><span class="label">OpenId：</span><span class="value"><?php echo htmlspecialchars($openIdInfo['openId'] ?? ''); ?></span></p>
                                                        <p><span class="label">类型：</span><span class="value"><?php echo htmlspecialchars($openIdInfo['openIdType'] ?? 0); ?></span></p>
                                                    <?php endforeach; ?>
                                                </div>
                                            <?php endif; ?>
                                            

                                            
                                            <div style="margin-top: 15px; display: flex; gap: 10px;">
                                                <form method="POST" action="" style="margin: 0;">
                                                    <input type="hidden" name="active_tab" value="query">
                                                    <input type="hidden" name="action" value="toggle_status">
                                                    <input type="hidden" name="customer_uid" value="<?php echo htmlspecialchars($member['customerUid'] ?? ''); ?>">
                                                    <input type="hidden" name="current_status" value="<?php echo $member['enable'] ?? 1; ?>">
                                                    <input type="hidden" name="phone" value="<?php echo htmlspecialchars($phone); ?>">
                                                    <input type="hidden" name="csrf_token" value="<?php echo generateCsrfToken(); ?>">
                                                    <button type="submit" class="btn btn-small" style="background-color: <?php echo $member['enable'] == 1 ? '#f56c6c' : '#67c23a'; ?>">
                                                        <?php echo $member['enable'] == 1 ? '禁用' : '启用'; ?>
                                                    </button>
                                                </form>
                                            </div>
                                        </div>
                                    </div>
                                <?php endforeach; ?>
                            </div>
                        <?php endif; ?>
                    </div>
                <?php endif; ?>
            </div>

            <!-- 会员绑定表单 -->
            <div class="form-section <?php echo $activeTab === 'bind' ? 'active' : ''; ?>" id="bind-section">
                <h3 style="margin-bottom: 15px;">会员绑定</h3>
                
                <!-- 查询会员表单 -->
                <form method="POST" action="" class="query-form" onsubmit="showLoading('bind-query-loading');">
                    <input type="hidden" name="active_tab" value="bind">
                    <input type="hidden" name="action" value="bind_query">
                    <input type="hidden" name="csrf_token" value="<?php echo generateCsrfToken(); ?>">
                    <input type="text" name="customer_num" placeholder="请输入会员号" required>
                    <button type="submit" class="btn btn-small">查询会员</button>
                </form>
                <div id="bind-query-loading" class="result hidden" style="margin-top: 10px;">正在查询会员，请稍候...</div>

                <!-- 会员信息展示 -->
                <?php if (isset($bindQueryResult) && $bindQueryResult['success'] && !empty($bindQueryResult['data'])): ?>
                    <div class="result success" style="margin-top: 15px;">
                        <strong>查询会员成功：</strong>
                        <div class="member-cards" style="margin-top: 10px;">
                            <?php $member = $bindQueryResult['data'][0]; ?>
                            <div class="member-card">
                                <h3>会员信息</h3>
                                <div class="member-info">
                                    <p><span class="label">会员UID：</span><span class="value"><?php echo htmlspecialchars($member['customerUid'] ?? ''); ?></span></p>
                                    <p><span class="label">会员号：</span><span class="value"><?php echo htmlspecialchars($member['number'] ?? ''); ?></span></p>
                                    <p><span class="label">姓名：</span><span class="value"><?php echo htmlspecialchars($member['name'] ?? ''); ?></span></p>
                                    <p><span class="label">当前手机号：</span><span class="value"><?php echo htmlspecialchars($member['phone'] ?? ''); ?></span></p>
                                    <p><span class="label">余额：</span><span class="value"><?php echo htmlspecialchars($member['balance'] ?? 0); ?> 元</span></p>
                                    <p><span class="label">积分：</span><span class="value"><?php echo htmlspecialchars($member['point'] ?? 0); ?></span></p>
                                    <p><span class="label">等级：</span><span class="value"><?php echo htmlspecialchars($member['categoryName'] ?? ''); ?></span></p>
                                    <p><span class="label">状态：</span><span class="value"><?php echo $member['enable'] == 1 ? '启用' : ($member['enable'] == 0 ? '禁用' : '删除'); ?></span></p>
                                    <p><span class="label">生日：</span><span class="value"><?php echo htmlspecialchars($member['birthday'] ?? ''); ?></span></p>
                                    <p><span class="label">QQ：</span><span class="value"><?php echo htmlspecialchars($member['qq'] ?? ''); ?></span></p>
                                    <p><span class="label">邮箱：</span><span class="value"><?php echo htmlspecialchars($member['email'] ?? ''); ?></span></p>
                                    <p><span class="label">地址：</span><span class="value"><?php echo htmlspecialchars($member['address'] ?? ''); ?></span></p>
                                    <p><span class="label">备注：</span><span class="value"><?php echo htmlspecialchars($member['remarks'] ?? ''); ?></span></p>
                                    <p><span class="label">创建日期：</span><span class="value"><?php echo htmlspecialchars($member['createdDate'] ?? ''); ?></span></p>
                                    <p><span class="label">是否赊账：</span><span class="value"><?php echo $member['onAccount'] == 1 ? '是' : '否'; ?></span></p>
                                    <p><span class="label">到期日期：</span><span class="value"><?php echo htmlspecialchars($member['expiryDate'] ?? ''); ?></span></p>
                                    <p><span class="label">开卡门店：</span><span class="value"><?php echo htmlspecialchars($member['createStoreAppIdOrAccount'] ?? ''); ?></span></p>
                                    <p><span class="label">部门：</span><span class="value"><?php echo htmlspecialchars($member['department'] ?? ''); ?></span></p>
                                    
                                    <?php if (!empty($member['extInfo'])): ?>
                                        <div style="margin-top: 10px; padding-top: 10px; border-top: 1px dashed #ddd;">
                                            <strong>扩展信息：</strong>
                                            <p><span class="label">性别：</span><span class="value"><?php echo isset($member['extInfo']['sex']) ? ($member['extInfo']['sex'] == 1 ? '男' : ($member['extInfo']['sex'] == 2 ? '女' : '未知')) : '未知'; ?></span></p>
                                            <p><span class="label">农历生日：</span><span class="value"><?php echo htmlspecialchars($member['extInfo']['lunarBirthday'] ?? ''); ?></span></p>
                                            <p><span class="label">总积分：</span><span class="value"><?php echo htmlspecialchars($member['extInfo']['totalPoint'] ?? 0); ?></span></p>
                                            <p><span class="label">信用额度：</span><span class="value"><?php echo htmlspecialchars($member['extInfo']['creditLimit'] ?? 0); ?> 元</span></p>
                                            <p><span class="label">信用期限：</span><span class="value"><?php echo htmlspecialchars($member['extInfo']['creditPeriod'] ?? 0); ?> 天</span></p>
                                            <p><span class="label">昵称：</span><span class="value"><?php echo htmlspecialchars($member['extInfo']['nickName'] ?? ''); ?></span></p>
                                            <p><span class="label">补贴金额：</span><span class="value"><?php echo htmlspecialchars($member['extInfo']['subsidyAmount'] ?? 0); ?> 元</span></p>
                                        </div>
                                    <?php endif; ?>
                                    
                                    <?php if (!empty($member['weixinOpenIds'])): ?>
                                        <div style="margin-top: 10px; padding-top: 10px; border-top: 1px dashed #ddd;">
                                            <strong>微信信息：</strong>
                                            <?php foreach ($member['weixinOpenIds'] as $openIdInfo): ?>
                                                <p><span class="label">OpenId：</span><span class="value"><?php echo htmlspecialchars($openIdInfo['openId'] ?? ''); ?></span></p>
                                                <p><span class="label">类型：</span><span class="value"><?php echo htmlspecialchars($openIdInfo['openIdType'] ?? 0); ?></span></p>
                                            <?php endforeach; ?>
                                        </div>
                                    <?php endif; ?>
                                </div>
                            </div>
                        </div>
                    </div>

                    <!-- 修改手机号表单 -->
                    <div style="margin-top: 20px; padding: 15px; background-color: #f8f9fa; border-radius: 6px;">
                        <h3 style="margin-bottom: 15px;">修改手机号</h3>
                        <form method="POST" action="" onsubmit="showLoading('bind-update-loading');">
                            <input type="hidden" name="active_tab" value="bind">
                            <input type="hidden" name="action" value="bind_update_phone">
                            <input type="hidden" name="customer_uid" value="<?php echo htmlspecialchars($bindQueryResult['uid']); ?>">
                            <input type="hidden" name="csrf_token" value="<?php echo generateCsrfToken(); ?>">
                            <div class="form-group">
                                <label for="bind-new-phone">新手机号 <span>*</span></label>
                                <input type="tel" id="bind-new-phone" name="new_phone" required placeholder="请输入新的11位手机号" pattern="^1[3-9]\d{9}$">
                            </div>
                            <button type="submit" class="btn">修改手机号</button>
                        </form>
                        <div id="bind-update-loading" class="result hidden" style="margin-top: 10px;">正在修改手机号，请稍候...</div>
                    </div>
                <?php endif; ?>

                <!-- 操作结果 -->
                <?php if ($operateResult && $activeTab === 'bind'): ?>
                    <div class="result <?php echo $operateResult['status']; ?>" style="margin-top: 15px;">
                        <?php echo htmlspecialchars($operateResult['msg']); ?>
                    </div>
                <?php endif; ?>
            </div>

            <!-- 发放优惠券表单 -->
            <div class="form-section <?php echo $activeTab === 'update' ? 'active' : ''; ?>" id="update-section">
                <form method="POST" action="" onsubmit="showLoading('update-loading');">
                    <input type="hidden" name="active_tab" value="update">
                    <input type="hidden" name="action" value="update">
                    <input type="hidden" name="csrf_token" value="<?php echo generateCsrfToken(); ?>">
                    <div class="form-group">
                        <label for="update-phone">手机号 <span>*</span></label>
                        <input type="tel" id="update-phone" name="phone" value="<?php echo htmlspecialchars($phone); ?>" required placeholder="请输入11位手机号" pattern="^1[3-9]\d{9}$">
                    </div>
                    <div class="form-group">
                        <label for="update-balance">余额变动（元） <span>*</span></label>
                        <input type="number" id="update-balance" name="update_balance" value="<?php echo htmlspecialchars($updateBalance); ?>" required step="0.01" placeholder="正数为充值，负数为扣减">
                    </div>
                    <button type="submit" class="btn">确认修改</button>
                </form>
                <div id="update-loading" class="result hidden" style="margin-top: 10px;">正在修改余额，请稍候...</div>

                <?php if ($operateResult && $activeTab === 'update'): ?>
                    <div class="result <?php echo $operateResult['status']; ?>">
                        <?php echo htmlspecialchars($operateResult['msg']); ?>
                    </div>
                <?php endif; ?>
            </div>

            <!-- 发放优惠券表单 -->
            <div class="form-section <?php echo $activeTab === 'coupon' ? 'active' : ''; ?>" id="coupon-section">
                <form method="POST" action="" onsubmit="showLoading('coupon-loading');">
                    <input type="hidden" name="active_tab" value="coupon">
                    <input type="hidden" name="action" value="send_coupon">
                    <input type="hidden" name="csrf_token" value="<?php echo generateCsrfToken(); ?>">
                    <div class="form-group">
                        <label for="coupon-phone">会员手机号 <span>*</span></label>
                        <input type="tel" id="coupon-phone" name="phone" value="<?php echo htmlspecialchars($phone); ?>" required placeholder="请输入11位手机号" pattern="^1[3-9]\d{9}$">
                    </div>
                    <div class="form-group">
                        <label for="coupon-rule-name">优惠券规则名称 <span>*</span></label>
                        <input type="text" id="coupon-rule-name" name="coupon_rule_name" value="<?php echo htmlspecialchars($couponRuleName); ?>" required placeholder="请输入规则名称关键词">
                    </div>
                    <button type="submit" class="btn">发优惠券</button>
                </form>
                <div id="coupon-loading" class="result hidden" style="margin-top: 10px;">正在发送优惠券，请稍候...</div>

                <?php if ($operateResult && $activeTab === 'coupon'): ?>
                    <div class="result <?php echo $operateResult['status']; ?>">
                        <?php echo htmlspecialchars($operateResult['msg']); ?>
                    </div>
                <?php endif; ?>
            </div>

            <!-- 优惠券规则查询表单 -->
            <div class="form-section <?php echo $activeTab === 'coupon_rules' ? 'active' : ''; ?>" id="coupon_rules-section">
                <form method="POST" action="" class="query-form" onsubmit="showLoading();">
                    <input type="hidden" name="active_tab" value="coupon_rules">
                    <input type="hidden" name="action" value="query_coupon_rules">
                    <input type="hidden" name="csrf_token" value="<?php echo generateCsrfToken(); ?>">
                    <input type="text" name="coupon_rule_keyword" value="<?php echo htmlspecialchars($_POST['coupon_rule_keyword'] ?? ''); ?>" placeholder="请输入规则名称关键字">
                    <button type="submit" class="btn btn-small">查询优惠券规则</button>
                </form>
                <div id="loading提示" class="result hidden" style="margin-top: 10px;">正在查询，请稍候...</div>

                <?php if ($couponRulesResult): ?>
                    <div class="result <?php echo $couponRulesResult['success'] ? 'success' : 'error'; ?>">
                        <?php echo htmlspecialchars($couponRulesResult['msg']); ?>
                        <?php if ($couponRulesResult['success'] && !empty($couponRulesResult['data'])): ?>
                            <div class="member-cards">
                                <?php foreach ($couponRulesResult['data'] as $index => $rule): ?>
                                    <div class="member-card">
                                        <h3>规则 <?php echo $index + 1; ?>：<?php echo htmlspecialchars($rule['name'] ?? ''); ?></h3>
                                        <div class="member-info">
                                            <p><span class="label">规则UID：</span><span class="value"><?php echo htmlspecialchars($rule['promotionCouponUid'] ?? ''); ?></span></p>
                                            <p><span class="label">类型：</span><span class="value">
                                                <?php 
                                                    $couponType = getValue($rule['couponType'], 0);
                                                    $typeMap = [
                                                        10 => '全场抵现券',
                                                        11 => '品类抵现券',
                                                        12 => '单品抵现券',
                                                        15 => '多品抵现券',
                                                        20 => '全场打折券',
                                                        21 => '品类打折券',
                                                        22 => '单品打折券',
                                                        23 => '单品特价券',
                                                        24 => '赠品提货券',
                                                        25 => '多品打折券',
                                                        30 => '免运费券'
                                                    ];
                                                    echo $typeMap[$couponType] ?? '未知类型';
                                                ?>
                                            </span></p>
                                            <p><span class="label">状态：</span><span class="value"><?php echo getValue($rule['enable'], 0) === 1 ? '启用' : '禁用'; ?></span></p>
                                            <p><span class="label">开始时间：</span><span class="value"><?php echo htmlspecialchars($rule['startDate'] ?? '未知'); ?></span></p>
                                            <p><span class="label">结束时间：</span><span class="value"><?php echo htmlspecialchars($rule['endDate'] ?? '未知'); ?></span></p>
                                            <?php if (isset($rule['requireAmount'])): ?>
                                                <p><span class="label">最低消费：</span><span class="value"><?php echo htmlspecialchars($rule['requireAmount'] ?? 0); ?> 元</span></p>
                                            <?php endif; ?>
                                            <?php if (isset($rule['backAmount'])): ?>
                                                <p><span class="label">抵现金额：</span><span class="value"><?php echo htmlspecialchars($rule['backAmount'] ?? 0); ?> 元</span></p>
                                            <?php endif; ?>
                                            <?php if (isset($rule['discount'])): ?>
                                                <p><span class="label">折扣：</span><span class="value"><?php echo htmlspecialchars($rule['discount'] ?? 0); ?> 折</span></p>
                                            <?php endif; ?>
                                            <p><span class="label">实体店可用：</span><span class="value"><?php echo getValue($rule['forRShop'], 0) === 1 ? '是' : '否'; ?></span></p>
                                            <p><span class="label">网店可用：</span><span class="value"><?php echo getValue($rule['forEShop'], 0) === 1 ? '是' : '否'; ?></span></p>
                                            <p><span class="label">会员专享：</span><span class="value"><?php echo getValue($rule['forCustomer'], 0) === 1 ? '是' : '否'; ?></span></p>
                                        </div>
                                    </div>
                                <?php endforeach; ?>
                            </div>
                        <?php endif; ?>
                    </div>
                <?php endif; ?>
            </div>

            <!-- 会员优惠券查询表单 -->
            <div class="form-section <?php echo $activeTab === 'member_coupons' ? 'active' : ''; ?>" id="member_coupons-section">
                <form method="POST" action="" class="query-form" onsubmit="showLoading('member-coupons-loading');">
                    <input type="hidden" name="active_tab" value="member_coupons">
                    <input type="hidden" name="action" value="query_member_coupons">
                    <input type="hidden" name="csrf_token" value="<?php echo generateCsrfToken(); ?>">
                    <input type="tel" name="phone" value="<?php echo htmlspecialchars($phone); ?>" placeholder="请输入会员手机号" required pattern="^1[3-9]\d{9}$">
                    <button type="submit" class="btn btn-small">查询优惠券</button>
                </form>
                <div id="member-coupons-loading" class="result hidden" style="margin-top: 10px;">正在查询，请稍候...</div>

                <?php if (isset($memberCouponsResult)): ?>
                    <div class="result <?php echo $memberCouponsResult['success'] ? 'success' : 'error'; ?>">
                        <?php echo htmlspecialchars($memberCouponsResult['msg']); ?>
                        <?php if ($memberCouponsResult['success'] && $memberCouponsResult['total'] > 0): ?>
                            <div class="member-cards">
                                <?php foreach ($memberCouponsResult['data'] as $index => $coupon): ?>
                                    <div class="member-card">
                                        <h3>优惠券 <?php echo $index + 1; ?></h3>
                                        <div class="member-info">
                                            <p><span class="label">券码：</span><span class="value"><?php echo htmlspecialchars($coupon['code'] ?? ''); ?></span></p>
                                            <p><span class="label">状态：</span><span class="value">未使用</span></p>
                                            <p><span class="label">有效期至：</span><span class="value"><?php echo htmlspecialchars($coupon['promotionCouponEndDate'] ?? '未知'); ?></span></p>
                                            <p><span class="label">优惠券名称：</span><span class="value"><?php echo htmlspecialchars($coupon['promotionCouponName'] ?? ''); ?></span></p>
                                            <p><span class="label">发放时间：</span><span class="value"><?php echo htmlspecialchars($coupon['createdDateTime'] ?? '未知'); ?></span></p>
                                        </div>
                                    </div>
                                <?php endforeach; ?>
                            </div>
                            
                            <!-- 分页控件 -->
                            <?php if ($memberCouponsResult['totalPages'] > 1): ?>
                                <div class="pagination">
                                    <button class="pagination-btn" <?php echo $memberCouponsResult['page'] <= 1 ? 'disabled' : ''; ?>>
                                        上一页
                                    </button>
                                    <span>第 <?php echo $memberCouponsResult['page']; ?> 页 / 共 <?php echo $memberCouponsResult['totalPages']; ?> 页</span>
                                    <span>总记录数：<?php echo $memberCouponsResult['total']; ?></span>
                                    <button class="pagination-btn" <?php echo $memberCouponsResult['page'] >= $memberCouponsResult['totalPages'] ? 'disabled' : ''; ?>>
                                        下一页
                                    </button>
                                </div>
                            <?php endif; ?>
                        <?php endif; ?>
                    </div>
                <?php endif; ?>
            </div>

            <!-- 会员充值记录查询表单 -->
            <div class="form-section <?php echo $activeTab === 'recharge' ? 'active' : ''; ?>" id="recharge-section">
                <form method="POST" action="" class="query-form" onsubmit="showLoading('recharge-loading');">
                    <input type="hidden" name="active_tab" value="recharge">
                    <input type="hidden" name="action" value="query_member_recharge">
                    <input type="hidden" name="csrf_token" value="<?php echo generateCsrfToken(); ?>">
                    <input type="tel" name="phone" value="<?php echo htmlspecialchars($phone); ?>" placeholder="请输入会员手机号" required pattern="^1[3-9]\d{9}$">
                    <button type="submit" class="btn btn-small">查询充值记录</button>
                </form>
                <div id="recharge-loading" class="result hidden" style="margin-top: 10px;">正在查询，请稍候...</div>

                <?php if (isset($rechargeResult)): ?>
                    <div class="result <?php echo $rechargeResult['success'] ? 'success' : 'error'; ?>">
                        <?php echo htmlspecialchars($rechargeResult['msg']); ?>
                        <?php if ($rechargeResult['success'] && $rechargeResult['total'] > 0): ?>
                            <div class="member-cards">
                                <?php foreach ($rechargeResult['data'] as $index => $record): ?>
                                    <div class="member-card">
                                        <h3>充值记录 <?php echo $index + 1; ?></h3>
                                        <div class="member-info">
                                            <p><span class="label">充值金额：</span><span class="value"><?php echo htmlspecialchars($record['amount'] ?? 0); ?> 元</span></p>
                                            <p><span class="label">充值时间：</span><span class="value"><?php echo htmlspecialchars($record['createdDate'] ?? '未知'); ?></span></p>
                                            <p><span class="label">充值方式：</span><span class="value"><?php echo htmlspecialchars($record['paymentMethod'] ?? '未知'); ?></span></p>
                                            <p><span class="label">操作人：</span><span class="value"><?php echo htmlspecialchars($record['operator'] ?? '未知'); ?></span></p>
                                            <p><span class="label">备注：</span><span class="value"><?php echo htmlspecialchars($record['remarks'] ?? ''); ?></span></p>
                                        </div>
                                    </div>
                                <?php endforeach; ?>
                            </div>
                            
                            <!-- 分页控件 -->
                            <?php if ($rechargeResult['totalPages'] > 1): ?>
                                <div class="pagination">
                                    <button class="pagination-btn" <?php echo $rechargeResult['page'] <= 1 ? 'disabled' : ''; ?>>
                                        上一页
                                    </button>
                                    <span>第 <?php echo $rechargeResult['page']; ?> 页 / 共 <?php echo $rechargeResult['totalPages']; ?> 页</span>
                                    <span>总记录数：<?php echo $rechargeResult['total']; ?></span>
                                    <button class="pagination-btn" <?php echo $rechargeResult['page'] >= $rechargeResult['totalPages'] ? 'disabled' : ''; ?>>
                                        下一页
                                    </button>
                                </div>
                            <?php endif; ?>
                        <?php endif; ?>
                    </div>
                <?php endif; ?>
            </div>

            <!-- 系统日志（仅管理员可见） -->
            <?php if ($canSeeLog): ?>
                <div class="form-section <?php echo $activeTab === 'log' ? 'active' : ''; ?>" id="log-section">
                    <form method="POST" action="" class="log-filter-form" onsubmit="showLoading('log-loading');">
                        <input type="hidden" name="active_tab" value="log">
                        <input type="hidden" name="action" value="query_log">
                        <input type="hidden" name="csrf_token" value="<?php echo generateCsrfToken(); ?>">
                        <div class="form-group">
                            <label for="log-start-date">开始日期</label>
                            <input type="date" id="log-start-date" name="log_start_date" value="<?php echo htmlspecialchars($logStartDate); ?>">
                        </div>
                        <div class="form-group">
                            <label for="log-end-date">结束日期</label>
                            <input type="date" id="log-end-date" name="log_end_date" value="<?php echo htmlspecialchars($logEndDate); ?>">
                        </div>
                        <div class="form-group">
                            <label for="log-type">日志类型</label>
                            <select id="log-type" name="log_type" class="form-control">
                                <option value="">全部类型</option>
                                <option value="login" <?php echo $logType === 'login' ? 'selected' : ''; ?>>登录</option>
                                <option value="login_error" <?php echo $logType === 'login_error' ? 'selected' : ''; ?>>登录失败</option>
                                <option value="query" <?php echo $logType === 'query' ? 'selected' : ''; ?>>会员查询</option>
                                <option value="coupon" <?php echo $logType === 'coupon' ? 'selected' : ''; ?>>发优惠券</option>
                                <option value="error" <?php echo $logType === 'error' ? 'selected' : ''; ?>>错误日志</option>
                                <option value="system" <?php echo $logType === 'system' ? 'selected' : ''; ?>>系统操作</option>
                                <option value="logout" <?php echo $logType === 'logout' ? 'selected' : ''; ?>>退出登录</option>
                            </select>
                        </div>
                        <div class="form-group">
                            <label for="log-page">页码</label>
                            <input type="number" id="log-page" name="log_page" value="<?php echo htmlspecialchars($logPage); ?>" min="1">
                        </div>
                        <button type="submit" class="btn btn-small">查询日志</button>
                    </form>
                    <div id="log-loading" class="result hidden" style="margin-top: 10px;">正在查询日志，请稍候...</div>

                    <!-- 日志列表 -->
                    <?php if ($logResult): ?>
                        <?php if (!empty($logResult['logs'])): ?>
                            <table class="log-table">
                                <thead>
                                    <tr>
                                        <th>时间</th>
                                        <th>操作人</th>
                                        <th>IP地址</th>
                                        <th>日志类型</th>
                                        <th>内容</th>
                                    </tr>
                                </thead>
                                <tbody>
                                    <?php foreach ($logResult['logs'] as $log): ?>
                                        <tr>
                                            <td><?php echo htmlspecialchars($log['time']); ?></td>
                                            <td><?php echo htmlspecialchars($log['user']); ?></td>
                                            <td><?php echo htmlspecialchars($log['ip']); ?></td>
                                            <td><?php echo htmlspecialchars($log['type']); ?></td>
                                            <td><?php echo htmlspecialchars($log['content']); ?></td>
                                        </tr>
                                    <?php endforeach; ?>
                                </tbody>
                            </table>

                            <!-- 分页控件 -->
                            <div class="pagination">
                                <button class="pagination-btn" <?php echo $logResult['page'] <= 1 ? 'disabled' : ''; ?>
                                    onclick="document.querySelector('[name=log_page]').value=<?php echo $logResult['page'] - 1; ?>; document.querySelector('.log-filter-form').submit();">
                                    上一页
                                </button>
                                <span>第 <?php echo $logResult['page']; ?> 页 / 共 <?php echo $logResult['totalPages']; ?> 页</span>
                                <span>总记录数：<?php echo $logResult['total']; ?></span>
                                <button class="pagination-btn" <?php echo $logResult['page'] >= $logResult['totalPages'] ? 'disabled' : ''; ?>
                                    onclick="document.querySelector('[name=log_page]').value=<?php echo $logResult['page'] + 1; ?>; document.querySelector('.log-filter-form').submit();">
                                    下一页
                                </button>
                            </div>
                        <?php else: ?>
                            <div class="result">暂无符合条件的日志记录</div>
                        <?php endif; ?>
                    <?php endif; ?>
                </div>
            <?php endif; ?>
        </div>

        <script>
            // 标签页切换
            document.querySelectorAll('.tab').forEach(tab => {
                tab.addEventListener('click', function() {
                    const tabId = this.getAttribute('data-tab');
                    
                    // 更新标签激活状态
                    document.querySelectorAll('.tab').forEach(t => t.classList.remove('active'));
                    this.classList.add('active');
                    
                    // 更新表单区域显示
                    document.querySelectorAll('.form-section').forEach(section => {
                        section.classList.remove('active');
                    });
                    document.getElementById(tabId + '-section').classList.add('active');
                    
                    // 更新表单active_tab值
                    const forms = document.querySelectorAll('form');
                    forms.forEach(form => {
                        const activeTabInput = form.querySelector('[name=active_tab]');
                        if (activeTabInput) {
                            activeTabInput.value = tabId;
                        }
                    });
                });
            });

            // 手机号格式过滤
            const phoneInputs = document.querySelectorAll('input[type=tel]');
            phoneInputs.forEach(input => {
                input.addEventListener('input', function() {
                    this.value = this.value.replace(/[^\d]/g, '');
                    if (this.value.length > 11) {
                        this.value = this.value.substring(0, 11);
                    }
                });
            });

            // 显示加载提示
            function showLoading(elementId = 'loading提示') {
                const loadingElement = document.getElementById(elementId);
                if (loadingElement) {
                    loadingElement.classList.remove('hidden');
                }
            }


        </script>
    <?php endif; ?>
</body>
</html>
