<?php

require_once __DIR__ . '/../inc/bootstrap.php';

if (isset($_GET['code'])) {
    $auth = base64_encode(YANDEX_CLIENT_ID . ':' . YANDEX_CLIENT_SECRET);
    $headers = ['Authorization: Basic ' . $auth];
    $url = 'https://oauth.yandex.ru/token';
    $data = [
        'grant_type' => 'authorization_code',
        'code'       => $_GET['code'],
    ];
    $response = YandexIoT::sendRequest($url, $headers, $data);
    if (isset($response['access_token'])) {
        $response['expires'] = $response['expires_in'] + time();
        if (file_put_contents(STORAGE_YANDEX_FILE, json_encode($response, JSON_THROW_ON_ERROR))) {
            echo 'Success';
        }
        die();
    }
}

header('Location: https://oauth.yandex.ru/authorize?response_type=code&client_id=' . YANDEX_CLIENT_ID . '&force_confirm=yes&scope=iot:view%20iot:control');
