<?php
require_once __DIR__.'/address_parser.php';

/**
 * $api = ['url_template'=>'https://...?nid={NID}&dob={DOB}&key={KEY}&id={ID}',
 *         'api_key'=>'...', 'api_id'=>'...', 'method'=>'GET']
 */
function api_call($api, $nid, $dob){
    $url = strtr($api['url_template'], [
        '{NID}'=>urlencode($nid),
        '{DOB}'=>urlencode($dob),
        '{KEY}'=>urlencode($api['api_key']??''),
        '{ID}' =>urlencode($api['api_id']??''),
    ]);
    $ch = curl_init($url);
    curl_setopt_array($ch, [
        CURLOPT_RETURNTRANSFER=>true,
        CURLOPT_TIMEOUT=>60,
        CURLOPT_FOLLOWLOCATION=>true,
        CURLOPT_SSL_VERIFYPEER=>false,
        CURLOPT_USERAGENT=>'Mozilla/5.0 NID-Client',
    ]);
    if(($api['method']??'GET')==='POST'){
        curl_setopt($ch, CURLOPT_POST, true);
        curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query([
            'nid'=>$nid,'dob'=>$dob,
            'key'=>$api['api_key']??'','api_key'=>$api['api_key']??'',
            'id'=>$api['api_id']??'','api_id'=>$api['api_id']??''
        ]));
    }
    $raw = curl_exec($ch);
    $code = curl_getinfo($ch, CURLINFO_HTTP_CODE);
    $err = curl_error($ch);
    curl_close($ch);

    if($raw===false) return ['ok'=>false,'error'=>"cURL: $err",'raw'=>null];

    $json = json_decode($raw, true);
    // detect insufficient / error
    $lower = strtolower($raw);
    $insufficient = (strpos($lower,'insufficient')!==false || strpos($lower,'balance')!==false
                     || strpos($lower,'no balance')!==false || strpos($lower,'payment required')!==false);

    if($json === null){
        return ['ok'=>false,'error'=>'Invalid JSON response','raw'=>$raw,'http'=>$code];
    }
    // common error flags
    if(isset($json['status']) && in_array(strtolower((string)$json['status']),['false','error','failed','0'])){
        return ['ok'=>false,'error'=>$json['message']??'API returned error','raw'=>$raw,'json'=>$json];
    }
    if($insufficient && !nid_parse($json)['nameEn']){
        return ['ok'=>false,'error'=>'API Insufficient / Balance শেষ','raw'=>$raw,'json'=>$json];
    }
    $parsed = nid_parse($json);
    if(!$parsed || (!$parsed['nameEn'] && !$parsed['nameBn'] && !$parsed['dob'])){
        return ['ok'=>false,'error'=>'কোনো তথ্য পাওয়া যায়নি','raw'=>$raw,'json'=>$json];
    }
    return ['ok'=>true,'json'=>$json,'parsed'=>$parsed,'raw'=>$raw];
}
