<?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'])) {
    echo json_encode(['success' => false, 'message' => 'Missing IP ID']);
    exit();
}

$id = intval($_POST['id']);

// 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();

// Delete IP
$sql_delete = "DELETE FROM allowed_ips WHERE id = ?";
$stmt_delete = $db2->prepare($sql_delete);
$stmt_delete->bind_param("i", $id);
$delete_success = $stmt_delete->execute();

if ($delete_success) {
    // Log the deletion
    $admin_username = $_SESSION['username'];
    $log_action = "Deleted Allowed IP";
    $log_message = "Deleted IP: $old_ip_address ($old_description) by $admin_username";

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

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