<?php
@ini_set('display_errors','0');
error_reporting(E_ALL & ~E_WARNING & ~E_NOTICE);

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__ . '/settings_store.php';

if (function_exists('ensure_db')) ensure_db(true);
if (function_exists('require_perm')) @require_perm('can_pppoe_cut_restore');
require_super_admin_confirmation('سرعة مفتوحة للمحددين');

$conn = $GLOBALS['conn'] ?? null;
if (!($conn instanceof mysqli)) {
  http_response_code(500);
  die('Database connection error');
}

function ua_sel_flash(string $type, string $msg): void { $_SESSION[$type] = $msg; }
function ua_sel_back(): void { header('Location: subscribers.php'); exit; }
function ua_sel_col_exists(mysqli $conn, string $table, string $col): bool {
  $t=$conn->real_escape_string($table); $c=$conn->real_escape_string($col);
  $rs=@$conn->query("SELECT 1 FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_SCHEMA=DATABASE() AND TABLE_NAME='$t' AND COLUMN_NAME='$c' LIMIT 1");
  return ($rs && $rs->num_rows>0);
}
function ua_sel_backup_table(mysqli $conn): void {
  @$conn->query("CREATE TABLE IF NOT EXISTS ppp_open_all_backup (
    id INT AUTO_INCREMENT PRIMARY KEY,
    subscriber_id INT NULL,
    username VARCHAR(128) NOT NULL,
    original_profile VARCHAR(128) NOT NULL DEFAULT '',
    original_rate_limit VARCHAR(255) NOT NULL DEFAULT '',
    backup_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
    UNIQUE KEY uq_username (username)
  ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4");
}
function ua_sel_invalidate_unsafe_cache(): void { @unlink(__DIR__ . '/cache/runtime/unsafe_speed_count.json'); }
function ua_sel_mark_open(mysqli $conn, int $subscriberId, string $openProfile='OPEN-ALL-UNLIMITED'): void {
  if ($subscriberId <= 0) return;
  $sets = [];
  if (ua_sel_col_exists($conn,'subscribers','speed_state')) $sets[] = "speed_state='OPEN_SPEED'";
  if (ua_sel_col_exists($conn,'subscribers','ppp_profile')) $sets[] = "ppp_profile='" . $conn->real_escape_string($openProfile) . "'";
  if (ua_sel_col_exists($conn,'subscribers','ppp_rate_limit')) $sets[] = "ppp_rate_limit=''";
  if ($sets) @$conn->query('UPDATE subscribers SET ' . implode(',', $sets) . ' WHERE id=' . (int)$subscriberId);
}

$action = strtolower(trim((string)($_GET['action'] ?? 'open')));
if ($action !== 'open') { ua_sel_flash('flash_warning','الإجراء غير صحيح.'); ua_sel_back(); }

$idsRaw = trim((string)($_GET['ids'] ?? ''));
$ids = array_values(array_unique(array_filter(array_map('intval', preg_split('/[^0-9]+/', $idsRaw)))));
if (!$ids) { ua_sel_flash('flash_warning','لم يتم تحديد مشتركين.'); ua_sel_back(); }
if (count($ids) > 300) $ids = array_slice($ids, 0, 300);

try {
  if (function_exists('mt_require_router_online_or_throw')) mt_require_router_online_or_throw($conn, 'سرعة مفتوحة للمحددين');

  ua_sel_backup_table($conn);
  $openProfile = 'OPEN-ALL-UNLIMITED';
  if (!mt_ppp_profile_ensure($conn, $openProfile, '')) {
    throw new RuntimeException((string)($GLOBALS['mt_last_error'] ?? 'تعذر تجهيز بروفايل السرعة المفتوحة.'));
  }

  $idList = implode(',', $ids);
  $cols = 'id, username';
  if (ua_sel_col_exists($conn,'subscribers','ppp_username')) $cols .= ', ppp_username';
  if (ua_sel_col_exists($conn,'subscribers','ppp_profile')) $cols .= ', ppp_profile';
  if (ua_sel_col_exists($conn,'subscribers','mt_profile')) $cols .= ', mt_profile';
  $rs = @$conn->query("SELECT $cols FROM subscribers WHERE id IN ($idList)");
  $targets = [];
  if ($rs) {
    while ($r=$rs->fetch_assoc()) {
      $u = trim((string)($r['ppp_username'] ?? ''));
      if ($u==='') $u = trim((string)($r['username'] ?? ''));
      if ($u==='') continue;
      $fallback = trim((string)($r['ppp_profile'] ?? ''));
      if ($fallback==='') $fallback = trim((string)($r['mt_profile'] ?? ''));
      $targets[$u] = ['subscriber_id'=>(int)($r['id'] ?? 0), 'fallback_profile'=>$fallback];
    }
  }
  if (!$targets) { ua_sel_flash('flash_warning','لا يوجد مشتركون صالحون للتنفيذ.'); ua_sel_back(); }

  $api = mt_api($conn);
  if (!$api) throw new RuntimeException((string)($GLOBALS['mt_last_error'] ?? 'فشل الاتصال بالمايكروتك.'));

  $stmt = @$conn->prepare("INSERT INTO ppp_open_all_backup(subscriber_id,username,original_profile,original_rate_limit) VALUES (?,?,?,?) ON DUPLICATE KEY UPDATE subscriber_id=VALUES(subscriber_id), original_profile=VALUES(original_profile), original_rate_limit=VALUES(original_rate_limit)");
  if (!$stmt) throw new RuntimeException('تعذر تجهيز النسخة الاحتياطية لملفات السرعة.');

  $changed=0;
  foreach ($targets as $username=>$meta) {
    $secret = mt_ppp_find_secret_row($api, $username);
    $secretId = trim((string)($secret['.id'] ?? $secret['id'] ?? ''));
    if ($secretId==='') continue;

    $origProfile = trim((string)($secret['profile'] ?? ''));
    if ($origProfile==='') $origProfile = trim((string)($meta['fallback_profile'] ?? ''));
    $origRate = trim((string)($secret['rate-limit'] ?? $secret['rate_limit'] ?? ''));

    $sid=(int)($meta['subscriber_id'] ?? 0);
    $stmt->bind_param('isss', $sid, $username, $origProfile, $origRate);
    if (!$stmt->execute()) throw new RuntimeException('فشل حفظ النسخة الاحتياطية للحساب: '.$username);

    $res = $api->command(['/ppp/secret/set', '=.id='.$secretId, '=profile='.$openProfile, '=rate-limit=']);
    $msg='';
    if (function_exists('mt_rows_has_error') && mt_rows_has_error($res,$msg)) throw new RuntimeException('فشل فتح سرعة الحساب '.$username.': '.$msg);
    @mt_ppp_active_disconnect($conn, $username);
    ua_sel_mark_open($conn, $sid, $openProfile);
    $changed++;
  }

  ua_sel_invalidate_unsafe_cache();
  ua_sel_flash('flash_success','تم فتح السرعة للمشتركين المحددين. عدد الحسابات المعدلة: '.$changed);
} catch (Throwable $e) {
  ua_sel_flash('flash_warning','فشل تنفيذ السرعة المفتوحة: '.$e->getMessage());
} finally {
  try { if (isset($api) && $api) $api->disconnect(); } catch (Throwable $e) {}
}
ua_sel_back();
