<?php
/**
 * 公共函数库
 */

// ========== 网站配置相关 ==========
function getSiteConfig($key = null) {
    global $db;
    static $config = null;
    if ($config === null && isset($db)) {
        $config = [];
        $result = $db->query("SELECT `key`, `value` FROM site_config");
        if ($result) {
            while ($row = $result->fetch_assoc()) {
                $config[$row['key']] = $row['value'];
            }
        }
    }
    if ($key === null) return $config;
    return isset($config[$key]) ? $config[$key] : null;
}

function updateSiteConfig($key, $value) {
    global $db;
    $key = $db->escape($key);
    $value = $db->escape($value);
    return $db->query("REPLACE INTO site_config (`key`, `value`) VALUES ('$key', '$value')");
}

// ========== JSON输出 ==========
function jsonOutput($data) {
    header('Content-Type: application/json');
    echo json_encode($data, JSON_UNESCAPED_UNICODE);
    exit;
}

// ========== 用户相关 ==========
function isLoggedIn() {
    return isset($_SESSION['user_id']);
}

function currentUser() {
    if (!isLoggedIn()) return null;
    global $db;
    $id = intval($_SESSION['user_id']);
    $result = $db->query("SELECT * FROM users WHERE id = $id");
    if ($result && $result->num_rows > 0) {
        $user = $result->fetch_assoc();
        if (!empty($user['permissions'])) {
            $user['permissions'] = json_decode($user['permissions'], true);
        }
        return $user;
    }
    return null;
}

function hasPermission($permission) {
    $user = currentUser();
    if (!$user) return false;
    if ($user['role'] === 'admin') return true;
    if ($user['role'] === 'employee') {
        $perms = $user['permissions'] ?? [];
        // 如果 permissions 是字符串，先解码
        if (is_string($perms)) {
            $perms = json_decode($perms, true);
        }
        return in_array($permission, (array)$perms);
    }
    return false;
}

function isAdmin() {
    $user = currentUser();
    return $user && $user['role'] === 'admin';
}

function isEmployeeOrAdmin() {
    $user = currentUser();
    return $user && in_array($user['role'], ['admin', 'employee']);
}

function requireLogin() {
    if (!isLoggedIn()) {
        redirect(SITE_URL . 'modules/home/login.php');
    }
}

function requireAdmin() {
    if (!isAdmin()) {
        redirect(SITE_URL . 'index.php');
    }
}

function redirect($url) {
    header("Location: $url");
    exit;
}

// ========== 授权码和订单 ==========
function generateLicenseCode() {
    return strtoupper(substr(md5(uniqid(mt_rand(), true)), 0, 16));
}

function generateOrderNo() {
    return date('YmdHis') . mt_rand(10000, 99999);
}

// ========== 用户组相关 ==========
function getUserCurrentGroup($user_id) {
    global $db;
    $sql = "SELECT ug.*, up.expire_date 
            FROM user_group_purchases up 
            JOIN user_groups ug ON up.group_id = ug.id 
            WHERE up.user_id = $user_id 
            AND (up.expire_date IS NULL OR up.expire_date >= CURDATE())
            ORDER BY up.id DESC LIMIT 1";
    $group = $db->fetchOne($sql);
    if (!$group) {
        $default = $db->fetchOne("SELECT * FROM user_groups WHERE price = 0 LIMIT 1");
        if (!$default) {
            $default = ['id' => 0, 'name' => '普通会员', 'discount' => 100];
        }
        return $default;
    }
    return $group;
}

function getDiscountedPrice($app_price, $user_id) {
    $group = getUserCurrentGroup($user_id);
    $discount = $group['discount'] ?? 100;
    return round($app_price * $discount / 100, 2);
}

// ========== 余额相关 ==========
function updateUserBalance($user_id, $amount, $remark = '') {
    global $db;
    $user_id = intval($user_id);
    $amount = floatval($amount);
    $db->query("UPDATE users SET balance = balance + $amount WHERE id = $user_id");
    $type = $amount > 0 ? 'recharge' : 'consume';
    $remark = $db->escape($remark);
    $db->query("INSERT INTO balance_logs (user_id, amount, type, remark) VALUES ($user_id, $amount, '$type', '$remark')");
}

function addBalanceLog($user_id, $amount, $type, $remark = '') {
    global $db;
    $user_id = intval($user_id);
    $amount = floatval($amount);
    $type = $db->escape($type);
    $remark = $db->escape($remark);
    $db->query("INSERT INTO balance_logs (user_id, amount, type, remark) VALUES ($user_id, $amount, '$type', '$remark')");
}

// ========== 链接相关 ==========
function getHeaderLinks() {
    global $db;
    return $db->fetchAll("SELECT name, url FROM links WHERE type='header' AND status=1 ORDER BY sort ASC");
}

function getFriendLinks() {
    global $db;
    return $db->fetchAll("SELECT name, url FROM links WHERE type='friend' AND status=1 ORDER BY sort ASC");
}

// ========== 统计相关 ==========
function getUserAppsCount($user_id) {
    global $db;
    $result = $db->query("SELECT COUNT(DISTINCT app_id) as cnt FROM licenses WHERE user_id = $user_id AND status = 1");
    $row = $result->fetch_assoc();
    return $row['cnt'] ?? 0;
}

function getUserLicensesCount($user_id) {
    global $db;
    $result = $db->query("SELECT COUNT(*) as cnt FROM licenses WHERE user_id = $user_id AND status = 1");
    $row = $result->fetch_assoc();
    return $row['cnt'] ?? 0;
}

function getUserOpenTicketsCount($user_id) {
    global $db;
    $result = $db->query("SELECT COUNT(*) as cnt FROM tickets WHERE user_id = $user_id AND status IN ('open','processing')");
    $row = $result->fetch_assoc();
    return $row['cnt'] ?? 0;
}

// ========== 支付方式相关 ==========
function getEnabledPaymentMethods() {
    $pay_config = json_decode(getSiteConfig('payment_config') ?? '{}', true);
    $methods = [];
    if (($pay_config['pay_alipay'] ?? 1) == 1) $methods[] = ['value' => 'alipay', 'name' => '支付宝'];
    if (($pay_config['pay_wxpay'] ?? 1) == 1) $methods[] = ['value' => 'wxpay', 'name' => '微信支付'];
    return $methods;
}

// ========== 分页 ==========
function paginate($total, $page, $perpage = 20, $url = '?') {
    $totalPages = ceil($total / $perpage);
    $page = max(1, min($page, $totalPages));
    $offset = ($page - 1) * $perpage;
    return [
        'total' => $total,
        'page' => $page,
        'perpage' => $perpage,
        'totalPages' => $totalPages,
        'offset' => $offset,
        'prev' => $page > 1 ? $url . 'page=' . ($page - 1) : null,
        'next' => $page < $totalPages ? $url . 'page=' . ($page + 1) : null,
    ];
}
// 获取客户端真实IP
function getClientIP() {
    if (isset($_SERVER['HTTP_CF_CONNECTING_IP'])) {
        return $_SERVER['HTTP_CF_CONNECTING_IP'];
    }
    if (isset($_SERVER['HTTP_X_FORWARDED_FOR'])) {
        $ip = $_SERVER['HTTP_X_FORWARDED_FOR'];
        return explode(',', $ip)[0];
    }
    if (isset($_SERVER['HTTP_CLIENT_IP'])) {
        return $_SERVER['HTTP_CLIENT_IP'];
    }
    return $_SERVER['REMOTE_ADDR'] ?? 'unknown';
}

// 获取IP所在城市（使用淘宝IP库）
function getIPCity($ip) {
    if ($ip == '127.0.0.1' || $ip == 'localhost' || $ip == 'unknown') {
        return '本地';
    }
    
    // 使用淘宝IP库
    $url = "http://ip.taobao.com/outGetIpInfo?ip={$ip}&accessKey=alibaba-inc";
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, $url);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ch, CURLOPT_TIMEOUT, 3);
    $response = curl_exec($ch);
    curl_close($ch);
    
    $data = json_decode($response, true);
    if ($data && $data['code'] == 0) {
        $country = $data['data']['country'] ?? '';
        $region = $data['data']['region'] ?? '';
        $city = $data['data']['city'] ?? '';
        return trim($country . ' ' . $region . ' ' . $city);
    }
    return '未知位置';
}

// 获取设备信息
function getDeviceInfo($user_agent) {
    if (strpos($user_agent, 'iPhone') !== false) return 'iPhone';
    if (strpos($user_agent, 'iPad') !== false) return 'iPad';
    if (strpos($user_agent, 'Android') !== false) return 'Android';
    if (strpos($user_agent, 'Windows NT') !== false) return 'Windows电脑';
    if (strpos($user_agent, 'Macintosh') !== false) return 'Mac电脑';
    if (strpos($user_agent, 'Linux') !== false) return 'Linux电脑';
    return '未知设备';
}
// ========== 增强的设备信息检测 ==========
function getDetailedDeviceInfo($user_agent) {
    $result = [
        'browser' => '未知浏览器',
        'device' => '未知设备',
        'device_model' => '',
        'full' => ''
    ];
    
    // ========== 检测浏览器 ==========
    if (strpos($user_agent, 'Edg/') !== false) {
        $result['browser'] = 'Edge';
    } elseif (strpos($user_agent, 'Chrome/') !== false && strpos($user_agent, 'Edg') === false) {
        $result['browser'] = 'Chrome';
    } elseif (strpos($user_agent, 'Firefox/') !== false) {
        $result['browser'] = 'Firefox';
    } elseif (strpos($user_agent, 'Safari/') !== false && strpos($user_agent, 'Chrome') === false) {
        $result['browser'] = 'Safari';
    } elseif (strpos($user_agent, 'OPR/') !== false || strpos($user_agent, 'Opera/') !== false) {
        $result['browser'] = 'Opera';
    } elseif (strpos($user_agent, 'MSIE') !== false || strpos($user_agent, 'Trident/') !== false) {
        $result['browser'] = 'IE';
    } elseif (strpos($user_agent, 'QQBrowser/') !== false) {
        $result['browser'] = 'QQ浏览器';
    } elseif (strpos($user_agent, 'UCBrowser/') !== false) {
        $result['browser'] = 'UC浏览器';
    } elseif (strpos($user_agent, 'MicroMessenger') !== false) {
        $result['browser'] = '微信';
    }
    
    // ========== 检测设备型号 ==========
    // 小米/红米系列
    if (preg_match('/Redmi\s+(\w+)/i', $user_agent, $match)) {
        $result['device'] = '红米 ' . $match[1];
        $result['device_model'] = 'Redmi ' . $match[1];
    } elseif (preg_match('/Redmi(\w+)/i', $user_agent, $match)) {
        $result['device'] = '红米 ' . $match[1];
        $result['device_model'] = 'Redmi ' . $match[1];
    } elseif (preg_match('/Mi\s+(\w+)/i', $user_agent, $match)) {
        $result['device'] = '小米 ' . $match[1];
        $result['device_model'] = 'Xiaomi ' . $match[1];
    } elseif (preg_match('/Xiaomi\s+(\w+)/i', $user_agent, $match)) {
        $result['device'] = '小米 ' . $match[1];
        $result['device_model'] = 'Xiaomi ' . $match[1];
    } elseif (preg_match('/MIX\s+(\w+)/i', $user_agent, $match)) {
        $result['device'] = '小米MIX ' . $match[1];
        $result['device_model'] = 'Xiaomi MIX ' . $match[1];
    } elseif (preg_match('/POCO\s+(\w+)/i', $user_agent, $match)) {
        $result['device'] = 'POCO ' . $match[1];
        $result['device_model'] = 'POCO ' . $match[1];
    }
    // 华为系列
    elseif (preg_match('/HUAWEI\s+(\w+)/i', $user_agent, $match)) {
        $result['device'] = '华为 ' . $match[1];
        $result['device_model'] = 'HUAWEI ' . $match[1];
    } elseif (preg_match('/HW-(\w+)/i', $user_agent, $match)) {
        $result['device'] = '华为 ' . $match[1];
        $result['device_model'] = 'HUAWEI ' . $match[1];
    } elseif (preg_match('/Honor\s+(\w+)/i', $user_agent, $match)) {
        $result['device'] = '荣耀 ' . $match[1];
        $result['device_model'] = 'Honor ' . $match[1];
    }
    // OPPO/一加系列
    elseif (preg_match('/OPPO\s+(\w+)/i', $user_agent, $match)) {
        $result['device'] = 'OPPO ' . $match[1];
        $result['device_model'] = 'OPPO ' . $match[1];
    } elseif (preg_match('/OnePlus\s+(\w+)/i', $user_agent, $match)) {
        $result['device'] = '一加 ' . $match[1];
        $result['device_model'] = 'OnePlus ' . $match[1];
    }
    // vivo/iQOO系列
    elseif (preg_match('/vivo\s+(\w+)/i', $user_agent, $match)) {
        $result['device'] = 'vivo ' . $match[1];
        $result['device_model'] = 'vivo ' . $match[1];
    } elseif (preg_match('/iQOO\s+(\w+)/i', $user_agent, $match)) {
        $result['device'] = 'iQOO ' . $match[1];
        $result['device_model'] = 'iQOO ' . $match[1];
    }
    // 三星系列
    elseif (preg_match('/SM-([A-Z]\d+)/i', $user_agent, $match)) {
        $result['device'] = '三星 ' . $match[1];
        $result['device_model'] = 'Samsung ' . $match[1];
    } elseif (preg_match('/Samsung\s+(\w+)/i', $user_agent, $match)) {
        $result['device'] = '三星 ' . $match[1];
        $result['device_model'] = 'Samsung ' . $match[1];
    }
    // iPhone系列
    elseif (strpos($user_agent, 'iPhone') !== false) {
        if (preg_match('/iPhone(\d+,\d+)/', $user_agent, $match)) {
            $model_map = [
                '17,1' => 'iPhone 15 Pro', '17,2' => 'iPhone 15 Pro Max', '17,3' => 'iPhone 15',
                '17,4' => 'iPhone 15 Plus', '16,1' => 'iPhone 14 Pro', '16,2' => 'iPhone 14 Pro Max',
                '16,3' => 'iPhone 14', '16,4' => 'iPhone 14 Plus', '15,2' => 'iPhone 13 Pro',
                '15,3' => 'iPhone 13 Pro Max', '15,4' => 'iPhone 13', '15,5' => 'iPhone 13 mini',
                '14,2' => 'iPhone 12 Pro', '14,3' => 'iPhone 12 Pro Max', '14,4' => 'iPhone 12 mini',
                '14,5' => 'iPhone 12', '13,1' => 'iPhone 11', '13,2' => 'iPhone 11 Pro',
                '13,3' => 'iPhone 11 Pro Max', '12,1' => 'iPhone XR', '12,3' => 'iPhone XS',
                '12,5' => 'iPhone XS Max', '11,2' => 'iPhone X', '11,8' => 'iPhone 8',
                '11,6' => 'iPhone 8 Plus', '9,1' => 'iPhone 7', '9,3' => 'iPhone 7',
                '9,2' => 'iPhone 7 Plus', '9,4' => 'iPhone 7 Plus', '8,1' => 'iPhone 6s',
                '8,2' => 'iPhone 6s Plus',
            ];
            $result['device'] = $model_map[$match[1]] ?? 'iPhone';
            $result['device_model'] = $result['device'];
        } else {
            $result['device'] = 'iPhone';
            $result['device_model'] = 'iPhone';
        }
    }
    // iPad系列
    elseif (strpos($user_agent, 'iPad') !== false) {
        $result['device'] = 'iPad';
        $result['device_model'] = 'iPad';
    }
    // 通用安卓设备
    elseif (strpos($user_agent, 'Android') !== false && strpos($user_agent, 'Mobile') !== false) {
        if ($result['device'] == '未知设备') {
            $result['device'] = '安卓手机';
            $result['device_model'] = 'Android Phone';
        }
    }
    // 电脑设备
    elseif (strpos($user_agent, 'Windows NT') !== false) {
        $result['device'] = '电脑';
        $result['device_model'] = 'PC';
    } elseif (strpos($user_agent, 'Macintosh') !== false) {
        $result['device'] = 'Mac电脑';
        $result['device_model'] = 'Mac';
    } elseif (strpos($user_agent, 'Linux') !== false) {
        $result['device'] = 'Linux电脑';
        $result['device_model'] = 'Linux PC';
    }
    
    // 组合完整信息（设备型号 + 浏览器）
    $result['full'] = $result['device'] . ' · ' . $result['browser'];
    
    return $result;
}
// 检查登录失败限制
function checkLoginLimit($ip) {
    global $db;
    
    // 清理过期的锁定记录（超过锁定时间）
    $db->query("DELETE FROM login_fail_log WHERE lock_until IS NOT NULL AND lock_until < NOW()");
    
    $record = $db->fetchOne("SELECT * FROM login_fail_log WHERE ip = '$ip' AND lock_until > NOW()");
    
    if ($record) {
        $lock_until = new DateTime($record['lock_until']);
        $now = new DateTime();
        $remaining = $now->diff($lock_until);
        $minutes = $remaining->i + 1;
        return [
            'locked' => true,
            'remaining_minutes' => $minutes,
            'message' => "登录失败次数过多，请 {$minutes} 分钟后重试"
        ];
    }
    
    return ['locked' => false];
}

// 记录登录失败
function recordLoginFail($ip, $username = '') {
    global $db;
    
    $record = $db->fetchOne("SELECT * FROM login_fail_log WHERE ip = '$ip' AND (lock_until IS NULL OR lock_until < NOW())");
    
    if ($record) {
        $new_count = $record['fail_count'] + 1;
        $lock_until = null;
        
        // 连续失败5次，锁定15分钟
        if ($new_count >= 5) {
            $lock_until = date('Y-m-d H:i:s', strtotime('+15 minutes'));
            $message = "登录失败次数过多，已锁定15分钟";
        } else {
            $message = "登录失败，还剩 " . (5 - $new_count) . " 次尝试机会";
        }
        
        $db->query("UPDATE login_fail_log SET fail_count = $new_count, last_fail_time = NOW(), lock_until = " . ($lock_until ? "'$lock_until'" : "NULL") . " WHERE ip = '$ip'");
        
        return [
            'fail_count' => $new_count,
            'remaining' => 5 - $new_count,
            'locked' => $lock_until !== null,
            'lock_until' => $lock_until,
            'message' => $message
        ];
    } else {
        // 新增记录
        $db->query("INSERT INTO login_fail_log (ip, username, fail_count, last_fail_time) VALUES ('$ip', '" . addslashes($username) . "', 1, NOW())");
        
        return [
            'fail_count' => 1,
            'remaining' => 4,
            'locked' => false,
            'message' => "登录失败，还剩 4 次尝试机会"
        ];
    }
}

// 登录成功后清除失败记录
function clearLoginFail($ip) {
    global $db;
    $db->query("DELETE FROM login_fail_log WHERE ip = '$ip'");
}

/**
 * 从数据库获取树形导航菜单
 * @param object $db 数据库实例
 * @return array 树形菜单数组
 */
function getNavMenus($db) {
    $allLinks = $db->fetchAll("
        SELECT * FROM links 
        WHERE type = 'header' AND status = 1 
        ORDER BY parent_id ASC, sort ASC
    ");
    
    $menus = [];
    $childrenMap = [];
    
    foreach ($allLinks as $link) {
        $parentId = $link['parent_id'] ?? 0;
        if ($parentId == 0) {
            $menus[$link['id']] = [
                'id' => $link['id'],
                'name' => $link['name'],
                'url' => $link['url'],
                'children' => []
            ];
        } else {
            if (!isset($childrenMap[$parentId])) {
                $childrenMap[$parentId] = [];
            }
            $childrenMap[$parentId][] = [
                'name' => $link['name'],
                'url' => $link['url']
            ];
        }
    }
    
    foreach ($menus as $id => &$menu) {
        if (isset($childrenMap[$id])) {
            $menu['children'] = $childrenMap[$id];
        }
    }
    
    return array_values($menus);
}
?>