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

// Redirect if user not logged in
if (!isset($_SESSION['user'])) {
    echo '<script>window.location.href = "index.php";</script>';
    exit();
}

$domainId = $_POST['domain_id'] ?? '';
$platform = $_GET['platform'] ?? '';

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

// Check if POST data is set
if ($_SERVER["REQUEST_METHOD"] === "POST") {

    $domain_ids_json = isset($_POST['domain_ids']) ? $_POST['domain_ids'] : '[]';
    $domain_ids = json_decode($domain_ids_json, true);

    // Validate input
    if (!is_array($domain_ids) || count($domain_ids) == 0) {
        echo "<script>alert('Domain IDs are required.'); window.location.href='domain.php';</script>";
        exit();
    }

    // Escape JSON string
    $domain_ids_json_escaped = mysqli_real_escape_string($con, json_encode($domain_ids));

    // Update only the domain_id column for the given domain ID
    $query = "UPDATE domain_data 
              SET domain_id='$domain_ids_json_escaped' 
              WHERE id='$domainId'";

    if (mysqli_query($con, $query)) {
        echo "<script>alert('$platform entry updated successfully.'); window.location.href='domain.php';</script>";
    } else {
        echo "<script>alert('Error while updating data.'); window.location.href='domain.php';</script>";
    }

    mysqli_close($con);

} else {
    echo "<script>window.location.href='domain.php';</script>";
    exit();
}
?>