<?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();
}

$platform = $_GET['platform'] ?? '';

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

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

    // Sanitize input
    $fraud_type = '';
    // $fraud_type = isset($_POST['fraud_type']) ? trim($_POST['fraud_type']) : '';
     $ATF = isset($_POST['atf']) ? trim($_POST['atf']) : '';
   
    $subject_id = isset($_POST['subject_id']) ? trim($_POST['subject_id']) : '';
    $notice_id = isset($_POST['notice_id']) ? trim($_POST['notice_id']) : '';
    $police_id = isset($_POST['police_id']) ? trim($_POST['police_id']) : '';
    
    $domain_ids_json = isset($_POST['domain_ids']) ? $_POST['domain_ids'] : '[]';

    // Decode Facebook IDs JSON into PHP array
    $domain_ids = json_decode($domain_ids_json, true);

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

    // Escape user inputs to prevent SQL injection
        $atf_no_escaped = mysqli_real_escape_string($con, $ATF);
//    $type_no_escaped = mysqli_real_escape_string($con, $type);
  //  $ack_no_escaped = mysqli_real_escape_string($con, $ack_no);
    $fraud_type_escaped = mysqli_real_escape_string($con, $fraud_type);
    $subject_id_escaped = mysqli_real_escape_string($con, $subject_id);
    $notice_id_escaped = mysqli_real_escape_string($con, $notice_id);
    $police_id_escaped = mysqli_real_escape_string($con, $police_id);
    $domain_ids_json_escaped = mysqli_real_escape_string($con, json_encode($domain_ids));

    // Insert a single row with all Facebook IDs stored as JSON string
    $query = "INSERT INTO domain_data (c_id,police_id, fraud_type,n_id,s_id, domain_id)
    VALUES ('$atf_no_escaped','$police_id_escaped','$fraud_type_escaped','$notice_id','$subject_id', '$domain_ids_json_escaped')";

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

    mysqli_close($con);

} else {
    // If accessed without POST, redirect back
    echo "<script>window.location.href='domain.php';</script>";
    exit();
}
?>