<?php
declare(strict_types=1);

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__ . '/security.php';
require_once __DIR__ . '/app_assets.php';
require_once __DIR__ . '/subscriber_router_setup_lib.php';

$agentMode = false;
$agentId = max(0, (int)($_GET['agent'] ?? $_POST['agent'] ?? 0));
$agentContext = null;
if ($agentId > 0) {
    require_once __DIR__ . '/agent_portal_lib.php';
    require_once __DIR__ . '/agent_edit_request_lib.php';
    $agentConn = ensure_db(true);
    $agentContext = agent_portal_boot($agentConn);
    $agentMode = (int)($agentContext['agent_id'] ?? 0) === $agentId && !empty($agentContext['logged']);
    if (!$agentMode) {
        header('Location: agent_portal.php?agent=' . $agentId);
        exit;
    }
    $conn = $agentConn;
} else {
    require_login('index.php?login=1');
    if (function_exists('require_perm')) require_perm('can_view_subscribers');
    if (function_exists('ensure_db')) ensure_db(true);
    $conn = $GLOBALS['conn'] ?? null;
}
if (!($conn instanceof mysqli)) { http_response_code(500); die('Database connection error'); }
$isAndroid = ((string)($_GET['ua_android'] ?? '') === '1') || stripos((string)($_SERVER['HTTP_USER_AGENT'] ?? ''), 'NetworkCustomersAndroid/') !== false;
$routerEmbedMode = !empty($_GET['embed']) || !empty($_GET['ua_modal']) || !empty($_GET['ua_sub_modal']) || !empty($_GET['iframe']);
if (!$agentMode && $routerEmbedMode && !defined('UA_LIGHTWEIGHT_FRAME')) define('UA_LIGHTWEIGHT_FRAME', true);
$routerPage = basename((string)($_SERVER['SCRIPT_NAME'] ?? 'android_router_setup.php'));
$persistentParams = [];
if ($isAndroid) $persistentParams['ua_android'] = 1;
if ($agentMode) $persistentParams['agent'] = $agentId;
$returnToProfilePrint = (string)($_GET['return_to_profile_print'] ?? $_POST['return_to_profile_print'] ?? '') === '1';
$agentEditToken = strtolower(trim((string)($_GET['agent_edit_token'] ?? $_POST['agent_edit_token'] ?? '')));
if ($returnToProfilePrint) $persistentParams['return_to_profile_print'] = 1;
if ($agentEditToken !== '') $persistentParams['agent_edit_token'] = $agentEditToken;
$platformQuery = $persistentParams ? http_build_query($persistentParams) . '&' : '';
$backUrl = $agentMode ? ('agent_portal.php?agent=' . $agentId) : 'subscribers.php';
srs_ensure_schema($conn);

function srs_page_setup(mysqli $conn, int $id): ?array {
    $stmt = $conn->prepare('SELECT r.*,s.full_name,s.phone FROM subscriber_router_setups r JOIN subscribers s ON s.id=r.subscriber_id WHERE r.id=? LIMIT 1');
    if (!$stmt) return null;
    $stmt->bind_param('i', $id); $stmt->execute();
    $row = $stmt->get_result()->fetch_assoc() ?: null; $stmt->close();
    if ($row) $row['payload'] = srs_decrypt((string)$row['encrypted_payload']);
    return $row;
}

function srs_page_agent_can_access(mysqli $conn, array $subscriber, int $agentId, string $editToken): bool {
    if ($agentId <= 0) return true;
    $ownsSubscriber = strtolower(trim((string)($subscriber['created_by_type'] ?? ''))) === 'agent'
        && (int)($subscriber['created_by_id'] ?? 0) === $agentId;
    if ($ownsSubscriber) return true;
    return $editToken !== ''
        && function_exists('ua_agent_edit_request_is_granted')
        && ua_agent_edit_request_is_granted($conn, $editToken, $agentId, (int)($subscriber['id'] ?? 0));
}

$msg = trim((string)($_SESSION['srs_flash'] ?? '')); unset($_SESSION['srs_flash']);
$err = '';
$subscriberId = max(0, (int)($_POST['subscriber_id'] ?? $_GET['subscriber_id'] ?? 0));
if ($subscriberId <= 0) {
    header('Location: ' . $backUrl);
    exit;
}

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    try {
        if (!ua_csrf_verify()) throw new RuntimeException('انتهت صلاحية الطلب. أعد فتح الصفحة.');
        if ((string)($_POST['action'] ?? '') !== 'save_setup') throw new RuntimeException('العملية غير معروفة.');
        $vendor = strtolower(trim((string)($_POST['vendor'] ?? '')));
        $profileKey = trim((string)($_POST['profile_key'] ?? ''));
        $profile = srs_profile($vendor, $profileKey);
        if (!$profile) throw new RuntimeException('اختر شركة وموديل وإصدار عتادي صحيحاً.');
        $stmt = $conn->prepare('SELECT * FROM subscribers WHERE id=? AND COALESCE(is_deleted,0)=0 LIMIT 1');
        $stmt->bind_param('i', $subscriberId); $stmt->execute();
        $subscriber = $stmt->get_result()->fetch_assoc(); $stmt->close();
        if (!$subscriber) throw new RuntimeException('المشترك المحدد غير موجود.');
        if ($agentMode && !srs_page_agent_can_access($conn, $subscriber, $agentId, $agentEditToken)) {
            throw new RuntimeException('لا توجد موافقة صالحة لإعداد راوتر هذا المشترك.');
        }
        $passwordLevel = strtolower(trim((string)($_POST['password_level'] ?? 'strong')));
        if (!in_array($passwordLevel, ['weak','medium','strong'], true)) $passwordLevel = 'strong';
        $wifi = [];
        foreach (['24'=>'2.4 GHz','5'=>'5 GHz','6'=>'6 GHz','7'=>'7 GHz','guest'=>'Guest'] as $key=>$label) {
            $key = (string)$key;
            $enabled = $key !== 'guest' || !empty($_POST['guest_enabled']);
            if (!$enabled || (!in_array($key, ['24','guest'], true) && !in_array($key, (array)$profile['bands'], true))) continue;
            $ssid = trim((string)($_POST['ssid_'.$key] ?? ''));
            $password = (string)($_POST['password_'.$key] ?? '');
            if ($password === '') $password = srs_password($passwordLevel);
            if ($ssid === '' || strlen($ssid) > 32) throw new RuntimeException('اسم شبكة ' . $label . ' يجب أن يكون من 1 إلى 32 بايت.');
            if (!srs_password_valid_for_level($password, $passwordLevel)) throw new RuntimeException('كلمة مرور ' . $label . ' لا تطابق مستوى الحماية المحدد.');
            $wifi[] = ['band'=>$key,'label'=>$label,'ssid'=>$ssid,'password'=>$password,'hidden'=>!empty($_POST['hidden_'.$key]),'qr'=>srs_wifi_qr_payload($ssid,$password,!empty($_POST['hidden_'.$key]))];
        }
        $pppUser = trim((string)($subscriber['ppp_username'] ?? $subscriber['username'] ?? ''));
        $pppPass = trim((string)($subscriber['ppp_password'] ?? $subscriber['password_plain'] ?? ''));
        if ($pppUser === '' || $pppPass === '') throw new RuntimeException('بيانات PPPoE للمشترك غير مكتملة.');
        $setupId = srs_save($conn, $subscriberId, $profile, ['pppoe_username'=>$pppUser,'pppoe_password'=>$pppPass,'password_level'=>$passwordLevel,'wifi'=>$wifi]);
        $_SESSION['srs_flash'] = 'تم حفظ إعدادات Wi‑Fi وإنشاء رموز QR للشبكات.';
        if ($returnToProfilePrint) {
            $printParams = [
                'subscriber_id' => $subscriberId,
                'setup_id' => $setupId,
                'include_wifi' => 1,
                'auto' => 1,
            ];
            if ($agentMode) $printParams['agent'] = $agentId;
            if ($agentEditToken !== '') $printParams['agent_edit_token'] = $agentEditToken;
            header('Location: subscriber_info_print.php?' . http_build_query($printParams));
        } else {
            header('Location: ' . $routerPage . '?' . $platformQuery . 'subscriber_id='.$subscriberId.'&setup_id='.$setupId.'#result');
        }
        exit;
    } catch (Throwable $e) { $err = $e->getMessage(); }
}

$subscriber = null;
if ($subscriberId > 0) {
    $stmt = $conn->prepare('SELECT * FROM subscribers WHERE id=? AND COALESCE(is_deleted,0)=0 LIMIT 1');
    $stmt->bind_param('i', $subscriberId); $stmt->execute();
    $subscriber = $stmt->get_result()->fetch_assoc() ?: null; $stmt->close();
    if ($subscriber && $agentMode && !srs_page_agent_can_access($conn, $subscriber, $agentId, $agentEditToken)) {
        http_response_code(403);
        $err = 'لا توجد موافقة صالحة لإعداد راوتر هذا المشترك.';
        $subscriber = null;
    }
}
$profiles = srs_profiles();
$selectedSetup = isset($_GET['setup_id']) ? srs_page_setup($conn, max(0,(int)$_GET['setup_id'])) : null;
$suggest24 = $subscriber ? srs_ssid($subscriber,'2.4') : '';
$suggest5 = $subscriber ? srs_ssid($subscriber,'5') : '';
$suggest6 = $subscriber ? srs_ssid($subscriber,'6') : '';
$suggest7 = $subscriber ? srs_ssid($subscriber,'7') : '';
$suggestGuest = $subscriber ? srs_ssid($subscriber,'guest') : '';
$companyName = trim((string)($agentContext['company']['company_name'] ?? ''));
if ($companyName === '' && function_exists('table_exists') && table_exists($conn, 'company_info')) {
    $companyResult = @$conn->query("SELECT company_name FROM company_info WHERE COALESCE(company_name,'')<>'' ORDER BY id=1 DESC,id ASC LIMIT 1");
    if ($companyResult && ($companyRow = $companyResult->fetch_assoc())) $companyName = trim((string)($companyRow['company_name'] ?? ''));
}
if ($companyName === '') $companyName = 'الشركة';
$printSubscriberName = trim((string)($subscriber['full_name'] ?? $selectedSetup['full_name'] ?? '')) ?: ('المشترك #' . $subscriberId);
require_once __DIR__ . '/output_devices_lib.php';
$wifiPrintRoute = ua_output_route($conn, 'wifi_qr_cards');
$thermalPaper = in_array((string)($wifiPrintRoute['paper_size'] ?? ''), ['58mm','80mm'], true) ? (string)$wifiPrintRoute['paper_size'] : '80mm';
$page_title = 'إعداد الراوتر';
$UA_FORCE_DESIGN_V2 = true;
$UA_PAGE_CSS = $isAndroid
    ? ['assets/css/android_router_setup.css']
    : ['assets/css/android_router_setup.css', 'assets/css/subscriber_router_setup.css'];
if ($agentMode) {
    agent_portal_render_head($page_title, $UA_PAGE_CSS);
    agent_portal_render_shell_start($conn, (array)$agentContext, 'router');
} else {
    include __DIR__ . '/header.php';
}
?>
<div class="content-wrapper android-router-setup <?= $isAndroid ? 'is-android' : 'is-desktop' ?>" data-router-setup>
  <main class="ars-main">
    <header class="ars-heading"><div><span>Subscriber Router Setup</span><h1>إعداد الراوتر</h1><p>إعداد حساب الإنترنت وشبكات Wi‑Fi مباشرة من بيانات المشترك.</p></div><a href="<?= h($backUrl) ?>"><i class="fa fa-arrow-right"></i><b>رجوع</b></a></header>
    <?php if($msg!==''): ?><div class="ars-alert is-success"><i class="fa fa-check-circle"></i><?= h($msg) ?></div><?php endif; ?>
    <?php if($err!==''): ?><div class="ars-alert is-error"><i class="fa fa-exclamation-circle"></i><?= h($err) ?></div><?php endif; ?>

    <section class="ars-card ars-subscriber-card">
      <div class="ars-card-head"><div><span>بيانات جاهزة من ملف المشترك</span><h2><?= h((string)($subscriber['full_name'] ?: ('مشترك #'.$subscriberId))) ?></h2></div><b class="ars-subscriber-id">#<?= $subscriberId ?></b></div>
      <div class="ars-ppp"><div><span>اسم شبكة Wi‑Fi المقترح</span><strong dir="ltr"><?= h($suggest24) ?></strong></div><div><span>اسم حساب PPPoE</span><strong dir="ltr"><?= h((string)($subscriber['ppp_username'] ?? $subscriber['username'] ?? '')) ?></strong></div><div><span>كلمة مرور PPPoE</span><strong dir="ltr"><?= h((string)($subscriber['ppp_password'] ?? $subscriber['password_plain'] ?? '')) ?></strong></div></div>
    </section>

    <?php if($subscriber): ?>
    <form method="post" data-router-form data-ua-android-native-layout>
      <?php ua_csrf_field(); ?><input type="hidden" name="action" value="save_setup"><input type="hidden" name="subscriber_id" value="<?= $subscriberId ?>"><?php if($agentMode): ?><input type="hidden" name="agent" value="<?= $agentId ?>"><?php endif; ?><?php if($returnToProfilePrint): ?><input type="hidden" name="return_to_profile_print" value="1"><?php endif; ?><?php if($agentEditToken !== ''): ?><input type="hidden" name="agent_edit_token" value="<?= h($agentEditToken) ?>"><?php endif; ?>
      <section class="ars-card ars-device-card">
        <div class="ars-card-head"><div><span>1 · نوع الراوتر</span><h2>الراوتر والنطاقات المدعومة</h2></div><i class="ars-router-glyph"><svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.8" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><path d="M5 11V5m14 6V5"/><rect x="3" y="11" width="18" height="8" rx="2"/><circle cx="7" cy="15" r="1"/><circle cx="11" cy="15" r="1"/><path d="M15 15h3"/></svg></i></div>
        <div class="ars-pair"><label><span>الشركة</span><select name="vendor" data-vendor required><?php foreach($profiles as $vendorKey=>$vendor): ?><option value="<?= h($vendorKey) ?>"><?= h((string)$vendor['label']) ?></option><?php endforeach; ?></select></label><label><span>الموديل والإصدار</span><select name="profile_key" data-profile required></select></label></div>
      </section>

      <section class="ars-card ars-networks-card">
        <div class="ars-card-head"><div><span>2 · الشبكات</span><h2>أسماء Wi‑Fi وكلمات المرور</h2></div><button type="button" data-generate-all><i class="fa fa-random"></i> توليد جديد</button></div>
        <div class="ars-generate-feedback" data-generate-feedback role="status" aria-live="polite" hidden></div>
        <div class="ars-security-level"><label><span>مستوى كلمة مرور Wi‑Fi</span><select name="password_level" data-level><option value="weak">ضعيف · 8 أرقام</option><option value="medium">متوسط · 8 أرقام + حرف + رمز</option><option value="strong" selected>قوي · أرقام وأحرف ورموز · 10 خانات</option></select></label><p data-level-help>كلمة قوية من 10 خانات، وتُنشأ عشوائياً من جديد عند كل طلب.</p></div>
        <div class="ars-networks-grid">
        <article class="ars-network" data-network-band="24"><header><div><i class="fa fa-wifi"></i><b>الشبكة الرئيسية · 2.4 GHz</b></div><button type="button" data-generate="24"><i class="fa fa-refresh"></i></button></header><label><span>اسم الشبكة من اسم المشترك بالإنجليزية</span><input name="ssid_24" value="<?= h($suggest24) ?>" maxlength="32" required data-required-network></label><label><span>كلمة مرور Wi‑Fi</span><div class="ars-password"><input name="password_24" dir="ltr" minlength="8" maxlength="10" required data-required-network><button type="button" data-toggle-password><i class="fa fa-eye"></i></button></div></label><label class="ars-check"><input type="checkbox" name="hidden_24"><span>شبكة مخفية</span></label></article>
        <article class="ars-network" data-network-band="5"><header><div><i class="fa fa-wifi"></i><b>النطاق الثاني · 5 GHz</b></div><button type="button" data-generate="5"><i class="fa fa-refresh"></i></button></header><label><span>اسم الشبكة</span><input name="ssid_5" value="<?= h($suggest5) ?>" maxlength="32" required data-required-network></label><label><span>كلمة مرور Wi‑Fi</span><div class="ars-password"><input name="password_5" dir="ltr" minlength="8" maxlength="10" required data-required-network><button type="button" data-toggle-password><i class="fa fa-eye"></i></button></div></label><label class="ars-check"><input type="checkbox" name="hidden_5"><span>شبكة مخفية</span></label></article>
        <article class="ars-network" data-network-band="6" hidden><header><div><i class="fa fa-wifi"></i><b>النطاق الإضافي · 6 GHz</b></div><button type="button" data-generate="6"><i class="fa fa-refresh"></i></button></header><label><span>اسم الشبكة</span><input name="ssid_6" value="<?= h($suggest6) ?>" maxlength="32" data-required-network></label><label><span>كلمة مرور Wi‑Fi</span><div class="ars-password"><input name="password_6" dir="ltr" minlength="8" maxlength="10" data-required-network><button type="button" data-toggle-password><i class="fa fa-eye"></i></button></div></label><label class="ars-check"><input type="checkbox" name="hidden_6"><span>شبكة مخفية</span></label></article>
        <article class="ars-network" data-network-band="7" hidden><header><div><i class="fa fa-wifi"></i><b>النطاق الإضافي · 7 GHz</b></div><button type="button" data-generate="7"><i class="fa fa-refresh"></i></button></header><label><span>اسم الشبكة</span><input name="ssid_7" value="<?= h($suggest7) ?>" maxlength="32" data-required-network></label><label><span>كلمة مرور Wi‑Fi</span><div class="ars-password"><input name="password_7" dir="ltr" minlength="8" maxlength="10" data-required-network><button type="button" data-toggle-password><i class="fa fa-eye"></i></button></div></label><label class="ars-check"><input type="checkbox" name="hidden_7"><span>شبكة مخفية</span></label></article>
        <article class="ars-network"><label class="ars-check ars-guest-toggle"><input type="checkbox" name="guest_enabled" value="1" data-guest-toggle><span>تفعيل شبكة ضيوف إضافية</span></label><div data-guest-fields hidden><label><span>اسم شبكة الضيوف</span><input name="ssid_guest" value="<?= h($suggestGuest) ?>" maxlength="32"></label><label><span>كلمة المرور</span><div class="ars-password"><input name="password_guest" dir="ltr" minlength="8" maxlength="10"><button type="button" data-toggle-password><i class="fa fa-eye"></i></button></div></label><label class="ars-check"><input type="checkbox" name="hidden_guest"><span>شبكة مخفية</span></label></div></article>
        </div>
        <button class="ars-primary"><i class="fa fa-save"></i><span>حفظ إعدادات Wi‑Fi وإنشاء QR</span></button>
      </section>
    </form>
    <?php endif; ?>

    <?php if($selectedSetup): $payload=(array)$selectedSetup['payload']; $wifi=array_values((array)($payload['wifi']??[])); $wifiSheets=array_chunk($wifi,2); ?>
    <section class="ars-card ars-result" id="result">
      <div class="ars-card-head"><div><span>3 · النتيجة</span><h2>بطاقات شبكات Wi‑Fi</h2></div><button type="button" onclick="window.print()"><i class="fa fa-print"></i> طباعة حرارية <?= h($thermalPaper) ?></button></div>
      <div class="ars-thermal-pages">
        <?php foreach($wifiSheets as $sheetIndex=>$sheetNetworks): ?>
          <section class="ars-thermal-sheet ars-paper-<?= h($thermalPaper) ?>" data-thermal-sheet>
            <header class="ars-print-brand"><strong><?= h($companyName) ?></strong><span><?= h($printSubscriberName) ?></span></header>
            <div class="ars-qr-grid"><?php foreach($sheetNetworks as $network): ?><article><div class="ars-qr" data-qr="<?= h((string)($network['qr']??'')) ?>"></div><h3 dir="ltr"><?= h((string)($network['ssid']??'')) ?></h3><p><?= h((string)($network['label']??'')) ?></p><strong dir="ltr"><?= h((string)($network['password']??'')) ?></strong></article><?php endforeach; ?></div>
            <footer class="ars-print-note">امسح الرمز للاتصال بالشبكة مباشرة</footer>
          </section>
        <?php endforeach; ?>
      </div>
    </section>
    <?php endif; ?>
  </main>
</div>
<?php if($selectedSetup) echo ua_asset_tag_js('qrcode_js'); ?>
<script>
(()=>{
 const profiles=<?= json_encode($profiles,JSON_UNESCAPED_UNICODE|JSON_UNESCAPED_SLASHES) ?>;
 const vendor=document.querySelector('[data-vendor]'),model=document.querySelector('[data-profile]');
 function fillModels(){if(!vendor||!model)return;const group=profiles[vendor.value]||{models:{}};model.innerHTML='';Object.entries(group.models).forEach(([key,p])=>{const o=document.createElement('option');o.value=key;o.textContent=p.model+' · '+p.revision;model.appendChild(o)});updateProfile()}
 function updateProfile(){
  if(!vendor||!model)return;
  const p=profiles[vendor.value]?.models?.[model.value];
  if(!p)return;
  document.querySelectorAll('[data-network-band]').forEach((network)=>{
   const band=network.dataset.networkBand;
   const supported=band==='24'||p.bands.includes(band);
   network.toggleAttribute('hidden',!supported);
   network.querySelectorAll('input,select,textarea,button').forEach((control)=>{
    control.disabled=!supported;
    if(control.matches('[data-required-network]'))control.required=supported;
   });
   if(supported&&!network.querySelector('.ars-password input')?.value)setPassword(band);
  });
 }
 vendor?.addEventListener('change',fillModels);model?.addEventListener('change',updateProfile);
 const digitChars='0123456789',letterChars='ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz',symbolChars='!#$%+-_@';
 function pick(chars,count){const values=new Uint32Array(count);crypto.getRandomValues(values);return Array.from(values,v=>chars[v%chars.length]).join('')}
 function shuffle(value){const chars=[...value],values=new Uint32Array(chars.length);crypto.getRandomValues(values);for(let i=chars.length-1;i>0;i--){const j=values[i]%(i+1);[chars[i],chars[j]]=[chars[j],chars[i]]}return chars.join('')}
 function randomPassword(){const level=document.querySelector('[data-level]')?.value||'strong';if(level==='weak')return pick(digitChars,8);if(level==='medium')return shuffle(pick(digitChars,8)+pick(letterChars,1)+pick(symbolChars,1));return shuffle(pick(digitChars,3)+pick(letterChars,4)+pick(symbolChars,3))}
 function setPassword(key){const input=document.querySelector('[name="password_'+key+'"]');if(!input)return null;input.value=randomPassword();return input}
 function activeNetworkKeys(){const keys=[];document.querySelectorAll('[data-network-band]:not([hidden])').forEach(n=>keys.push(n.dataset.networkBand));if(document.querySelector('[data-guest-toggle]')?.checked)keys.push('guest');return keys}
 function refreshLevelHelp(){const level=document.querySelector('[data-level]')?.value||'strong',help=document.querySelector('[data-level-help]');if(!help)return;help.textContent=level==='weak'?'8 أرقام عشوائية تتغير في كل مرة.':(level==='medium'?'10 خانات: 8 أرقام وحرف واحد ورمز واحد.':'10 خانات عشوائية من الأرقام والأحرف والرموز.')}
 let generationTimer=0;
 function showGenerated(keys){
  const inputs=keys.map(setPassword).filter(Boolean),feedback=document.querySelector('[data-generate-feedback]');
  if(!inputs.length)return;
  clearTimeout(generationTimer);
  inputs.forEach(input=>{if(!input.dataset.beforeGenerateType)input.dataset.beforeGenerateType=input.type;input.type='text';input.classList.add('is-regenerated')});
  if(feedback){feedback.hidden=false;feedback.innerHTML='<i class="fa fa-check-circle"></i> تم توليد '+inputs.length+' كلمة مرور جديدة وإظهارها مؤقتاً.'}
  generationTimer=setTimeout(()=>{
   inputs.forEach(input=>{if(input.dataset.beforeGenerateType==='password')input.type='password';input.classList.remove('is-regenerated');delete input.dataset.beforeGenerateType});
   if(feedback)feedback.hidden=true;
  },4000);
 }
 function regenerateVisible(announce=true){const keys=activeNetworkKeys();if(announce)showGenerated(keys);else keys.forEach(setPassword);return keys}
 document.querySelectorAll('[data-generate]').forEach(b=>b.addEventListener('click',()=>showGenerated([b.dataset.generate])));document.querySelector('[data-generate-all]')?.addEventListener('click',()=>regenerateVisible(true));
 document.querySelector('[data-level]')?.addEventListener('change',()=>{refreshLevelHelp();regenerateVisible(true)});
 document.querySelectorAll('[data-toggle-password]').forEach(b=>b.addEventListener('click',()=>{const i=b.parentElement.querySelector('input');i.type=i.type==='password'?'text':'password';b.querySelector('i').className='fa '+(i.type==='password'?'fa-eye':'fa-eye-slash')}));document.querySelectorAll('.ars-password input').forEach(i=>i.type='password');
 const guest=document.querySelector('[data-guest-toggle]'),guestFields=document.querySelector('[data-guest-fields]');guest?.addEventListener('change',()=>{guestFields.hidden=!guest.checked;guestFields.querySelectorAll('input').forEach(i=>i.required=guest.checked);if(guest.checked)setPassword('guest')});
 document.querySelector('[data-router-form]')?.addEventListener('submit',()=>{document.querySelectorAll('.ars-password input').forEach(i=>i.type='password')});
 fillModels();
 if(document.querySelector('[data-router-form]')){refreshLevelHelp();regenerateVisible(false)}
 document.querySelectorAll('[data-qr]').forEach(el=>{
  if(window.QRCode){
   new QRCode(el,{text:el.dataset.qr,width:164,height:164,correctLevel:QRCode.CorrectLevel.M});
  }else if(window.QRLocal){
   el.replaceChildren(QRLocal.create(el.dataset.qr,4).toCanvas(164));
  }
 });
})();
</script>
<?php if($selectedSetup){ require_once __DIR__ . '/output_devices_lib.php'; ua_output_print_bootstrap($conn, 'wifi_qr_cards', (string)$selectedSetup['id']); } ?>
<?php if($agentMode) agent_portal_render_shell_end(); else include __DIR__ . '/footer.php'; ?>
