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

// Only allow POST
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."]);
        exit();
    }

    $pid = $data['pid'] ?? null;

    if (empty($pid)) {
        http_response_code(400);
        echo json_encode(["error" => "Missing 'pid' in request."]);
        exit();
    }

    $pid_escaped = mysqli_real_escape_string($con, $pid);

    $query = "SELECT `id`, `pid`, `i_name`, `i_number`, `i_designation`, `i_sign` 
              FROM `police` 
              WHERE `pid` = '$pid_escaped'";

    $result = mysqli_query($con, $query);

    if ($result) {
        $rows = [];
        while ($row = mysqli_fetch_assoc($result)) {
            $rows[] = $row;
        }

        echo json_encode([
            "success" => true,
            "data" => $rows
        ]);
    } else {
        http_response_code(500);
        echo json_encode([
            "error" => "Query failed.",
            "details" => mysqli_error($con)
        ]);
    }
} else {
    http_response_code(405);
    echo json_encode(["error" => "Only POST requests allowed."]);
}
?>