<?php
header("Content-Type: application/json");
include "../config.php"; // Adjust path as needed

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $rawData = file_get_contents("php://input");
    $data = json_decode($rawData, true);

    if ($data === null && json_last_error() !== JSON_ERROR_NONE) {
        http_response_code(400);
        echo json_encode(["error" => "Invalid JSON format."]);
        exit();
    }

    // Extract and sanitize inputs
    $uid         = $data['uid'] ?? null;
    $pid         = $data['pid'] ?? null;
    $police_id   = $data['police_id'] ?? '';
    $atf         = trim($data['atf'] ?? '');
    $ack_no      = trim($data['acknowledgement_number'] ?? '');
    $fraud_type  = trim($data['fraud_type'] ?? '');
    $subject_id  = trim($data['subject_id'] ?? '');
    $notice_id   = trim($data['notice_id'] ?? '');
    $domain_ids  = $data['domain_ids'] ?? [];

    // Validate
    if (empty($uid) || empty($pid) || empty($ack_no) || !is_array($domain_ids) || count($domain_ids) === 0) {
        http_response_code(400);
        echo json_encode(["error" => "Missing required fields or domain_ids is empty."]);
        exit();
    }

    // Escape & Encode
    $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);
    $atf_escaped           = mysqli_real_escape_string($con, $atf);
    $domain_ids_json       = mysqli_real_escape_string($con, json_encode($domain_ids, JSON_UNESCAPED_UNICODE));
    $mobile = "true";
    // Insert Query
    $query = "INSERT INTO domain_data (
        uid, pid, police_id, atf, ack_no, fraud_type, notice_id, subject_id, domain_id,mobile
    ) VALUES (
        '$uid', '$pid', '$police_id_escaped', '$atf_escaped', '$ack_no_escaped',
        '$fraud_type_escaped', '$notice_id_escaped', '$subject_id_escaped', '$domain_ids_json','$mobile'
    )";

    if (mysqli_query($con, $query)) {
        echo json_encode([
            "success" => true,
            "message" => "Domain entries added successfully.",
            "id" => mysqli_insert_id($con)
        ]);
    } else {
        http_response_code(500);
        echo json_encode([
            "error" => "Database insert failed.",
            "details" => mysqli_error($con)
        ]);
    }
} else {
    http_response_code(405); // Method Not Allowed
    echo json_encode(["error" => "Only POST requests are allowed."]);
}
?>