<?php
session_start();
include "config.php";

if (!isset($_SESSION['user'])) {
    header("Location: index.php");
    exit();
}

$user = $_SESSION['user'];
$pid = $user['pid'];
$uid = $user['id'];

if ($_SERVER["REQUEST_METHOD"] === "POST") {

    $IPDRID = (int) ($_POST['ipdr_id'] ?? 0);
    $data_ids_json = $_POST['data_ids'] ?? '[]';

    if ($IPDRID === 0) {
        echo "<script>alert('Invalid IPDR ID'); window.location.href='ipdr.php';</script>";
        exit();
    }

    $data_ids_arr = json_decode($data_ids_json, true);

    if (!is_array($data_ids_arr) || count($data_ids_arr) === 0) {
        echo "<script>alert('No IP data found'); window.location.href='ipdr.php';</script>";
        exit();
    }

    // Escape JSON
    $ip_data_esc = mysqli_real_escape_string($con, json_encode($data_ids_arr));

    // ✅ UPDATE ONLY ip_data
    $query = "
        UPDATE ipdr
        SET ip_data = '$ip_data_esc'
        WHERE id = $IPDRID
    ";

    if (mysqli_query($con, $query)) {
        echo "<script>alert('IP data updated successfully'); window.location.href='ipdr.php';</script>";
    } else {
        echo "<script>alert('DB Error: " . mysqli_error($con) . "'); window.location.href='ipdr.php';</script>";
    }

    mysqli_close($con);
} else {
    header("Location: ipdr.php");
    exit();
}
?>