<?
if ($_POST['action'] == 'funddelete' && $_POST['delete']) {
	// first lookup all the sponsorships inside the fund
	$id = intval($_POST['delete']);
	$q = $pdo->prepare("SELECT * FROM fundraising_goals WHERE id=? AND year=?");
	$q->execute([$id,$config['FISCALYEAR']]);
	$f = $q->fetch(PDO::FETCH_OBJ);
	// hold yer horses, no deleting system funds!
	if ($f) {
		if ($f->system == 'no') {
			$stmt = $pdo->prepare("DELETE FROM fundraising_donations WHERE fundraising_goal=? AND fiscalyear=?");
			$stmt->execute([$f->type,$config['FISCALYEAR']]);
			$stmt = $pdo->prepare("DELETE FROM fundraising_goals WHERE id=?");
			$stmt->execute([$id]);
			if ($pdo->rowCount())
				happy_('Successfully removed fund %1', array($f->name));
		} else {
			error_('Cannot remove system fund');
		}
	}
	exit;
}
if ($_POST['action'] == 'fundedit' || $_POST['action'] == 'fundadd') {
	$fundraising_id = intval($_POST['fundraising_id']);
	if ($fundraising_id) {
		$q = $pdo->prepare("SELECT * FROM fundraising_goals WHERE id=?");
		$q->execute([$fundraising_id]);
		$f = $q->fetch(PDO::FETCH_OBJ);
		$system = $f->system;
	}
	$name = $_POST['name'];
	$goal = $_POST['goal'];
	$description = $_POST['description'];
	$budget = intval($_POST['budget']);
}

if ($_POST['action'] == 'fundedit') {
	if (($system == 'yes' && $budget) || ($system == 'no' && $budget && $goal && $name)) {
		if ($system == 'yes') {
			$stmt = $pdo->prepare("UPDATE fundraising SET budget=?, description=? WHERE id=?");
			$stmt->execute([$budget,$description,$fundraising_id]);
		} else {
			$stmt = $pdo->prepare("UPDATE fundraising SET budget=?, description=?, goal=?, name=? WHERE id=?");
			$stmt->execute([$budget,$description,$goal,$name,$fundraising_id]);
		}

		if ($pdo->errorInfo())
			error_('MySQL Error: %1', array($pdo->errorInfo()));
		else
			happy_('Saved fund changes');
	} else {
		error_('Required fields were missing, please try again');
	}
	exit;
}
if ($_POST['action'] == 'fundadd') {
	if ($goal && $type && $name) {
		$stmt = $pdo->prepare("INSERT INTO fundraising_goals (goal,name,description,system,budget,fiscalyear) VALUES (?,?,?,'no',?,?)");
		$stmt->execute([$goal,$name,$description,$budget,$config['FISCALYEAR']]);
		happy_('Added new fund');
	} else
		error_('Required fields were missing, please try again');
	if ($pdo->errorInfo())
		error_('MySQL Error: %1', array($pdo->errorInfo()));
	exit;
}

?>