<?php
if (!defined('ALLOW_MANUAL_PPP_CUT_EXECUTION')) define('ALLOW_MANUAL_PPP_CUT_EXECUTION', true);
@ini_set('display_errors','0');
@ini_set('max_execution_time','0');
@set_time_limit(0);
error_reporting(E_ALL & ~E_WARNING & ~E_NOTICE);
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__ . '/mikrotik_lib.php';
require_once __DIR__ . '/subscriber_history_lib.php';
require_once __DIR__ . '/subscribers_bulk_action_lib.php';

require_login('index.php?login=1');
if (function_exists('require_perm')) @require_perm('can_manage_subscribers');
if (function_exists('ensure_db')) ensure_db(true);

$conn = $GLOBALS['conn'] ?? null;
if (!($conn instanceof mysqli)) {
  $_SESSION['flash_warning'] = 'Database connection error';
  header('Location: subscribers.php');
  exit;
}

function bulk_redirect_back(): void {
  header('Location: subscribers.php');
  exit;
}

function bulk_store_and_confirm(): void {
  $action = strtolower(trim((string)($_POST['action'] ?? '')));
  $ids = bulk_parse_ids_value($_POST['ids'] ?? []);

  if (!$ids || !bulk_action_allowed($action)) {
    $_SESSION['flash_warning'] = 'طلب الإدارة الجماعية غير صالح.';
    bulk_redirect_back();
  }

  $go = bulk_build_run_go($action, $ids);
  header('Location: super_admin_guard.php?go=' . urlencode($go));
  exit;
}

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
  bulk_store_and_confirm();
}

if (isset($_GET['single']) && (int)($_GET['single'] ?? 0) === 1) {
  $action = strtolower(trim((string)($_GET['action'] ?? '')));
  $ids = bulk_parse_ids_value([$_GET['id'] ?? 0]);
  if (!$ids || !bulk_action_allowed($action)) {
    $_SESSION['flash_warning'] = 'طلب الإدارة الجماعية غير صالح.';
    bulk_redirect_back();
  }
  $go = bulk_build_run_go($action, $ids);
  header('Location: super_admin_guard.php?go=' . urlencode($go));
  exit;
}

if (!isset($_GET['run'])) {
  bulk_redirect_back();
}

$action = strtolower(trim((string)($_GET['action'] ?? '')));
$ids = bulk_parse_ids_value($_GET['ids'] ?? '');

if (!$ids || !bulk_action_allowed($action)) {
  $_SESSION['flash_warning'] = 'طلب الإدارة الجماعية غير صالح.';
  bulk_redirect_back();
}

$confirmGo = bulk_build_run_go($action, $ids);
require_super_admin_confirmation('إدارة جماعية للمشتركين', $confirmGo);

try {
  $result = bulk_execute_actions($conn, $action, $ids, [
    'source' => 'page',
    'router_context' => 'تنفيذ جماعي للمشتركين',
    'max_errors' => 5,
    'message_prefix' => 'تم تنفيذ إجراء ',
  ]);
  $_SESSION[((int)($result['failed'] ?? 0) > 0) ? 'flash_warning' : 'flash_success'] = (string)($result['message'] ?? 'تم التنفيذ');
} catch (Throwable $e) {
  $_SESSION['flash_warning'] = 'فشل التنفيذ: ' . $e->getMessage();
}

bulk_redirect_back();
