<?php
/*
 * This Source Code Form is subject to the terms of the Mozilla Public
 * License, v. 2.0. If a copy of the MPL was not distributed with this
 * file, You can obtain one at http://mozilla.org/MPL/2.0/.
 */

require __DIR__ . "/../../required.php";


header("Content-Security-Policy: default-src '*';");
header('Access-Control-Allow-Origin: *');

$redirecttologin = false;

// Yeah you'll need to change these if you're using this.
// Sorry about that.
$thisurl = "https://track.netsyms.com/api/login/index.php";
$iconurl = "https://track.netsyms.com/static/img/logo.svg";

/**
 * Show a simple HTML page with a line of text and a button.  Matches the UI of
 * the AccountHub login flow.
 *
 * @global type $SETTINGS
 * @global type $SECURE_NONCE
 * @global type $Strings
 * @param string $title Text to show, passed through i18n
 * @param string $button Button text, passed through i18n
 * @param string $url URL for the button
 */
function showHTML(string $title, string $button = "", string $url = "", string $message = "") {
    global $SETTINGS, $iconurl;
    ?>
    <!DOCTYPE html>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1">

    <title><?php echo $SETTINGS['site_title']; ?></title>

    <link rel="icon" href="<?php echo $iconurl; ?>">

    <link href="https://static.netsyms.net/bootstrap/4/bootstrap.materia.min.css" rel="stylesheet">
    <style>
        .display-5 {
            font-size: 2.5rem;
            font-weight: 300;
            line-height: 1.2;
        }

        .banner-image {
            max-height: 100px;
            margin: 2em auto;
            border: 1px solid grey;
            border-radius: 15%;
        }
    </style>

    <div class="container mt-4">
        <div class="row justify-content-center">
            <div class="col-12 text-center">
                <img class="banner-image" src="<?php echo $iconurl; ?>" />
            </div>

            <div class="col-12 text-center">
                <h1 class="display-5 mb-4"><?php echo $title; ?></h1>
            </div>

            <?php if (!empty($message)) { ?>
                <div class="col-12 col-sm-8 col-lg-6">
                    <div class="card mt-4">
                        <div class="card-body">
                            <p>
                                <?php echo $message; ?>
                            </p>
                        </div>
                    </div>
                </div>
            <?php } ?>

            <?php if (!empty($button)) { ?>
                <div class="col-12 col-sm-8 col-lg-6">
                    <div class="card mt-4">
                        <div class="card-body">
                            <a href="<?php echo $url; ?>" class="btn btn-primary btn-block"><?php echo $button; ?></a>
                        </div>
                    </div>
                </div>
            <?php } ?>
        </div>
    </div>
    <?php
}

if (empty($_SESSION["login_code"])) {
    $redirecttologin = true;
} else {
    try {
        $uidinfo = AccountHubApi::get("checkloginkey", ["code" => $_SESSION["login_code"]]);

        if ($uidinfo["status"] == "ERROR") {
            throw new Exception();
        }
        if (is_numeric($uidinfo['uid'])) {
            $user = new User($uidinfo['uid'] * 1);

            $addpassresp = AccountHubApi::get(
                            "addapppassword",
                            [
                                "desc" => $SETTINGS["site_title"],
                                "username" => $user->getUsername()
                            ],
                            true
            );

            $_SESSION["login_code"] = null;

            $redirecturl = "https://apploginhelper.netsyms.net/?user:" . htmlentities($user->getUsername()) . "&password:" . htmlentities($addpassresp["pass"]);

            header("Location: $redirecturl");
            showHTML("Continue", "Click Here", $redirecturl);
        } else {
            throw new Exception();
        }
    } catch (Exception $ex) {
        $redirecttologin = true;
    }
}

if ($redirecttologin) {
    try {
        $codedata = AccountHubApi::get("getloginkey", ["appname" => $SETTINGS["site_title"], "appicon" => $iconurl], true);

        if ($codedata['status'] != "OK") {
            throw new Exception("There was a problem. Try again later.");
        }

        $_SESSION["login_code"] = $codedata["code"];

        $locationurl = $codedata["loginurl"] . "?code=" . htmlentities($codedata["code"]) . "&redirect=" . htmlentities($thisurl);

        header("Location: $locationurl");
        showHTML("Continue", "Continue", $locationurl);
        die();
    } catch (Exception $ex) {
        showHTML("Error", "", "", $ex->getMessage());
    }
}