<?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'];
$uid = $user['id'];

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

    // Sanitize input
    $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']) : '';
    $data_ids_json = isset($_POST['data_ids']) ? $_POST['data_ids'] : '[]';

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

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

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

    // Insert a single row with all Facebook IDs stored as JSON string
    $query = "INSERT INTO cdr (c_id,police_id,n_id,s_id, cdr_id) 
    VALUES ('$atf','$police_id_escaped','$notice_id_escaped','$subject_id_escaped', '$data_ids_json_escaped')";

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

    mysqli_close($con);

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