<?php

function is_admin_login() {
    // 首先检查SESSION中的管理员登录状态
    if (isset($_SESSION['admin_user']) && !empty($_SESSION['admin_user'])) {
        return $_SESSION['admin_user'];
    }
    
    // 然后检查cookie中的admin_token
    if (!isset($_COOKIE['admin_token'])) {
        return false;
    }
    $token = $_COOKIE['admin_token'];
    $code = authcode($token, 'DECODE', SYS_KEY);
    if (!$code) {
        return false;
    }
    $arr = explode("\t", $code);
    if (count($arr) != 2) {
        return false;
    }
    global $conf, $password_hash;
    $session = md5($arr[0] . $conf['pwd'] . $password_hash);
    if ($arr[1] != $session) {
        return false;
    }
    // 验证通过，同步到SESSION
    $_SESSION['admin_user'] = $arr[0];
    $_SESSION['admin_login_time'] = time();
    return $arr[0];
}

function is_user_login() {
    // 调试日志已禁用
    $debug_log = function($msg) {
        // 不记录任何日志
        return;
    };

    if (!isset($_COOKIE['user_token'])) {
        return false;
    }
    $token = $_COOKIE['user_token'];
    
    $code = authcode($token, 'DECODE', SYS_KEY);
    
    if (!$code) {
        return false;
    }
    $arr = explode("\t", $code);
    
    if (count($arr) != 2) {
        return false;
    }
    global $DB, $password_hash, $conf;
    
    $zj = $DB->get_row("SELECT * FROM `zj` WHERE `user`='{$arr[0]}'");
    
    if (!$zj) {
        return false;
    }
    $session = md5($arr[0] . $zj['pass'] . $password_hash);
    
    if ($arr[1] != $session) {
        return false;
    }
    
    if ($conf['kzmbqk'] != 'true') {
        return false;
    }
    if ($zj['zt'] == '已过期') {
        return false;
    }
    if ($zj['zt'] == '已禁用') {
        return false;
    }
    if ($zj['zt'] == '已暂停') {
        return false;
    }
    
    // 记录用户登录地区
    record_user_login_region($zj);
    
    return $zj;
}

/**
 * 记录用户登录地区
 * @param array $user 用户信息
 */
function record_user_login_region($user) {
    global $DB;
    
    // 获取用户IP
    $ip = get_client_ip();
    if (empty($ip) || $ip == '127.0.0.1' || $ip == 'localhost') {
        return;
    }
    
    // 检查表是否存在
    $table_exists = $DB->query("SHOW TABLES LIKE 'user_login_region'");
    if (!$table_exists || $DB->num_rows($table_exists) == 0) {
        return;
    }
    
    // 根据IP获取地区（使用淘宝IP地址库或IP138）
    $region = get_ip_region($ip);
    
    // 检查今天是否已记录
    $today = date('Y-m-d');
    $user_id_escaped = intval($user['id']);
    $username_escaped = $DB->escape($user['user']);
    $ip_escaped = $DB->escape($ip);
    $region_escaped = $DB->escape($region);
    $existing = $DB->get_row("SELECT * FROM `user_login_region` WHERE `user_id`='{$user_id_escaped}' AND `ip`='{$ip_escaped}' AND DATE(`login_time`)='{$today}'");
    
    if (!$existing) {
        // 插入新记录
        $DB->query("INSERT INTO `user_login_region` (`user_id`, `username`, `ip`, `region`, `login_time`) VALUES ('{$user_id_escaped}', '{$username_escaped}', '{$ip_escaped}', '{$region_escaped}', NOW())");
    }
}

/**
 * 根据IP获取地区
 * @param string $ip IP地址
 * @return string 地区名称
 */
function get_ip_region($ip) {
    // 使用 ip-api.com 查询IP地区（免费，无需key）
    $url = "http://ip-api.com/json/{$ip}?lang=zh-CN";

    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, $url);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ch, CURLOPT_TIMEOUT, 5);
    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);

    $response = curl_exec($ch);
    curl_close($ch);

    if ($response) {
        $data = json_decode($response, true);
        if ($data && $data['status'] == 'success' && isset($data['regionName'])) {
            $region = $data['regionName'] ?? '';
            // 去掉"省"、"市"后缀，返回简称
            $region = str_replace(['省', '市', '自治区', '特别行政区', '回族', '维吾尔', '壮族'], '', $region);
            return $region;
        }
    }

    return '';
}

/**
 * 获取客户端IP
 * @return string IP地址
 */
function get_client_ip() {
    $ip = '';
    if (isset($_SERVER['HTTP_X_FORWARDED_FOR'])) {
        $ip = $_SERVER['HTTP_X_FORWARDED_FOR'];
    } elseif (isset($_SERVER['HTTP_CLIENT_IP'])) {
        $ip = $_SERVER['HTTP_CLIENT_IP'];
    } elseif (isset($_SERVER['REMOTE_ADDR'])) {
        $ip = $_SERVER['REMOTE_ADDR'];
    }
    return $ip;
}

function check_admin() {
    $admin = is_admin_login();
    if (!$admin) {
        header('Location: /admin/login.php');
        exit;
    }
    return $admin;
}

function check_user() {
    $user = is_user_login();
    if (!$user) {
        header('Location: /user/login.php');
        exit;
    }
    return $user;
}
?>
