<?php $PAGE_TITLE='Auto Server Copy'; require __DIR__.'/_layout.php';
require_once __DIR__.'/../includes/api_client.php';

$services=$pdo->query("SELECT s.*,a.name AS api_name FROM services s LEFT JOIN apis a ON a.id=s.api_id WHERE s.active=1 AND s.kind='api' AND a.active=1 ORDER BY s.id")->fetchAll();
$result=null; $err=null; $cached=false; $orderId=null;

if($_SERVER['REQUEST_METHOD']==='POST'){csrf_check();
  $sid=(int)($_POST['service_id']??0);
  $nid=preg_replace('/\D/','',$_POST['nid']??'');
  $dob=trim($_POST['dob']??'');
  $svc=null; foreach($services as $s) if($s['id']==$sid){$svc=$s;break;}
  if(!$svc) $err='সার্ভিস নির্বাচন করুন';
  elseif(!$nid||!$dob) $err='NID ও DOB দিন';
  else{
    // dob normalize (DD-MM-YYYY -> YYYY-MM-DD)
    if(preg_match('/^\d{2}-\d{2}-\d{4}$/',$dob)){$p=explode('-',$dob); $dob="$p[2]-$p[1]-$p[0]";}
    // Auto-prefix: 13-digit NID + valid YYYY-MM-DD DOB => prepend YYYY to make 17-digit
    if(strlen($nid)===13 && preg_match('/^(\d{4})-\d{2}-\d{2}$/',$dob,$m)){
      $nid=$m[1].$nid;
    }
    // duplicate cache?
    $c=$pdo->prepare("SELECT * FROM nid_cache WHERE nid=? AND dob=?"); $c->execute([$nid,$dob]); $ch=$c->fetch();
    if($ch){
      $json=$ch['response_json']; $parsed=nid_parse($json);
      $cached=true; $result=$parsed;
      // save 0-price order
      $pdo->prepare("INSERT INTO orders(user_id,service_id,api_id,nid,dob,response_json,status,price,cached) VALUES(?,?,?,?,?,?, 'success',0,1)")
          ->execute([$U['id'],$sid,$svc['api_id'],$nid,$dob,$json]);
      $orderId=$pdo->lastInsertId();
    } else {
      if($U['balance'] < $svc['price']){$err='ব্যালেন্স যথেষ্ট নয়। রিচার্জ করুন।';}
      else{
        $api=$pdo->prepare("SELECT * FROM apis WHERE id=?"); $api->execute([$svc['api_id']]); $api=$api->fetch();
        $res=api_call($api,$nid,$dob);
        if(!$res['ok']){$err=$res['error'];
          $pdo->prepare("INSERT INTO orders(user_id,service_id,api_id,nid,dob,response_json,status,price) VALUES(?,?,?,?,?,?, 'failed',0)")
              ->execute([$U['id'],$sid,$svc['api_id'],$nid,$dob,$res['raw']]);
        } else {
          $json=$res['raw']; $result=$res['parsed'];
          // deduct
          $pdo->prepare("UPDATE users SET balance=balance-? WHERE id=?")->execute([$svc['price'],$U['id']]);
          log_txn($pdo,$U['id'],'debit',$svc['price'],'',"NID: $nid");
          $pdo->prepare("INSERT INTO orders(user_id,service_id,api_id,nid,dob,response_json,status,price) VALUES(?,?,?,?,?,?, 'success',?)")
              ->execute([$U['id'],$sid,$svc['api_id'],$nid,$dob,$json,$svc['price']]);
          $orderId=$pdo->lastInsertId();
          $pdo->prepare("INSERT INTO nid_cache(nid,dob,response_json,api_id) VALUES(?,?,?,?)")
              ->execute([$nid,$dob,$json,$svc['api_id']]);
          $U['balance'] -= $svc['price'];
        }
      }
    }
  }
}
$history=$pdo->prepare("SELECT o.*,s.name AS sname FROM orders o LEFT JOIN services s ON s.id=o.service_id WHERE o.user_id=? ORDER BY o.id DESC LIMIT 10");
$history->execute([$U['id']]); $history=$history->fetchAll();
?>
<h2 style="margin-bottom:14px">🔍 Auto Sarver Copy</h2>
<div class="card">
<?php if($err):?><div class="alert err"><?=e($err)?></div><?php endif;?>
<?php if($cached):?><div class="alert ok">✅ ক্যাশ থেকে দেখানো হয়েছে — কোনো টাকা কাটা হয়নি।</div><?php endif;?>
<form method="post" class="grid g3" id="nidSearchForm"><?=csrf_field()?>
<div class="field"><label>সার্ভিস</label>
<select name="service_id" class="input" required>
<option value="">-- সিলেক্ট --</option>
<?php foreach($services as $s):?><option value="<?=$s['id']?>"><?=e($s['name'])?> — <?=money($s['price'])?></option><?php endforeach;?>
</select></div>
<div class="field"><label>NID Number</label><input class="input" id="nidInput" name="nid" required placeholder="১০/১৩/১৭ digit"><small id="nidHint" style="color:#64748b"></small></div>
<div class="field"><label>জন্ম তারিখ (YYYY-MM-DD)</label><input class="input" id="dobInput" name="dob" type="text" required inputmode="numeric" pattern="\d{4}-\d{2}-\d{2}" placeholder="1995-08-25" title="ফরম্যাট: YYYY-MM-DD (যেমন 1995-08-25)" maxlength="10"></div>
<div style="grid-column:1/-1"><button class="btn">🔎 সার্চ করুন</button></div>
</form>
<?php if(!$services):?><p style="margin-top:14px;color:#64748b">⚠️ কোনো সার্ভিস এখনো এড করা হয়নি। অ্যাডমিন কে বলুন।</p><?php endif;?>
</div>


<style>
#nidLoadingOverlay{position:fixed;inset:0;background:rgba(15,23,42,.92);z-index:99999;display:none;align-items:center;justify-content:center;flex-direction:column;color:#fff;font-family:inherit;backdrop-filter:blur(4px)}
#nidLoadingOverlay.show{display:flex}
#nidLoadingOverlay .spinner{width:70px;height:70px;border:6px solid rgba(255,255,255,.15);border-top-color:#22c55e;border-radius:50%;animation:nidspin 1s linear infinite;margin-bottom:22px}
#nidLoadingOverlay .txt{font-size:20px;font-weight:600;letter-spacing:.3px}
#nidLoadingOverlay .sub{margin-top:8px;font-size:14px;color:#cbd5e1}
@keyframes nidspin{to{transform:rotate(360deg)}}
</style>
<?php $__isPost = ($_SERVER['REQUEST_METHOD']==='POST'); ?>
<div id="nidLoadingOverlay" role="status" aria-live="polite">
  <div class="spinner"></div>
  <div class="txt" id="nidOverlayTxt">🔎 তথ্য খোঁজা হচ্ছে...</div>
  <div class="sub" id="nidOverlaySub">অনুগ্রহ করে অপেক্ষা করুন, পেজ রিফ্রেশ করবেন না</div>
</div>

<script>
(function(){
  var nidEl=document.getElementById('nidInput');
  var dobEl=document.getElementById('dobInput');
  var hint=document.getElementById('nidHint');
  if(!nidEl||!dobEl) return;

  // Track user's original 13-digit entry so we can re-apply/remove prefix as DOB changes.
  var originalNid=null;

  function digits(s){return (s||'').replace(/\D/g,'');}

  function apply(){
    var nid=digits(nidEl.value);
    var dob=dobEl.value.trim();
    var m=dob.match(/^(\d{4})-\d{2}-\d{2}$/);

    // If currently showing a 17-digit that we auto-prefixed, and user changed DOB/NID, revert to original 13.
    if(originalNid && nid.length===17 && nid.slice(4)===originalNid){
      // still auto-prefixed state
      if(!m){
        // DOB no longer valid -> revert to 13
        nidEl.value=originalNid;
        nid=originalNid;
        hint.textContent='';
      } else if(nid.slice(0,4)!==m[1]){
        // Year changed -> update prefix
        nidEl.value=m[1]+originalNid;
        nid=nidEl.value;
        hint.textContent='✅ অটো ১৭ ডিজিটে রূপান্তর হয়েছে (YYYY যুক্ত)';
      }
      return;
    }

    // Fresh evaluation
    if(nid.length===13 && m){
      originalNid=nid;
      nidEl.value=m[1]+nid;
      hint.textContent='✅ অটো ১৭ ডিজিটে রূপান্তর হয়েছে (YYYY যুক্ত)';
    } else {
      if(nid.length!==17) originalNid=null;
      hint.textContent='';
    }
  }

  nidEl.addEventListener('input',function(){
    // user typed manually — reset tracking
    originalNid=null;
    hint.textContent='';
    apply();
  });
  dobEl.addEventListener('input',apply);
  dobEl.addEventListener('change',apply);

  var form=document.getElementById('nidSearchForm');
  var overlay=document.getElementById('nidLoadingOverlay');
  var txtEl=document.getElementById('nidOverlayTxt');
  var subEl=document.getElementById('nidOverlaySub');
  var spinEl=overlay?overlay.querySelector('.spinner'):null;
  function showOverlay(msg,sub){
    if(!overlay) return;
    if(txtEl) txtEl.innerHTML=msg;
    if(subEl) subEl.innerHTML=sub||'';
    if(spinEl) spinEl.style.display='';
    overlay.classList.add('show');
    document.body.style.overflow='hidden';
  }
  function hideOverlay(){
    if(!overlay) return;
    overlay.classList.remove('show');
    document.body.style.overflow='';
  }
  if(form && overlay && window.fetch){
    form.addEventListener('submit',function(ev){
      if(typeof form.checkValidity==='function' && !form.checkValidity()) return;
      ev.preventDefault();
      showOverlay('🔎 তথ্য খোঁজা হচ্ছে...','অনুগ্রহ করে অপেক্ষা করুন, পেজ রিফ্রেশ করবেন না');
      var fd=new FormData(form);
      fetch(window.location.href,{method:'POST',body:fd,credentials:'same-origin',headers:{'X-Requested-With':'XMLHttpRequest'}})
        .then(function(r){return r.text();})
        .then(function(html){
          // Parse response and swap main content only (no full navigation → no white flash)
          var doc=new DOMParser().parseFromString(html,'text/html');
          // pick main content container: prefer the same wrapper the layout uses
          var newMain = doc.querySelector('.container') || doc.querySelector('main') || doc.body;
          var curMain = document.querySelector('.container') || document.querySelector('main') || document.body;
          if(newMain && curMain){
            // success flash text
            if(txtEl) txtEl.innerHTML='✅ তথ্য পাওয়া গিয়েছে';
            if(subEl) subEl.innerHTML='ডাউনলোড অপশন প্রস্তুত হচ্ছে...';
            if(spinEl) spinEl.style.display='none';
            setTimeout(function(){
              curMain.innerHTML = newMain.innerHTML;
              // re-run any inline scripts in swapped content
              var scripts = curMain.querySelectorAll('script');
              scripts.forEach(function(old){
                var s=document.createElement('script');
                if(old.src) s.src=old.src; else s.textContent=old.textContent;
                old.parentNode.replaceChild(s,old);
              });
              // scroll to result if present
              var res=document.querySelector('.nid-result');
              if(res) res.scrollIntoView({behavior:'smooth',block:'start'});
              hideOverlay();
            },500);
          } else {
            // fallback: full reload with response
            document.open();document.write(html);document.close();
          }
        })
        .catch(function(){
          // Network failure → fallback to normal submit
          hideOverlay();
          form.submit();
        });
    });
    window.addEventListener('pageshow',function(e){ if(e.persisted) hideOverlay(); });
  } else if(form && overlay){
    // No fetch → fallback: at least show overlay on submit
    form.addEventListener('submit',function(){
      if(typeof form.checkValidity==='function' && !form.checkValidity()) return;
      showOverlay('🔎 তথ্য খোঁজা হচ্ছে...','অনুগ্রহ করে অপেক্ষা করুন');
    });
  }
})();
</script>


<?php if($result):?>
<div class="nid-result">
<div class="head"><b>✅ তথ্য পাওয়া গেছে</b>
<?php if($orderId):?><a class="btn sm ghost" href="download.php?id=<?=$orderId?>">📥 Download</a><?php endif;?>
</div>
<div class="body">
<?php
$rows=[
 'নাম (English)'=>'nameEn','নাম (বাংলা)'=>'nameBn','NID'=>'nid','পুরাতন NID'=>'oldNid',
 'জন্ম তারিখ'=>'dob','লিঙ্গ'=>'gender','পিতা'=>'father','মাতা'=>'mother',
 'স্বামী/স্ত্রী'=>'spouse','রক্তের গ্রুপ'=>'bloodGroup','ধর্ম'=>'religion','পেশা'=>'occupation',
 'বর্তমান ঠিকানা'=>'presentAddress','স্থায়ী ঠিকানা'=>'permanentAddress',
];
foreach($rows as $L=>$k) if(!empty($result[$k])):?>
<div class="nid-row"><div class="k"><?=e($L)?></div><div class="v"><?=e($result[$k])?></div></div>
<?php endif;?>
</div></div>
<?php endif;?>

<div style="margin-top:24px">
<h3>📜 সাম্প্রতিক সার্চ</h3>
<table style="margin-top:10px"><thead><tr><th>#</th><th>NID</th><th>DOB</th><th>Service</th><th>Price</th><th>Status</th><th>Action</th></tr></thead><tbody>
<?php foreach($history as $h):?>
<tr>
<td>#<?=$h['id']?></td><td><?=e($h['nid'])?></td><td><?=e($h['dob'])?></td>
<td><?=e($h['sname'])?></td>
<td><?=$h['cached']?'<span class=badge>Cached</span>':money($h['price'])?></td>
<td><span class="badge <?=$h['status']==='success'?'ok':'fail'?>"><?=e($h['status'])?></span></td>
<td>
<?php if($h['status']==='success'):?>
<a class="btn sm" href="download.php?id=<?=$h['id']?>">📥</a>
<?php endif;?>
<a class="btn sm danger" href="history.php?del=<?=$h['id']?>" onclick="return confirm('Delete?')">🗑️</a>
</td>
</tr>
<?php endforeach;?>
<?php if(!$history):?><tr><td colspan="7" style="text-align:center;color:#64748b">কোনো হিস্টোরি নেই</td></tr><?php endif;?>
</tbody></table>
</div>
<?php require __DIR__.'/_footer.php';
