<?php
if (session_status() === PHP_SESSION_NONE) session_start();
require_once __DIR__ . '/helpers.php';
require_once __DIR__ . '/auth.php';
require_once __DIR__ . '/db_bootstrap.php';
require_once __DIR__ . '/super_admin_guard.php';
require_once __DIR__ . '/subscriber_id_sequence_lib.php';

require_login('index.php?login=1');
if (function_exists('require_perm')) require_perm('can_manage_subscribers');
require_super_admin_confirmation('تفريغ أرشيف المشتركين');
if (function_exists('ensure_db')) ensure_db(true);
$conn = $GLOBALS['conn'] ?? null;
if (!($conn instanceof mysqli)) { $_SESSION['flash_err']='DB connection failed'; header('Location: subscribers_archive.php'); exit; }

// Reserve every current and archived serial before physical deletion.
ua_subscriber_id_registry_ensure($conn);
$ok = @$conn->query("DELETE FROM subscribers WHERE COALESCE(is_deleted,0)=1");
if ($ok) {
  $_SESSION['flash_ok'] = 'تم تفريغ أرشيف المشتركين بنجاح.';
} else {
  $_SESSION['flash_err'] = 'فشل تفريغ الأرشيف: ' . ($conn->error ?? 'unknown');
}
header('Location: subscribers_archive.php');
exit;
