<?php
	error_reporting(E_ALL ^ E_NOTICE);

	include_once('../include/lucidAuth.functions.php');

    // Start with checking $_REQUEST['ref']
	if (!empty($_REQUEST['ref'])) {
		try {
			$queryString = json_decode(base64_decode($_REQUEST['ref']), JSON_OBJECT_AS_ARRAY);
		}
		catch (Exception $e) {
			// Silently fail, unless explicitly specified otherwise
            header("HTTP/1.1 400 Bad Request");
			if ($settings->Debug['Verbose']) throw new Exception($e);
            exit;
		}

        switch ($queryString['action']) {
            case 'login':
                if (validateToken($queryString['token'])['status'] === "Success") {
                    // This request appears valid; try storing a cookie
                    $httpHost = $_SERVER['HTTP_HOST'];
                    $httpOrigin = $_SERVER['HTTP_ORIGIN'];
                    // Check if $_SERVER['HTTP_HOST'] and $_SERVER['HTTP_ORIGIN'] match any of the configured domains (either explicitly or as a subdomain)
                    //   This might seem backwards, but relying on $_SERVER directly allows spoofed values with potential security risks
                    $cookieDomain = array_values(array_filter($settings->Session['CookieDomains'], function ($value) use ($httpHost) {
                        return (strlen($value) > strlen($httpHost)) ? false : (0 === substr_compare($httpHost, $value, -strlen($value)));
                    }))[0];
                    $originDomain = array_values(array_filter($settings->Session['CookieDomains'], function ($value) use ($httpOrigin) {
                        return (strlen($value) > strlen($httpOrigin)) ? false : (0 === substr_compare($httpOrigin, $value, -strlen($value)));
                    }))[0];
                    if (($cookieDomain && (is_null($httpOrigin) || $originDomain)) && setcookie('JWT', $queryString['token'], (time() + $settings->Session['Duration']), '/', '.' . $cookieDomain)) {
                        header("Access-Control-Allow-Origin: {$_SERVER['HTTP_ORIGIN']}");
                        header('Access-Control-Allow-Credentials: true');
                        header('Access-Control-Max-Age: 86400');
                        header("HTTP/1.1 202 Accepted");
                        exit;
                    }
                    else {
                        header("HTTP/1.1 400 Bad Request");
                        exit;
                    }
                }
                else {
                    header("HTTP/1.1 401 Unauthorized");
                    exit;
                }
                break;
            default:
                header("HTTP/1.1 400 Bad Request");
                exit;
                break;
        }
	}
    else {
        header("HTTP/1.1 400 Bad Request");
        exit;
    }
?>