<?php
ob_start();
require_once dirname(__DIR__) . '/config.php';
require_once dirname(__DIR__) . '/includes/github_config.php';
require_once dirname(__DIR__) . '/includes/functions.php';

$config = getGithubConfig();

session_start();

$state = $_GET['state'] ?? '';
if ($state !== ($_SESSION['github_state'] ?? '')) {
    die('State 验证失败，请重试');
}
unset($_SESSION['github_state']);

$code = $_GET['code'] ?? '';
if (empty($code)) die('授权失败');

$ch = curl_init('https://github.com/login/oauth/access_token');
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query([
    'client_id'     => $config['client_id'],
    'client_secret' => $config['client_secret'],
    'code'          => $code,
    'redirect_uri'  => $config['redirect_uri'],
]));
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, ['Accept: application/json']);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
$response = curl_exec($ch);
curl_close($ch);

$tokenData = json_decode($response, true);
$accessToken = $tokenData['access_token'] ?? '';
if (empty($accessToken)) die('Token 获取失败');

$ch = curl_init('https://api.github.com/user');
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, ['Authorization: token ' . $accessToken, 'User-Agent: App']);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
$githubUser = json_decode(curl_exec($ch), true);
curl_close($ch);

$email = $githubUser['email'] ?? '';
if (empty($email)) {
    $ch = curl_init('https://api.github.com/user/emails');
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ch, CURLOPT_HTTPHEADER, ['Authorization: token ' . $accessToken, 'User-Agent: App']);
    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
    $emails = json_decode(curl_exec($ch), true);
    curl_close($ch);
    foreach ($emails as $e) {
        if ($e['primary'] && $e['verified']) { $email = $e['email']; break; }
    }
}

$openid = $githubUser['id'];
$nickname = $githubUser['login'] ?? 'GitHub用户';
$avatar = $githubUser['avatar_url'] ?? '';
$ip = $_SERVER['REMOTE_ADDR'] ?? 'unknown';

$existing = $db->fetchOne("SELECT * FROM users WHERE union_id = '$openid' AND union_type = 'github'");
if (!$existing) {
    $b = $db->fetchOne("SELECT user_id FROM user_oauth_bindings WHERE oauth_type = 'github' AND openid = '$openid'");
    if ($b) $existing = $db->fetchOne("SELECT * FROM users WHERE id = {$b['user_id']}");
}
if (!$existing && !empty($email)) {
    $existing = $db->fetchOne("SELECT * FROM users WHERE email = '$email'");
    if ($existing) {
        $db->query("UPDATE users SET union_id = '$openid', union_type = 'github', avatar_url = '$avatar' WHERE id = {$existing['id']}");
        $db->query("INSERT INTO user_oauth_bindings (user_id, oauth_type, openid, nickname, avatar) VALUES ({$existing['id']}, 'github', '$openid', '$nickname', '$avatar') ON DUPLICATE KEY UPDATE nickname = '$nickname', avatar = '$avatar'");
    }
}

if ($existing) {
    clearLoginFail($ip);
    $_SESSION['user_id'] = $existing['id'];
    $_SESSION['username'] = $existing['username'];
    $_SESSION['role'] = $existing['role'];
    header('Location: ' . SITE_URL . 'admin.php');
    exit;
}

$username = $nickname;
if ($db->fetchOne("SELECT id FROM users WHERE username = '$username'")) $username .= '_' . $openid;
$hashed = password_hash(bin2hex(random_bytes(16)), PASSWORD_DEFAULT);
$db->query("INSERT INTO users (username, password, email, union_id, union_type, avatar_url, role, status, is_oauth_user, need_change_password) VALUES ('$username', '$hashed', '$email', '$openid', 'github', '$avatar', 'user', 1, 1, 0)");
$uid = $db->insertId();
if ($uid) {
    $db->query("INSERT INTO user_oauth_bindings (user_id, oauth_type, openid, nickname, avatar) VALUES ($uid, 'github', '$openid', '$nickname', '$avatar')");
    $_SESSION['user_id'] = $uid;
    $_SESSION['username'] = $username;
    $_SESSION['role'] = 'user';
    $_SESSION['should_change_password'] = true;
    header('Location: ' . SITE_URL . 'admin.php');
    exit;
}
die('登录失败');