<?php
header("Content-Type: application/json; charset=utf-8");
header("Access-Control-Allow-Origin: *");

if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
    echo json_encode(["success" => false, "message" => "Only POST allowed"]);
    exit;
}

if (!isset($_FILES['pdf'])) {
    echo json_encode(["success" => false, "message" => "PDF file is required"]);
    exit;
}

$apiUrl = "https://sign.onlineshopbd.top/sign2nid.php";

// Forward uploaded PDF to main API
$file = new CURLFile($_FILES['pdf']['tmp_name'], $_FILES['pdf']['type'], $_FILES['pdf']['name']);
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $apiUrl);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, ["pdf" => $file]);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$response = curl_exec($ch);
curl_close($ch);

$main = json_decode($response, true);

if (!$main || $main['success'] !== true) {
    echo json_encode(["success" => false, "message" => "Main API error"]);
    exit;
}

$data = $main['data'];

// Convert DOB format for output only
$dobFinal = date("j M Y", strtotime($data['dateOfBirth']));
// ---- Address Cleaning ----
$addr = $data['presentAddress']['addressLine'] ?? $data['permanentAddress']['addressLine'] ?? $data['address'] ?? "";

// Replace Bengali punctuation variations
$addr = str_replace("রাস্তাঃ", "রাস্তা:", $addr);
$addr = str_replace("গ্রাম/রাস্তাঃ", "গ্রাম/রাস্তা:", $addr);
$addr = str_replace("ইউনিয়ন/ওয়ার্ডঃ", "ইউনিয়ন:", $addr);
$addr = str_replace("পোস্ট অফিসঃ", "ডাকঘর:", $addr);
$addr = str_replace("পোস্ট কোডঃ", "-", $addr);

// Extract উপজেলা & জেলা only names
$addr = preg_replace('/উপজেলাঃ\s*([^,]+)/u', '$1', $addr);
$addr = preg_replace('/জেলাঃ\s*([^,]+)/u', '$1', $addr);

// Remove ইউনিয়ন part completely
$addr = preg_replace('/ইউনিয়নঃ?\s*[^,]+,?/u', '', $addr);
$addr = preg_replace('/ইউনিয়নঃ?\s*[^,]+$/u', '', $addr);

// Fix postcode part like ", - 7210" or "-7210"
$addr = preg_replace('/,\s*-\s*(\d+)/u', ' - $1', $addr);
$addr = preg_replace('/-\s*(\d+)/u', ' - $1', $addr);

// Remove duplicate commas and extra spaces
$addr = preg_replace('/,+/u', ',', $addr);
$addr = preg_replace('/\s+/u', ' ', $addr);
$addr = trim($addr, " ,");

// Keep only important segments
$parts = explode(",", $addr);
$keep = [];
foreach ($parts as $p) {
    $p = trim($p);
    if ($p === "") continue;
    if (str_contains($p, "বিভাগ")) continue;
    if (str_contains($p, "region")) continue;
    if (str_contains($p, "rmo")) continue;
    if (str_contains($p, "mobile")) continue;
    if (str_contains($p, "voter")) continue;
    if (str_contains($p, "ভাংবাড়িয়া")) continue; // ইউনিয়ন name remove
    $keep[] = $p;
}

$addrFinal = implode(", ", $keep);

// Ensure last 2 segments are উপজেলা, জেলা only
$segments = $keep;
$last = array_slice($segments, -2);
$others = array_slice($segments, 0, count($segments) - 2);
$addrFinal = implode(", ", $others) . ", " . implode(", ", $last);


// ---- Map to your required output JSON ----
$output = [
    "userIMG"      => $data['photo'] ?? "",
    "signIMG"      => $data['sign'] ?? "",
    "nameBn"       => $data['nameBn'] ?? "",
    "nameEn"       => $data['nameEn'] ?? "",
    "nationalId"   => $data['nationalId'] ?? "",
    "pin"          => $data['pin'] ?? "",
    "fatherName"   => $data['father'] ? str_replace("মোঃ ", "", $data['father']) : "",
    "motherName"   => $data['mother'] ?? "",
    "birthPlace"   => $data['birthPlace'] ?? "",
    "dateOfBirth"  => $dobFinal,
    "blood_group"  => $data['bloodGroup'] ?? "",
    "address"      => $addrFinal
];

echo json_encode($output, JSON_UNESCAPED_UNICODE | JSON_PRETTY_PRINT);

