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

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

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

    $pid = isset($data['pid']) ? mysqli_real_escape_string($con, $data['pid']) : null;

    if (!$pid) {
        http_response_code(400);
        echo json_encode(["error" => "Missing required field: pid"]);
        exit();
    }

    $response = [];

    // BANK Data
    $bankQueries = [
        'kyc' => "SELECT COUNT(*) AS total FROM kyc WHERE type = 'KYC' AND policestation_id = '$pid'",
        'lien' => "SELECT COUNT(*) AS total FROM kyc WHERE type = 'LIEN AMOUNT' AND policestation_id = '$pid'",
        'comply' => "SELECT COUNT(*) AS total FROM comply_order WHERE pid = '$pid'",
        'cctv' => "SELECT COUNT(*) AS total FROM cctv WHERE pid = '$pid'"
    ];

    foreach ($bankQueries as $key => $query) {
        $result = mysqli_query($con, $query);
        $row = mysqli_fetch_assoc($result);
        $response['bank'][$key] = $row['total'] ?? 0;
    }

    // SOCIAL MEDIA Data
    $platforms = ['facebook', 'instagram', 'whatsapp', 'twitter', 'snapchat', 'google'];
    foreach ($platforms as $platform) {
        $query = "SELECT COUNT(*) AS total FROM social_media WHERE type = '$platform' AND pid = '$pid'";
        $result = mysqli_query($con, $query);
        $row = mysqli_fetch_assoc($result);
        $response['social_media'][$platform] = $row['total'] ?? 0;
    }

    // OTHER Data
    $otherTables = [
        'domain' => "SELECT COUNT(*) AS total FROM domain_data WHERE pid = '$pid'",
        'cdr' => "SELECT COUNT(*) AS total FROM cdr WHERE pid = '$pid'"
    ];

    foreach ($otherTables as $key => $query) {
        $result = mysqli_query($con, $query);
        $row = mysqli_fetch_assoc($result);
        $response['other'][$key] = $row['total'] ?? 0;
    }

    echo json_encode(["success" => true, "data" => $response]);
} else {
    http_response_code(405);
    echo json_encode(["error" => "Only POST requests allowed."]);
}
?>