<?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['id'], $_POST['ip_address'], $_POST['description'])) {
    echo json_encode(['success' => false, 'message' => 'Missing fields']);
    exit();
}

$id = intval($_POST['id']);
$new_ip_address = trim($_POST['ip_address']);
$new_description = trim($_POST['description']);

// Fetch old values for logging
$sql_old = "SELECT ip_address, description FROM allowed_ips WHERE id = ?";
$stmt_old = $db2->prepare($sql_old);
$stmt_old->bind_param("i", $id);
$stmt_old->execute();
$result_old = $stmt_old->get_result();
if ($result_old->num_rows === 0) {
    echo json_encode(['success' => false, 'message' => 'IP not found']);
    exit();
}
$old_data = $result_old->fetch_assoc();
$old_ip_address = $old_data['ip_address'];
$old_description = $old_data['description'];
$stmt_old->close();

// Update IP
$sql_update = "UPDATE allowed_ips SET ip_address = ?, description = ? WHERE id = ?";
$stmt_update = $db2->prepare($sql_update);
$stmt_update->bind_param("ssi", $new_ip_address, $new_description, $id);
$update_success = $stmt_update->execute();

if ($update_success) {
    // Log the edit
    $admin_username = $_SESSION['username'];
    $log_action = "Edited Allowed IP";
    $log_message = "Edited IP: $old_ip_address ($old_description) → $new_ip_address ($new_description) by $admin_username";

    $log_sql = "INSERT INTO settings_log (username, action, setting_name, old_value, new_value, timestamp)
                VALUES (?, ?, 'Allowed IP Edit', ?, ?, NOW())";
    $stmt_log = $db2->prepare($log_sql);
    $stmt_log->bind_param("ssss", $admin_username, $log_action, $old_ip_address, $log_message);
    $stmt_log->execute();
    $stmt_log->close();

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