<?php


$accessControl = array(
	"IncludeFile" => true
);

require_once 'AccessControl.php';

$last_subscription_id = $session->userinfo['subscriptionid'];

$create_log = false;
# Is there a new subscription set for the user? If so we can now reset the session array
if(!empty($_POST['set_subscription']) && is_numeric($_POST['set_subscription'])){
	# Update the database
	$db->Execute("UPDATE ". TBL_USERS ." set subscriptionid = ".$db->Quote($_POST['set_subscription'])." WHERE username = '{$session->username}'");
	# Remove the userinfo session so that on reload it gets renewed.
	unset($_SESSION['userinfo']);
	session_write_close();

	# Overwrite the current id for this screen
	$session->userinfo['subscriptionid'] = $_POST['set_subscription'];

	echoWarning(_CLOSE_SUBSCRIPTION_DIALOG,"margin:15px;");

	$create_log = true;
}

$report_ids = array();
$r = $db->Execute("SELECT * FROM ". TBL_REPORTS);
while($row = $r->fetchRow()){
	$report_ids[$row['id']] = $row;
}

$r = $db->Execute("SELECT  * FROM ". TBL_SUBSCRIPTIONS ." ORDER BY id DESC");
$subscriptions = array();

while($row = $r->fetchRow()){
	# Set an array for all subscriptions
	$data = json_decode($row['value'],true);

	$subscriptions[$row['id']] = array("id" => $row['id']);

	foreach ($data as $k => $v) {
		if(!empty($v["value"])){
			$subscriptions[$row['id']][$k] = $v["value"];
		}
	}

	if(!empty($data['reports'])){

		$subscriptions[$row['id']]['reports'] = array();

		foreach ($data['reports'] as $rid) {
			$rp = json_decode($report_ids[$rid]['value'], true);
			$subscriptions[$row['id']]['reports'][] = $rp["Label"];
		}
	}
}

$current_subscription = $current_subscription ?? $subscriptions[$session->userinfo['subscriptionid']];

# add an log entry here because here we also have the subscription name ;)
if ($create_log === true) {
	if ((isset($current_subscription['Price'])) && (empty($current_subscription['Price']))) {
		$price = 0;
	} else {
		$price = $current_subscription['Price'];
	}
	$now = time();
	$nowd = date("Y-m-d H:i:s", $now);
	$lastsub = $subscriptions[$last_subscription_id];
	NewSubscriptionLogEntry(
		"On $nowd Changed from {$lastsub['Name']} to {$current_subscription['Name']}",
		$current_subscription['Name'],
		$price
	);
}

if(file_exists("templates/subscriptions.php")){
	include_once "templates/subscriptions.php";
} else {
	include_once "templates/subscriptions-example.php";
}
?>

