<?php
$page_title = 'MikroTik';
require_once __DIR__ . '/auth.php';
require_once __DIR__ . '/helpers.php';

require_login();
if(function_exists('require_perm')) require_perm('can_settings');

$uaAndroidMikrotikSettings = ((string)($_GET['ua_android'] ?? '') === '1')
  || stripos((string)($_SERVER['HTTP_USER_AGENT'] ?? ''), 'NetworkCustomersAndroid/') !== false;
$UA_FORCE_DESIGN_V2 = true;
$UA_PAGE_CSS = ['assets/css/pages/mikrotik_settings_admin.css'];
if ($uaAndroidMikrotikSettings) $UA_PAGE_CSS[] = 'assets/css/android_mikrotik_settings.css';
include __DIR__ . '/header.php';
include __DIR__ . '/sidebar.php';

$err=""; $msg="";
$row = ['host'=>'','username'=>'','password'=>'','api_port'=>8728,'queue_parent'=>'','cut_speed'=>'0/0','limit_speed'=>'512k/512k'];

// Interfaces used by live gauges/monitoring (stored in app_settings to avoid DB schema changes)
$wan_interface  = get_app_setting($conn,'mikrotik_wan_interface','');
$subs_interface = get_app_setting($conn,'mikrotik_subs_interface','');

if(table_exists($conn,'mikrotik_settings')){
  $r = $conn->query("SELECT * FROM mikrotik_settings WHERE id=1 LIMIT 1");
  if($r && $r->num_rows) $row = array_merge($row, $r->fetch_assoc());
}

if(isset($_POST['save'])){
  $host = trim($_POST['host'] ?? '');
  $user = trim($_POST['username'] ?? '');
  $pass = trim($_POST['password'] ?? '');
  $port = intval($_POST['api_port'] ?? 8728);
  $parent = trim($_POST['queue_parent'] ?? '');
  $cut = trim($_POST['cut_speed'] ?? '0/0');
  $limit = trim($_POST['limit_speed'] ?? '512k/512k');

  $wan_interface  = trim($_POST['wan_interface'] ?? '');
  $subs_interface = trim($_POST['subs_interface'] ?? '');

  if(!table_exists($conn,'mikrotik_settings')){
    $err="جدول mikrotik_settings غير موجود";
  } else {
    $sql = "INSERT INTO mikrotik_settings (id,host,username,password,api_port,queue_parent,cut_speed,limit_speed)
            VALUES (1,
              '".$conn->real_escape_string($host)."',
              '".$conn->real_escape_string($user)."',
              '".$conn->real_escape_string($pass)."',
              $port,
              '".$conn->real_escape_string($parent)."',
              '".$conn->real_escape_string($cut)."',
              '".$conn->real_escape_string($limit)."'
            )
            ON DUPLICATE KEY UPDATE
              host=VALUES(host), username=VALUES(username), password=VALUES(password),
              api_port=VALUES(api_port), queue_parent=VALUES(queue_parent),
              cut_speed=VALUES(cut_speed), limit_speed=VALUES(limit_speed)";
    if($conn->query($sql)) $msg="تم حفظ إعدادات MikroTik ✅";
    else $err="DB Error: ".$conn->error;
  }

  // Save interfaces (even if DB table missing) so gauges can work
  set_app_setting($conn,'mikrotik_wan_interface',$wan_interface);
  set_app_setting($conn,'mikrotik_subs_interface',$subs_interface);
}

if ($uaAndroidMikrotikSettings) {
  require __DIR__ . '/android_mikrotik_settings.php';
  include __DIR__ . '/footer.php';
  return;
}
?>

<div class="content-wrapper ua-extracted-page ua-mikrotik-settings-page">
  <section class="content-header"><div class="container-fluid"><h1>إعدادات MikroTik</h1></div></section>
  <section class="content">
    <div class="container-fluid">
      <header class="ua-mikrotik-settings-hero">
        <div>
          <span><i class="fa fa-server"></i> RouterOS API</span>
          <h1>إعدادات MikroTik</h1>
          <p>إدارة اتصال API وواجهات القياس وحدود السرعة من موضع واحد.</p>
        </div>
        <a class="btn btn-info" href="mikrotik_dashboard.php"><i class="fa fa-dashboard"></i> فتح المراقبة</a>
      </header>
      <?php if($msg){ ?><div class="alert alert-success"><?= h($msg) ?></div><?php } ?>
      <?php if($err){ ?><div class="alert alert-danger"><?= h($err) ?></div><?php } ?>

      <div class="card compact">
        <div class="card-body">
          <form method="post" class="form-compact labels-left">
            <div class="row">
              <div class="col-md-4">
                <label>Host</label>
                <input class="form-control" name="host" value="<?= h($row['host']) ?>">
              </div>
              <div class="col-md-4">
                <label>Username</label>
                <input class="form-control" name="username" value="<?= h($row['username']) ?>">
              </div>
              <div class="col-md-4">
                <label>Password</label>
                <input class="form-control" name="password" value="<?= h($row['password']) ?>">
              </div>
            </div>

            <div class="row mt-3">
              <div class="col-md-3">
                <label>API Port</label>
                <input class="form-control" name="api_port" value="<?= h($row['api_port']) ?>">
              </div>
              <div class="col-md-3">
                <label>Queue Parent</label>
                <input class="form-control" name="queue_parent" value="<?= h($row['queue_parent']) ?>">
              </div>
              <div class="col-md-3">
                <label>Cut Speed</label>
                <input class="form-control" name="cut_speed" value="<?= h($row['cut_speed']) ?>">
              </div>
              <div class="col-md-3">
                <label>Limit 512</label>
                <input class="form-control" name="limit_speed" value="<?= h($row['limit_speed']) ?>">
              </div>
            </div>

            <div class="row mt-3">
              <div class="col-md-4">
                <label>WAN Interface (اختياري)</label>
                <div class="input-group">
                  <input class="form-control" name="wan_interface" id="wan_interface" value="<?= h($wan_interface) ?>" placeholder="ether1 / pppoe-out1 ...">
                  <div class="input-group-append">
                    <button class="btn btn-outline-primary" type="button" id="btnFetchIfs"><i class="fa fa-refresh"></i> جلب المنافذ</button>
                  </div>
                </div>
                <small class="text-muted">للعداد/القياس من واجهة الإنترنت (إن رغبت لاحقاً)</small>
              </div>
              <div class="col-md-4">
                <label>Subscribers Interface</label>
                <input class="form-control" name="subs_interface" id="subs_interface" value="<?= h($subs_interface) ?>" placeholder="bridge-lan / ether2 ...">
                <small class="text-muted">يُستخدم لقياس الإنترنت الصادر للمشتركين (Monitor Traffic)</small>
              </div>
              <div class="col-md-4">
                <label>اختبار الاتصال</label>
                <div>
                  <button type="button" class="btn btn-info" id="btnTestMk"><i class="fa fa-plug"></i> Test</button>
                  <span id="mkTestResult" class="ml-2"></span>
                </div>
              </div>
            </div>

            <div class="mt-4">
              <button class="btn btn-success" name="save"><i class="fa fa-save"></i> حفظ</button>
            </div>
          </form>
        </div>
      </div>

      <script>
      (function(){
        const btn = document.getElementById('btnFetchIfs');
        const btnTest = document.getElementById('btnTestMk');
        const res = document.getElementById('mkTestResult');
        const wan = document.getElementById('wan_interface');
        const subs = document.getElementById('subs_interface');

        async function fetchJson(url){
          const r = await fetch(url, {credentials:'same-origin'});
          return await r.json();
        }

        if(btn){
          btn.addEventListener('click', async () => {
            res.textContent = '...';
            try {
              const d = await fetchJson('api/mikrotik_interfaces.php');
              if(!d.ok) throw new Error(d.error || 'Error');
              // Build a simple prompt list (no debug shown)
              const names = (d.interfaces||[]).map(x=>x.name).filter(Boolean);
              if(names.length===0){ res.textContent = 'لا توجد منافذ'; return; }
              const choice = prompt('أسماء المنافذ المتاحة:\n' + names.join('\n') + '\n\nاكتب اسم المنفذ للمشتركين:', subs.value || names[0]);
              if(choice!==null){ subs.value = choice.trim(); }
              res.textContent = 'تم جلب القائمة ✅';
            } catch(e){
              res.textContent = 'تعذر جلب المنافذ';
            }
          });
        }

        if(btnTest){
          btnTest.addEventListener('click', async () => {
            res.textContent = '...';
            try {
              const d = await fetchJson('api/mikrotik_status.php');
              res.textContent = d.connected ? 'متصل ✅' : 'غير متصل ❌';
            } catch(e){
              res.textContent = 'غير متصل ❌';
            }
          });
        }
      })();
      </script>

    </div>
  </section>
</div>

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