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

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

// Enable error reporting for debugging
error_reporting(E_ALL);
ini_set('display_errors', 1);

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

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

$ip_address = trim($_POST['ip_address']);
$description = trim($_POST['description']);

// Debugging: Log values before inserting
error_log("Adding IP: $ip_address with Description: $description");

// Check if IP already exists
$sql_check = "SELECT id FROM allowed_ips WHERE ip_address = ?";
$stmt_check = $db2->prepare($sql_check);
if (!$stmt_check) {
    echo json_encode(['success' => false, 'message' => 'Database error: ' . $db2->error]);
    exit();
}
$stmt_check->bind_param("s", $ip_address);
$stmt_check->execute();
$result_check = $stmt_check->get_result();
if ($result_check->num_rows > 0) {
    echo json_encode(['success' => false, 'message' => 'IP already exists']);
    exit();
}
$stmt_check->close();

// Insert IP into the database
$sql_insert = "INSERT INTO allowed_ips (ip_address, description) VALUES (?, ?)";
$stmt_insert = $db2->prepare($sql_insert);
if (!$stmt_insert) {
    echo json_encode(['success' => false, 'message' => 'Database error: ' . $db2->error]);
    exit();
}
$stmt_insert->bind_param("ss", $ip_address, $description);
$insert_success = $stmt_insert->execute();

if ($insert_success) {
    // Log the addition
    $admin_username = $_SESSION['username'];
    $log_action = "Added Allowed IP";
    $log_message = "Added IP: $ip_address ($description) by $admin_username";

    $log_sql = "INSERT INTO settings_log (username, action, setting_name, old_value, new_value, timestamp)
                VALUES (?, ?, 'Allowed IP Addition', NULL, ?, NOW())";
    $stmt_log = $db2->prepare($log_sql);
    if (!$stmt_log) {
        echo json_encode(['success' => false, 'message' => 'Log error: ' . $db2->error]);
        exit();
    }
    $stmt_log->bind_param("sss", $admin_username, $log_action, $log_message);
    $stmt_log->execute();
    $stmt_log->close();

    echo json_encode(['success' => true, 'message' => 'IP added successfully']);
} else {
    echo json_encode(['success' => false, 'message' => 'Failed to add IP: ' . $stmt_insert->error]);
}
$stmt_insert->close();
?>
