<?php
header("Content-Type: application/json; charset=UTF-8");
require "vendor/autoload.php";

use Smalot\PdfParser\Parser;

$response = ["success"=>false,"data"=>null,"message"=>""];

function f($label,$txt){ 
    return preg_match('/'.preg_quote($label,'/').'[\s:\t]*([^\n]+)/u',$txt,$m)?trim($m[1]):null;
}

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    if (!isset($_FILES['pdf'])) {
        echo json_encode(["success"=>false,"message"=>"PDF not uploaded"]);
        exit;
    }

    $pdfFile = $_FILES['pdf']['tmp_name'];

    $parser = new Parser();
    $pdf = $parser->parseFile($pdfFile);
    $text = trim($pdf->getText());

    // ----- IMAGE EXTRACT -----
    $images = $pdf->getObjectsByType('XObject', 'Image');
    $photoUrl = null;
    $signUrl  = null;

   if (count($images) >= 2) {
    $i = 0;
    foreach ($images as $img) {
        $dataImg = $img->getContent();
        $file = ($i==0?"photo_":"sign_").time().".png";
        file_put_contents("image/" . $file, $dataImg); // image folder এ save

        if ($i==0) $photoUrl = "https://sign.onlineshopbd.top/image/" . $file;
        if ($i==1) $signUrl  = "https://sign.onlineshopbd.top/image/" . $file;

        $i++;
        if ($i>1) break;
    }
}


    // ---- FIELD EXTRACTION ----
    $apiBlood = f("Blood Group", $text) ?? f("BloodGroup", $text);
    $bloodGroup = $apiBlood ? trim($apiBlood) : "";

    if (strcasecmp($bloodGroup, "TIN") === 0) {
        $bloodGroup = "";
    }

    $apiGender   = f("Gender", $text) ?? f("gender", $text);
    $apiReligion = f("Religion", $text) ?? f("ধর্ম", $text) ?? f("religion", $text);

    $nid = f("National ID",$text);
    if ($nid && str_contains($nid," ")) $nid = explode(" ",$nid)[0];
    $nid = trim($nid ?? "");

    $father = f("Father Name",$text);
    if ($father) {
        $father = preg_replace("/^মো[:\.ঃ ]*/u","",$father);
        $father = "মোঃ " . trim($father);
    }
    $father = trim($father ?? "");

    $mother = f("Mother Name",$text) ?? f("Mother\nName",$text);
    $mother = trim($mother ?? "");

    // ---- SPOUSE LOGIC ----
    $spouseRaw = f("Spouse Name",$text) ?? f("Spouse",$text);
    $spouse = $spouseRaw ? trim($spouseRaw) : "";

    if (strcasecmp($spouse, "Name") === 0) {
        $spouse = "";
    }

    $mobile = f("Mobile",$text);
    if ($mobile) {
        $mobile = preg_replace("/[^0-9]/u","",$mobile);
        $mobile = trim($mobile);
    }
    $mobile = trim($mobile ?? "");

    $occupationRaw = f("Occupation", $text) ?? f("পেশা", $text);
    $occupation = $occupationRaw ? trim($occupationRaw) : null;

    $educationRaw = f("Education", $text) ?? f("শিক্ষা", $text);
    $education = $educationRaw ? trim($educationRaw) : null;

    $voterNo = f("Voter No",$text) ?? f("National Id/Voter No/Voter Id",$text);
    if (!$voterNo || $voterNo=="/Voter Id") $voterNo = "180214615700";
    $voterNo = trim($voterNo);

    $voterArea = f("Voter Area",$text);
    $voterArea = preg_replace("/\(.*/u","", $voterArea ?? "");
    $voterArea = trim($voterArea);

    // ---- ADDRESS FIX ----
    $division = f("Permanent Address Division",$text) ?? f("Division",$text);
    if ($division) $division = preg_replace("/District.*/u","",$division);
    $division = trim($division ?? "খুলনা");

    $district = f("Permanent Address District",$text) ?? f("District",$text);
    if ($district) $district = preg_replace("/Union\/Ward.*/u","",$district);
    $district = trim($district ?? "চুয়াডাঙ্গা");

    $region = f("Region",$text);
    $region = trim($region ?? $division);

    $rmo = f("RMO",$text);
    if ($rmo) $rmo = preg_replace("/City|Municipality|Corporation|Union\/Ward.*/u","",$rmo);
    $rmo = trim($rmo ?? "পল্লী");

    $upozila = f("Upozila",$text);
    if ($upozila) $upozila = preg_replace("/Union\/Ward.*/u","",$upozila);
    $upozila = trim($upozila ?? "আলমডাংগা");

    $union = f("Union/Ward",$text);
    $union = trim($union ?? "ভাংবাড়িয়া");

    $mouza = f("Mouza/Moholla",$text);
    if (!$mouza || strtolower($mouza)==="additional") $mouza = "Additional";
    $mouza = trim($mouza);

    $village = f("Village/Road",$text);
    if (!$village || strtolower($village)==="additional") $village = "নগর বোয়ালিয়া";
    $village = trim($village);

    $holding = f("Home/Holding No",$text) ?? "১৭৬/০৮";
    $holding = trim($holding);

    $postOffice = f("Post Office",$text);
    if ($postOffice && str_contains($postOffice,"Postal Code")) {
        $postOffice = explode("Postal Code",$postOffice)[0];
    }
    $postOffice = trim($postOffice ?? "হাটবোয়ালিয়া");

    $postCode = f("Postal Code",$text) ?? "7210";
    $postCode = preg_replace("/[^0-9০-৯]/u","",$postCode);
    $postCode = trim($postCode);

    // আজকের তারিখ বাংলা ফরম্যাটে
    $today = date("d-m-Y");
    $bnToday = str_replace(
        ["0","1","2","3","4","5","6","7","8","9","-"],
        ["০","১","২","৩","৪","৫","৬","৭","৮","৯","-"],
        $today
    );

    // Address line তৈরি
    if ($mouza === "Additional") {
        $addressLine = "বাসা/হোল্ডিং: $holding, গ্রাম/রাস্তাঃ $village, ইউনিয়ন/ওয়ার্ডঃ $union, পোস্ট অফিসঃ $postOffice, পোস্ট কোডঃ $postCode, উপজেলাঃ $upozila, জেলাঃ $district, বিভাগঃ $region, $division।";
    } else {
        $addressLine = "বাসা/হোল্ডিং: $holding, গ্রাম/রাস্তাঃ $village, মৌজা/মহল্লাঃ $mouza, ইউনিয়ন/ওয়ার্ডঃ $union, পোস্ট অফিসঃ $postOffice, পোস্ট কোডঃ $postCode, উপজেলাঃ $upozila, জেলাঃ $district, বিভাগঃ $region, $division।";
    }

    // ---- FINAL JSON ----
    $data = [
        "nameBn" => f("Name(Bangla)",$text) ?? "",
        "nameEn" => f("Name(English)",$text) ?? "",
        "nationalId" => $nid,
        "pin" => f("Pin",$text) ?? "",
        "dateOfBirth" => f("Date of Birth",$text) ?? "",
        "dateOfToday" => $bnToday,
        "father" => $father,
        "mother" => $mother,
        "spouse" => $spouse,
        "gender" => $apiGender ?? "",
        "bloodGroup" => $bloodGroup,
        "religion" => $apiReligion ?? "",
        "birthPlace" => f("Birth Place",$text) ?? "",
        "voterArea" => $voterArea,
        "voterAreaCode" => null,
        "voterNo" => $voterNo,
        "mobile" => $mobile,
        "slNo" => f("Sl No",$text) ?? "",
        "photo" => $photoUrl,
        "sign" => $signUrl,

        "permanentAddress" => [
            "division"=>$division,
            "district"=>$district,
            "region"=>$region,
            "rmo"=>$rmo,
            "upozila"=>$upozila,
            "postOffice"=>$postOffice,
            "postCode"=>$postCode,
            "unionOrWard"=>$union,
            "wardForUnionPorishod"=>"3",
            "mouzaOrMoholla"=>$mouza,
            "villageOrRoad"=>$village,
            "houseOrHoldingNo"=>$holding,
            "addressLine"=>$addressLine
        ],

        "presentAddress" => [
            "division"=>$division,
            "district"=>$district,
            "region"=>$region,
            "rmo"=>$rmo,
            "upozila"=>$upozila,
            "postOffice"=>$postOffice,
            "postCode"=>$postCode,
            "unionOrWard"=>$union,
            "wardForUnionPorishod"=>"3",
            "mouzaOrMoholla"=>$mouza,
            "villageOrRoad"=>$village,
            "houseOrHoldingNo"=>$holding,
            "addressLine"=>$addressLine
        ]
    ];

    if ($occupation!==null) $data["occupation"]=$occupation;
    if ($education!==null)  $data["education"]=$education;

    $response["success"]=true;
    $response["data"]=$data;
    $response["message"]="PDF processed successfully!";
    echo json_encode($response, JSON_PRETTY_PRINT | JSON_UNESCAPED_UNICODE);
    exit;
}

if (php_sapi_name()==='cli') {
    echo json_encode(["success"=>true,"message"=>"API Ready ✔"],JSON_PRETTY_PRINT|JSON_UNESCAPED_UNICODE);
}
