<?php
declare(strict_types=1);

require_once __DIR__ . '/auth.php';
require_once __DIR__ . '/db_bootstrap.php';
require_once __DIR__ . '/helpers.php';
require_once __DIR__ . '/quota_lib.php';
require_once __DIR__ . '/mikrotik_lib.php';
require_once __DIR__ . '/ppp_active_cache_lib.php';
require_once __DIR__ . '/subscriber_status_lib.php';
require_once __DIR__ . '/subscribers_lib.php';
require_once __DIR__ . '/subscriber_contracts_lib.php';
require_once __DIR__ . '/company_profile_lib.php';
require_once __DIR__ . '/subscriber_custom_print_lib.php';

require_login('index.php?login=1');
if (function_exists('require_perm')) require_perm('can_view_subscribers');
$conn = ensure_db(true);

$ids = scp_parse_ids((string)($_REQUEST['ids'] ?? ''));
$columns = scp_parse_columns($_REQUEST['columns'] ?? []);
if (!$ids) { http_response_code(422); exit('حدد مشتركاً واحداً على الأقل.'); }
if (!$columns) { http_response_code(422); exit('اختر عموداً واحداً على الأقل.'); }

$dataFilter = strtolower(trim((string)($_REQUEST['data_filter'] ?? 'all')));
if (!in_array($dataFilter, ['all', 'complete', 'incomplete'], true)) $dataFilter = 'all';
$credentialMode = strtolower(trim((string)($_REQUEST['credentials'] ?? 'current'))) === 'encrypted' ? 'encrypted' : 'current';
$contractRequiredFields = [];
try {
    if (function_exists('sc_ensure_schema')) sc_ensure_schema($conn);
    $filterDefinition = sc_contract_filter_definition($conn);
    $contractRequiredFields = (array)($filterDefinition['required_fields'] ?? []);
} catch (Throwable $filterError) {
    $contractRequiredFields = [];
}

$catalog = scp_column_catalog();
$allRows = scp_fetch_rows($conn, $ids, $credentialMode, $contractRequiredFields);
$rows = array_values(array_filter($allRows, static function(array $row) use ($dataFilter): bool {
    if ($dataFilter === 'all') return true;
    $complete = !empty($row['_complete']);
    return $dataFilter === 'complete' ? $complete : !$complete;
}));
$omittedCount = count($allRows) - count($rows);
$company = company_profile_fetch($conn);
$format = strtolower(trim((string)($_GET['format'] ?? 'screen')));
if (!in_array($format, ['screen', 'word', 'csv'], true)) $format = 'screen';
$baseQuery = http_build_query([
    'ids' => implode(',', $ids),
    'columns' => $columns,
    'data_filter' => $dataFilter,
    'credentials' => $credentialMode,
]);

if ($format === 'csv') {
    $filename = 'subscribers-custom-' . date('Ymd-His') . '.csv';
    header('Content-Type: text/csv; charset=UTF-8');
    header('Content-Disposition: attachment; filename="' . $filename . '"');
    header('Cache-Control: no-store, no-cache, must-revalidate');
    $out = fopen('php://output', 'wb');
    fwrite($out, "\xEF\xBB\xBF");
    fputcsv($out, array_map(static fn(string $key): string => (string)$catalog[$key], $columns));
    foreach ($rows as $row) fputcsv($out, array_map(static fn(string $key): string => (string)($row[$key] ?? '—'), $columns));
    fclose($out);
    exit;
}

if ($format === 'word') {
    $filename = 'subscribers-custom-' . 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_custom_print.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/subscriber_custom_print.css?v=<?= (int)(@filemtime(__DIR__ . '/assets/css/subscriber_custom_print.css') ?: 1) ?>">
  <?php endif; ?>
</head>
<body class="<?= $format === 'word' ? 'scp-word' : '' ?>">
<?php if ($format === 'screen'): ?>
<header class="scp-toolbar">
  <div class="scp-toolbar-head">
    <strong><i class="fa fa-print"></i> الطباعة المخصصة</strong>
    <span><?= count($rows) ?> مشترك · <?= count($columns) ?> أعمدة<?php if ($omittedCount > 0): ?> · <?= $omittedCount ?> مستثنى حسب الفلتر<?php endif; ?></span>
  </div>
  <form method="get" class="scp-filter-form" data-scp-filter-form>
    <input type="hidden" name="ids" value="<?= h(implode(',', $ids)) ?>">
    <?php foreach ($columns as $column): ?><input type="hidden" name="columns[]" value="<?= h($column) ?>"><?php endforeach; ?>
    <label><span>فلتر المعلومات</span><select name="data_filter"><option value="all" <?= $dataFilter === 'all' ? 'selected' : '' ?>>الجميع</option><option value="complete" <?= $dataFilter === 'complete' ? 'selected' : '' ?>>مكتملة المعلومات فقط</option><option value="incomplete" <?= $dataFilter === 'incomplete' ? 'selected' : '' ?>>ناقصة المعلومات فقط</option></select></label>
    <label><span>بيانات الدخول</span><select name="credentials"><option value="current" <?= $credentialMode === 'current' ? 'selected' : '' ?>>الحالية</option><option value="encrypted" <?= $credentialMode === 'encrypted' ? 'selected' : '' ?>>المشفرة المجهزة</option></select></label>
    <button type="submit" title="تطبيق خيارات العرض"><i class="fa fa-check"></i><span>تطبيق</span></button>
  </form>
  <nav aria-label="خيارات التصدير والطباعة">
    <button type="button" data-scp-print title="طباعة أو حفظ PDF"><i class="fa fa-file-pdf-o"></i><span>طباعة / PDF</span></button>
    <a href="subscriber_custom_print.php?<?= h($baseQuery) ?>&amp;format=word" title="تصدير Word"><i class="fa fa-file-word-o"></i><span>Word</span></a>
    <a href="subscriber_custom_print.php?<?= h($baseQuery) ?>&amp;format=csv" title="تصدير CSV"><i class="fa fa-file-excel-o"></i><span>CSV</span></a>
    <a class="scp-back" href="subscribers.php" title="العودة إلى المشتركين"><i class="fa fa-arrow-left"></i><span>العودة</span></a>
  </nav>
</header>
<section class="scp-loading" data-scp-loading hidden aria-live="polite" aria-busy="true">
  <div class="scp-loading-head"><span><i class="fa fa-cog fa-spin"></i><b>جاري تجهيز المعاينة</b></span><strong><?= count($ids) ?> مشترك</strong></div>
  <div class="scp-loading-track"><span></span></div>
  <p>يتم تطبيق الفلاتر وتجهيز بيانات الجدول، يرجى إبقاء الصفحة مفتوحة.</p>
</section>
<?php endif; ?>

<main class="scp-sheet">
  <header class="scp-report-head">
    <div>
      <h1><?= h(trim((string)($company['company_name'] ?? '')) ?: 'قائمة المشتركين') ?></h1>
      <p>تقرير مخصص للمشتركين المحددين</p>
    </div>
    <div class="scp-report-meta"><span>تاريخ الإنشاء</span><b dir="ltr"><?= h(date('Y-m-d H:i')) ?></b></div>
  </header>

  <?php if (!$rows): ?>
    <p class="scp-empty">لم يتم العثور على مشتركين صالحين ضمن التحديد.</p>
  <?php else: ?>
  <div class="scp-table-wrap">
    <table>
      <thead><tr><?php foreach ($columns as $key): ?><th><?= h((string)$catalog[$key]) ?></th><?php endforeach; ?></tr></thead>
      <tbody>
      <?php foreach ($rows as $row): ?><tr><?php foreach ($columns as $key): ?><td class="scp-col-<?= h($key) ?>"><?= h((string)($row[$key] ?? '—')) ?></td><?php endforeach; ?></tr><?php endforeach; ?>
      </tbody>
    </table>
  </div>
  <?php endif; ?>

  <footer><span>عدد السجلات: <?= count($rows) ?></span><span><?= h(function_exists('company_profile_program_name') ? company_profile_program_name() : 'Network Customers') ?></span></footer>
</main>
<?php if ($format === 'screen'): ?><script>
document.querySelector('[data-scp-print]')?.addEventListener('click',function(){window.print();});
(function(){
  var form=document.querySelector('[data-scp-filter-form]');
  var loading=document.querySelector('[data-scp-loading]');
  if(!form||!loading)return;
  form.addEventListener('submit',function(event){
    if(form.dataset.submitting==='1')return;
    event.preventDefault();
    form.dataset.submitting='1';
    loading.hidden=false;
    form.querySelectorAll('button[type="submit"]').forEach(function(control){control.disabled=true;});
    requestAnimationFrame(function(){setTimeout(function(){form.submit();},60);});
  });
  window.addEventListener('pageshow',function(){
    form.dataset.submitting='0';
    form.querySelectorAll('button[type="submit"]').forEach(function(control){control.disabled=false;});
    loading.hidden=true;
  });
})();
</script><?php endif; ?>
</body>
</html>
