<?php
ob_start(); // ua_history_clean_export_buffer
@ini_set('display_errors','0');
error_reporting(E_ALL & ~E_WARNING & ~E_NOTICE);
$page_title = 'سجل المشترك';
require_once __DIR__ . '/auth.php';
require_once __DIR__ . '/db_bootstrap.php';
require_once __DIR__ . '/super_admin_guard.php';
require_once __DIR__ . '/subscriber_history_lib.php';
require_once __DIR__ . '/subscriber_mikrotik_watch_lib.php';
require_once __DIR__ . '/quota_lib.php';
if (function_exists('ensure_db')) ensure_db(true);
$conn = $GLOBALS['conn'] ?? null;
if (!($conn instanceof mysqli)) { http_response_code(500); die('Database connection error'); }
require_super_admin_confirmation('سجل المشترك');
sh_ensure_schema($conn);
if (function_exists('mtwatch_ensure_schema')) @mtwatch_ensure_schema($conn);
// لا نشغّل أي مزامنة MikroTik ثقيلة عند فتح السجل.
// السجل يقرأ من قاعدة البيانات فقط، والمزامنة تعمل من cron/mikrotik_watch_worker.php.
$id = (int)($_GET['id'] ?? 0);
if ($id <= 0) { http_response_code(400); die('Bad request'); }
$sub = sh_get_subscriber($conn, $id);
if (!$sub) { http_response_code(404); die('Subscriber not found'); }
$username = sh_subscriber_username($sub);
$histLastMac = (string)($sub['last_caller_id'] ?? '');
$histCurrentMac = (string)($sub['current_caller_id'] ?? '');
$histLastInfo = ($histLastMac !== '' && function_exists('macvendor_identify')) ? macvendor_identify($conn, $histLastMac) : ['label'=>''];
$histCurrentInfo = ($histCurrentMac !== '' && function_exists('macvendor_identify')) ? macvendor_identify($conn, $histCurrentMac) : ['label'=>''];
$histLastLabel = trim((string)($histLastInfo['label'] ?? ''));
$histCurrentLabel = trim((string)($histCurrentInfo['label'] ?? ''));
if ($histLastLabel === '' || $histLastLabel === 'غير معروف') $histLastLabel = trim(((string)($sub['last_mac_vendor'] ?? '')) . (((string)($sub['last_device_type'] ?? '')) !== '' ? ' / ' . (string)($sub['last_device_type'] ?? '') : ''));
if ($histCurrentLabel === '' || $histCurrentLabel === 'غير معروف') $histCurrentLabel = trim(((string)($sub['current_mac_vendor'] ?? '')) . (((string)($sub['current_device_type'] ?? '')) !== '' ? ' / ' . (string)($sub['current_device_type'] ?? '') : ''));
sh_mark_registered($conn, $id, (string)($sub['registered_at'] ?? '') ?: null);
if (!function_exists('h')) {
  function h($v){ return htmlspecialchars((string)$v, ENT_QUOTES, 'UTF-8'); }
}
function money_cols(mysqli $conn): array {
  $all = [];
  foreach (['amount','total_amount','paid_amount','remaining_amount'] as $c) {
    if (sh_col_exists($conn,'invoices',$c)) $all[] = $c;
  }
  return $all;
}
$invoiceDateCol = sh_col_exists($conn,'invoices','created_at') ? 'created_at' : (sh_col_exists($conn,'invoices','date') ? 'date' : 'id');
$invoiceRows = [];
if (sh_table_exists($conn,'invoices') && sh_col_exists($conn,'invoices','subscriber_id')) {
  $q = @$conn->query("SELECT * FROM invoices WHERE subscriber_id=".(int)$id." ORDER BY $invoiceDateCol DESC, id DESC LIMIT 100");
  if ($q) while($r = $q->fetch_assoc()) $invoiceRows[] = $r;
}
$usageRows = [];
if (sh_table_exists($conn,'ppp_usage_monthly')) {
  if (sh_col_exists($conn,'ppp_usage_monthly','username') && sh_col_exists($conn,'ppp_usage_monthly','cycle_month')) {
    $u = $conn->real_escape_string($username);
    $q = @$conn->query("SELECT cycle_month AS month_key, used_bytes FROM ppp_usage_monthly WHERE username='$u' ORDER BY cycle_month DESC LIMIT 24");
    if ($q) while($r = $q->fetch_assoc()) $usageRows[] = $r;
  } elseif (sh_col_exists($conn,'ppp_usage_monthly','subscriber_id') && sh_col_exists($conn,'ppp_usage_monthly','month_key')) {
    $q = @$conn->query("SELECT month_key, used_bytes FROM ppp_usage_monthly WHERE subscriber_id=".(int)$id." ORDER BY month_key DESC LIMIT 24");
    if ($q) while($r = $q->fetch_assoc()) $usageRows[] = $r;
  }
}
$eventRows = [];
$q = @$conn->query("SELECT * FROM subscriber_activity_log WHERE subscriber_id=".(int)$id." ORDER BY event_at DESC, id DESC LIMIT 200");
if ($q) while($r = $q->fetch_assoc()) $eventRows[] = $r;

$historySubject = trim((string)($sub['full_name'] ?? ''));
if ($historySubject === '') $historySubject = $username;

function ua_history_export_safe_filename(string $name, string $ext): string {
  $name = trim(preg_replace('/[^\p{Arabic}\p{L}\p{N}_\-]+/u', '_', $name), '_');
  if ($name === '') $name = 'subscriber_history';
  return $name . '_' . date('Ymd_His') . '.' . $ext;
}
function ua_history_export_basic_rows(array $sub, string $username, string $histLastLabel, string $histCurrentLabel): array {
  return [
    ['الاسم', (string)($sub['full_name'] ?? '')],
    ['اسم المستخدم', $username],
    ['تاريخ التسجيل', (string)($sub['registered_at'] ?? '—')],
    ['تاريخ أول تفعيل', (string)($sub['first_activated_at'] ?? '—')],
    ['تاريخ آخر اتصال', (string)($sub['last_seen_at'] ?? '—')],
    ['تاريخ آخر فصل', (string)(($sub['mt_last_logged_out'] ?? '') ?: (($sub['ppp_last_cut_at'] ?? '') ?: (($sub['last_disconnect_at'] ?? '') ?: '—')))],
    ['آخر MAC سجل دخول', (string)($sub['last_caller_id'] ?? '—')],
    ['نوع جهاز آخر MAC', $histLastLabel ?: '—'],
    ['MAC الحالي', (string)($sub['current_caller_id'] ?? '—')],
    ['نوع الجهاز الحالي', $histCurrentLabel ?: '—'],
    ['IP الحالي', (string)($sub['current_ip'] ?? '—')],
    ['سبب آخر خروج', (string)($sub['mt_last_disconnect_reason'] ?? '—')],
  ];
}

function ua_history_clean_event_details(string $details): string {
  $details = trim(str_replace([' من كاش الجلسات','من كاش الجلسات',' كاش الجلسات'], '', $details));
  $details = preg_replace('/\s+/u', ' ', (string)$details);
  return trim((string)$details);
}

function ua_history_text_has(string $haystack, string $needle): bool {
  return $needle !== '' && strpos($haystack, $needle) !== false;
}

function ua_history_event_view(array $ev): array {
  $key = strtoupper(trim((string)($ev['action_key'] ?? '')));
  $label = trim((string)($ev['action_label'] ?? ''));
  $details = ua_history_clean_event_details((string)($ev['details'] ?? ''));
  $haystackRaw = $key . ' ' . $label . ' ' . $details;
  $haystack = function_exists('mb_strtolower') ? mb_strtolower($haystackRaw, 'UTF-8') : strtolower($haystackRaw);

  if ($key === 'DISCONNECTED' || ua_history_text_has($haystack, 'disconnected') || ua_history_text_has($haystack, 'logged_out') || ua_history_text_has($haystack, 'خروج') || ua_history_text_has($haystack, 'انقطاع') || ua_history_text_has($haystack, 'فصل')) {
    return ['action' => 'انقطاع', 'details' => 'تم تسجيل فصل/انقطاع المشترك'];
  }
  if ($key === 'CONNECTED' || ua_history_text_has($haystack, 'connected') || ua_history_text_has($haystack, 'اتصال') || ua_history_text_has($haystack, 'نشط')) {
    return ['action' => 'اتصال', 'details' => 'تم تسجيل اتصال المشترك'];
  }
  if ($key === 'FIRST_ACTIVATED' || ua_history_text_has($haystack, 'first_activated') || ua_history_text_has($haystack, 'أول تفعيل') || ua_history_text_has($haystack, 'أول ظهور')) {
    return ['action' => 'أول ظهور', 'details' => 'أول ظهور للمشترك أونلاين'];
  }
  if ($key === 'REGISTERED' || ua_history_text_has($haystack, 'registered') || ua_history_text_has($haystack, 'تسجيل المشترك')) {
    return ['action' => 'تسجيل', 'details' => 'تم تسجيل المشترك في النظام'];
  }

  return [
    'action' => ($label !== '' ? $label : 'حركة'),
    'details' => ($details !== '' ? $details : 'تم تسجيل حركة للمشترك'),
  ];
}

function ua_history_pdf_utf16_hex(string $text): string {
  $text = str_replace(["\r", "\n", "\t"], ' ', $text);
  if (function_exists('mb_convert_encoding')) {
    $bin = mb_convert_encoding($text, 'UTF-16BE', 'UTF-8');
  } else {
    $bin = @iconv('UTF-8', 'UTF-16BE//IGNORE', $text);
    if ($bin === false) $bin = '';
  }
  return strtoupper(bin2hex((string)$bin));
}
function ua_history_pdf_lines(array $sub, string $username, string $histLastLabel, string $histCurrentLabel, array $invoiceRows, array $usageRows, array $eventRows, string $invoiceDateCol): array {
  $lines = [];
  $lines[] = 'سجل المشترك - ' . (string)($sub['full_name'] ?? $username);
  $lines[] = '------------------------------';
  $lines[] = 'بيانات أساسية';
  foreach (ua_history_export_basic_rows($sub, $username, $histLastLabel, $histCurrentLabel) as $row) {
    $lines[] = (string)$row[0] . ': ' . (string)$row[1];
  }
  $lines[] = '';
  $lines[] = 'الفواتير';
  if ($invoiceRows) {
    foreach (array_slice($invoiceRows, 0, 40) as $inv) {
      $lines[] = '#' . (string)($inv['id'] ?? '') . ' | ' . (string)($inv['cycle_month'] ?? '—') . ' | ' . (string)($inv['status'] ?? ($inv['payment_status'] ?? '—')) . ' | ' . (string)($inv['amount'] ?? ($inv['total_amount'] ?? '0')) . ' | ' . (string)($inv[$invoiceDateCol] ?? '—');
    }
  } else {
    $lines[] = 'لا توجد فواتير';
  }
  $lines[] = '';
  $lines[] = 'الاستهلاك الشهري الكلي';
  if ($usageRows) {
    foreach (array_slice($usageRows, 0, 40) as $ur) {
      $bytes = (int)($ur['used_bytes'] ?? 0);
      $lines[] = (string)($ur['month_key'] ?? '') . ' | ' . number_format($bytes / 1073741824, 2) . ' GB';
    }
  } else {
    $lines[] = 'لا توجد بيانات استهلاك';
  }
  $lines[] = '';
  $lines[] = 'سجل الحركات';
  if ($eventRows) {
    foreach (array_slice($eventRows, 0, 120) as $ev) {
      $eventView = ua_history_event_view($ev);
      $lines[] = (string)($ev['event_at'] ?? '—') . ' | ' . $eventView['action'] . ' | ' . $eventView['details'];
    }
  } else {
    $lines[] = 'لا توجد حركات مسجلة بعد';
  }
  return $lines;
}
function ua_history_make_pdf_document(array $lines): string {
  $objects = [];
  $add = function(string $body) use (&$objects): int { $objects[] = $body; return count($objects); };
  $fontDesc = $add('<< /Type /FontDescriptor /FontName /Arial /Flags 32 /FontBBox [0 -250 1100 1000] /ItalicAngle 0 /Ascent 905 /Descent -212 /CapHeight 716 /StemV 80 >>');
  $cidFont = $add('<< /Type /Font /Subtype /CIDFontType2 /BaseFont /Arial /CIDSystemInfo << /Registry (Adobe) /Ordering (Identity) /Supplement 0 >> /FontDescriptor '.$fontDesc.' 0 R /DW 600 >>');
  $toUnicodeStream = "/CIDInit /ProcSet findresource begin\n" .
    "12 dict begin\n" .
    "begincmap\n" .
    "/CIDSystemInfo << /Registry (Adobe) /Ordering (UCS) /Supplement 0 >> def\n" .
    "/CMapName /Adobe-Identity-UCS def\n" .
    "/CMapType 2 def\n" .
    "1 begincodespacerange\n" .
    "<0000> <FFFF>\n" .
    "endcodespacerange\n" .
    "1 beginbfrange\n" .
    "<0000> <FFFF> <0000>\n" .
    "endbfrange\n" .
    "endcmap\n" .
    "CMapName currentdict /CMap defineresource pop\n" .
    "end\n" .
    "end\n";
  $toUnicode = $add('<< /Length ' . strlen($toUnicodeStream) . " >>\nstream\n" . $toUnicodeStream . "endstream");
  $font = $add('<< /Type /Font /Subtype /Type0 /BaseFont /Arial /Encoding /Identity-H /DescendantFonts ['.$cidFont.' 0 R] /ToUnicode '.$toUnicode.' 0 R >>');
  $kids = [];
  $perPage = 42;
  $pageChunks = array_chunk($lines, $perPage);
  if (!$pageChunks) $pageChunks = [[]];
  foreach ($pageChunks as $chunk) {
    $y = 805;
    $stream = "";
    foreach ($chunk as $idx => $line) {
      $fontSize = ($idx === 0) ? 16 : 10;
      $x = 42;
      $hex = ua_history_pdf_utf16_hex((string)$line);
      $stream .= "BT /F1 {$fontSize} Tf {$x} {$y} Td <{$hex}> Tj ET\n";
      $y -= ($idx === 0 ? 24 : 16);
    }
    $content = $add('<< /Length '.strlen($stream).' >>' . "\nstream\n" . $stream . "endstream");
    $page = $add('<< /Type /Page /Parent 0 0 R /MediaBox [0 0 595 842] /Resources << /Font << /F1 '.$font.' 0 R >> >> /Contents '.$content.' 0 R >>');
    $kids[] = $page;
  }
  $pagesObjNum = count($objects) + 1;
  foreach ($kids as $pageObj) {
    $objects[$pageObj-1] = str_replace('/Parent 0 0 R', '/Parent '.$pagesObjNum.' 0 R', $objects[$pageObj-1]);
  }
  $pages = $add('<< /Type /Pages /Kids ['.implode(' ', array_map(fn($n)=>$n.' 0 R', $kids)).'] /Count '.count($kids).' >>');
  $catalog = $add('<< /Type /Catalog /Pages '.$pages.' 0 R >>');
  $pdf = "%PDF-1.4\n%\xE2\xE3\xCF\xD3\n";
  $offsets = [0];
  foreach ($objects as $i => $body) {
    $offsets[$i+1] = strlen($pdf);
    $pdf .= ($i+1)." 0 obj\n".$body."\nendobj\n";
  }
  $xref = strlen($pdf);
  $pdf .= "xref\n0 ".(count($objects)+1)."\n0000000000 65535 f \n";
  for ($i=1; $i<=count($objects); $i++) $pdf .= sprintf('%010d 00000 n ', $offsets[$i]) . "\n";
  $pdf .= "trailer\n<< /Size ".(count($objects)+1)." /Root {$catalog} 0 R >>\nstartxref\n{$xref}\n%%EOF";
  return $pdf;
}

function ua_history_render_export_tables(array $sub, string $username, string $histLastLabel, string $histCurrentLabel, array $invoiceRows, array $usageRows, array $eventRows, string $invoiceDateCol): string {
  ob_start();
  ?>
  <h1>سجل المشترك - <?= h((string)($sub['full_name'] ?? $username)) ?></h1>
  <h2>بيانات أساسية</h2>
  <table border="1" cellspacing="0" cellpadding="6">
    <tbody>
    <?php foreach (ua_history_export_basic_rows($sub,$username,$histLastLabel,$histCurrentLabel) as $row): ?>
      <tr><th><?= h($row[0]) ?></th><td><?= h($row[1]) ?></td></tr>
    <?php endforeach; ?>
    </tbody>
  </table>
  <h2>الفواتير</h2>
  <table border="1" cellspacing="0" cellpadding="6">
    <thead><tr><th>#</th><th>الدورة</th><th>الحالة</th><th>المبلغ</th><th>التاريخ</th></tr></thead>
    <tbody>
    <?php if ($invoiceRows): foreach ($invoiceRows as $inv): ?>
      <tr><td><?= (int)($inv['id'] ?? 0) ?></td><td><?= h($inv['cycle_month'] ?? '—') ?></td><td><?= h($inv['status'] ?? ($inv['payment_status'] ?? '—')) ?></td><td><?= h($inv['amount'] ?? ($inv['total_amount'] ?? '0')) ?></td><td><?= h($inv[$invoiceDateCol] ?? '—') ?></td></tr>
    <?php endforeach; else: ?><tr><td colspan="5">لا توجد فواتير</td></tr><?php endif; ?>
    </tbody>
  </table>
  <h2>الاستهلاك الشهري الكلي</h2>
  <table border="1" cellspacing="0" cellpadding="6">
    <thead><tr><th>الشهر</th><th>الاستهلاك</th></tr></thead>
    <tbody>
    <?php if ($usageRows): foreach ($usageRows as $ur): $bytes=(int)($ur['used_bytes']??0); ?>
      <tr><td><?= h($ur['month_key'] ?? '') ?></td><td><?= number_format($bytes / 1073741824, 2) ?> GB</td></tr>
    <?php endforeach; else: ?><tr><td colspan="2">لا توجد بيانات استهلاك</td></tr><?php endif; ?>
    </tbody>
  </table>
  <h2>سجل الحركات</h2>
  <table border="1" cellspacing="0" cellpadding="6">
    <thead><tr><th style="width:24%">التاريخ</th><th style="width:16%">الحركة</th><th style="width:60%">التفاصيل</th></tr></thead>
    <tbody>
    <?php if ($eventRows): foreach ($eventRows as $ev): $eventView = ua_history_event_view($ev); ?>
      <tr><td><?= h($ev['event_at'] ?? '—') ?></td><td><?= h($eventView['action']) ?></td><td><?= h($eventView['details']) ?></td></tr>
    <?php endforeach; else: ?><tr><td colspan="3">لا توجد حركات مسجلة بعد</td></tr><?php endif; ?>
    </tbody>
  </table>
  <?php
  return (string)ob_get_clean();
}

function ua_history_render_pdf_html_document(array $sub, string $username, string $histLastLabel, string $histCurrentLabel, array $invoiceRows, array $usageRows, array $eventRows, string $invoiceDateCol): string {
  $title = 'سجل المشترك - ' . (string)($sub['full_name'] ?? $username);
  $tables = ua_history_render_export_tables($sub, $username, $histLastLabel, $histCurrentLabel, $invoiceRows, $usageRows, $eventRows, $invoiceDateCol);
  return '<!doctype html><html lang="ar" dir="rtl"><head><meta charset="utf-8"><title>'.h($title).'</title><style>' .
    '@page{size:A4 portrait;margin:10mm}' .
    '*{box-sizing:border-box}' .
    'html,body{background:#fff;color:#111}' .
    'body{font-family:Tahoma,Arial,"Segoe UI",sans-serif;margin:0;direction:rtl;font-size:12px;line-height:1.35}' .
    'h1{font-size:22px;margin:0 0 14px;text-align:right;font-weight:800}' .
    'h2{font-size:16px;margin:18px 0 8px;text-align:right;font-weight:800}' .
    'table{width:100%;border-collapse:collapse;margin:8px 0 16px;page-break-inside:auto}' .
    'thead{display:table-header-group}' .
    'tr{page-break-inside:avoid;page-break-after:auto}' .
    'th,td{border:1px solid #999;padding:5px 7px;text-align:right;vertical-align:top;color:#111}' .
    'th{background:#eee;font-weight:800}' .
    '.ua-print-meta{font-size:10px;color:#444;margin-bottom:8px;text-align:left;direction:ltr}' .
    '</style></head><body><div class="ua-print-meta">'.date('Y-m-d H:i:s').'</div>' . $tables . '</body></html>';
}

function ua_history_file_uri(string $path): string {
  $path = str_replace('\\', '/', $path);
  if (preg_match('/^[A-Za-z]:\//', $path)) {
    $prefix = substr($path, 0, 2);
    $rest = substr($path, 2);
    $parts = array_map('rawurlencode', array_filter(explode('/', $rest), 'strlen'));
    return 'file:///' . $prefix . '/' . implode('/', $parts);
  }
  $parts = array_map('rawurlencode', array_filter(explode('/', $path), 'strlen'));
  return 'file:///' . implode('/', $parts);
}

function ua_history_shell_arg(string $arg): string {
  if (DIRECTORY_SEPARATOR === '\\') {
    return '"' . str_replace(['\\', '"'], ['\\\\', '\\"'], $arg) . '"';
  }
  return escapeshellarg($arg);
}

function ua_history_find_pdf_browser(): string {
  $candidates = [];
  if (DIRECTORY_SEPARATOR === '\\') {
    $pf = getenv('ProgramFiles') ?: 'C:\\Program Files';
    $pf86 = getenv('ProgramFiles(x86)') ?: 'C:\\Program Files (x86)';
    $local = getenv('LOCALAPPDATA') ?: '';
    $candidates = [
      $pf . '\\Microsoft\\Edge\\Application\\msedge.exe',
      $pf86 . '\\Microsoft\\Edge\\Application\\msedge.exe',
      $pf . '\\Google\\Chrome\\Application\\chrome.exe',
      $pf86 . '\\Google\\Chrome\\Application\\chrome.exe',
    ];
    if ($local !== '') $candidates[] = $local . '\\Google\\Chrome\\Application\\chrome.exe';
  } else {
    $candidates = ['/usr/bin/google-chrome','/usr/bin/chromium-browser','/usr/bin/chromium','/snap/bin/chromium','/usr/bin/microsoft-edge'];
  }
  foreach ($candidates as $path) {
    if ($path && is_file($path)) return $path;
  }
  return '';
}

function ua_history_render_pdf_with_browser(string $html, string &$err = ''): string {
  if (!function_exists('proc_open')) { $err = 'proc_open غير متاح على الخادم.'; return ''; }
  $browser = ua_history_find_pdf_browser();
  if ($browser === '') { $err = 'لم يتم العثور على Edge/Chrome لتوليد PDF.'; return ''; }
  $base = rtrim((string)sys_get_temp_dir(), "\\/") . DIRECTORY_SEPARATOR . 'ua_history_pdf_' . uniqid('', true);
  if (!@mkdir($base, 0777, true) && !is_dir($base)) { $err = 'تعذر إنشاء مجلد مؤقت.'; return ''; }
  $htmlPath = $base . DIRECTORY_SEPARATOR . 'report.html';
  $pdfPath = $base . DIRECTORY_SEPARATOR . 'report.pdf';
  $profile = $base . DIRECTORY_SEPARATOR . 'profile';
  @mkdir($profile, 0777, true);
  if (@file_put_contents($htmlPath, $html) === false) { $err = 'تعذر كتابة ملف HTML مؤقت.'; return ''; }
  $uri = ua_history_file_uri($htmlPath);
  $args = [
    $browser,
    '--headless=new',
    '--disable-gpu',
    '--no-first-run',
    '--no-default-browser-check',
    '--disable-extensions',
    '--disable-background-networking',
    '--allow-file-access-from-files',
    '--user-data-dir=' . $profile,
    '--print-to-pdf=' . $pdfPath,
    $uri,
  ];
  $cmd = implode(' ', array_map('ua_history_shell_arg', $args));
  $desc = [0=>['pipe','r'], 1=>['pipe','w'], 2=>['pipe','w']];
  $proc = @proc_open($cmd, $desc, $pipes, null, null);
  if (!is_resource($proc)) { $err = 'تعذر تشغيل محرك توليد PDF.'; return ''; }
  @fclose($pipes[0]);
  $start = microtime(true);
  $stdout = '';
  $stderr = '';
  while (true) {
    $status = proc_get_status($proc);
    if (!$status['running']) break;
    if ((microtime(true) - $start) > 30) {
      @proc_terminate($proc);
      $err = 'انتهت مهلة توليد PDF.';
      break;
    }
    usleep(150000);
  }
  if (isset($pipes[1]) && is_resource($pipes[1])) { $stdout = stream_get_contents($pipes[1]); fclose($pipes[1]); }
  if (isset($pipes[2]) && is_resource($pipes[2])) { $stderr = stream_get_contents($pipes[2]); fclose($pipes[2]); }
  @proc_close($proc);
  if ($err !== '') return '';
  if (!is_file($pdfPath) || filesize($pdfPath) < 1000) {
    $err = 'فشل توليد ملف PDF من المتصفح.' . (($stderr !== '') ? (' ' . trim($stderr)) : '');
    return '';
  }
  $data = (string)@file_get_contents($pdfPath);
  if (strncmp($data, '%PDF', 4) !== 0) { $err = 'الملف المولد ليس PDF صالحاً.'; return ''; }
  return $data;
}




$export = strtolower(trim((string)($_GET['export'] ?? '')));
if ($export === 'pdf_file') {
  $pdfName = ua_history_export_safe_filename($username, 'pdf');
  $pdfErr = '';
  $pdfHtml = ua_history_render_pdf_html_document($sub,$username,$histLastLabel,$histCurrentLabel,$invoiceRows,$usageRows,$eventRows,$invoiceDateCol);
  $pdfData = ua_history_render_pdf_with_browser($pdfHtml, $pdfErr);
  while (ob_get_level() > 0) { @ob_end_clean(); }
  if ($pdfData === '') {
    http_response_code(500);
    header('Content-Type: text/plain; charset=UTF-8');
    echo 'فشل توليد PDF: ' . $pdfErr;
    exit;
  }
  header('Content-Type: application/pdf');
  header('Content-Disposition: attachment; filename="' . $pdfName . '"');
  header('Content-Length: ' . strlen($pdfData));
  echo $pdfData;
  exit;
}
if ($export === 'pdf') {
  header('Content-Type: text/html; charset=UTF-8');
  $historyReturnUrl = 'subscribers_history.php?id=' . (int)$id;
  echo '<!doctype html><html lang="ar" dir="rtl"><head><meta charset="utf-8"><title>سجل المشترك - '.h($username).'</title><style>html,body{background:#fff!important;color:#111!important}body{font-family:Tahoma,Arial,sans-serif;margin:24px;color:#111}.ua-report-toolbar{position:sticky;top:0;z-index:5;display:flex;gap:8px;align-items:center;justify-content:flex-start;margin:-24px -24px 20px;padding:10px 16px;background:#f7f7f7;border-bottom:1px solid #cfcfcf}.ua-report-toolbar button,.ua-report-toolbar a{appearance:none;border:1px solid #777;background:#fff;color:#111;text-decoration:none;border-radius:4px;padding:7px 14px;font:700 13px Tahoma,Arial,sans-serif;cursor:pointer}.ua-report-toolbar button:hover,.ua-report-toolbar a:hover{background:#eee}h1{font-size:20px;margin:0 0 18px}h2{font-size:16px;margin:18px 0 8px}table{border-collapse:collapse;margin:10px 0 18px;width:100%}td,th{border:1px solid #999;padding:6px;text-align:right;font-size:12px;color:#111}th{background:#eee}@page{margin:10mm}@media print{.ua-report-toolbar{display:none!important}body{margin:0}}</style></head><body>';
  $savePdfInline = <<<'JS'
event.preventDefault();event.stopPropagation();(async function(btn){
  btn.disabled = true;
  try {
    var url = btn.getAttribute('data-pdf-url');
    var filename = btn.getAttribute('data-filename') || 'subscriber_history.pdf';
    if (!url) throw new Error('رابط ملف PDF غير موجود.');
    var res = await fetch(url, {credentials:'same-origin', cache:'no-store'});
    if (!res.ok) throw new Error('فشل تجهيز ملف PDF.');
    var blob = await res.blob();
    async function writeToHandle(fileHandle){
      var writable = await fileHandle.createWritable();
      await writable.write(blob);
      await writable.close();
    }
    if (window.showDirectoryPicker) {
      var dir = await window.showDirectoryPicker({mode:'readwrite'});
      var fileHandle = await dir.getFileHandle(filename, {create:true});
      await writeToHandle(fileHandle);
      alert('تم حفظ ملف PDF داخل المجلد المحدد.');
      return;
    }
    if (window.showSaveFilePicker) {
      var handle = await window.showSaveFilePicker({suggestedName:filename, types:[{description:'PDF', accept:{'application/pdf':['.pdf']}}]});
      await writeToHandle(handle);
      alert('تم حفظ ملف PDF بنجاح.');
      return;
    }
    var a = document.createElement('a');
    a.href = URL.createObjectURL(blob);
    a.download = filename;
    document.body.appendChild(a);
    a.click();
    setTimeout(function(){ URL.revokeObjectURL(a.href); a.remove(); }, 1000);
    alert('المتصفح لا يدعم اختيار مجلد الحفظ؛ تم تنزيل الملف بالطريقة العادية.');
  } catch(e) {
    if (!(e && e.name === 'AbortError')) alert((e && e.message) || 'فشل حفظ ملف PDF.');
  } finally {
    btn.disabled = false;
  }
})(this);return false;
JS;
  echo '<div class="ua-report-toolbar"><button type="button" id="uaSavePdfFileBtn" data-pdf-url="subscribers_history.php?id='.(int)$id.'&amp;export=pdf_file" data-filename="'.h(ua_history_export_safe_filename($username, 'pdf')).'" onclick="'.h($savePdfInline).'">حفظ PDF</button><a href="'.h($historyReturnUrl).'" onclick="if(window.opener){window.close();return false;}">العودة لسجل المشترك</a></div>';
  echo ua_history_render_export_tables($sub,$username,$histLastLabel,$histCurrentLabel,$invoiceRows,$usageRows,$eventRows,$invoiceDateCol);
  echo '</body></html>';
  exit;
}

$UA_FORCE_DESIGN_V2 = true;
$UA_PAGE_CSS = ['assets/css/ua_subscribers_history_adapter.css'];
require_once __DIR__ . '/header.php';
require_once __DIR__ . '/sidebar.php';
?>
<div class="content-wrapper ua-history-contract-page">
  <section class="content ua-history-content">
    <div class="ua-history-shell">
      <header class="ua-history-head">
        <div class="ua-history-titlebox">
          <div class="ua-history-titleline-main">
            <span class="ua-history-title-main">سجل المشترك</span>
            <span class="ua-history-title-name"><?= h($historySubject) ?></span>
            <p class="ua-history-note" role="note">
              <button type="button" class="ua-history-help" data-tip="قراءة موحّدة لبيانات الاتصال والفواتير والاستهلاك والحركات المسجلة" aria-label="قراءة موحّدة لبيانات الاتصال والفواتير والاستهلاك والحركات المسجلة" title="قراءة موحّدة لبيانات الاتصال والفواتير والاستهلاك والحركات المسجلة">؟</button>
            </p>
          </div>
        </div>
        <div class="ua-history-actions" aria-label="أدوات تصدير سجل المشترك">
          <button type="button" class="ua-history-action" data-history-pdf-file-url="subscribers_history.php?id=<?= (int)$id ?>&amp;export=pdf_file" data-history-pdf-filename="<?= h(ua_history_export_safe_filename($username, 'pdf')) ?>" onclick="event.preventDefault();event.stopPropagation();return (async function(btn){btn.disabled=true;btn.setAttribute('aria-busy','true');btn.classList.add('is-busy');try{var api=(window.showSaveFilePicker?window:((window.top&&window.top.showSaveFilePicker)?window.top:null));if(!api){alert('لا يمكن فتح نافذة اختيار مسار الحفظ من هذا المتصفح. يجب تشغيله على Chromium/Edge داعم أو من نسخة البرنامج المكتبي لاحقاً.');return false;}var filename=btn.getAttribute('data-history-pdf-filename')||'subscriber_history.pdf';var url=btn.getAttribute('data-history-pdf-file-url');var handle=await api.showSaveFilePicker({suggestedName:filename,types:[{description:'PDF',accept:{'application/pdf':['.pdf']}}]});var res=await fetch(url,{credentials:'same-origin',cache:'no-store'});if(!res.ok)throw new Error('فشل تجهيز ملف PDF.');var blob=await res.blob();var out=(blob.type==='application/pdf')?blob:new Blob([blob],{type:'application/pdf'});var writable=await handle.createWritable();await writable.write(out);await writable.close();alert('تم حفظ ملف PDF في المسار المحدد.');}catch(e){if(!(e&&e.name==='AbortError'))alert((e&&e.message)||'فشل حفظ ملف PDF.');}finally{btn.disabled=false;btn.removeAttribute('aria-busy');btn.classList.remove('is-busy');}return false;})(this);"><i class="fa fa-file-pdf-o" aria-hidden="true"></i><span>PDF</span></button>
        </div>
      </header>

      <section class="ua-history-card ua-history-card-main">
        <div class="ua-history-card-head">
          <h2>بيانات أساسية</h2>
        </div>
        <div class="ua-history-card-body">
          <div class="ua-history-metric-grid">
            <div class="ua-history-metric"><span class="ua-history-label">الاسم</span><strong class="ua-history-value"><?= h($sub['full_name'] ?? '') ?></strong></div>
            <div class="ua-history-metric"><span class="ua-history-label">اسم المستخدم</span><strong class="ua-history-value"><?= h($username) ?></strong></div>
            <div class="ua-history-metric"><span class="ua-history-label">تاريخ التسجيل</span><strong class="ua-history-value"><?= h($sub['registered_at'] ?? '—') ?></strong></div>
            <div class="ua-history-metric"><span class="ua-history-label">تاريخ أول تفعيل</span><strong class="ua-history-value"><?= h($sub['first_activated_at'] ?? '—') ?></strong></div>
            <div class="ua-history-metric"><span class="ua-history-label">تاريخ آخر اتصال</span><strong class="ua-history-value"><?= h($sub['last_seen_at'] ?? '—') ?></strong></div>
            <div class="ua-history-metric"><span class="ua-history-label">تاريخ آخر فصل</span><strong class="ua-history-value"><?= h(($sub['mt_last_logged_out'] ?? '') ?: (($sub['ppp_last_cut_at'] ?? '') ?: (($sub['last_disconnect_at'] ?? '') ?: '—'))) ?></strong></div>
            <div class="ua-history-metric"><span class="ua-history-label">آخر MAC سجل دخول</span><strong class="ua-history-value"><?= h($sub['last_caller_id'] ?? '—') ?></strong></div>
            <div class="ua-history-metric"><span class="ua-history-label">نوع جهاز آخر MAC</span><strong class="ua-history-value"><?= h($histLastLabel ?: '—') ?></strong></div>
            <div class="ua-history-metric"><span class="ua-history-label">MAC الحالي</span><strong class="ua-history-value"><?= h($sub['current_caller_id'] ?? '—') ?></strong></div>
            <div class="ua-history-metric"><span class="ua-history-label">نوع الجهاز الحالي</span><strong class="ua-history-value"><?= h($histCurrentLabel ?: '—') ?></strong></div>
            <div class="ua-history-metric"><span class="ua-history-label">IP الحالي</span><strong class="ua-history-value"><?= h($sub['current_ip'] ?? '—') ?></strong></div>
            <div class="ua-history-metric"><span class="ua-history-label">سبب آخر خروج</span><strong class="ua-history-value"><?= h($sub['mt_last_disconnect_reason'] ?? '—') ?></strong></div>
          </div>
        </div>
      </section>

      <div class="ua-history-two-col">
        <section class="ua-history-card">
          <div class="ua-history-card-head">
            <h2>الفواتير</h2>
          </div>
          <div class="ua-history-card-body">
            <div class="ua-history-table-wrap">
              <table class="ua-history-table">
                <thead><tr><th>#</th><th>الدورة</th><th>الحالة</th><th>المبلغ</th><th>التاريخ</th></tr></thead>
                <tbody>
                <?php if ($invoiceRows): foreach ($invoiceRows as $inv): ?>
                  <tr>
                    <td><?= (int)($inv['id'] ?? 0) ?></td>
                    <td><?= h($inv['cycle_month'] ?? '—') ?></td>
                    <td><?= h($inv['status'] ?? ($inv['payment_status'] ?? '—')) ?></td>
                    <td><?= h($inv['amount'] ?? ($inv['total_amount'] ?? '0')) ?></td>
                    <td><?= h($inv[$invoiceDateCol] ?? '—') ?></td>
                  </tr>
                <?php endforeach; else: ?>
                  <tr><td colspan="5" class="ua-history-empty">لا توجد فواتير</td></tr>
                <?php endif; ?>
                </tbody>
              </table>
            </div>
          </div>
        </section>

        <section class="ua-history-card">
          <div class="ua-history-card-head">
            <h2>الاستهلاك الشهري الكلي</h2>
          </div>
          <div class="ua-history-card-body">
            <div class="ua-history-table-wrap">
              <table class="ua-history-table">
                <thead><tr><th>الشهر</th><th>الاستهلاك</th></tr></thead>
                <tbody>
                <?php if ($usageRows): foreach ($usageRows as $ur): $bytes=(int)($ur['used_bytes']??0); ?>
                  <tr>
                    <td><?= h($ur['month_key'] ?? '') ?></td>
                    <td><?= number_format($bytes / 1073741824, 2) ?> GB</td>
                  </tr>
                <?php endforeach; else: ?>
                  <tr><td colspan="2" class="ua-history-empty">لا توجد بيانات استهلاك</td></tr>
                <?php endif; ?>
                </tbody>
              </table>
            </div>
          </div>
        </section>
      </div>

      <section class="ua-history-card ua-history-card-wide">
        <div class="ua-history-card-head">
          <h2>سجل الحركات</h2>
        </div>
        <div class="ua-history-card-body">
          <div class="ua-history-table-wrap ua-history-table-wrap-tall">
            <table class="ua-history-table ua-history-events-table">
              <colgroup>
                <col class="ua-history-event-date">
                <col class="ua-history-event-action">
                <col class="ua-history-event-details">
              </colgroup>
              <thead><tr><th>التاريخ</th><th>الحركة</th><th>التفاصيل</th></tr></thead>
              <tbody>
              <?php if ($eventRows): foreach ($eventRows as $ev): $eventView = ua_history_event_view($ev); ?>
                <tr>
                  <td><?= h($ev['event_at'] ?? '—') ?></td>
                  <td><?= h($eventView['action']) ?></td>
                  <td><?= h($eventView['details']) ?></td>
                </tr>
              <?php endforeach; else: ?>
                <tr><td colspan="3" class="ua-history-empty">لا توجد حركات مسجلة بعد</td></tr>
              <?php endif; ?>
              </tbody>
            </table>
          </div>
        </div>
      </section>
    </div>
  </section>
</div>


<?php require_once __DIR__ . '/footer.php'; ?>
