<?php
declare(strict_types=1);

require_once __DIR__ . '/auth.php';
require_once __DIR__ . '/db_bootstrap.php';
require_once __DIR__ . '/helpers.php';
require_once __DIR__ . '/subscribers_lib.php';
require_once __DIR__ . '/company_profile_lib.php';
require_once __DIR__ . '/subscriber_contracts_lib.php';
require_login('index.php?login=1');
if (function_exists('require_perm')) require_perm('can_view_subscribers');
$conn = ensure_db(true);
subs_ensure_pppoe_cols($conn);
sc_ensure_schema($conn);

function sib_ids(string $raw): array {
    $ids = [];
    $limit = function_exists('sc_contract_export_max_count') ? sc_contract_export_max_count() : 1000;
    foreach (preg_split('/[^0-9]+/', $raw, -1, PREG_SPLIT_NO_EMPTY) as $value) {
        $id = (int)$value;
        if ($id > 0) $ids[$id] = $id;
        if (count($ids) >= $limit) break;
    }
    return array_values($ids);
}
function sib_value(array $row, array $keys): string {
    foreach ($keys as $key) {
        $value = trim((string)($row[$key] ?? ''));
        if ($value !== '') return $value;
    }
    return '';
}
function sib_credentials(mysqli $conn, array $row, string $mode): array {
    $encrypted = $mode === 'encrypted';
    $stageStatus = $encrypted ? subs_policy_staged_account_status($conn, $row) : ['ready'=>true,'stale'=>false,'message'=>''];
    $usePrepared = $encrypted && !empty($stageStatus['ready']);
    return [
        'username' => $usePrepared ? trim((string)($row['pending_ppp_username'] ?? '')) : ($encrypted ? '' : sib_value($row, ['ppp_username','username'])),
        'password' => $usePrepared ? (string)($row['pending_ppp_password'] ?? '') : ($encrypted ? '' : sib_value($row, ['ppp_password','password_plain'])),
        'profile' => $usePrepared ? trim((string)($row['pending_ppp_profile'] ?? '')) : ($encrypted ? '' : sib_value($row, ['ppp_profile','pppoe_profile','mt_profile'])),
        'rate' => subs_rate_limit_display($usePrepared
            ? trim((string)($row['pending_ppp_rate_limit'] ?? ''))
            : ($encrypted ? '' : sib_value($row, ['ppp_rate_limit','mt_rate_limit']))),
        'stale' => !empty($stageStatus['stale']),
        'message' => (string)($stageStatus['message'] ?? ''),
    ];
}
function sib_company_contact_text(array $company): string {
    $parts = [];
    $address = trim((string)($company['address'] ?? ''));
    if ($address !== '') $parts[] = $address;
    foreach (company_profile_contact_lines($company) as $contact) {
        $label = trim((string)($contact['label'] ?? ''));
        $value = trim((string)($contact['value'] ?? ''));
        if ($value !== '') $parts[] = ($label !== '' ? $label . ': ' : '') . $value;
    }
    return implode(' • ', $parts);
}

$idsRaw = (string)($_REQUEST['ids'] ?? '');
$ids = sib_ids($idsRaw);
if (!$ids) { http_response_code(422); exit('حدد مشتركاً واحداً على الأقل.'); }
$mode = strtolower((string)($_REQUEST['credentials'] ?? 'current')) === 'encrypted' ? 'encrypted' : 'current';
$filter = strtolower((string)($_REQUEST['data_filter'] ?? 'all'));
if (!in_array($filter, ['all','complete','incomplete'], true)) $filter = 'all';
$format = strtolower((string)($_GET['format'] ?? 'screen'));
$company = company_profile_fetch($conn);
$companyContactText = sib_company_contact_text($company);
$programName = company_profile_program_name();

$contractFilterWarning = '';
try {
    $contractFilterDefinition = sc_contract_filter_definition($conn);
} catch (Throwable $contractFilterError) {
    $contractFilterDefinition = ['template'=>null, 'required_fields'=>[], 'field_labels'=>sc_contract_field_catalog()];
    $contractFilterWarning = $contractFilterError->getMessage();
}
$contractRequiredFields = (array)$contractFilterDefinition['required_fields'];
$contractFieldLabels = (array)$contractFilterDefinition['field_labels'];
$contractTemplateName = trim((string)($contractFilterDefinition['template']['name'] ?? ''));

$rows = [];
$idList = implode(',', array_map('intval', $ids));
$rs = @$conn->query("SELECT s.*,COALESCE(sec.name,CAST(s.sector_id AS CHAR),'') sector_name FROM subscribers s LEFT JOIN sectors sec ON sec.id=s.sector_id WHERE s.id IN ($idList) AND COALESCE(s.is_deleted,0)=0 ORDER BY FIELD(s.id,$idList)");
if ($rs) while ($row = $rs->fetch_assoc()) $rows[] = $row;

$eligible = [];
$omitted = [];
$stageIds = [];
$stalePrepared = 0;
foreach ($rows as $row) {
    $credentials = sib_credentials($conn, $row, $mode);
    $missingFields = sc_contract_missing_fields($row, $contractRequiredFields);
    $complete = $missingFields === [];
    $include = $filter === 'all' || ($filter === 'complete' && $complete) || ($filter === 'incomplete' && !$complete);
    $row['_credentials'] = $credentials;
    $row['_complete'] = $complete;
    $row['_missing_contract_fields'] = array_map(
        static fn(string $field): string => (string)($contractFieldLabels[$field] ?? $field),
        $missingFields
    );
    if ($include) {
        $eligible[] = $row;
        $stageIds[] = (int)$row['id'];
        if (!empty($credentials['stale'])) $stalePrepared++;
    } else {
        $omitted[] = $row;
    }
}

if ($format === 'word') {
    $filename = 'subscriber-information-' . $mode . '-' . date('Ymd-His') . '.doc';
    header('Content-Type: application/msword; charset=UTF-8');
    header('Content-Disposition: attachment; filename="' . $filename . '"');
    header('Cache-Control: no-store, no-cache, must-revalidate');
}
?><!doctype html>
<html lang="ar" dir="rtl">
<head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width,initial-scale=1">
  <title>تصدير معلومات المشتركين</title>
  <?php if($format === 'word'): ?><style><?= (string)@file_get_contents(__DIR__.'/assets/css/subscriber_info_bulk_export.css') ?></style><?php else: ?>
  <link rel="stylesheet" href="assets/vendor/fontawesome/4.7.0/css/font-awesome.min.css">
  <link rel="stylesheet" href="assets/css/ua_global_feedback.css?v=<?= (int)(@filemtime(__DIR__.'/assets/css/ua_global_feedback.css') ?: 1) ?>">
  <link rel="stylesheet" href="assets/css/subscriber_info_bulk_export.css?v=<?= (int)(@filemtime(__DIR__.'/assets/css/subscriber_info_bulk_export.css') ?: 1) ?>">
  <?php endif; ?>
</head>
<body class="<?= $format === 'word' ? 'sib-word-export' : '' ?>">
<?php if($format !== 'word'): ?>
<header class="sib-toolbar">
  <div class="sib-toolbar-row">
    <div class="sib-stage-sequence" aria-label="تسلسل إعداد البيانات">
      <form method="get" class="sib-filter-form" data-sib-filter-form>
        <input type="hidden" name="ids" value="<?= h(implode(',', $ids)) ?>">
        <label class="sib-step" data-step="1"><span>فلتر المعلومات</span>
          <select name="data_filter" data-sib-stage-lock><option value="all" <?= $filter==='all'?'selected':'' ?>>الجميع</option><option value="complete" <?= $filter==='complete'?'selected':'' ?>>مكتملة المعلومات فقط</option><option value="incomplete" <?= $filter==='incomplete'?'selected':'' ?>>ناقصة المعلومات فقط</option></select>
        </label>
        <label class="sib-step" data-step="2"><span>بيانات الدخول</span>
          <select name="credentials" data-sib-stage-lock><option value="current" <?= $mode==='current'?'selected':'' ?>>الحالية</option><option value="encrypted" <?= $mode==='encrypted'?'selected':'' ?>>المشفرة المجهزة</option></select>
        </label>
        <div class="sib-step sib-stage-control" data-step="3"><span>تجهيز التشفير</span>
          <button type="button" class="sib-icon-button sib-stage-button" data-sib-stage-start data-sib-stage-lock title="تجهيز التشفير للمحددين" aria-label="تجهيز التشفير للمحددين"><i class="fa fa-key"></i><span class="sib-sr-only">تجهيز التشفير للمحددين</span></button>
        </div>
        <div class="sib-export-actions" aria-label="خيارات التصدير">
          <button type="submit" class="sib-icon-button" data-sib-stage-lock title="تطبيق خيارات العرض" aria-label="تطبيق خيارات العرض"><i class="fa fa-check"></i><span class="sib-sr-only">تطبيق خيارات العرض</span></button>
          <button type="button" class="sib-icon-button" data-sib-print data-sib-stage-lock title="تصدير PDF أو طباعة" aria-label="تصدير PDF أو طباعة"><i class="fa fa-file-pdf-o"></i><span class="sib-sr-only">تصدير PDF أو طباعة</span></button>
          <button type="submit" class="sib-icon-button" name="format" value="word" data-sib-stage-lock title="تصدير Word" aria-label="تصدير Word"><i class="fa fa-file-word-o"></i><span class="sib-sr-only">تصدير Word</span></button>
        </div>
      </form>
    </div>
    <a class="sib-icon-button sib-back-button" href="subscribers.php" title="العودة إلى المشتركين" aria-label="العودة إلى المشتركين"><i class="fa fa-arrow-left"></i><span class="sib-sr-only">العودة إلى المشتركين</span></a>
  </div>
  <form method="post" class="sib-stage-form" data-sib-stage-form hidden>
    <?php if(function_exists('ua_csrf_field')) ua_csrf_field(); ?>
    <input type="hidden" name="ids" value="<?= h(implode(',', $stageIds)) ?>">
  </form>
  <div class="sib-summary"><b><?= count($eligible) ?></b> ضمن نتيجة التصدير وفق شروط العقود <span><?= count($omitted) ?> مستثنى حسب الفلتر</span><?php if($contractTemplateName !== ''): ?> <em>قالب: <?= h($contractTemplateName) ?></em><?php endif; ?></div>
  <?php if($contractFilterWarning !== ''): ?><div class="sib-notice is-error"><i class="fa fa-exclamation-triangle"></i><span><?= h($contractFilterWarning) ?></span></div><?php endif; ?>
  <?php if($stalePrepared > 0): ?><div class="sib-notice is-warning"><i class="fa fa-exclamation-triangle"></i><span><?= (int)$stalePrepared ?> من بيانات التشفير المجهزة تتبع لاحقة سابقة، لذلك لم تُعرض. اضغط «تجهيز التشفير» لإعادة توليدها وفق اللاحقة الحالية <b dir="ltr">@<?= h(subs_policy_pppoe_domain($conn)) ?></b>.</span></div><?php endif; ?>
  <section class="sib-progress" data-sib-progress hidden aria-live="polite">
    <div class="sib-progress-head"><span><i class="fa fa-cog fa-spin" data-sib-progress-icon></i><b data-sib-progress-title>جاري تجهيز الحسابات</b></span><strong data-sib-progress-count>0 / <?= count($stageIds) ?></strong></div>
    <div class="sib-progress-track"><span data-sib-progress-fill></span></div>
    <p data-sib-progress-status>يتم تجهيز الدفعة الأولى...</p>
    <details data-sib-progress-errors hidden><summary>عرض الحسابات التي تعذر تجهيزها</summary><ul data-sib-progress-error-list></ul></details>
    <button type="button" class="sib-progress-reload" data-sib-stage-reload hidden><i class="fa fa-refresh"></i><span>تحديث وعرض البيانات المشفرة</span></button>
  </section>
  <?php if($omitted): ?><details class="sib-omitted"><summary>عرض السجلات المستثناة وفق شروط العقود</summary><p><?php foreach($omitted as $i=>$row): ?><?= $i ? '، ' : '' ?>#<?= (int)$row['id'] ?> <?= h((string)($row['full_name'] ?? 'بدون اسم')) ?><?php if(!empty($row['_missing_contract_fields'])): ?> (<?= h(implode('، ',(array)$row['_missing_contract_fields'])) ?>)<?php endif; ?><?php endforeach; ?></p></details><?php endif; ?>
</header>
<?php endif; ?>

<main class="sib-pages">
<?php if(!$eligible): ?><p class="sib-empty">لا توجد سجلات تطابق خيار التصدير.</p><?php endif; ?>
<?php foreach($eligible as $row): $c=$row['_credentials']; $speedDisplay=subs_speed_display($row,(string)$c['profile']); ?>
  <article class="sib-page">
    <header>
      <div class="sib-page-heading">
        <div class="sib-company-brand"><b><?= h((string)$company['company_name']) ?></b><?php if($companyContactText !== ''): ?><span><?= h($companyContactText) ?></span><?php endif; ?></div>
        <div class="sib-subscriber-title"><small>بطاقة معلومات المشترك</small><h1><?= h((string)($row['full_name'] ?? '')) ?></h1></div>
      </div>
      <strong>#<?= (int)$row['id'] ?></strong>
    </header>
    <section class="sib-content">
    <div class="sib-qr"><?php if($c['username'] !== '' && $c['password'] !== ''): ?><div data-sib-qr="<?= h($c['username'] . "\n" . $c['password']) ?>"></div><small>بيانات الدخول</small><?php else: ?><div class="sib-qr-empty"><i class="fa fa-lock"></i><span>غير مجهزة</span></div><?php endif; ?></div>
    <div class="sib-grid">
      <div class="sib-grid-wide"><span>الاسم</span><b><?= h((string)($row['full_name'] ?? '—')) ?></b></div>
      <div><span>الهاتف</span><b dir="ltr"><?= h((string)($row['phone'] ?? '—')) ?></b></div>
      <div class="sib-grid-wide"><span>العنوان</span><b><?= h(sib_value($row,['address_area','address']) ?: '—') ?></b></div>
      <div><span>الوثيقة</span><b><?= h(trim(sib_value($row,['document_type']).' '.sib_value($row,['document_number'])) ?: '—') ?></b></div>
      <div><span>PPPoE Profile</span><code><?= h($c['profile'] ?: '—') ?></code></div>
      <div><span>Rate Limit</span><code dir="ltr"><?= h($c['rate'] ?: '—') ?></code></div>
      <div><span>السرعة</span><b dir="ltr"><?= h($speedDisplay ?: '—') ?></b></div>
      <div class="sib-account sib-grid-wide"><span>PPPoE Username</span><code><?= h($c['username'] ?: '—') ?></code></div>
      <div class="sib-account"><span>PPPoE Password</span><code><?= h($c['password'] ?: '—') ?></code></div>
    </div>
    </section>
    <footer><span>تاريخ التصدير <?= h(date('Y-m-d H:i')) ?></span><span><?= h($programName) ?></span></footer>
  </article>
<?php endforeach; ?>
</main>
<?php if($format !== 'word'): ?>
<script src="assets/js/qr_local.min.js"></script>
<script src="assets/js/ua_global_feedback.js?v=<?= (int)(@filemtime(__DIR__.'/assets/js/ua_global_feedback.js') ?: 1) ?>"></script>
<script>
document.querySelectorAll('[data-sib-qr]').forEach(function(element){
  try {
    if(!window.QRLocal || !element.dataset.sibQr) return;
    var canvas = QRLocal.create(element.dataset.sibQr, 4).toCanvas(116);
    canvas.style.width='116px'; canvas.style.height='116px';
    element.replaceChildren(canvas);
  } catch(error) { element.textContent='QR'; }
});

(function(){
  'use strict';
  var stageForm = document.querySelector('[data-sib-stage-form]');
  var filterForm = document.querySelector('[data-sib-filter-form]');
  var startButton = document.querySelector('[data-sib-stage-start]');
  var printButton = document.querySelector('[data-sib-print]');
  var progress = document.querySelector('[data-sib-progress]');
  if (!stageForm || !filterForm || !startButton || !progress) return;
  var fill = progress.querySelector('[data-sib-progress-fill]');
  var count = progress.querySelector('[data-sib-progress-count]');
  var title = progress.querySelector('[data-sib-progress-title]');
  var status = progress.querySelector('[data-sib-progress-status]');
  var icon = progress.querySelector('[data-sib-progress-icon]');
  var errorBox = progress.querySelector('[data-sib-progress-errors]');
  var errorList = progress.querySelector('[data-sib-progress-error-list]');
  var reloadButton = progress.querySelector('[data-sib-stage-reload]');
  var running = false;
  var ids = String(stageForm.querySelector('input[name="ids"]')?.value || '').split(/[^0-9]+/).map(Number).filter(function(id){return id>0;});
  function lock(value){
    document.querySelectorAll('[data-sib-stage-lock]').forEach(function(control){control.disabled=!!value;});
    startButton.classList.toggle('is-running',!!value);
  }
  function encryptedUrl(){
    var url = new URL(location.href);
    url.searchParams.set('credentials','encrypted');
    url.searchParams.delete('format');
    return url.href;
  }
  function updateProgress(processed,total,succeeded,failed){
    var pct = total ? Math.round((processed/total)*100) : 0;
    fill.style.width = pct + '%';
    count.textContent = processed + ' / ' + total;
    status.textContent = 'تم تجهيز ' + succeeded + ' بنجاح' + (failed ? '، وتعذر تجهيز ' + failed : '') + ' — ' + pct + '%';
  }
  if (printButton) printButton.addEventListener('click',function(){window.print();});
  if (reloadButton) reloadButton.addEventListener('click',function(){location.assign(encryptedUrl());});
  startButton.addEventListener('click', async function(){
    if (running || !ids.length) return;
    if (typeof window.uaDialog !== 'function') {
      if (typeof window.uaToast === 'function') window.uaToast('تعذر تحميل نافذة التأكيد. أعد تحميل الصفحة ثم حاول مجدداً.','error');
      return;
    }
    var ok = await window.uaDialog({
      title: 'تجهيز التشفير للمحددين',
      message: 'سيتم تجهيز بيانات مشفرة لعدد ' + ids.length + ' مشترك داخل قاعدة البيانات فقط، دون حذف أو استبدال أي حساب حالي.',
      kind: 'confirm',
      showCancel: true,
      confirmText: 'تجهيز البيانات',
      cancelText: 'إلغاء',
      icon: 'fa-key'
    });
    if (!ok) return;
    running = true;
    lock(true);
    progress.hidden = false;
    progress.className = 'sib-progress is-running';
    icon.className = 'fa fa-cog fa-spin';
    fill.style.width = '0%';
    title.textContent = 'جاري تجهيز الحسابات';
    status.textContent = 'يتم تجهيز الدفعة الأولى...';
    count.textContent = '0 / ' + ids.length;
    errorBox.hidden = true;
    errorList.innerHTML = '';
    reloadButton.hidden = true;
    var processed = 0, succeeded = 0, failed = 0, failures = [], fatal = false;
    var csrf = stageForm.querySelector('input[name="ua_csrf"],input[name="csrf_token"],input[name="_token"],input[name="csrf"]');
    for (var offset = 0; offset < ids.length; offset += 8) {
      var chunk = ids.slice(offset, offset + 8);
      var body = new FormData();
      if (csrf) body.append(csrf.name, csrf.value);
      chunk.forEach(function(id){body.append('ids[]',String(id));});
      try {
        var response = await fetch('api/subscriber_info_stage_batch.php',{
          method:'POST',body:body,credentials:'same-origin',cache:'no-store',
          headers:{'Accept':'application/json','X-Requested-With':'XMLHttpRequest'}
        });
        var data = await response.json().catch(function(){return {ok:false,message:'استجابة غير مفهومة'};});
        if (!response.ok || !data.ok) {
          var requestError = new Error(data.message || 'فشل تجهيز الدفعة');
          requestError.fatal = response.status === 401 || response.status === 403 || response.status === 419;
          throw requestError;
        }
        succeeded += Number(data.succeeded || 0);
        failed += Number(data.failed || 0);
        (data.results || []).forEach(function(item){if(!item.ok)failures.push('#'+item.id+': '+(item.message||'تعذر التجهيز'));});
      } catch (error) {
        failed += chunk.length;
        chunk.forEach(function(id){failures.push('#'+id+': '+(error&&error.message?error.message:'فشل الاتصال'));});
        fatal = !!(error && error.fatal);
      }
      processed += chunk.length;
      updateProgress(processed,ids.length,succeeded,failed);
      if (fatal) {
        var remaining = ids.slice(processed);
        failed += remaining.length;
        remaining.forEach(function(id){failures.push('#'+id+': توقفت العملية لحماية الطلب بعد انتهاء الجلسة أو الصلاحية');});
        processed = ids.length;
        updateProgress(processed,ids.length,succeeded,failed);
        break;
      }
    }
    running = false;
    lock(false);
    if (failed === 0) {
      progress.className = 'sib-progress is-complete';
      title.textContent = 'اكتمل تجهيز الحسابات';
      icon.className = 'fa fa-check-circle';
      status.textContent = 'تم تجهيز ' + succeeded + ' حساب بنجاح. يجري تحديث البطاقات المشفرة...';
      window.setTimeout(function(){location.assign(encryptedUrl());},900);
      return;
    }
    progress.className = 'sib-progress is-partial';
    title.textContent = succeeded ? 'اكتمل التجهيز مع بعض الأخطاء' : 'تعذر تجهيز الحسابات';
    icon.className = 'fa fa-exclamation-triangle';
    errorBox.hidden = false;
    failures.forEach(function(message){var li=document.createElement('li');li.textContent=message;errorList.appendChild(li);});
    reloadButton.hidden = succeeded === 0;
  });
})();
</script>
<?php endif; ?>
</body>
</html>
