<?php
$page_title = 'إعدادات الكروت والترافيك';
require_once __DIR__ . '/auth.php';
require_once __DIR__ . '/db_bootstrap.php';
if (function_exists('ensure_db')) ensure_db(true);
require_once __DIR__ . '/helpers.php';
$UA_FORCE_DESIGN_V2 = true;
$uaAndroidSettingsHud = ((string)($_GET['ua_android'] ?? '') === '1') || stripos((string)($_SERVER['HTTP_USER_AGENT'] ?? ''), 'NetworkCustomersAndroid/') !== false;
if ($uaAndroidSettingsHud) $UA_PAGE_CSS = ['assets/css/android_settings_hud.css'];
require_once __DIR__ . '/header.php';
require_once __DIR__ . '/sidebar.php';
require_once __DIR__ . '/comms_admin_lib.php';

$conn = $GLOBALS['conn'] ?? null;
if (!($conn instanceof mysqli)) {
  echo "<div class='content-wrapper'><section class='content p-3'><div class='alert alert-danger'>تعذر الاتصال بقاعدة البيانات.</div></section></div>";
  require_once __DIR__ . '/footer.php';
  exit;
}

comms_ensure_tables($conn);

if (!function_exists('h')) {
  function h($s){ return htmlspecialchars((string)$s, ENT_QUOTES, 'UTF-8'); }
}

function ua_settings_schema(mysqli $conn): string {
  static $schema = null;
  if ($schema !== null) return $schema;
  try {
    $rs = @$conn->query("SHOW COLUMNS FROM app_settings LIKE 'setting_key'");
    if ($rs && $rs->num_rows > 0) { $schema = 'setting_key'; return $schema; }
  } catch (Throwable $e) {}
  $schema = 'key';
  return $schema;
}
function ua_ensure_settings_table(mysqli $conn): void {
  @$conn->query("CREATE TABLE IF NOT EXISTS app_settings (
    id INT AUTO_INCREMENT PRIMARY KEY,
    setting_key VARCHAR(120) NOT NULL,
    setting_value LONGTEXT NULL,
    updated_at DATETIME DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
    UNIQUE KEY uniq_setting_key (setting_key)
  ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4");
}
function ua_get_setting2(mysqli $conn, string $key, $default = null) {
  $schema = ua_settings_schema($conn);
  $k = $conn->real_escape_string($key);
  if ($schema === 'setting_key') {
    $r = @$conn->query("SELECT setting_value v FROM app_settings WHERE setting_key='$k' LIMIT 1");
  } else {
    $r = @$conn->query("SELECT value v FROM app_settings WHERE `key`='$k' LIMIT 1");
  }
  if ($r && ($row = $r->fetch_assoc())) return $row['v'];
  return $default;
}
function ua_set_setting2(mysqli $conn, string $key, string $value): void {
  $schema = ua_settings_schema($conn);
  if ($schema === 'setting_key') {
    $stmt = @$conn->prepare("INSERT INTO app_settings (setting_key,setting_value) VALUES (?,?) ON DUPLICATE KEY UPDATE setting_value=VALUES(setting_value), updated_at=NOW()");
  } else {
    $stmt = @$conn->prepare("INSERT INTO app_settings (`key`,`value`) VALUES (?,?) ON DUPLICATE KEY UPDATE `value`=VALUES(`value`), updated_at=NOW()");
  }
  if ($stmt) {
    $stmt->bind_param('ss', $key, $value);
    @$stmt->execute();
    $stmt->close();
  }
}

ua_ensure_settings_table($conn);
$routers = comms_get_routers($conn);
$enabledRouters = array_values(array_filter($routers, fn($r) => (int)($r['is_enabled'] ?? 0) === 1));

$msg = '';
$err = '';

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
  $primaryRouterId = (int)($_POST['primary_router_id'] ?? 0);
  $pppRouterId = (int)($_POST['ppp_router_id'] ?? 0);
  $resourceRouterIds = array_map('intval', (array)($_POST['resource_router_ids'] ?? []));
  $globalMax = trim((string)($_POST['hud_max_mbps'] ?? '100'));
  $disconnectAlertEnabled = isset($_POST['noc_device_disconnect_alert_enabled']) ? '1' : '0';
  if (!preg_match('/^\d+(\.\d+)?$/', $globalMax)) $globalMax = '100';

  $srcEnabled = (array)($_POST['traffic_enabled'] ?? []);
  $srcRouter = (array)($_POST['traffic_router_id'] ?? []);
  $srcIface = (array)($_POST['traffic_iface'] ?? []);
  $srcLabel = (array)($_POST['traffic_label'] ?? []);
  $srcMax = (array)($_POST['traffic_max_mbps'] ?? []);

  $sources = [];
  $rowsCount = max(count($srcRouter), count($srcIface), count($srcLabel), count($srcMax));
  for ($i=0; $i<$rowsCount; $i++) {
    $routerId = (int)($srcRouter[$i] ?? 0);
    $iface = trim((string)($srcIface[$i] ?? ''));
    $label = trim((string)($srcLabel[$i] ?? ''));
    $max = trim((string)($srcMax[$i] ?? $globalMax));
    if (!preg_match('/^\d+(\.\d+)?$/', $max)) $max = $globalMax;
    $enabled = isset($srcEnabled[$i]) ? 1 : 0;
    if ($routerId <= 0 && $iface === '' && $label === '') continue;
    $sources[] = [
      'enabled' => $enabled,
      'router_id' => $routerId,
      'iface' => $iface,
      'label' => $label,
      'max_mbps' => (float)$max,
    ];
  }

  ua_set_setting2($conn, 'noc_primary_router_id', (string)$primaryRouterId);
  ua_set_setting2($conn, 'noc_ppp_router_id', (string)$pppRouterId);
  ua_set_setting2($conn, 'noc_resource_router_ids', json_encode(array_values(array_unique(array_filter($resourceRouterIds))), JSON_UNESCAPED_UNICODE));
  ua_set_setting2($conn, 'noc_traffic_sources', json_encode($sources, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES));
  ua_set_setting2($conn, 'hud_max_mbps', (string)$globalMax);
  ua_set_setting2($conn, 'noc_device_disconnect_alert_enabled', $disconnectAlertEnabled);

  $msg = 'تم حفظ إعدادات الكروت والترافيك.';
}

$primaryRouterId = (int)ua_get_setting2($conn, 'noc_primary_router_id', '0');
$pppRouterId = (int)ua_get_setting2($conn, 'noc_ppp_router_id', '0');
$resourceRouterIds = json_decode((string)ua_get_setting2($conn, 'noc_resource_router_ids', '[]'), true);
if (!is_array($resourceRouterIds)) $resourceRouterIds = [];
$trafficSources = json_decode((string)ua_get_setting2($conn, 'noc_traffic_sources', '[]'), true);
if (!is_array($trafficSources)) $trafficSources = [];
$globalMax = (string)ua_get_setting2($conn, 'hud_max_mbps', '100');
$disconnectAlertEnabled = (string)ua_get_setting2($conn, 'noc_device_disconnect_alert_enabled', '1') !== '0';

$routerMap = [];
foreach ($routers as $r) $routerMap[(int)$r['id']] = $r;
?>
<div class="content-wrapper ua-extracted-page">
  <section class="content p-3">
    <div class="card">
      <div class="card-body">
        <div class="d-flex flex-wrap justify-content-between align-items-start gap-3 mb-4">
          <div>
            <h4 class="mb-1">إعدادات الكروت والترافيك</h4>
            <div class="text-muted small">هذه الصفحة عامة ومرنة: يمكن تخصيص الراوتر الأساسي، راوتر PPP، كروت الموارد، ومصادر الترافيك المتعددة لأي شبكة.</div>
          </div>
          <div class="d-flex gap-2">
            <a class="btn btn-outline-secondary" href="dashboard.php">رجوع للوحة التحكم</a>
            <a class="btn btn-outline-info" href="api/noc_stats.php" target="_blank">اختبار JSON</a>
          </div>
        </div>

        <?php if ($msg): ?><div class="alert alert-success"><?= h($msg) ?></div><?php endif; ?>
        <?php if ($err): ?><div class="alert alert-danger"><?= h($err) ?></div><?php endif; ?>

        <form method="post" id="nocSettingsForm">
          <div class="row g-3">
            <div class="col-lg-4">
              <label class="form-label">الراوتر الأساسي للوحة</label>
              <select class="form-control" name="primary_router_id">
                <option value="0">تلقائي</option>
                <?php foreach ($enabledRouters as $r): ?>
                  <option value="<?= (int)$r['id'] ?>" <?= $primaryRouterId === (int)$r['id'] ? 'selected' : '' ?>><?= h($r['name'].' ('.$r['host'].')') ?></option>
                <?php endforeach; ?>
              </select>
              <div class="form-text">يُستخدم كمرجع عام للوحة عند غياب إعدادات أخرى.</div>
            </div>

            <div class="col-lg-4">
              <label class="form-label">راوتر PPP / المشتركين</label>
              <select class="form-control" name="ppp_router_id">
                <option value="0">تلقائي</option>
                <?php foreach ($enabledRouters as $r): ?>
                  <option value="<?= (int)$r['id'] ?>" <?= $pppRouterId === (int)$r['id'] ? 'selected' : '' ?>><?= h($r['name'].' ('.$r['role'].')') ?></option>
                <?php endforeach; ?>
              </select>
              <div class="form-text">تُقرأ منه جلسات PPP والإحصاءات الحية للمشتركين.</div>
            </div>

            <div class="col-lg-4">
              <label class="form-label">القيمة الافتراضية Max لكل كرت ترافيك (Mbps)</label>
              <input class="form-control" name="hud_max_mbps" value="<?= h($globalMax) ?>">
              <div class="form-text">يمكن تغييرها لكل مصدر ترافيك على حدة.</div>
            </div>
          </div>

          <section class="ua-connectivity-alert-setting" aria-labelledby="uaConnectivityAlertSettingTitle">
            <div class="ua-connectivity-alert-setting__icon" aria-hidden="true"><i class="fa fa-exclamation-triangle"></i></div>
            <div class="ua-connectivity-alert-setting__copy">
              <h5 id="uaConnectivityAlertSettingTitle">تنبيه خطر عند فقد الاتصال</h5>
              <p>يعرض تنبيهاً واضحاً في منتصف الشاشة إذا انتقل أي راوتر أو مرسل أو مستقبل من حالة اتصال مؤكدة إلى حالة انقطاع مؤكدة. حالات القراءة غير المكتملة لا تُعامل كانقطاع.</p>
            </div>
            <label class="ua-connectivity-alert-setting__toggle">
              <input type="checkbox" name="noc_device_disconnect_alert_enabled" value="1" <?= $disconnectAlertEnabled ? 'checked' : '' ?>>
              <span aria-hidden="true"></span>
              <b>تفعيل التنبيه</b>
            </label>
            <button type="button" class="btn btn-outline-danger ua-connectivity-alert-setting__preview" id="previewDisconnectAlert">
              <i class="fa fa-eye" aria-hidden="true"></i> معاينة التنبيه
            </button>
          </section>

          <hr class="my-4">

          <h5 class="mb-3">الراوترات التي ستظهر ككروت موارد</h5>
          <div class="row">
            <?php if (!$enabledRouters): ?>
              <div class="col-12"><div class="alert alert-warning mb-0">لا توجد راوترات مفعّلة في صفحة إدارة الراوترات.</div></div>
            <?php else: ?>
              <?php foreach ($enabledRouters as $r): ?>
                <div class="col-md-4 mb-2">
                  <label class="form-check border rounded p-3 w-100 d-block">
                    <input class="form-check-input me-2" type="checkbox" name="resource_router_ids[]" value="<?= (int)$r['id'] ?>" <?= in_array((int)$r['id'], array_map('intval', $resourceRouterIds), true) ? 'checked' : '' ?>>
                    <span class="fw-bold"><?= h($r['name']) ?></span>
                    <span class="text-muted small d-block"><?= h($r['host']) ?> • <?= h($r['role']) ?></span>
                  </label>
                </div>
              <?php endforeach; ?>
            <?php endif; ?>
          </div>
          <div class="form-text mt-1">إذا لم تختر أي راوتر، ستظهر كل الراوترات المفعلة تلقائياً في لوحة التحكم.</div>

          <hr class="my-4">

          <div class="d-flex justify-content-between align-items-center mb-3">
            <div>
              <h5 class="mb-1">مصادر الترافيك اللحظي</h5>
              <div class="text-muted small">أضف أكثر من راوتر وأكثر من منفذ، وكل مصدر ينشئ كرتاً مستقلاً في اللوحة.</div>
            </div>
            <button type="button" class="btn btn-outline-primary" id="addTrafficRow">إضافة مصدر ترافيك</button>
          </div>

          <div class="table-responsive">
            <table class="table table-bordered align-middle" id="trafficSourcesTable">
              <thead>
                <tr>
                  <th class="ua-u-w-70">تفعيل</th>
                  <th>الراوتر</th>
                  <th>الواجهة</th>
                  <th>اسم الكرت</th>
                  <th class="ua-u-w-140">Max Mbps</th>
                  <th class="ua-u-w-120">منافذ</th>
                  <th class="ua-u-w-80">حذف</th>
                </tr>
              </thead>
              <tbody id="trafficRows">
              <?php if ($trafficSources): ?>
                <?php foreach ($trafficSources as $i => $src): ?>
                  <tr>
                    <td class="text-center"><input type="checkbox" name="traffic_enabled[<?= (int)$i ?>]" <?= !empty($src['enabled']) ? 'checked' : '' ?>></td>
                    <td>
                      <select class="form-control traffic-router" name="traffic_router_id[<?= (int)$i ?>]">
                        <option value="0">اختر الراوتر</option>
                        <?php foreach ($enabledRouters as $r): ?>
                          <option value="<?= (int)$r['id'] ?>" <?= (int)($src['router_id'] ?? 0) === (int)$r['id'] ? 'selected' : '' ?>><?= h($r['name'].' ('.$r['host'].')') ?></option>
                        <?php endforeach; ?>
                      </select>
                    </td>
                    <td><input class="form-control traffic-iface" name="traffic_iface[<?= (int)$i ?>]" value="<?= h($src['iface'] ?? '') ?>" placeholder="sfp-sfpplus1 / ether1 / pppoe-out1"></td>
                    <td><input class="form-control" name="traffic_label[<?= (int)$i ?>]" value="<?= h($src['label'] ?? '') ?>" placeholder="مثال: الإنترنت الرئيسي"></td>
                    <td><input class="form-control" name="traffic_max_mbps[<?= (int)$i ?>]" value="<?= h((string)($src['max_mbps'] ?? $globalMax)) ?>"></td>
                    <td><button type="button" class="btn btn-sm btn-outline-info fetch-ifs">جلب</button></td>
                    <td><button type="button" class="btn btn-sm btn-outline-danger remove-row">حذف</button></td>
                  </tr>
                <?php endforeach; ?>
              <?php endif; ?>
              </tbody>
            </table>
          </div>

          <div class="d-flex gap-2 mt-4">
            <button class="btn btn-success" type="submit">حفظ الإعدادات</button>
            <button class="btn btn-outline-secondary" type="button" id="seedOneRow">إضافة صف افتراضي</button>
          </div>
        </form>
      </div>
    </div>
  </section>
</div>

<script>
(function(){
  const tbody = document.getElementById('trafficRows');
  const addBtn = document.getElementById('addTrafficRow');
  const seedBtn = document.getElementById('seedOneRow');
  const routers = <?= json_encode(array_map(function($r){ return ['id'=>(int)$r['id'],'name'=>$r['name'],'host'=>$r['host']]; }, $enabledRouters), JSON_UNESCAPED_UNICODE|JSON_UNESCAPED_SLASHES) ?>;
  let idx = <?= count($trafficSources) ?>;

  document.getElementById('previewDisconnectAlert')?.addEventListener('click', () => {
    const message = {type: 'ua-device-disconnect-alert-preview'};
    if (window.top === window && window.UADeviceDisconnectAlert?.preview) {
      window.UADeviceDisconnectAlert.preview();
      return;
    }
    window.top.postMessage(message, window.location.origin);
  });

  <?php if ($msg): ?>
  window.setTimeout(() => {
    const configuration = {
      type: 'ua-device-disconnect-alert-config',
      enabled: <?= $disconnectAlertEnabled ? 'true' : 'false' ?>
    };
    if (window.top.UADeviceDisconnectAlert?.setEnabled) {
      window.top.UADeviceDisconnectAlert.setEnabled(configuration.enabled);
    } else {
      window.top.postMessage(configuration, window.location.origin);
    }
  }, 0);
  <?php endif; ?>

  function routerOptions(selected){
    let html = '<option value="0">اختر الراوتر</option>';
    routers.forEach(r => {
      html += `<option value="${r.id}" ${String(selected)===String(r.id)?'selected':''}>${r.name} (${r.host})</option>`;
    });
    return html;
  }

  function addRow(data){
    if (!tbody) return;
    const i = idx++;
    const row = document.createElement('tr');
    row.innerHTML = `
      <td class="text-center"><input type="checkbox" name="traffic_enabled[${i}]" ${data?.enabled ? 'checked' : 'checked'}></td>
      <td><select class="form-control traffic-router" name="traffic_router_id[${i}]">${routerOptions(data?.router_id || 0)}</select></td>
      <td><input class="form-control traffic-iface" name="traffic_iface[${i}]" value="${data?.iface || ''}" placeholder="sfp-sfpplus1 / ether1 / pppoe-out1"></td>
      <td><input class="form-control" name="traffic_label[${i}]" value="${data?.label || ''}" placeholder="مثال: الإنترنت الرئيسي"></td>
      <td><input class="form-control" name="traffic_max_mbps[${i}]" value="${data?.max_mbps || <?= json_encode($globalMax) ?>}"></td>
      <td><button type="button" class="btn btn-sm btn-outline-info fetch-ifs">جلب</button></td>
      <td><button type="button" class="btn btn-sm btn-outline-danger remove-row">حذف</button></td>`;
    tbody.appendChild(row);
  }

  async function fetchInterfaces(routerId){
    const res = await fetch('api/mikrotik_interfaces.php?router_id=' + encodeURIComponent(routerId), {credentials:'same-origin'});
    return await res.json();
  }

  addBtn?.addEventListener('click', () => addRow());
  seedBtn?.addEventListener('click', () => addRow());

  if (tbody && !tbody.children.length) addRow();

  tbody?.addEventListener('click', async (e) => {
    const removeBtn = e.target.closest('.remove-row');
    if (removeBtn) {
      removeBtn.closest('tr')?.remove();
      return;
    }
    const fetchBtn = e.target.closest('.fetch-ifs');
    if (fetchBtn) {
      const tr = fetchBtn.closest('tr');
      const routerId = tr?.querySelector('.traffic-router')?.value || '0';
      if (!routerId || routerId === '0') {
        alert('اختر الراوتر أولاً.');
        return;
      }
      fetchBtn.disabled = true;
      const old = fetchBtn.textContent;
      fetchBtn.textContent = '...';
      try {
        const d = await fetchInterfaces(routerId);
        if (!d.ok) throw new Error(d.error || 'error');
        const names = (d.interfaces || []).map(x => x.name).filter(Boolean);
        if (!names.length) throw new Error('لا توجد منافذ');
        const choice = prompt('المنافذ المتاحة:\n' + names.join('\n') + '\n\nاكتب اسم المنفذ المطلوب:', tr.querySelector('.traffic-iface')?.value || names[0]);
        if (choice !== null) {
          tr.querySelector('.traffic-iface').value = choice.trim();
        }
      } catch(err) {
        alert('تعذر جلب المنافذ لهذا الراوتر.');
      } finally {
        fetchBtn.disabled = false;
        fetchBtn.textContent = old;
      }
    }
  });
})();
</script>

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