<?php
include "../../include/auth.php"; // Authentication
include "../../include/lskfjwfe.php"; // Database connection

header('Content-Type: application/json');

// Validate request method
if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
    echo json_encode(['success' => false, 'message' => 'Invalid request method']);
    exit();
}

// Validate input
if (!isset($_POST['setting_name'], $_POST['setting_value'])) {
    echo json_encode(['success' => false, 'message' => 'Missing required fields']);
    exit();
}

$setting_name = trim($_POST['setting_name']);
$setting_value = intval($_POST['setting_value']);

// Validate setting name
$allowed_settings = ['sitelive', 'regon', 'ipblock']; // Now includes ipblock
if (!in_array($setting_name, $allowed_settings)) {
    echo json_encode(['success' => false, 'message' => 'Invalid setting']);
    exit();
}

// Fetch old value for logging
$sql_old = "SELECT $setting_name FROM settings WHERE id = 1";
$stmt_old = $db2->prepare($sql_old);
$stmt_old->execute();
$result_old = $stmt_old->get_result();
$row_old = $result_old->fetch_assoc();
$old_value = $row_old ? $row_old[$setting_name] : 'N/A';
$stmt_old->close();

// Update settings in the database
$sql_update = "UPDATE settings SET $setting_name = ? WHERE id = 1";
$stmt_update = $db2->prepare($sql_update);
$stmt_update->bind_param("i", $setting_value);
$update_success = $stmt_update->execute();

if ($update_success) {
    // Log the change
    $admin_username = $_SESSION['username'];
    $log_action = "Updated Setting";
    $log_message = "$setting_name changed from $old_value to $setting_value by $admin_username";

    $log_sql = "INSERT INTO settings_log (username, action, setting_name, old_value, new_value, timestamp)
                VALUES (?, ?, ?, ?, ?, NOW())";
    $stmt_log = $db2->prepare($log_sql);
    $stmt_log->bind_param("sssss", $admin_username, $log_action, $setting_name, $old_value, $setting_value);
    $stmt_log->execute();
    $stmt_log->close();

    echo json_encode(['success' => true, 'message' => "$setting_name updated successfully"]);
} else {
    echo json_encode(['success' => false, 'message' => 'Failed to update setting']);
}
?>
