<?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
    $atf = isset($_POST['atf']) ? trim($_POST['atf']) : '';
    $fraud_type = '';
    $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']) : '';
    
    $social_ids_json = isset($_POST['social_ids']) ? $_POST['social_ids'] : '[]';

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

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

    // Escape user inputs to prevent SQL injection
    $atf_type_escaped = mysqli_real_escape_string($con, $atf);
    $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);
    $social_ids_json_escaped = mysqli_real_escape_string($con, json_encode($social_ids));

    // Insert a single row with all Facebook IDs stored as JSON string
    $query = "INSERT INTO social_media (c_id,police_id,fraud_type,n_id,s_id, social_id,type) 
    VALUES ('$atf_type_escaped','$police_id_escaped', '$fraud_type_escaped','$notice_id','$subject_id', '$social_ids_json_escaped','$platform')";

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

    mysqli_close($con);

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