<?php
/**
 * Smart NID JSON parser.
 * যেকোনো API structure থেকে name, address, parents, dob ইত্যাদি বের করে আনে।
 */

function nid_flatten($data, $prefix='', &$out=[]){
    if(is_array($data) || is_object($data)){
        foreach((array)$data as $k=>$v){
            $key = $prefix===''? (string)$k : $prefix.'.'.$k;
            if(is_array($v)||is_object($v)) nid_flatten($v,$key,$out);
            else $out[$key] = $v;
        }
    }
    return $out;
}

function nid_find($flat, array $needles){
    // needles: substrings (lowercase) to look for in key path
    foreach($flat as $k=>$v){
        if($v===null||$v==='') continue;
        $lk = strtolower($k);
        foreach($needles as $n){
            if(strpos($lk, strtolower($n))!==false) return (string)$v;
        }
    }
    return '';
}

function nid_find_all($flat, array $needles){
    $res=[];
    foreach($flat as $k=>$v){
        if($v===null||$v==='') continue;
        $lk = strtolower($k);
        foreach($needles as $n){
            if(strpos($lk, strtolower($n))!==false){ $res[$k]=(string)$v; break; }
        }
    }
    return $res;
}

/** সম্ভাব্য সব key থেকে single address line/object বানায় */
function nid_build_address($flat, $type='present'){
    // type = present | permanent
    $groups = $type==='present'
        ? ['present','preaddress','pre_address','pre.','preinfo','presentinfo','curr']
        : ['permanent','peraddress','per_address','per.','perinfo','permanentinfo','parmanent'];

    // 1) direct addressLine
    foreach(['addressline','address_line','fulladdress','address'] as $suf){
        foreach($groups as $g){
            foreach($flat as $k=>$v){
                $lk=strtolower($k);
                if(strpos($lk,$g)!==false && strpos($lk,$suf)!==false && $v!=='') return (string)$v;
            }
        }
    }
    // 2) build from parts
    $parts=[];
    $labels=['division'=>['division','বিভাগ'],
             'district'=>['district','জেলা','zila','zilla'],
             'upazila'=>['upazila','upozila','thana','uapzila','উপজেলা'],
             'union'=>['union','ইউনিয়ন','unionward','municipality','pouro'],
             'ward'=>['ward','ওয়ার্ড','wardno'],
             'postoffice'=>['postoffice','post_office','post ','postcode','postal','ডাকঘর'],
             'village'=>['village','mouza','moholla','para','গ্রাম','road','rmo'],
             'houseno'=>['houseno','house_no','holding','বাড়ি']];
    foreach($labels as $lab=>$needles){
        foreach($flat as $k=>$v){
            if($v==='') continue;
            $lk=strtolower($k); $matchGroup=false;
            foreach($groups as $g) if(strpos($lk,$g)!==false){$matchGroup=true;break;}
            if(!$matchGroup) continue;
            foreach($needles as $n){
                if(strpos($lk,strtolower($n))!==false){ $parts[$lab]=trim((string)$v); break; }
            }
        }
    }
    $order=['houseno','village','ward','union','postoffice','upazila','district','division'];
    $out=[]; foreach($order as $o) if(!empty($parts[$o])) $out[]=$parts[$o];
    if($out) return implode(', ',$out);

    // 3) fallback: any key containing "address"
    return nid_find($flat, [$type.'address', 'address']);
}

function nid_parse($json){
    if(is_string($json)) $data=json_decode($json,true); else $data=$json;
    if(!$data) return null;
    // unwrap common wrappers
    if(isset($data['data'])) $data=$data['data'];
    if(isset($data['data-Info'])) $data=$data['data-Info'];
    if(isset($data['result'])) $data=$data['result'];

    $flat = nid_flatten($data);

    return [
        'nameEn'   => nid_find($flat, ['nameen','name_english','englishname','en_name']),
        'nameBn'   => nid_find($flat, ['namebn','name_bangla','banglaname','bn_name','fullname','name']),
        'father'   => nid_find($flat, ['father','fathername','pitar','পিতা']),
        'mother'   => nid_find($flat, ['mother','mothername','matar','মাতা']),
        'spouse'   => nid_find($flat, ['spouse','husband','wife','স্বামী','স্ত্রী']),
        'dob'      => nid_find($flat, ['dateofbirth','date_of_birth','dob','birth','জন্ম']),
        'nid'      => nid_find($flat, ['nationalid','national_id','nidnumber','nid_no','nid ','pin']),
        'oldNid'   => nid_find($flat, ['oldid','old_nid','oldnid','voterid']),
        'gender'   => nid_find($flat, ['gender','sex','লিঙ্গ']),
        'bloodGroup'=> nid_find($flat, ['blood','রক্ত']),
        'religion' => nid_find($flat, ['religion','ধর্ম']),
        'occupation'=> nid_find($flat, ['occupation','profession','পেশা']),
        'birthPlace'=> nid_find($flat, ['birthplace','place_of_birth']),
        'photo'    => nid_find($flat, ['photo','image','picture','ছবি']),
        'signature'=> nid_find($flat, ['signature','sign','স্বাক্ষর']),
        'presentAddress'   => nid_build_address($flat,'present'),
        'permanentAddress' => nid_build_address($flat,'permanent'),
        '_raw' => $data,
        '_flat'=> $flat,
    ];
}
