<?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") {

    $atf = $_POST['atf'] ?? '';
    $subject_id = $_POST['subject_id'] ?? '';
    $notice_id = $_POST['notice_id'] ?? '';
    $police_id = $_POST['police_id'] ?? '';
    $data_ids_json = $_POST['data_ids'] ?? '[]';

    $data_ids_ = json_decode($data_ids_json, true);

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

    // Escape everything
    $cid_esc = mysqli_real_escape_string($con, $atf);
    $subject_id_esc = mysqli_real_escape_string($con, $subject_id);
    $notice_id_esc = mysqli_real_escape_string($con, $notice_id);
    $police_id_esc = mysqli_real_escape_string($con, $police_id);
    $data_ids_esc = mysqli_real_escape_string($con, json_encode($data_ids_, true));

    $query = "INSERT INTO ipdr (c_id, police_id, notice_id, subject_id, ip_data)
              VALUES ('$cid_esc', '$police_id_esc', '$notice_id_esc', '$subject_id_esc', '$data_ids_esc')";

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

    mysqli_close($con);

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