<?php

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

// Настройки
$client_id = get_plugin_setting('oauth_yandex', 'client_id');
$client_secret = get_plugin_setting('oauth_yandex', 'client_secret');
$redirect_uri = homeLink() . '/oauth/yandex/auth';

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

    session_start();
    $state = bin2hex(random_bytes(16));
    $_SESSION['ya_state'] = $state;

    $params = [
        'response_type' => 'code',
        'client_id' => $client_id,
        'redirect_uri' => $redirect_uri,
        'state' => $state,
        'scope' => 'login:email login:info'
    ];

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

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

// -----------------------------
// 2. Яндекс вернул code
// -----------------------------
session_start();

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

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

if ($state !== ($_SESSION['ya_state'] ?? null)) {
    exit("Yandex error: state mismatch");
}

// -----------------------------
// 3. Обмен кода на токен
// -----------------------------
$token_url = "https://oauth.yandex.ru/token";

$post = [
    'grant_type' => 'authorization_code',
    'code' => $code,
    'client_id' => $client_id,
    'client_secret' => $client_secret,
    '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("Yandex error: no access_token");
}

$access_token = $token['access_token'];

// -----------------------------
// 4. Получаем профиль через /info
// -----------------------------
$info_url = "https://login.yandex.ru/info?format=json";

$ch = curl_init($info_url);
curl_setopt_array($ch, [
    CURLOPT_RETURNTRANSFER => true,
    CURLOPT_HTTPHEADER => [
        "Authorization: OAuth " . $access_token
    ]
]);

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

$info = json_decode($info_raw, true);

$ya_id = $info['id'] ?? null;
if (!$ya_id) {
    exit("Yandex error: no id");
}

$email = $info['default_email'] ?? null;
if (!$email && !empty($info['emails'][0])) {
    $email = $info['emails'][0];
}

$first = $info['first_name'] ?? 'Yandex';
$last = $info['last_name'] ?? 'User';

$name = trim($first . ' ' . $last);

// -----------------------------
// 5. Логин / регистрация
// -----------------------------
if (!$email) {
    $email = "yandex_" . $ya_id . "@ya.local";
}

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

$oauth_provider = 'yandex';
$oauth_sub = $ya_id;

$us = FetchAssoc(dbquery(
    "SELECT id, login, pass, salt FROM users WHERE oauth_provider = ? AND oauth_sub = ? LIMIT 1",
    [$oauth_provider, $oauth_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 = 'ya' . 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);

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

$uid = InGetLastInsertId();

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