<?php

$accessControl = array('Admin' => true); 
require_once '../../AccessControl.php';

if($validUserRequired && !$session->isAdmin()){
	echoWarning(_MUST_BE_ADMIN,"margin:10px;");
	exit;
}

function CheckEmpty($input){
	if(empty($input) && $input != 0){ return true; }
	return false;
}

include_once("../../components/Subscriptions/subscriptions.php");

$subscriptions = new Subscriptions();
$subscriptions->install_subscription_system();

#save a new subscription
$errors = 0;
if(isset($_POST['subsave#submit'])){
	unset($_POST['subsave#submit']);
	foreach($_POST as $key => $value){
		if($key !== "id#hidden"){
			if(checkEmpty($value) == true){
				$errors ++;
			}
		}
	}	
	if($errors === 0){
		$subscriptions->new_subscription($_POST);
	} else {
		echo '{ "Status": "Error", "Message": "'. _COULD_NOT_SAVE_SUBSCRIPTIONS .'" }'; exit;
	}
}

#edit subscription
if(isset($_POST['subedit#submit'])){
	unset($_POST['subedit#submit']);
	$subscriptions->edit_subscription($_POST);
}

# copy a subscription
if(isset($_POST["copy_from"])){
	$id = $_POST['copy_from'];
	$name = $_POST['copy_to'];
	$subscriptions->copySubscription($id, $name);	
}


#edit subscription reports
if(isset($_POST['editsubscriptionReports'])){
	foreach($_POST as $id => $rs){
		if(is_numeric($id)){
			$subscriptions->edit_reports($id,$rs);
		}
	}
}

#delete a subscription
if(isset($_POST["deletesub"])){
	if($_POST["subtodelete"] == $subscriptions->global_sub){
		# Reset the default
		setGlobalSetting("DefaultSubscription","");
		$subscriptions->global_sub = "";
	}
	$subscriptions->delete_subscription($_POST["subtodelete"],$_POST["deletesub"]);
}

if(isset($_POST["default_subscription"])){
	# Save Subscription as default for new users
	$id = empty($subscriptions->subscripts[ $_POST["default_subscription"] ]['id']) ? "" : $subscriptions->subscripts[ $_POST["default_subscription"] ]['id'];
	setGlobalSetting("DefaultSubscription",$id);
	$subscriptions->global_sub = $id;
}

if(isset($_GET["no_promo"])){	
	setGlobalSetting("no_promo",$_GET["no_promo"]);	
}

echo json_encode(array(
	"Status" => "Success",
	"no_promo" => getGlobalSetting("no_promo", false)
));
?>