<?php
require_once __DIR__ . '/db.php';
require_once __DIR__ . '/cron/ensure_traffic_tables.php';
require_once __DIR__ . '/lib/mikrotik_client.php';

mysqli_set_charset($conn, 'utf8');
ensure_traffic_tables($conn);

// ensure row exists
$res = $conn->query("SELECT * FROM mikrotik_settings ORDER BY id ASC LIMIT 1");
$settings = $res ? $res->fetch_assoc() : null;
if (!$settings) {
    $conn->query("INSERT INTO mikrotik_settings (host, username, password, api_port, queue_parent, cut_speed, limit_speed, subscriber_interface, wan_interface) VALUES ('192.168.88.1','admin','admin',8728,'','0/0','512k/512k','','')");
    $settings = mt_get_settings($conn);
}

$message = '';
if (isset($_POST['save'])) {
    $host = trim($_POST['host'] ?? '');
    $username = trim($_POST['username'] ?? '');
    $password = trim($_POST['password'] ?? '');
    $api_port = (int)($_POST['api_port'] ?? 8728);
    $queue_parent = trim($_POST['queue_parent'] ?? '');
    $cut_speed = trim($_POST['cut_speed'] ?? '0/0');
    $limit_speed = trim($_POST['limit_speed'] ?? '512k/512k');
    $subscriber_interface = trim($_POST['subscriber_interface'] ?? '');
    $wan_interface = trim($_POST['wan_interface'] ?? '');

    if ($api_port <= 0) $api_port = 8728;

    $stmt = $conn->prepare("UPDATE mikrotik_settings SET host=?, username=?, password=?, api_port=?, queue_parent=?, cut_speed=?, limit_speed=?, subscriber_interface=?, wan_interface=? WHERE id=?");
    $id = (int)$settings['id'];
    $stmt->bind_param('sssisssssi', $host, $username, $password, $api_port, $queue_parent, $cut_speed, $limit_speed, $subscriber_interface, $wan_interface, $id);
    $stmt->execute();

    $message = '✅ تم حفظ إعدادات MikroTik';
    $settings = mt_get_settings($conn);
}

// Try load interfaces list
$interfaces = [];
$api = mt_connect($conn);
if ($api) {
    $interfaces = mt_list_interfaces($api);
    mt_disconnect($api);
}
?>
<!DOCTYPE html>
<html lang="ar" dir="rtl">
<head>
<meta charset="UTF-8">
<title>إعدادات MikroTik</title>
<style>
body{font-family:Tahoma,Arial; margin:20px;}
label{display:block; margin-top:10px; font-weight:bold;}
input,select{width:420px; padding:8px;}
.small{color:#666; font-size:12px;}
button{padding:8px 16px; margin-top:14px;}
.box{max-width:760px; border:1px solid #ddd; border-radius:10px; padding:16px;}
.ok{background:#e9ffe9; border:1px solid #b9f3b9; padding:10px; border-radius:8px; margin-bottom:10px;}
.warn{background:#fff7e6; border:1px solid #ffd27a; padding:10px; border-radius:8px; margin-top:10px;}
</style>
</head>
<body>
<h2>إعدادات MikroTik</h2>
<?php if ($message): ?>
<div class="ok"><?php echo htmlspecialchars($message); ?></div>
<?php endif; ?>
<div class="box">
<form method="post">
    <label>IP / Host</label>
    <input type="text" name="host" value="<?php echo htmlspecialchars($settings['host'] ?? ''); ?>" required>

    <label>اسم المستخدم</label>
    <input type="text" name="username" value="<?php echo htmlspecialchars($settings['username'] ?? ''); ?>" required>

    <label>كلمة المرور</label>
    <input type="password" name="password" value="<?php echo htmlspecialchars($settings['password'] ?? ''); ?>" required>

    <label>منفذ RouterOS API (Port)</label>
    <input type="number" name="api_port" value="<?php echo htmlspecialchars($settings['api_port'] ?? '8728'); ?>" required>
    <div class="small">افتراضي: 8728</div>

    <label>WAN Interface (لقياس الإنترنت الأساسي)</label>
    <select name="wan_interface">
        <option value="">-- اختر --</option>
        <?php foreach ($interfaces as $if): ?>
            <option value="<?php echo htmlspecialchars($if); ?>" <?php echo (($settings['wan_interface'] ?? '') === $if) ? 'selected' : ''; ?>><?php echo htmlspecialchars($if); ?></option>
        <?php endforeach; ?>
    </select>

    <label>Subscribers Interface (لقياس الصادر للمشتركين)</label>
    <select name="subscriber_interface">
        <option value="">-- اختر --</option>
        <?php foreach ($interfaces as $if): ?>
            <option value="<?php echo htmlspecialchars($if); ?>" <?php echo (($settings['subscriber_interface'] ?? '') === $if) ? 'selected' : ''; ?>><?php echo htmlspecialchars($if); ?></option>
        <?php endforeach; ?>
    </select>

    <label>Parent Queue (اختياري)</label>
    <input type="text" name="queue_parent" value="<?php echo htmlspecialchars($settings['queue_parent'] ?? ''); ?>">

    <label>Cut Speed (عند القطع: 0/0)</label>
    <input type="text" name="cut_speed" value="<?php echo htmlspecialchars($settings['cut_speed'] ?? '0/0'); ?>">

    <label>Limit Speed (عند التخفيض: 512k/512k)</label>
    <input type="text" name="limit_speed" value="<?php echo htmlspecialchars($settings['limit_speed'] ?? '512k/512k'); ?>">

    <button type="submit" name="save">حفظ</button>
</form>

<div class="warn">
<strong>ملاحظة:</strong> قائمة الواجهات تظهر فقط إذا كان اتصال RouterOS API يعمل.
</div>
</div>

<p><a href="index.php">⬅ العودة</a></p>
</body>
</html>
