<?php

require_once __DIR__ . '/Include/Config.php';
require_once __DIR__ . '/Include/PageInit.php';

use ChurchCRM\Authentication\AuthenticationManager;
use ChurchCRM\Service\DonationFundService;
use ChurchCRM\Utils\InputUtils;
use ChurchCRM\Utils\RedirectUtils;

// Security: user must be administrator to use this page
AuthenticationManager::redirectHomeIfNotAdmin();

$fundId = InputUtils::legacyFilterInput($_GET['FundID'], 'int');
$action = InputUtils::legacyFilterInput($_GET['Action']);

$service = new DonationFundService();

if ($action === 'delete') {
    try {
        $service->deleteFund((int) $fundId);
        RedirectUtils::redirect('DonationFundEditor.php?Action=delete');
    } catch (\Exception $e) {
        RedirectUtils::redirect('DonationFundEditor.php?DeleteError=' . urlencode($e->getMessage()));
    }
} elseif ($action === 'up' || $action === 'down') {
    try {
        $service->reorderFund((int) $fundId, $action);
        RedirectUtils::redirect('DonationFundEditor.php');
    } catch (\Exception $e) {
        RedirectUtils::redirect('DonationFundEditor.php?ReorderError=' . urlencode($e->getMessage()));
    }
}
