<?php
// admin/subscribers_archive.php (Archive list - separate page)

if (session_status() === PHP_SESSION_NONE) session_start();

require_once __DIR__ . '/helpers.php';
require_once __DIR__ . '/lang.php';
require_once __DIR__ . '/auth.php';
require_once __DIR__ . '/db_bootstrap.php';
require_once __DIR__ . '/db_schema_helpers.php';

require_login('index.php?login=1');
if (function_exists('require_perm')) require_perm('can_subscribers');

if (function_exists('ensure_db')) ensure_db(true);
$conn = $GLOBALS['conn'] ?? null;
if(!$conn) die('DB connection failed');

if (!function_exists('h')) { function h($s){ return htmlspecialchars((string)$s, ENT_QUOTES, 'UTF-8'); } }

$flash_ok  = $_SESSION['flash_ok'] ?? '';
$flash_err = $_SESSION['flash_err'] ?? '';
unset($_SESSION['flash_ok'], $_SESSION['flash_err']);

$q = isset($_GET['q']) ? trim((string)$_GET['q']) : '';
$like = '%' . $q . '%';

$where = "(s.is_deleted=1)";
$types = "";
$params = [];

if ($q !== '') {
  $searchCols = ['username', 'full_name', 'phone', 'ppp_username'];
  if (col_exists($conn, 'subscribers', 'mikrotik_serial')) $searchCols[] = 'mikrotik_serial';
  $idCondition = ctype_digit($q) ? ('s.id=' . (int)$q . ' OR ') : '';
  $where .= " AND (" . $idCondition . implode(' OR ', array_map(static function($col) {
    return "s.`$col` LIKE ?";
  }, $searchCols)) . ")";
  $types = str_repeat('s', count($searchCols));
  $params = array_fill(0, count($searchCols), $like);
}

$sql = "
SELECT s.id, s.full_name, s.username, s.phone,
       " . (col_exists($conn, 'subscribers', 'package') ? "s.package" : "NULL AS package") . ",
       " . (col_exists($conn, 'subscribers', 'speed') ? "s.speed" : "NULL AS speed") . ",
       s.package_name, s.speed_name, s.ppp_username, s.status,
       " . (col_exists($conn, 'subscribers', 'mikrotik_serial') ? "s.mikrotik_serial" : "NULL AS mikrotik_serial") . ",
       s.created_at, s.deleted_at
FROM subscribers s
WHERE $where
ORDER BY s.deleted_at DESC, s.id DESC
";

if($types){
  $stmt = $conn->prepare($sql);
  $stmt->bind_param($types, ...$params);
  $stmt->execute();
  $rows = $stmt->get_result();
} else {
  $rows = $conn->query($sql);
}

$page_title = 'أرشيف المشتركين';
if (!defined('UA_EMBED')) define('UA_EMBED', isset($_GET['embed']) && $_GET['embed'] == '1');
$UA_FORCE_DESIGN_V2 = true;
include __DIR__ . '/header.php';
?>
<div class="content-wrapper ua-extracted-page ua-subscriber-child-page ua-sub-child-archive">
  <section class="content">
    <div class="ua-page-v2">
      <header class="ua-page-head">
        <div class="ua-page-title">
          <h1>أرشيف المشتركين</h1>
          <p>عرض المشتركين المؤرشفين والبحث عنهم أو استعادتم عند الحاجة.</p>
        </div>
        <div class="ua-page-actions">
          <a class="btn btn-outline-secondary" href="subscribers.php"><i class="fa fa-arrow-right"></i> رجوع للمشتركين</a>
        </div>
      </header>

      <?php if($flash_ok): ?><div class="ua-alert alert-success"><?=h($flash_ok)?></div><?php endif; ?>
      <?php if($flash_err): ?><div class="ua-alert alert-danger"><?=h($flash_err)?></div><?php endif; ?>

      <section class="ua-page-toolbar">
          <form method="get" class="ua-page-filters ua-u-full-width">
            <div class="ua-search-control">
              <i class="fa fa-search"></i>
              <input class="form-control" name="q" data-ua-subscriber-search value="<?=h($q)?>" placeholder="ID أو بحث في الأرشيف...">
            </div>
            <div class="ua-toolbar-actions">
              <button class="btn btn-primary" type="submit">بحث</button>
              <a class="btn btn-outline-dark" href="super_admin_guard.php?go=<?= urlencode('subscribers_archive_purge.php?back=subscribers_archive.php') ?>" onclick="return confirm('سيتم تفريغ كامل أرشيف المشتركين. متابعة؟');">تفريغ الأرشيف</a>
            </div>
          </form>
      </section>

      <section class="ua-panel-v2">
        <div class="ua-panel-body">
          <div class="ua-table-wrap">
          <table class="ua-table">
            <thead>
              <tr>
                <th>#</th><th>الاسم</th><th>المستخدم</th><th>الهاتف</th><th>الباقة</th><th>السرعة</th>
                <th>PPPoE</th><th>الحالة</th><th>Serial</th><th>تاريخ الأرشفة</th><th>إجراءات</th>
              </tr>
            </thead>
            <tbody>
            <?php if($rows && $rows->num_rows): while($r=$rows->fetch_assoc()):
              $pkg = $r['package'] ?: ($r['package_name'] ?: '-');
              $spd = $r['speed'] ?: ($r['speed_name'] ?: '-');
              $pppu = $r['ppp_username'] ?: ($r['username'] ?: '');
            ?>
              <tr>
                <td><?= (int)$r['id'] ?></td>
                <td><?= h($r['full_name'] ?? '-') ?></td>
                <td><?= h($r['username'] ?? '-') ?></td>
                <td><?= h($r['phone'] ?? '-') ?></td>
                <td><?= h($pkg) ?></td>
                <td><?= h($spd) ?></td>
                <td><code><?= h($pppu ?: '-') ?></code></td>
                <td><?= h($r['status'] ?? '-') ?></td>
                <td><code><?= h($r['mikrotik_serial'] ?? '-') ?></code></td>
                <td><?= h($r['deleted_at'] ?? '-') ?></td>
                <td>
                  <a class="btn btn-sm btn-outline-secondary" href="subscribers_view.php?id=<?= (int)$r['id'] ?>">عرض</a>
                  <a class="btn btn-sm btn-success ms-1 js-ua-restore" href="subscribers_restore.php?id=<?= (int)$r['id'] ?>" data-id="<?= (int)$r['id'] ?>">استعادة</a>
                </td>
              </tr>
            <?php endwhile; else: ?>
              <tr><td colspan="20" class="text-center">لا يوجد بيانات</td></tr>
            <?php endif; ?>
            </tbody>
          </table>
          </div>
        </div>
      </section>

    </div>
  </section>
</div>


<div class="modal fade" id="uaRestoreModal" tabindex="-1" aria-hidden="true">
  <div class="modal-dialog modal-dialog-centered">
    <div class="modal-content bg-dark text-white border-warning">
      <div class="modal-header">
        <h5 class="modal-title">استعادة من الأرشيف</h5>
        <button type="button" class="btn-close btn-close-white" data-bs-dismiss="modal" aria-label="Close"></button>
      </div>
      <div class="modal-body">
        <p class="mb-2">اختر طريقة الاستعادة:</p>
        <div class="d-grid gap-2">
          <a id="uaRestoreKeep" class="btn btn-success" href="#">استعادة مع السجل السابق</a>
          <a id="uaRestoreClean" class="btn btn-warning" href="#">استعادة بدون السجل السابق</a>
        </div>
      </div>
    </div>
  </div>
</div>
<script>
(function(){
  const modalEl = document.getElementById('uaRestoreModal');
  if (!modalEl || typeof bootstrap === 'undefined') return;
  const modal = new bootstrap.Modal(modalEl);
  const keep = document.getElementById('uaRestoreKeep');
  const clean = document.getElementById('uaRestoreClean');
  document.querySelectorAll('.js-ua-restore').forEach(function(a){
    a.addEventListener('click', function(ev){
      ev.preventDefault();
      const base = a.getAttribute('href');
      keep.href = base + '&mode=keep';
      clean.href = base + '&mode=clean';
      modal.show();
    });
  });
})();
</script>

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