<?php
require 'db.php';
require 'functions.php';
requireRole(['admin']);

$fee = cleanInput($_POST['registrationfee'] ?? '');
$validityyears = cleanInput($_POST['passvalidityyears'] ?? '');
$renewalyears = cleanInput($_POST['renewalyears'] ?? '');
$minage = cleanInput($_POST['minage'] ?? '');

if ($fee === '' || $validityyears === '' || $renewalyears === '' || $minage === '') {
    jsonOut(false, 'All fields are required');
}
if (!is_numeric($fee) || bccomp($fee, '0', 2) < 0) {
    jsonOut(false, 'Registration fee must be a valid non-negative amount');
}
if (!ctype_digit((string)$validityyears) || (int)$validityyears < 1) {
    jsonOut(false, 'Pass validity must be a positive whole number of years');
}
if (!in_array($renewalyears, ['1', '2'], true)) {
    jsonOut(false, 'Renewal period must be 1 or 2 years');
}
if (!ctype_digit((string)$minage) || (int)$minage < 1) {
    jsonOut(false, 'Minimum age must be a positive whole number');
}

try {
    $feeclean = moneyStr($fee); // normalize to 2dp string, BCMath-safe
    setSetting($pdo, 'registrationfee', $feeclean);
    setSetting($pdo, 'passvalidityyears', $validityyears);
    setSetting($pdo, 'renewalyears', $renewalyears);
    setSetting($pdo, 'minage', $minage);

    logActivity($pdo, 'setting', 0, 'update', 'admin', currentUserId(), 'Settings updated');

    jsonOut(true, 'Settings saved successfully');
} catch (Exception $e) {
    logDebug('[ajax_admin_settings] ' . $e->getMessage());
    jsonOut(false, 'Failed to save settings');
}
