<?php
$page_title = 'المعالج الذكي | Smart Wizard';
require_once __DIR__ . '/auth.php';
require_login();
if(function_exists('require_any_perm')) require_any_perm(['can_settings','can_mikrotik_sync']);
elseif(function_exists('require_perm')) require_perm('can_settings');
$UA_FORCE_DESIGN_V2 = true;
$uaAndroidNetworkWizard = ((string)($_GET['ua_android'] ?? '') === '1')
  || stripos((string)($_SERVER['HTTP_USER_AGENT'] ?? ''), 'NetworkCustomersAndroid/') !== false;
$UA_PAGE_CSS = ['assets/css/wizard_network.css'];
if ($uaAndroidNetworkWizard) $UA_PAGE_CSS[] = 'assets/css/android_wizard_network.css';
require_once __DIR__ . '/header.php';
require_once __DIR__ . '/sidebar.php';

$comms_active = 'wizard';
require_once __DIR__ . '/comms_admin_lib.php';

$conn = $GLOBALS['conn'];
comms_ensure_tables($conn);

$routers = comms_get_routers($conn);
$uplink_default = comms_router_by_role($conn,'uplink');
$pppoe_default  = comms_router_by_role($conn,'pppoe');

$router_test_id = intval($_GET['router_test'] ?? 0);
$test_result = null;

if($router_test_id){
  $router = comms_get_router($conn,$router_test_id);
  if($router){
    $err='';
    $api = comms_mt_connect($router,$err);
    if($api){
      comms_mt_safe_disconnect($api);
      $test_result=['ok'=>true,'msg'=>'نجح الاتصال بالراوتر (API).'];
    } else {
      $test_result=['ok'=>false,'msg'=>$err];
    }
  } else {
    $test_result=['ok'=>false,'msg'=>'الراوتر غير موجود.'];
  }
}

$action = $_POST['action'] ?? '';
$diag = null;
$ping = null;
$recommendation = null;
$apply = null;
$result = null;

// Templates
$template = pv('template','standard');
$tpl_rec = null;
$tpl_apply = null;
$tpl_test = null;

function pv($k,$d=''){ return trim($_POST[$k] ?? $d); }

if($action==='detect_wan'){
  $uplink_id = intval($_POST['uplink_router_id'] ?? 0);
  $wan_if = pv('wan_interface','ether1');
  $chosen_mode = pv('chosen_wan_mode','auto');

  $router = comms_get_router($conn,$uplink_id);
  if(!$router){
    $diag = ['ok'=>false,'error'=>'اختر Router1 (uplink) أولاً.'];
  } else {
    $err='';
    $res = comms_detect_wan($conn,$router,$wan_if,$err);
    $diag = $res;
    if(!empty($res['ok'])){
      $det = $res['data']['mode_detected'] ?? 'unknown';
      // recommendation logic
      if($chosen_mode==='auto'){
        $recommendation = "تم اكتشاف الوضع الحالي على WAN: ".h($det).". أنصح باعتماد نفس الوضع.";
      } else if($det !== 'unknown' && $chosen_mode !== $det){
        $recommendation = "⚠️ يبدو أن WAN عندك يعمل على <b>".h($det)."</b> وليس <b>".h($chosen_mode)."</b>. أنصح بتبديل الإعداد إلى: <b>".h($det)."</b>.";
      } else {
        $recommendation = "✅ اختيارك متوافق مع التشخيص.";
      }
    }
  }
}

if($action==='ping_test'){
  $uplink_id = intval($_POST['uplink_router_id'] ?? 0);
  $target = pv('ping_target','1.1.1.1');
  $router = comms_get_router($conn,$uplink_id);
  if(!$router){
    $ping = ['ok'=>false,'error'=>'اختر Router1 (uplink) أولاً.'];
  } else {
    $err='';
    $ping = comms_ping_test($conn,$router,$target,$err);
  }
}

if($action==='apply_wan'){
  $uplink_id = intval($_POST['uplink_router_id'] ?? 0);
  $wan_if = pv('wan_interface','ether1');
  $mode = pv('apply_wan_mode','dhcp');

  $router = comms_get_router($conn,$uplink_id);
  if(!$router){
    $apply = ['ok'=>false,'error'=>'اختر Router1 (uplink) أولاً.'];
  } else {
    // payload for idempotency
    $params = [];
    if($mode==='static'){
      $params = [
        'ip_cidr'=>pv('static_ip_cidr',''),
        'gateway'=>pv('static_gateway',''),
        'dns'=>pv('static_dns','')
      ];
    } elseif($mode==='pppoe'){
      $params = [
        'pppoe_user'=>pv('pppoe_user',''),
        'pppoe_pass'=>pv('pppoe_pass','')
      ];
    } else {
      $params = [ 'dns'=>pv('dhcp_dns','') ];
    }

    $uid = intval($_SESSION['user_id'] ?? 0) ?: null;
    $action_key = 'wan_apply:'.intval($router['id']).':'.trim($wan_if).':'.trim($mode);
    $apply = comms_action_once($conn, $action_key, ['wan_if'=>$wan_if,'mode'=>$mode,'params'=>$params], $uid, function() use ($conn,$router,$wan_if,$mode,$params){
      $err='';
      return comms_apply_wan($conn,$router,$wan_if,$mode,$params,$err);
    });
  }
}

// --- Auto Detect Links / Apply Transit / Test All (Ensure) ---
// IMPORTANT: keep handlers BEFORE any HTML output to avoid printing PHP code on the page.
if($_SERVER['REQUEST_METHOD']==='POST'){
  switch($action){
    case 'auto_detect_links':
      $result = comms_detect_topology($conn);
      break;

    case 'apply_transit':
      $det = comms_detect_topology($conn);
      if(empty($det) || empty($det['ok'])){
        $result = $det ?: ['ok'=>false,'msg'=>'Topology detection failed'];
      } else {
        $links = $det['links'] ?? [];
        $opts = [
          'transit_uplink' => $links['transit_uplink'] ?? '',
          'transit_pppoe'  => $links['transit_pppoe'] ?? '',
          'r1_ip' => pv('r1_transit_ip','10.255.255.1/30'),
          'r2_ip' => pv('r2_transit_ip','10.255.255.2/30'),
        ];
        $result = comms_apply_transit($conn, $opts);
      }
      break;

    case 'test_all':
      $result = comms_test_all($conn);
      break;
  }
}

// ===== Templates Engine (Arabic + English) =====
function tpl_list(): array {
  return [
    'standard' => [
      'title'=>'قالب الشبكة القياسي | Standard ISP Template',
      'desc'=>'Static/DHCP/PPPoE WAN + Router2 PPPoE + VLAN + Pool لكل VLAN (الأفضل لشركات الإنترنت).'
    ],
    'dhcp_uplink' => [
      'title'=>'قالب DHCP مزود | DHCP Uplink Template',
      'desc'=>'Uplink عبر DHCP على Router1 + Router2 PPPoE/VLAN.'
    ],
    'pppoe_uplink' => [
      'title'=>'قالب PPPoE مزود | PPPoE Uplink Template',
      'desc'=>'Uplink عبر PPPoE Client على Router1 + Router2 PPPoE/VLAN.'
    ],
    'single_router_pppoe' => [
      'title'=>'قالب راوتر واحد | Single Router Template',
      'desc'=>'راوتر واحد يقوم بـ WAN + PPPoE للمشتركين.'
    ],
    'dhcp_queues' => [
      'title'=>'قالب DHCP + Queues | DHCP + Queues Template',
      'desc'=>'الزبائن عبر DHCP + Simple Queues للتحكم بالسرعة (بدون PPPoE).'
    ],
    'hotspot' => [
      'title'=>'قالب Hotspot | Hotspot Template',
      'desc'=>'مناسب للكافيهات/التجمعات: Hotspot users/vouchers.'
    ],
    'hybrid' => [
      'title'=>'قالب هجين | Hybrid Template',
      'desc'=>'PPPoE للمشتركين + Hotspot للعام.'
    ],
  ];
}

// Recommend plan for selected template (no RouterOS commands printed)
function tpl_recommend(mysqli $conn, string $template, array $routers, ?array $uplink_default, ?array $pppoe_default): array {
  $tpls = tpl_list();
  if(!isset($tpls[$template])) $template='standard';

  $uplink = $uplink_default;
  $pppoe  = $pppoe_default;
  $notes=[];
  if(!$uplink) $notes[]='⚠️ لم يتم تعيين Router1 (uplink) بعد. أضفه من صفحة إدارة الراوترات.';
  if(!$pppoe && in_array($template,['standard','dhcp_uplink','pppoe_uplink','hybrid'],true))
    $notes[]='⚠️ لم يتم تعيين Router2 (pppoe) بعد. أضفه من صفحة إدارة الراوترات.';

  $plan=[
    'template'=>$template,
    'wan_mode'=>'auto',
    'wan_interface'=>'auto',
    'transit_subnet'=>'10.255.255.0/30',
    'router1_transit_ip'=>'10.255.255.1/30',
    'router2_transit_ip'=>'10.255.255.2/30',
    'pppoe_per_vlan'=>true,
    'pool_pattern'=>'10.10.<VLAN>.0/24',
    'bridge_name'=>'bridge-pppoe'
  ];
  // WAN preference per template
  if($template==='dhcp_uplink') $plan['wan_mode']='dhcp';
  if($template==='pppoe_uplink') $plan['wan_mode']='pppoe';
  if($template==='dhcp_queues') $plan['wan_mode']='auto';
  if($template==='hotspot') $plan['wan_mode']='auto';

  // Auto detect WAN interface on uplink if possible
  if($uplink){
    $err='';
    $best = comms_detect_best_wan_interface($conn,$uplink,$err);
    if(!empty($best['ok'])){
      $plan['wan_interface'] = $best['data']['wan_interface'] ?? 'ether1';
      $plan['wan_confidence']= $best['data']['confidence'] ?? 'low';
      $plan['wan_reason']    = $best['data']['reason'] ?? '';
      // If WAN mode auto, use detected
      if($plan['wan_mode']==='auto' && $plan['wan_interface']){
        $dErr='';
        $det = comms_detect_wan($conn,$uplink,$plan['wan_interface'],$dErr);
        if(!empty($det['ok'])) $plan['wan_mode']=$det['data']['mode_detected'] ?? 'auto';
      }
    } else {
      $notes[]='⚠️ لم يتمكن النظام من اكتشاف WAN تلقائياً: '.h($best['error'] ?? $err);
    }
  }

  // sectors plan
  $sectors = comms_get_sectors($conn);
  $plan['sectors_count']=count($sectors);
  $plan['sectors'] = [];
  foreach($sectors as $s){
    $vid=intval($s['vlan_id']);
    $plan['sectors'][]=[
      'id'=>intval($s['id']),
      'name'=>$s['name'],
      'vlan_id'=>$vid,
      'pool'=>comms_suggest_pool_for_vlan($vid)
    ];
  }

  return ['ok'=>true,'notes'=>$notes,'plan'=>$plan,'tpl'=>$tpls[$template]];
}

if($action==='tpl_recommend'){
  $template = pv('template','standard');
  $tpl_rec = tpl_recommend($conn,$template,$routers,$uplink_default,$pppoe_default);
}

if($action==='tpl_apply'){
  $template = pv('template','standard');
  $uid = intval($_SESSION['user_id'] ?? 0) ?: null;
  $rec = tpl_recommend($conn,$template,$routers,$uplink_default,$pppoe_default);
  if(empty($rec['ok'])){
    $tpl_apply = ['ok'=>false,'error'=>'فشل توليد الخطة.'];
  } else {
    $plan = $rec['plan'];
    // Apply: update sector pool suggestions + apply sectors ensure (VLAN+Pool+PPPoE)
    $tpl_apply = comms_action_once($conn, 'template_apply_'.$template, $plan, $uid, function() use ($conn,$plan){
      // Update pools suggestion in DB
      foreach($plan['sectors'] as $sx){
        comms_update_sector_pool($conn, intval($sx['id']), $sx['pool']);
      }
      // Apply each sector PPPoE ensure (only for enabled sectors)
      foreach(comms_get_sectors($conn) as $s){
        if(intval($s['is_enabled'] ?? 1)!==1) continue;
        $router = comms_get_router($conn, intval($s['router_id']));
        if(!$router) continue;
        $err='';
        // per-sector idempotency
        $payload=[
          'router_id'=>intval($router['id']),
          'vlan_id'=>intval($s['vlan_id']),
          'trunk'=>$s['trunk_interface'],
          'bridge'=>$s['bridge_name'],
          'pool_name'=>$s['pppoe_pool_name'],
          'pool_range'=>$s['pppoe_pool_range'],
          'local_ip'=>$s['pppoe_local_ip']
        ];
        comms_action_once($conn, 'tpl_apply_sector_'.intval($s['id']), $payload, null, function() use ($conn,$router,$s,&$err){
          return comms_apply_sector_pppoe($conn,$router,$s,$err);
        });
      }
      return ['ok'=>true,'msg'=>'تم تطبيق القالب: تحديث Pools + تطبيق القطاعات (VLAN/Pool/PPPoE) بدون تكرار.'];
    });
  }
}

if ($uaAndroidNetworkWizard) {
  require __DIR__ . '/android_wizard_network.php';
  require_once __DIR__ . '/footer.php';
  exit;
}


?>
<div class="content-wrapper ua-extracted-page ua-u-rtl-right" dir="rtl">
  <section class="content-header">
    <h1 class="ua-u-text-right">المعالج الذكي | Smart Wizard</h1>
    <p class="text-muted">تشخيص تلقائي + اقتراح السيناريو الصحيح (Templates) + تطبيق Ensure — بدون طباعة أوامر على الواجهة.</p>
  </section>

  <section class="content">
    <div class="row">
      <div class="col-md-12">
        <div class="box box-default">
          <div class="box-header with-border"><h3 class="box-title">0) قوالب السيناريو | Scenario Templates</h3></div>
          <div class="box-body">
            <?php $tpls = tpl_list(); ?>
            <form method="post" class="form-inline ua-u-mb-10 wn-template-form">
              <input type="hidden" name="action" value="tpl_recommend">
              <div class="form-group ua-u-width-65">
                <label class="ua-u-ml-10">Template</label>
                <select class="form-control ua-u-full-width" name="template">
                  <?php foreach($tpls as $k=>$t): ?>
                    <option value="<?=h($k)?>" <?=((pv('template','standard')===$k)?'selected':'')?>><?=h($t['title'])?></option>
                  <?php endforeach; ?>
                </select>
              </div>
              <button class="btn btn-info" type="submit">⭐ اقتراح الخطة | Recommend Plan</button>
            </form>

            <?php if($tpl_rec && !empty($tpl_rec['ok'])): ?>
              <div class="alert alert-success">
                <b><?=h($tpl_rec['tpl']['title'] ?? '')?></b><br>
                <small><?=h($tpl_rec['tpl']['desc'] ?? '')?></small>
              </div>
              <?php if(!empty($tpl_rec['notes'])): ?>
                <div class="alert alert-warning">
                  <?php foreach($tpl_rec['notes'] as $n): ?>
                    <div><?= $n ?></div>
                  <?php endforeach; ?>
                </div>
              <?php endif; ?>
              <?php $p = $tpl_rec['plan']; ?>
              <div class="row">
                <div class="col-md-4">
                  <div class="callout callout-info ua-u-mb-10">
                    <b>WAN Mode</b>: <?=h($p['wan_mode'])?><br>
                    <b>WAN Interface</b>: <?=h($p['wan_interface'] ?? '-')?>
                    <?php if(!empty($p['wan_confidence'])): ?><br><small>Confidence: <?=h($p['wan_confidence'])?> (<?=h($p['wan_reason'] ?? '')?>)</small><?php endif; ?>
                  </div>
                </div>
                <div class="col-md-4">
                  <div class="callout callout-warning ua-u-mb-10">
                    <b>Transit</b>: <?=h($p['transit_subnet'])?><br>
                    R1: <?=h($p['router1_transit_ip'])?><br>
                    R2: <?=h($p['router2_transit_ip'])?>
                  </div>
                </div>
                <div class="col-md-4">
                  <div class="callout callout-success ua-u-mb-10">
                    <b>PPPoE</b>: Per VLAN Pools ✅<br>
                    Pattern: <?=h($p['pool_pattern'])?><br>
                    Sectors: <?=h((string)$p['sectors_count'])?>
                  </div>
                </div>
              </div>

              <form method="post" onsubmit="return confirm('تطبيق القالب؟ سيتم تحديث Pools وتطبيق القطاعات (Ensure).');">
                <input type="hidden" name="action" value="tpl_apply">
                <input type="hidden" name="template" value="<?=h($p['template'])?>">
                <button class="btn btn-success btn-block">✅ تطبيق الخطة | Apply Plan (Ensure)</button>
              </form>
            <?php endif; ?>

            <?php if($tpl_apply): ?>
              <?php if(!empty($tpl_apply['ok'])): ?>
                <div class="alert alert-<?=!empty($tpl_apply['skipped'])?'warning':'success'?>">
                  <?=!empty($tpl_apply['skipped'])?'⚠️ ':'✅ '?><?=h($tpl_apply['msg'] ?? 'تم')?></div>
              <?php else: ?>
                <div class="alert alert-danger">❌ <?=h($tpl_apply['error'] ?? 'فشل')?></div>
              <?php endif; ?>
            <?php endif; ?>

            <div class="alert alert-info ua-u-mt-10">
              <b>مهم:</b> هذا القسم لا يعرض أوامر RouterOS على الواجهة. فقط اقتراحات + نتائج تطبيق Ensure.
            </div>
          </div>
        </div>
      </div>
    </div>
    <?php if($test_result): ?>
      <div class="alert alert-<?= $test_result['ok']?'success':'danger' ?>"><?= $test_result['ok']?'✅ ':'❌ ' ?><?=h($test_result['msg'])?></div>
    <?php endif; ?>

    <div class="row">
      <div class="col-md-6">
        <div class="box box-success">
          <div class="box-header with-border"><h3 class="box-title">1) اختيار الراوترات</h3></div>
          <div class="box-body">
            <form method="post" class="wn-diagnose-form">
              <input type="hidden" name="action" value="detect_wan">
              <div class="form-group">
                <label>Router1 (Uplink)</label>
                <select class="form-control" name="uplink_router_id">
                  <option value="">-- اختر --</option>
                  <?php foreach($routers as $r): ?>
                    <?php
                      $sel = '';
                      $pref = $uplink_default ? intval($uplink_default['id']) : 0;
                      $cur = intval($_POST['uplink_router_id'] ?? $pref);
                      if($cur && $cur==intval($r['id'])) $sel='selected';
                    ?>
                    <option value="<?=h($r['id'])?>" <?=$sel?>><?=h($r['name'])?> (<?=h($r['role'])?>)</option>
                  <?php endforeach; ?>
                </select>
              </div>

              <div class="form-group">
                <label>WAN Interface على Router1</label>
                <input class="form-control" name="wan_interface" value="<?=h($_POST['wan_interface'] ?? 'ether1')?>" placeholder="ether1">
                <small class="text-muted">اكتب اسم المنفذ كما هو في الميكروتك.</small>
              </div>

              <div class="form-group">
                <label>نوع اتصال الإنترنت الذي اخترته</label>
                <?php $cm = $_POST['chosen_wan_mode'] ?? 'auto'; ?>
                <select class="form-control" name="chosen_wan_mode">
                  <option value="auto" <?=($cm==='auto'?'selected':'')?>>تلقائي (اقترح لي الصحيح)</option>
                  <option value="static" <?=($cm==='static'?'selected':'')?>>Static</option>
                  <option value="dhcp" <?=($cm==='dhcp'?'selected':'')?>>DHCP</option>
                  <option value="pppoe" <?=($cm==='pppoe'?'selected':'')?>>PPPoE Client</option>
                </select>
              </div>

              <button class="btn btn-success btn-block" type="submit">تشخيص WAN واقتراح الصحيح</button>
            </form>

            <?php if($recommendation): ?>
              <div class="alert alert-info ua-u-mt-10"><?= $recommendation ?></div>
            <?php endif; ?>

            <?php if($diag && empty($diag['ok'])): ?>
              <div class="alert alert-danger ua-u-mt-10"><?=h($diag['error'] ?? 'فشل التشخيص.')?></div>
            <?php endif; ?>

            <?php if($diag && !empty($diag['ok'])): ?>
              <?php $d=$diag['data']; ?>
              <div class="box box-default ua-u-mt-10">
                <div class="box-header with-border"><h3 class="box-title">نتيجة التشخيص</h3></div>
                <div class="box-body">
                  <ul class="list-unstyled">
                    <li><b>الوضع المكتشف:</b> <?=h($d['mode_detected'])?></li>
                    <li><b>Default Route:</b> <?= $d['has_default_route'] ? 'نعم' : 'لا' ?></li>
                    <li><b>Gateway:</b> <?=h($d['gateway'] ?? '-')?></li>
                    <li><b>PPPoE Client Running:</b> <?= $d['pppoe_client_running'] ? 'نعم' : 'لا' ?></li>
                    <li><b>DHCP Bound:</b> <?= $d['dhcp_bound'] ? 'نعم' : 'لا' ?></li>
                    <li><b>IP على WAN:</b> <?=h($d['static_ip'] ?? '-')?></li>
                  </ul>
                  <p class="text-muted ua-u-m0">ملاحظة: التطبيق الآلي لوضع WAN (Static/DHCP/PPPoE) سيكون عبر زر "تطبيق" لاحقاً بعد إدخال القيم اللازمة.</p>
                </div>
              </div>
            <?php endif; ?>
          </div>
        </div>
      </div>

      <div class="col-md-6">
        <div class="box box-primary">
          <div class="box-header with-border"><h3 class="box-title">2) اختبار Internet (Ping)</h3></div>
          <div class="box-body">
            <form method="post" class="wn-ping-form">
              <input type="hidden" name="action" value="ping_test">
              <div class="form-group">
                <label>Router1 (Uplink)</label>
                <select class="form-control" name="uplink_router_id">
                  <option value="">-- اختر --</option>
                  <?php foreach($routers as $r): ?>
                    <?php
                      $pref = $uplink_default ? intval($uplink_default['id']) : 0;
                      $cur = intval($_POST['uplink_router_id'] ?? $pref);
                      $sel = ($cur && $cur==intval($r['id'])) ? 'selected' : '';
                    ?>
                    <option value="<?=h($r['id'])?>" <?=$sel?>><?=h($r['name'])?> (<?=h($r['role'])?>)</option>
                  <?php endforeach; ?>
                </select>
              </div>
              <div class="form-group">
                <label>Ping Target</label>
                <input class="form-control" name="ping_target" value="<?=h($_POST['ping_target'] ?? '1.1.1.1')?>">
              </div>
              <button class="btn btn-primary btn-block" type="submit">تنفيذ Ping</button>
            </form>

            <?php if($ping): ?>
              <?php if(!empty($ping['ok'])): ?>
                <div class="alert alert-success ua-u-mt-10">✅ Ping تم (تم استلام نتيجة).</div>
                <pre class="ua-u-code-output"><?=h(print_r($ping['data'], true))?></pre>
              <?php else: ?>
                <div class="alert alert-danger ua-u-mt-10">❌ <?=h($ping['error'] ?? 'فشل Ping')?></div>
              <?php endif; ?>
            <?php endif; ?>

            <div class="alert alert-warning ua-u-mt-10">
              <b>مهم:</b> لا يتم عرض أي أوامر RouterOS هنا. فقط نتائج مفهومة.
            </div>
          </div>
        </div>
      </div>

    </div>

    <div class="row">
      <div class="col-md-12">
        <div class="box box-warning">
          <div class="box-header with-border"><h3 class="box-title">3) تطبيق إعداد WAN على Router1 (بدون WinBox)</h3></div>
          <div class="box-body">
            <?php if($apply): ?>
              <?php if(!empty($apply['ok'])): ?>
                <?php $sk = !empty($apply['skipped']); ?>
                <div class="alert alert-<?= $sk ? 'warning':'success' ?>">
                  <?= $sk ? '⚠️ ' : '✅ ' ?><?= h($apply['msg'] ?? ($sk?'تم التخطي':'تم.')) ?>
                </div>
              <?php else: ?>
                <div class="alert alert-danger">❌ <?= h($apply['error'] ?? 'فشل التنفيذ') ?></div>
              <?php endif; ?>
            <?php endif; ?>

            <?php $am = $_POST['apply_wan_mode'] ?? 'dhcp'; ?>
            <form method="post" id="applyWanForm" class="wn-apply-form">
              <input type="hidden" name="action" value="apply_wan">

              <div class="row">
                <div class="col-md-4">
                  <div class="form-group">
                    <label>Router1 (Uplink)</label>
                    <select class="form-control" name="uplink_router_id" required>
                      <option value="">-- اختر --</option>
                      <?php foreach($routers as $r): ?>
                        <?php
                          $pref = $uplink_default ? intval($uplink_default['id']) : 0;
                          $cur = intval($_POST['uplink_router_id'] ?? $pref);
                          $sel = ($cur && $cur==intval($r['id'])) ? 'selected' : '';
                        ?>
                        <option value="<?=h($r['id'])?>" <?=$sel?>><?=h($r['name'])?> (<?=h($r['role'])?>)</option>
                      <?php endforeach; ?>
                    </select>
                  </div>
                </div>
                <div class="col-md-4">
                  <div class="form-group">
                    <label>WAN Interface</label>
                    <input class="form-control" name="wan_interface" value="<?=h($_POST['wan_interface'] ?? 'ether1')?>" placeholder="ether1" required>
                  </div>
                </div>
                <div class="col-md-4">
                  <div class="form-group">
                    <label>وضع WAN</label>
                    <select class="form-control" name="apply_wan_mode" id="applyWanMode">
                      <option value="dhcp" <?=($am==='dhcp'?'selected':'')?>>DHCP</option>
                      <option value="static" <?=($am==='static'?'selected':'')?>>Static</option>
                      <option value="pppoe" <?=($am==='pppoe'?'selected':'')?>>PPPoE Client</option>
                    </select>
                    <small class="text-muted">ننفّذ فقط ما هو ناقص (Ensure) ونمنع تكرار التنفيذ بنفس الإعدادات.</small>
                  </div>
                </div>
              </div>

              <div class="ua-u-hidden" id="wanStaticFields">
                <div class="row">
                  <div class="col-md-4">
                    <div class="form-group">
                      <label>Static IP/Mask (CIDR)</label>
                      <input class="form-control" name="static_ip_cidr" value="<?=h($_POST['static_ip_cidr'] ?? '')?>" placeholder="مثال: 100.64.1.2/29">
                    </div>
                  </div>
                  <div class="col-md-4">
                    <div class="form-group">
                      <label>Gateway</label>
                      <input class="form-control" name="static_gateway" value="<?=h($_POST['static_gateway'] ?? '')?>" placeholder="مثال: 100.64.1.1">
                    </div>
                  </div>
                  <div class="col-md-4">
                    <div class="form-group">
                      <label>DNS (اختياري)</label>
                      <input class="form-control" name="static_dns" value="<?=h($_POST['static_dns'] ?? '')?>" placeholder="1.1.1.1,8.8.8.8">
                    </div>
                  </div>
                </div>
              </div>

              <div class="ua-u-hidden" id="wanPppoeFields">
                <div class="row">
                  <div class="col-md-6">
                    <div class="form-group">
                      <label>PPPoE Username</label>
                      <input class="form-control" name="pppoe_user" value="<?=h($_POST['pppoe_user'] ?? '')?>">
                    </div>
                  </div>
                  <div class="col-md-6">
                    <div class="form-group">
                      <label>PPPoE Password</label>
                      <input class="form-control" name="pppoe_pass" value="<?=h($_POST['pppoe_pass'] ?? '')?>">
                    </div>
                  </div>
                </div>
              </div>

              <div class="ua-u-hidden" id="wanDhcpFields">
                <div class="row">
                  <div class="col-md-6">
                    <div class="form-group">
                      <label>DNS (اختياري)</label>
                      <input class="form-control" name="dhcp_dns" value="<?=h($_POST['dhcp_dns'] ?? '')?>" placeholder="1.1.1.1,8.8.8.8">
                    </div>
                  </div>
                </div>
              </div>

              <button class="btn btn-warning btn-block" type="submit">تطبيق WAN الآن</button>
            </form>

            <script>
              (function(){
                function toggleFields(){
                  var m = document.getElementById('applyWanMode').value;
                  document.getElementById('wanStaticFields').style.display = (m==='static') ? 'block':'none';
                  document.getElementById('wanPppoeFields').style.display  = (m==='pppoe')  ? 'block':'none';
                  document.getElementById('wanDhcpFields').style.display   = (m==='dhcp')   ? 'block':'none';
                }
                document.getElementById('applyWanMode').addEventListener('change', toggleFields);
                toggleFields();
              })();
            </script>


    <div class="row">
      <div class="col-md-12">
        <div class="box box-primary">
          <div class="box-header with-border"><h3 class="box-title">4) Auto Detect Transit/Trunk | اكتشاف تلقائي للربط</h3></div>
          <div class="box-body">
            <form method="post" class="form-inline">
              <input type="hidden" name="action" value="auto_detect_links">
              <button class="btn btn-primary" type="submit">🔍 Auto Detect Links | اكتشاف الربط</button>
            </form>
            <?php if($result && ($result['ok']??false) && isset($result['links'])): ?>
              <hr>
              <div class="row">
                <div class="col-md-3"><div class="callout callout-info"><b>WAN</b><br><?=h($result['links']['uplink_wan'] ?? '-')?></div></div>
                <div class="col-md-3"><div class="callout callout-warning"><b>Transit R1</b><br><?=h($result['links']['transit_uplink'] ?? '-')?></div></div>
                <div class="col-md-3"><div class="callout callout-warning"><b>Transit R2</b><br><?=h($result['links']['transit_pppoe'] ?? '-')?></div></div>
                <div class="col-md-3"><div class="callout callout-success"><b>Trunk R2</b><br><?=h($result['links']['trunk_pppoe'] ?? '-')?></div></div>
              </div>
              <small class="text-muted">Confidence: <?=h($result['links']['confidence'] ?? '-')?></small>
            <?php elseif($result && ($result['ok']??false)===false && ($action??'')==='auto_detect_links'): ?>
              <div class="alert alert-danger ua-u-mt-10"><?=h($result['msg'] ?? '')?></div>
            <?php endif; ?>
          </div>
        </div>
      </div>
    </div>

    <div class="row">
      <div class="col-md-6">
        <div class="box box-success">
          <div class="box-header with-border"><h3 class="box-title">5) Apply Transit + Routes | تطبيق الربط والمسارات</h3></div>
          <div class="box-body">
            <form method="post" class="wn-transit-form">
              <input type="hidden" name="action" value="apply_transit">
              <div class="form-group">
                <label>R1 Transit IP</label>
                <input class="form-control" name="r1_transit_ip" value="<?=h($_POST['r1_transit_ip'] ?? '10.255.255.1/30')?>"/>
              </div>
              <div class="form-group">
                <label>R2 Transit IP</label>
                <input class="form-control" name="r2_transit_ip" value="<?=h($_POST['r2_transit_ip'] ?? '10.255.255.2/30')?>"/>
              </div>
              <button class="btn btn-success btn-block" type="submit">✅ Apply Transit (Ensure)</button>
            </form>
            <?php if($result && ($action??'')==='apply_transit'): ?>
              <hr>
              <?php if($result['ok']??false): ?>
                <?php foreach(($result['msgs'] ?? []) as $m): ?>
                  <div class="alert alert-info ua-u-my-6"><?=h($m)?></div>
                <?php endforeach; ?>
              <?php else: ?>
                <div class="alert alert-danger"><?=h($result['msg'] ?? '')?></div>
              <?php endif; ?>
            <?php endif; ?>
          </div>
        </div>
      </div>

      <div class="col-md-6">
        <div class="box box-default">
          <div class="box-header with-border"><h3 class="box-title">6) Test All Checklist | اختبار شامل</h3></div>
          <div class="box-body">
            <form method="post">
              <input type="hidden" name="action" value="test_all">
              <button class="btn btn-default btn-block" type="submit">🧪 Test All</button>
            </form>
            <?php if($result && ($action??'')==='test_all'): ?>
              <hr>
              <?php if($result['ok']??false): ?>
                <table class="table table-bordered table-striped ua-u-text-right">
                  <thead><tr><th>الفحص</th><th>Result</th><th>Value</th></tr></thead>
                  <tbody>
                    <?php foreach(($result['results'] ?? []) as $r): ?>
                      <tr>
                        <td><?=h($r['ar'])?> | <?=h($r['k'])?></td>
                        <td><?= ($r['ok']?'✅ PASS':'❌ FAIL') ?></td>
                        <td><?=h($r['v'] ?? '')?></td>
                      </tr>
                    <?php endforeach; ?>
                  </tbody>
                </table>
              <?php else: ?>
                <div class="alert alert-danger"><?=h($result['msg'] ?? '')?></div>
              <?php endif; ?>
            <?php endif; ?>
          </div>
        </div>
      </div>
    </div>
            <div class="alert alert-info ua-u-mt-10">
              <b>ملاحظة:</b> الواجهة لا تعرض أوامر RouterOS إطلاقاً. فقط نتيجة التطبيق. إذا كانت الإعدادات مطبقة مسبقاً بنفس القيم، سيتم تخطي التنفيذ تلقائياً.
            </div>
          </div>
        </div>
      </div>
    </div>

  </section>
</div>
<?php require_once __DIR__ . '/footer.php'; ?>
