<?php

session_start();

require __DIR__ . '/vendor/autoload.php';

if (empty($_GET['code'])) { //Auth token received by pnut
    // TODO: Handle auth errors
    die("Error authenticating, did not receive a code");
}

if (!empty($_GET['type'])) {
} else {
    $config = include __DIR__ . '/config.php';
    $internal_pics_dir = __DIR__ . $config['pics_dir'];
    $app = new Phlaym\Roastmonday\Roastmonday($config, $internal_pics_dir);
}
$success = $app->authenticate($_GET['code']);
if ($success) {
    if (!empty($_SESSION[$app->app_name . 'redirect_after_auth'])) {
        $url = $_SESSION[$app->app_name . 'redirect_after_auth'];
        header("Location: " . $url);
        echo('<script>console.debug("Authentication successful!");</script>');
        echo '<meta http-equiv="refresh" content="0;url=' . $url . '">';
        echo '<script>window.location.replace("'
        . $url
        . '");</script>Redirecting to <a href="'
        . $url
        . '">'
        . $url
        . '</a>';
    } else {
        die('Succesfully authorized!');
    }
} else {
    die("Error authenticating");
}
