<?php
require_once __DIR__.'/../config/config.php';
require_user();
require_once __DIR__.'/../includes/address_parser.php';

$U = current_user();
$id = (int)($_GET['id'] ?? 0);
$s = $pdo->prepare("SELECT * FROM orders WHERE id=? AND user_id=?");
$s->execute([$id, $U['id']]);
$o = $s->fetch();
if (!$o) die('Not found');

$p = nid_parse($o['response_json']);
$raw = json_decode($o['response_json'], true) ?: [];
$d = $raw['data-Info'] ?? $raw['data'] ?? $raw;

// Helper: pick first non-empty value
function pick(...$vals) {
    foreach ($vals as $v) {
        if ($v !== null && $v !== '' && trim((string)$v) !== '') return (string)$v;
    }
    return '';
}
// English digits -> Bangla digits
function bn_num($s) {
    return str_replace(
        ['0','1','2','3','4','5','6','7','8','9'],
        ['০','১','২','৩','৪','৫','৬','৭','৮','৯'],
        (string)$s
    );
}
// Weekday in Bangla from a date string
function calc_birthday_bn($dob) {
    if (!$dob) return '';
    try { $dt = new DateTime($dob); } catch (Exception $e) { return ''; }
    $map = [
        'Saturday'  => 'শনিবার',
        'Sunday'    => 'রবিবার',
        'Monday'    => 'সোমবার',
        'Tuesday'   => 'মঙ্গলবার',
        'Wednesday' => 'বুধবার',
        'Thursday'  => 'বৃহস্পতিবার',
        'Friday'    => 'শুক্রবার',
    ];
    return $map[$dt->format('l')] ?? '';
}
// Age in Bangla ("XX বছর")
function calc_age_bn($dob) {
    if (!$dob) return '';
    try { $dt = new DateTime($dob); $now = new DateTime(); } catch (Exception $e) { return ''; }
    if ($dt > $now) return '';
    $y = $now->diff($dt)->y;
    return bn_num($y).' বছর';
}
// Helper: extract address line from array/string
function addr_line($a) {
    if (!$a) return '';
    if (is_string($a)) return $a;
    if (is_array($a)) {
        if (!empty($a['addressLine'])) return $a['addressLine'];
        if (!empty($a['address']))     return $a['address'];
        if (!empty($a['fullAddress'])) return $a['fullAddress'];
        $parts = [];
        foreach (['holding','village','mouza','union','postOffice','upazila','district','division'] as $k) {
            if (!empty($a[$k])) $parts[] = $a[$k];
        }
        return implode(', ', $parts);
    }
    return '';
}

// Map all fields (fallback: parsed $p → raw $d → order row)
$nationalId  = pick($d['nationalId']   ?? '', $p['nid'] ?? '', $o['nid'] ?? '');
// 13-digit NID: response থেকে সরাসরি; না থাকলে N/A
$nationalId13 = pick(
    $d['nationalId13'] ?? '',
    $d['nid13']        ?? '',
    $d['nationalID13'] ?? '',
    $raw['nationalId13'] ?? ''
);
if ($nationalId13 === '') $nationalId13 = 'N/A';

$oldId       = pick($p['oldNid']      ?? '', $d['oldId']      ?? '');
$pin         = pick($d['pin']         ?? '', $p['pin']        ?? '');
$name        = pick($p['nameBn']      ?? '', $d['nameBangla'] ?? '', $d['name'] ?? '');
$nameEn      = pick($p['nameEn']      ?? '', $d['nameEnglish']?? '', $d['nameEn'] ?? '');
$dob         = pick($p['dob']         ?? '', $d['dateOfBirth']?? '');
$father      = pick($p['father']      ?? '', $d['fatherName'] ?? '');
$mother      = pick($p['mother']      ?? '', $d['motherName'] ?? '');
$gender      = pick($p['gender']      ?? '', $d['gender']     ?? '');
$religion    = pick($p['religion']    ?? '', $d['religion']   ?? '');
$birthPlace  = pick($p['birthPlace']  ?? '', $d['birthPlace'] ?? '', $d['placeOfBirth'] ?? '');
$voterArea   = pick($p['voterArea']   ?? '', $d['voterArea']  ?? '');

// জন্মবার / বয়স — response এ থাকলে সেটা, না থাকলে dob থেকে হিসাব
$birthDay    = pick($p['birthDay'] ?? '', $d['birthDayBangla'] ?? '', $d['birthDay'] ?? '', calc_birthday_bn($dob));
$age         = pick($p['age']      ?? '', $d['ageBangla']      ?? '', $d['age']      ?? '', calc_age_bn($dob));

$photo       = pick($p['photo']       ?? '', $d['photo']      ?? '');

// Address — try parsed first, then raw preAddress/perAddress
$presentAddr = pick(
    $p['presentAddress']    ?? '',
    addr_line($d['preAddress']       ?? null),
    addr_line($d['presentAddress']   ?? null),
    addr_line($d['present_address']  ?? null),
    addr_line($d['address']          ?? null)
);
$permanentAddr = pick(
    $p['permanentAddress']  ?? '',
    addr_line($d['perAddress']        ?? null),
    addr_line($d['permanentAddress']  ?? null),
    addr_line($d['permanent_address'] ?? null),
    $presentAddr
);
?>
<!DOCTYPE html>
<html lang="bn">
<head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title><?= htmlspecialchars($nameEn ?: 'Server Copy') ?></title>
  <link href="https://surokkha.gov.bd/favicon.png" rel="icon">
  <link href="https://fonts.googleapis.com/css2?family=Hind+Siliguri:wght@300;400;500;600;700&display=swap" rel="stylesheet">
  <style>
    @import url('https://fonts.maateen.me/solaiman-lipi/font.css');
    @page { size:A4; margin:0; }
    * { box-sizing:border-box; margin:0; padding:0; }
    body { font-family:'Solaimanlipi','Hind Siliguri',Arial,sans-serif; font-weight:normal; text-align:center; background:#888; }
    .normal-data,.data-value,.addr-details { font-weight:normal !important; }
    .section-title { font-weight:bold !important; font-size:16px; }
    .hind-siliguri-text { font-family:'Hind Siliguri','Solaimanlipi',Arial,sans-serif; font-weight:normal; font-size:12px; line-height:1.4; }
    .field-label { font-weight:normal; font-size:13px; }
    .page-wrap { padding:20px 0 30px; }
    .background { background-color:lightgrey; position:relative; width:750px; height:1065px; margin:auto; box-shadow:0 8px 32px rgba(0,0,0,.4); }
    .background img.crane { max-width:100%; height:100%; display:block; }
    #print { background:#03a9f4; padding:8px; width:700px; height:40px; border:0; font-size:25px; font-weight:bold; cursor:pointer; box-shadow:1px 4px 4px #878787; color:#fff; border-radius:10px; margin:25px auto; display:none; }
    @media print {
      @page { size:A4; margin:0; }
      html,body { width:210mm; height:297mm; background:#fff !important; margin:0; padding:0; }
      #print { display:none !important; }
      .page-wrap { margin-top:0; padding:0; }
      .background { width:210mm; height:297mm; box-shadow:none; }
      .background img.crane { width:210mm; height:297mm; }
    }
  </style>
</head>
<body onload="document.getElementById('print').style.display='block';">
<div class="page-wrap">
  <div class="background">
    <img class="crane" src="https://raw.githubusercontent.com/matherofsetuxyz/hfhtf/main/cbimage.png" width="750" height="1065" alt="">

    <div style="position:absolute;left:30%;top:8%;font-size:16px;color:rgb(255,224,0);"><b>National Identity Registration Wing (NIDW)</b></div>
    <div style="position:absolute;left:37%;top:11%;font-size:14px;color:rgb(255,47,161);"><b>Select Your Search Category</b></div>
    <div style="position:absolute;left:45%;top:12.8%;font-size:12px;color:rgb(8,121,4);">Search By NID / Voter No.</div>
    <div style="position:absolute;left:45%;top:14.3%;font-size:12px;color:rgb(7,119,184);">Search By Form No.</div>
    <div style="position:absolute;left:30%;top:16.9%;font-size:12px;color:rgb(252,0,0);"><b>NID or Voter No*</b></div>
    <div style="position:absolute;left:45%;top:16.9%;font-size:12px;color:rgb(143,143,143);">NID</div>
    <div style="position:absolute;left:62.9%;top:17.1%;font-size:11px;color:#fff;">Submit</div>
    <div style="position:absolute;left:89%;top:11.55%;font-size:11px;color:#fff;">Home</div>

    <!-- জাতীয় পরিচিতি তথ্য -->
    <div style="position:absolute;left:37%;top:27%;color:#070707;" class="section-title"><b>জাতীয় পরিচিতি তথ্য</b></div>
    <div style="position:absolute;left:37%;top:29.5%;color:#070707;" class="field-label">জাতীয় পরিচয় পত্র নম্বর</div>
    <div style="position:absolute;left:55%;top:29.5%;font-size:14px;color:#070707;" class="normal-data"><?= htmlspecialchars($nationalId) ?></div>
    <div style="position:absolute;left:37%;top:31.8%;color:#070707;" class="field-label">১৩ ডিজিট এনআইডি</div>
    <div style="position:absolute;left:55%;top:31.8%;font-size:14px;color:#070707;" class="normal-data"><?= htmlspecialchars($nationalId13) ?></div>
    <div style="position:absolute;left:37%;top:34.1%;color:#070707;" class="field-label">পিন নম্বর</div>
    <div style="position:absolute;left:55%;top:34.1%;font-size:14px;color:#070707;" class="normal-data"><?= htmlspecialchars($pin) ?></div>
    <div style="position:absolute;left:37%;top:36.4%;color:#070707;" class="field-label">পূর্ববর্তী পরিচয়পত্র নম্বর</div>
    <div style="position:absolute;left:55%;top:36.4%;font-size:14px;color:#070707;" class="normal-data"><?= htmlspecialchars($oldId) ?></div>
    <div style="position:absolute;left:37%;top:38.7%;color:#070707;" class="field-label">ভোটার এলাকা</div>
    <div style="position:absolute;left:55%;top:38.7%;font-size:14px;color:#070707;" class="normal-data"><?= htmlspecialchars($voterArea) ?></div>
    <div style="position:absolute;left:37%;top:41%;color:#070707;" class="field-label">জন্মস্থান</div>
    <div style="position:absolute;left:55%;top:41%;font-size:14px;color:#070707;" class="normal-data"><?= htmlspecialchars($birthPlace) ?></div>

    <!-- ব্যক্তিগত তথ্য -->
    <div style="position:absolute;left:37%;top:43%;color:#070707;" class="section-title"><b>ব্যক্তিগত তথ্য</b></div>
    <div style="position:absolute;left:37%;top:46%;font-size:14px;color:#070707;" class="field-label">নাম (বাংলা)</div>
    <div style="position:absolute;left:55%;top:46%;font-size:14px;color:#070707;" class="normal-data"><?= htmlspecialchars($name) ?></div>
    <div style="position:absolute;left:37%;top:48.7%;font-size:14px;color:#070707;" class="field-label">নাম (ইংরেজি)</div>
    <div style="position:absolute;left:55%;top:48.7%;font-size:14px;color:#070707;" class="normal-data"><?= htmlspecialchars($nameEn) ?></div>
    <div style="position:absolute;left:37%;top:51.3%;font-size:14px;color:#070707;" class="field-label">জন্ম তারিখ</div>
    <div style="position:absolute;left:55%;top:51.3%;font-size:14px;color:#070707;" class="normal-data"><?= htmlspecialchars($dob) ?></div>
    <div style="position:absolute;left:37%;top:54%;font-size:14px;color:#070707;" class="field-label">পিতার নাম</div>
    <div style="position:absolute;left:55%;top:54%;font-size:14px;color:#070707;" class="normal-data"><?= htmlspecialchars($father) ?></div>
    <div style="position:absolute;left:37%;top:56.7%;font-size:14px;color:#070707;" class="field-label">মাতার নাম</div>
    <div style="position:absolute;left:55%;top:56.7%;font-size:14px;color:#070707;" class="normal-data"><?= htmlspecialchars($mother) ?></div>

    <!-- অন্যান্য তথ্য -->
    <div style="position:absolute;left:37%;top:59%;color:#070707;" class="section-title"><b>অন্যান্য তথ্য</b></div>
    <div style="position:absolute;left:37%;top:62.5%;font-size:14px;color:#070707;" class="field-label">লিঙ্গ</div>
    <div style="position:absolute;left:55%;top:62.5%;font-size:14px;color:#070707;" class="normal-data"><?= htmlspecialchars($gender) ?></div>
    <div style="position:absolute;left:37%;top:65%;font-size:14px;color:#070707;" class="field-label">ধর্ম</div>
    <div style="position:absolute;left:55%;top:65%;font-size:14px;color:#070707;" class="normal-data"><?= htmlspecialchars($religion) ?></div>
    <div style="position:absolute;left:37%;top:68%;font-size:14px;color:#070707;" class="field-label">জন্মবার</div>
    <div style="position:absolute;left:55%;top:68%;font-size:14px;color:#070707;" class="normal-data"><?= htmlspecialchars($birthDay) ?></div>
    <div style="position:absolute;left:37%;top:70.5%;font-size:14px;color:#070707;" class="field-label">বয়স</div>
    <div style="position:absolute;left:55%;top:70.5%;font-size:14px;color:#070707;" class="normal-data"><?= htmlspecialchars($age) ?></div>

    <!-- বর্তমান ঠিকানা -->
    <div style="position:absolute;left:37%;top:72.9%;color:#070707;" class="section-title"><b>বর্তমান ঠিকানা</b></div>
    <div style="position:absolute;left:37%;top:75.6%;width:48%;color:#070707;text-align:left;" class="hind-siliguri-text addr-details">
      <?= htmlspecialchars($presentAddr) ?>
    </div>

    <!-- স্থায়ী ঠিকানা -->
    <div style="position:absolute;left:37%;top:82%;color:#070707;" class="section-title"><b>স্থায়ী ঠিকানা</b></div>
    <div style="position:absolute;left:37%;top:84.6%;width:48%;color:#070707;text-align:left;" class="hind-siliguri-text addr-details">
      <?= htmlspecialchars($permanentAddr) ?>
    </div>

    <div style="position:absolute;top:92%;width:100%;font-size:12px;text-align:center;color:red;">উপরে প্রদর্শিত তথ্যসমূহ জাতীয় পরিচয়পত্র সংশ্লিষ্ট, ভোটার তালিকার সাথে সরাসরি সম্পর্কযুক্ত নয়।</div>
    <div style="position:absolute;top:93.5%;width:100%;text-align:center;font-size:12px;color:#030303;">This is Software Generated Report From Bangladesh Election Commission, Signature &amp; Seal Aren't Required.</div>

    <div style="position:absolute;left:16%;top:25.7%;">
      <img src="<?= htmlspecialchars($photo) ?>" height="140" width="121" style="border-radius:10px" alt="">
    </div>
    <div style="position:absolute;left:15.5%;top:44%;width:130px;text-align:center;">
      <img src="https://api.qrserver.com/v1/create-qr-code/?size=150x150&data=<?= urlencode($nameEn.'%'.$nationalId.'%'.$dob) ?>" height="100" width="100" alt="">
    </div>
    <div style="position:absolute;left:15.5%;top:39.6%;width:130px;font-weight:bold;font-size:13px;color:#070707;text-align:center;">
      <?= htmlspecialchars($nameEn) ?>
    </div>

    <button class="print" id="print" onclick="window.print()">SAVE</button>
  </div>
</div>
</body>
</html>
