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

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 inputs
    $platform     = $data['platform'] ?? '';
    $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'] ?? '');
    $police_id    = trim($data['police_id'] ?? '');
    $social_ids   = $data['social_ids'] ?? [];
    $uid          = $data['uid'] ?? null;
    $pid          = $data['pid'] ?? null;

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

    // ✅ Escape + Encode
    $social_ids_json     = mysqli_real_escape_string($con, json_encode($social_ids, JSON_UNESCAPED_UNICODE));
    $ack_no_escaped      = mysqli_real_escape_string($con, $ack_no);
    $atf_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);
    $platform_escaped    = mysqli_real_escape_string($con, $platform);
    $mobile = "true";

    // ✅ Insert Query
    $query = "INSERT INTO social_media (
        uid, pid, police_id, atf, ack_no, fraud_type, notice_id, subject_id, social_id, type,mobile
    ) VALUES (
        '$uid', '$pid', '$police_id_escaped', '$atf_escaped', '$ack_no_escaped',
        '$fraud_type_escaped', '$notice_id_escaped', '$subject_id_escaped', '$social_ids_json', '$platform_escaped','$mobile'
    )";

    if (mysqli_query($con, $query)) {
        echo json_encode(["success" => true, "message" => "$platform entry added successfully."]);
    } else {
        http_response_code(500);
        echo json_encode(["error" => "Database insert failed.", "details" => mysqli_error($con)]);
    }
} else {
    http_response_code(405);
    echo json_encode(["error" => "Only POST requests are allowed."]);
}