<?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 and sanitize
    $uid         = $data['uid'] ?? null;
    $pid         = $data['pid'] ?? null;
    $atf         = trim($data['atf'] ?? '');
    $ack_no      = trim($data['acknowledgement_number'] ?? '');
    $subject_id  = trim($data['subject_id'] ?? '');
    $notice_id   = trim($data['notice_id'] ?? '');
    $police_id   = trim($data['police_id'] ?? '');
    $cdr_data    = $data['cdr_data'] ?? [];

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

    // Prepare JSON string
    $cdr_json = json_encode($cdr_data, JSON_UNESCAPED_UNICODE);
    $cdr_json_escaped = mysqli_real_escape_string($con, $cdr_json);
    $ack_no_escaped   = mysqli_real_escape_string($con, $ack_no);
    $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);
    $mobile = "true";

    $query = "INSERT INTO cdr (
        uid, pid, police_id, atf, ack_no, notice_id, subject_id, cdr_id,mobile
    ) VALUES (
        '$uid', '$pid', '$police_id_escaped', '$atf_escaped', '$ack_no_escaped',
        '$notice_id_escaped', '$subject_id_escaped', '$cdr_json_escaped','$mobile'
    )";

    if (mysqli_query($con, $query)) {
        echo json_encode([
            "success" => true,
            "message" => "CDR data saved successfully.",
            "cdr_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);
    echo json_encode(["error" => "Only POST requests are allowed."]);
}
?>