<?php
require_once $_SERVER['DOCUMENT_ROOT'] . '/core/core.php';

// Настройки
$application_id = get_plugin_setting('oauth_vk', 'application_id');
$redirect_uri = homeLink() . '/oauth/vk/auth';

// -----------------------------
// 1. Первый заход → редирект на VK ID
// -----------------------------
if (!isset($_GET['code'])) {

    // Генерируем PKCE
    $code_verifier = bin2hex(random_bytes(64));
    $code_challenge = rtrim(strtr(base64_encode(hash('sha256', $code_verifier, true)), '+/', '-_'), '=');
    $state = bin2hex(random_bytes(16));

    // Сохраняем в сессию
    session_start();
    $_SESSION['vkid_code_verifier'] = $code_verifier;
    $_SESSION['vkid_state'] = $state;

    $params = [
        'response_type' => 'code',
        'client_id' => $application_id,
        'redirect_uri' => $redirect_uri,
        'code_challenge' => $code_challenge,
        'code_challenge_method' => 'S256',
        'state' => $state,
        'scope' => 'vkid.personal_info'
    ];

    $url = "https://id.vk.ru/authorize?" . http_build_query($params);

    header("Location: $url");
    exit;
}

// -----------------------------
// 2. VK ID вернул code
// -----------------------------
session_start();

$code = $_GET['code'] ?? null;
$state = $_GET['state'] ?? null;
$device_id = $_GET['device_id'] ?? null;

if (!$code || !$state || !$device_id) {
    exit("VK ID error: missing parameters");
}

if ($state !== $_SESSION['vkid_state']) {
    exit("VK ID error: state mismatch");
}

$code_verifier = $_SESSION['vkid_code_verifier'];

// -----------------------------
// 3. Обмен кода на токены
// -----------------------------
$token_url = "https://id.vk.ru/oauth2/auth";

$post = [
    'grant_type' => 'authorization_code',
    'client_id' => $application_id,
    'code' => $code,
    'code_verifier' => $code_verifier,
    'device_id' => $device_id,
    'redirect_uri' => $redirect_uri
];

$ch = curl_init($token_url);
curl_setopt_array($ch, [
    CURLOPT_RETURNTRANSFER => true,
    CURLOPT_POST => true,
    CURLOPT_POSTFIELDS => http_build_query($post),
    CURLOPT_HTTPHEADER => ["Content-Type: application/x-www-form-urlencoded"]
]);

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

$token = json_decode($response, true);

if (empty($token['access_token'])) {
    exit("VK ID error: no access_token");
}

$id_token = $token['id_token'];

// -----------------------------
// 4. Получаем профиль через id_token (JWT)
// -----------------------------
$parts = explode('.', $id_token);
$payload = json_decode(base64_decode(strtr($parts[1], '-_', '+/')), true);

$email = $payload['email'] ?? null;
$first = $payload['first_name'] ?? 'VK';
$last = $payload['last_name'] ?? 'User';

$name = trim("$first $last");

// -----------------------------
// 5. Логин / регистрация
// -----------------------------
if (!$email) {
    $email = "vkid_" . $payload['sub'] . "@vk.local";
}

$email = chars($email);
$name = chars($name);

$us = FetchAssoc(dbquery(
    "SELECT id, login, pass, salt FROM users WHERE oauth_provider = 'vkid' AND oauth_sub = ? LIMIT 1",
    [$payload['sub']]
));

if ($us) {
    $login = $us['login'];
    $password = $us['pass'];
    require_once $_SERVER['DOCUMENT_ROOT'] . '/core/elements/autolog.php';
    exit;
}

$login = mb_substr(preg_replace('~[^a-z0-9\-]+~i', '', $first), 0, 13);
if (mb_strlen($login) < 3) {
    $login = 'vkid' . rand(1000, 9999);
}

$exists_login = DataResult(dbquery(
    "SELECT COUNT(id) FROM users WHERE login = ?",
    [$login]
));

if ($exists_login > 0) {
    $login .= '_' . rand(100, 999);
}

$salt = genRandomString(15);
$password = CryptorPass(genRandomString(35), $salt);
$fp = genRandomString(28);
$oauth_provider = 'vkid';
$oauth_sub = $payload['sub'];

create_user($login, $password, $email, $salt, '1', $oauth_sub, $oauth_provider, $fp);

$uid = InGetLastInsertId();

require_once $_SERVER['DOCUMENT_ROOT'] . '/core/elements/autolog.php';
exit;
