<?php
/*
Usage
	Endpoint: https://unloze.com/api/private_user_upgrade_api.php
	Query strings:
		api_key		- Required: Should be set to the secret API key
		provider	- Optional: Should be set to the wanted provider. Defaults to a default provider.
		<id query>	- Required: A respective ID query string should be set. E.g. the Steam provider requires a "steam_id" query string.
        days_amount - Required: The amount of days to give as userUpgrade. this is related to event rewards.
*/

// --- CONFIG START ---
// API key for authorization
$api_key = "";

// Provider name with given query string
$provider_config = array(
	"th_cap_steam" => "steam_id",
	"minecraft" => "uuid"
);

// For backwards compatibility
$default_provider = "th_cap_steam";

// Responses
$response_error_apikey = 'API KEY INVALID';
$response_no_account_associated = 'NOACCOUNT';
$response_group_none = 'NOGROUP';
$response_error_id = 'MISSING ID';



// --- CONFIG END ---

// TODO: Use single query string for ID?

// Prints the reason and exits.
function quitWithReason($reason, $status_code = 200){
	
	http_response_code($status_code);
	echo $reason;
	die;
}

function debug_to_console($data) {
    $output = $data;
    if (is_array($output))
        $output = implode(',', $output);
    echo "<script>console.log('Debug Objects: " . $output . "' );</script>";
}


// Check the API key
if(!isset($_GET['api_key']) || $_GET['api_key'] !== $api_key){
	quitWithReason($response_error_apikey, 401);
}


// Load XenForo stuffs
require ('bootstrap_user_upgrade.php');

// Fetch provider from query string. If none is found, use the default provider.
$provider = isset($_GET['provider']) ? $_GET['provider'] : $default_provider;


$days_reward = $_GET['days_reward'];

//debug_to_console("$days_reward"); //will always be set.

// Check if the given provider has been configured
if(!array_key_exists($provider, $provider_config)){
	quitWithReason($response_error_provider, 404);
}

// Check if the ID is set.
if(!isset($_GET[$provider_config[$provider]])){
	quitWithReason($response_error_id, 404);
}


// Fetch the respective ID query string.
$provider_key = $_GET[$provider_config[$provider]];

// Use finder for external accounts
$connectedAccountFinder = \XF::finder('XF:UserConnectedAccount');

// Search for external accounts with the given provider and ID
$stAssoc = $connectedAccountFinder->where('provider', $provider)->where('provider_key', $provider_key)->fetchOne();

// If no account is associated to the steam account return NOACCOUNT
if(empty($stAssoc)){
	quitWithReason($response_no_account_associated, 500);
}

// Load XenForo model for users
$userFinder = \XF::finder('XF:User');

// Fetch the user from the external account entry
$user = $userFinder->where('user_id', $stAssoc->user_id)->fetchOne();

// (This should not happen) If no user is found, assign no group.
if(empty($user)){
	// Push error to XenForo error log.
	trigger_error("External account association exists for non-existing user ID (" . $stAssoc->user_id . ").");
	quitWithReason($response_group_none, 500);
}

//debug_to_console("$stAssoc->user_id");

// Get UserUpgrade Information
$upgradeFinder = \XF::finder('XF:UserUpgrade');
$userUpgrade = $upgradeFinder->where('user_upgrade_id', 1)->fetchOne(); //its 1 because it should not matter which userupgrade we pick. its actually 1 month vip.

//debug_to_console("$user");

//before upgrading the user lets confirm if they already have a running vip duration. if they do we update it instead of creating a new one.
// Get Active Upgrade Information
$userUpgradeActiveFinder = \XF::Finder('XF:UserUpgradeActive');
$activeUserUpgrades = $userUpgradeActiveFinder->where('user_id', $stAssoc->user_id)->fetchOne();
//debug_to_console("$activeUserUpgrades");

if (isset($activeUserUpgrades))
{
    debug_to_console("has user upgrade");
    $userUpgrade_new = $activeUserUpgrades->Upgrade;
    $expireDate = $activeUserUpgrades->end_date;
    //debug_to_console("$userUpgrade_new");
    //debug_to_console("$expireDate");
    if ($expireDate === 0) {
        quitWithReason(" end ", 200);
    }


    $dateObject = date_create_from_format('U', $expireDate);
    $intervalString = "P{$days_reward}D";
    $interval = new DateInterval($intervalString);
    $dateObject->add($interval);
    $newTimestamp = $dateObject->getTimestamp();
    
    //debug_to_console("$newTimestamp");
    $upgradeService = $app->service('XF:User\Upgrade', $userUpgrade_new, $user);
    $upgradeService->setEndDate($newTimestamp);
    $upgradeService->ignoreUnpurchasable(true);
    $upgradeService->upgrade();
}
else
{
    debug_to_console("no user upgrade so far");
    // add days to current date
    $date = strtotime("+$days_reward day");

    // Upgrade User
    $upgradeService = $app->service('XF:User\Upgrade', $userUpgrade, $user);
    $upgradeService->setEndDate($date);
    $upgradeService->ignoreUnpurchasable(true);
    $upgradeService->upgrade();
}

quitWithReason(" end ", 200);

