<?php
$page_title = 'إدارة الراوترات';
require_once __DIR__ . '/auth.php';
require_login();
if(function_exists('require_perm')) require_perm('can_settings');
$UA_FORCE_DESIGN_V2 = true;
$UA_PAGE_CSS = ['assets/css/pages/routers_admin.css'];
$uaAndroidRouters = ((string)($_GET['ua_android'] ?? '') === '1')
  || stripos((string)($_SERVER['HTTP_USER_AGENT'] ?? ''), 'NetworkCustomersAndroid/') !== false;
if ($uaAndroidRouters) $UA_PAGE_CSS[] = 'assets/css/android_routers.css';
require_once __DIR__ . '/header.php';
require_once __DIR__ . '/sidebar.php';

$comms_active = 'routers';
require_once __DIR__ . '/comms_admin_lib.php';
require_once __DIR__ . '/security_alerts_lib.php';

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

$action = $_POST['action'] ?? '';
$msg = null; $msg_type='success';

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

function router_security_actor(): string {
  return (string)($_SESSION['admin_username'] ?? $_SESSION['admin_user'] ?? $_SESSION['username'] ?? '');
}

function router_security_change_labels(array $old, array $new): array {
  $fields = [
    'name' => 'اسم الراوتر',
    'host' => 'عنوان الراوتر',
    'api_port' => 'منفذ API',
    'username' => 'اسم مستخدم الاتصال',
    'password' => 'كلمة مرور الاتصال',
    'role' => 'الدور',
    'is_enabled' => 'حالة التفعيل',
    'notes' => 'الملاحظات',
  ];
  $changes = [];
  foreach ($fields as $field => $label) {
    $oldValue = (string)($old[$field] ?? '');
    $newValue = (string)($new[$field] ?? '');
    if ($field === 'api_port' || $field === 'is_enabled') {
      $oldValue = (string)(int)$oldValue;
      $newValue = (string)(int)$newValue;
    }
    if ($oldValue === $newValue) continue;
    $item = ['field' => $field, 'label' => $label];
    if ($field === 'password') {
      $item['password_changed'] = true;
    } else {
      $item['from'] = $oldValue;
      $item['to'] = $newValue;
    }
    $changes[] = $item;
  }
  return $changes;
}

function router_security_record_config_event(mysqli $conn, string $type, string $severity, string $title, string $message, array $router, array $meta = []): void {
  $routerId = (int)($router['id'] ?? 0);
  $routerName = (string)($router['name'] ?? '');
  $routerHost = (string)($router['host'] ?? '');
  $meta = array_merge([
    'source' => 'routers_admin_page',
    'router_id' => $routerId,
    'router_name' => $routerName,
    'router_host' => $routerHost,
  ], $meta);
  $key = hash('sha256', 'app-router-security|' . $type . '|' . $routerId . '|' . $routerHost . '|' . microtime(true));
  ua_security_record_event($conn, $key, $type, $severity, $title, $message, [
    'username' => router_security_actor(),
    'meta' => $meta,
  ]);
}

if ($action === 'save_router') {
  $id = intval($_POST['id'] ?? 0);
  $name = post('name');
  $host = post('host');
  $api_port = intval($_POST['api_port'] ?? 8728);
  $username = post('username');
  $password = post('password');
  $role = post('role','other');
  $is_enabled = isset($_POST['is_enabled']) ? 1 : 0;
  $notes = post('notes');

  if ($name==='' || $host==='' || $username==='' || $password==='') {
    $msg_type='danger'; $msg='يرجى تعبئة الاسم و IP واسم المستخدم وكلمة المرور.';
  } else {
    $nameE=$conn->real_escape_string($name);
    $hostE=$conn->real_escape_string($host);
    $userE=$conn->real_escape_string($username);
    $passE=$conn->real_escape_string($password);
    $roleE=$conn->real_escape_string($role);
    $notesE=$conn->real_escape_string($notes);
    $api_port=max(1,$api_port);
    $newRouter = [
      'id' => $id,
      'name' => $name,
      'host' => $host,
      'api_port' => $api_port,
      'username' => $username,
      'password' => $password,
      'role' => $role,
      'is_enabled' => $is_enabled,
      'notes' => $notes,
    ];

    if($id>0){
      $oldRouter = comms_get_router($conn, $id);
      $conn->query("UPDATE routers SET name='$nameE',host='$hostE',api_port=$api_port,username='$userE',password='$passE',role='$roleE',is_enabled=$is_enabled,notes='$notesE' WHERE id=$id");
      if ($oldRouter && (int)$conn->errno === 0) {
        $newRouter['id'] = $id;
        $changes = router_security_change_labels($oldRouter, $newRouter);
        if ($changes) {
          $sensitive = false;
          foreach ($changes as $c) {
            if (in_array($c['field'], ['username','password','host','api_port'], true)) {
              $sensitive = true;
              break;
            }
          }
          $labels = array_map(function($c){ return $c['label']; }, $changes);
          router_security_record_config_event(
            $conn,
            $sensitive ? 'app_router_credentials_changed' : 'app_router_config_changed',
            $sensitive ? 'danger' : 'warn',
            $sensitive ? 'تغيير حساس في بيانات اتصال الراوتر' : 'تغيير إعدادات الراوتر',
            'تم تعديل الراوتر ' . $name . ' (' . $host . '). الحقول المتغيرة: ' . implode('، ', $labels) . '.',
            $newRouter,
            [
              'action' => 'update_router',
              'changed_fields' => $changes,
              'password_value_stored' => false,
            ]
          );
        }
      }
      $msg='تم تحديث الراوتر.';
    } else {
      $conn->query("INSERT INTO routers(name,host,api_port,username,password,role,is_enabled,notes) VALUES('$nameE','$hostE',$api_port,'$userE','$passE','$roleE',$is_enabled,'$notesE')");
      if ((int)$conn->errno === 0) {
        $newRouter['id'] = (int)$conn->insert_id;
        router_security_record_config_event(
          $conn,
          'app_router_added',
          'danger',
          'إضافة راوتر جديد',
          'تمت إضافة الراوتر ' . $name . ' (' . $host . ') إلى إعدادات الاتصال.',
          $newRouter,
          [
            'action' => 'insert_router',
            'router_role' => $role,
            'is_enabled' => $is_enabled,
            'password_value_stored' => false,
          ]
        );
      }
      $msg='تمت إضافة الراوتر.';
    }
  }
}

if ($action === 'delete_router') {
  $id=intval($_POST['id'] ?? 0);
  if($id>0){
    $oldRouter = comms_get_router($conn, $id);
    $conn->query("DELETE FROM routers WHERE id=$id");
    if($oldRouter && (int)$conn->errno === 0){
      router_security_record_config_event(
        $conn,
        'app_router_deleted',
        'danger',
        'حذف راوتر من النظام',
        'تم حذف الراوتر ' . (string)($oldRouter['name'] ?? '') . ' (' . (string)($oldRouter['host'] ?? '') . ') من إعدادات الاتصال.',
        $oldRouter,
        [
          'action' => 'delete_router',
          'deleted_router_role' => (string)($oldRouter['role'] ?? ''),
          'password_value_stored' => false,
        ]
      );
    }
    $msg='تم حذف الراوتر.';
  }
}

$edit_id = intval($_GET['edit'] ?? 0);
$edit = $edit_id ? comms_get_router($conn,$edit_id) : null;

$routers = comms_get_routers($conn);
$router_total = count($routers);
$router_enabled = 0;
$router_uplink = 0;
$router_pppoe = 0;
foreach ($routers as $r) {
  if (!empty($r['is_enabled'])) $router_enabled++;
  if (($r['role'] ?? '') === 'uplink') $router_uplink++;
  if (($r['role'] ?? '') === 'pppoe') $router_pppoe++;
}
if ($uaAndroidRouters) {
  require __DIR__ . '/android_routers.php';
  require_once __DIR__ . '/footer.php';
  exit;
}
?>
<div class="content-wrapper ua-manual-page ua-network-admin-page ua-network-routers ua-u-rtl-right" dir="rtl">
  <section class="content-header ua-net-hero">
    <div class="ua-net-hero__main">
      <span class="ua-net-kicker"><i class="fa fa-server"></i> MikroTik API</span>
    <h1 class="ua-u-text-right">إدارة الراوترات</h1>
    <p class="text-muted">أضف Router1 (uplink) و Router2 (pppoe). لا يتم عرض أي أوامر على الواجهة.</p>
    </div>
    <div class="ua-net-hero__actions">
      <a class="ua-net-action" href="wizard_network.php"><i class="fa fa-magic"></i><span>Smart Wizard</span></a>
      <a class="ua-net-action ua-net-action--ghost" href="mikrotik_dashboard.php"><i class="fa fa-dashboard"></i><span>Monitor</span></a>
    </div>
  </section>

  <section class="content">
    <?php if($msg): ?>
      <div class="alert alert-<?=h($msg_type)?>"><?=h($msg)?></div>
    <?php endif; ?>

    <div class="box box-success ua-net-panel ua-router-form-strip">
      <div class="box-header with-border"><h3 class="box-title"><?= $edit ? 'تعديل راوتر' : 'إضافة راوتر' ?></h3></div>
      <div class="box-body">
        <form method="post" class="ua-net-form ua-router-inline-form">
          <input type="hidden" name="action" value="save_router">
          <input type="hidden" name="id" value="<?=h($edit['id'] ?? 0)?>">
          <div class="form-group"><label>الاسم</label><input class="form-control" name="name" value="<?=h($edit['name'] ?? '')?>" placeholder="Router1 / Router2"></div>
          <div class="form-group"><label>IP / Host</label><input class="form-control" name="host" value="<?=h($edit['host'] ?? '')?>" placeholder="192.168.88.1"></div>
          <div class="form-group"><label>API Port</label><input class="form-control" name="api_port" value="<?=h($edit['api_port'] ?? 8728)?>"></div>
          <div class="form-group"><label>Username</label><input class="form-control" name="username" value="<?=h($edit['username'] ?? '')?>"></div>
          <div class="form-group"><label>Password</label><input class="form-control" type="password" name="password" value="<?=h($edit['password'] ?? '')?>" autocomplete="new-password"></div>
          <div class="form-group">
            <label>الدور</label>
            <?php $role = $edit['role'] ?? 'other'; ?>
            <select class="form-control" name="role">
              <option value="uplink" <?=($role==='uplink'?'selected':'')?>>uplink (استقبال الإنترنت)</option>
              <option value="pppoe" <?=($role==='pppoe'?'selected':'')?>>pppoe (إدارة المشتركين)</option>
              <option value="monitor" <?=($role==='monitor'?'selected':'')?>>monitor (مراقبة)</option>
              <option value="other" <?=($role==='other'?'selected':'')?>>other</option>
            </select>
          </div>
          <div class="form-group ua-router-enabled-field"><label><input type="checkbox" name="is_enabled" <?=(!isset($edit) || ($edit['is_enabled'] ?? 1) ? 'checked':'')?> > مفعل</label></div>
          <div class="form-group ua-router-notes-field"><label>ملاحظات</label><textarea class="form-control" name="notes" rows="1"><?=h($edit['notes'] ?? '')?></textarea></div>
          <button class="btn btn-success" type="submit"><i class="fa fa-save"></i> حفظ</button>
          <?php if($edit): ?><a class="btn btn-default ua-router-cancel" href="routers.php">إلغاء التعديل</a><?php endif; ?>
        </form>
      </div>
    </div>

    <div class="ua-net-stats" aria-label="Network router summary">
      <div class="ua-net-stat"><i class="fa fa-server"></i><span>Routers</span><strong><?=h((string)$router_total)?></strong></div>
      <div class="ua-net-stat is-green"><i class="fa fa-check-circle"></i><span>Enabled</span><strong><?=h((string)$router_enabled)?></strong></div>
      <div class="ua-net-stat is-cyan"><i class="fa fa-cloud"></i><span>Uplink</span><strong><?=h((string)$router_uplink)?></strong></div>
      <div class="ua-net-stat is-gold"><i class="fa fa-users"></i><span>PPPoE</span><strong><?=h((string)$router_pppoe)?></strong></div>
    </div>

    <div class="row ua-net-layout">
      <div class="col-md-12">
        <div class="box box-primary ua-net-panel">
          <div class="box-header with-border"><h3 class="box-title">قائمة الراوترات</h3></div>
          <div class="box-body table-responsive">
            <table class="table table-bordered table-striped ua-net-table">
              <thead>
                <tr>
                  <th>#</th><th>الاسم</th><th>IP</th><th>Port</th><th>الدور</th><th>الحالة</th><th>إجراءات</th>
                </tr>
              </thead>
              <tbody>
              <?php foreach($routers as $r): ?>
                <tr>
                  <td><?=h($r['id'])?></td>
                  <td><?=h($r['name'])?></td>
                  <td><?=h($r['host'])?></td>
                  <td><?=h($r['api_port'])?></td>
                  <td><?=h($r['role'])?></td>
                  <td title="هذه حالة تفعيل الإعداد وليست نتيجة اتصال حي"><span class="ua-net-status <?= $r['is_enabled'] ? 'is-enabled' : 'is-disabled' ?>"><?=($r['is_enabled']?'مفعّل بالإعدادات':'متوقف')?></span></td>
                  <td class="ua-net-actions ua-u-nowrap">
                    <a class="btn btn-xs btn-warning" href="routers.php?edit=<?=h($r['id'])?>">تعديل</a>
                    <form class="ua-u-inline" method="post" onsubmit="return confirm('حذف الراوتر؟');">
                      <input type="hidden" name="action" value="delete_router">
                      <input type="hidden" name="id" value="<?=h($r['id'])?>">
                      <button class="btn btn-xs btn-danger" type="submit">حذف</button>
                    </form>
                    <button class="btn btn-xs btn-info" type="button" data-router-test="<?=h($r['id'])?>">اختبار</button>
                    <span class="ua-net-test-result" data-router-test-result="<?=h($r['id'])?>" hidden></span>
                  </td>
                </tr>
              <?php endforeach; ?>
              <?php if(count($routers)==0): ?>
                <tr><td colspan="7" class="text-center text-muted">لا يوجد راوترات بعد.</td></tr>
              <?php endif; ?>
              </tbody>
            </table>
          </div>
        </div>
      </div>

    </div>
  </section>
</div>
<script>
(function(){
  document.querySelectorAll('[data-router-test]').forEach(function(button){
    button.addEventListener('click', function(){
      var id = button.getAttribute('data-router-test') || '';
      var result = document.querySelector('[data-router-test-result="' + id + '"]');
      if(!id || !result) return;
      button.disabled = true;
      result.hidden = false;
      result.className = 'ua-net-test-result is-running';
      result.textContent = 'جارٍ اختبار الاتصال والقراءة...';
      fetch('api/router_test.php?router_id=' + encodeURIComponent(id), {
        headers:{'X-Requested-With':'XMLHttpRequest'},
        cache:'no-store'
      })
        .then(function(response){ return response.json(); })
        .then(function(data){
          result.className = 'ua-net-test-result ' + (data && data.ok ? 'is-success' : 'is-error');
          result.textContent = (data && data.message) ? data.message : 'لم تصل نتيجة صالحة من الاختبار.';
        })
        .catch(function(error){
          result.className = 'ua-net-test-result is-error';
          result.textContent = error && error.message ? error.message : 'تعذر تنفيذ الاختبار.';
        })
        .finally(function(){ button.disabled = false; });
    });
  });
})();
</script>
<?php require_once __DIR__ . '/footer.php'; ?>
