<?php
// admin/mikrotik_profiles_sync.php

if (session_status() === PHP_SESSION_NONE) session_start();

// Stage 2: keep optional parent config if the deployment uses it, then load local DB bootstrap.
$__ua_parent_config = dirname(__DIR__) . '/config.php';
if (is_file($__ua_parent_config)) {
  require_once $__ua_parent_config;
}
require_once __DIR__ . '/db_bootstrap.php';
if (function_exists('ensure_db')) {
  ensure_db(true);
}
unset($__ua_parent_config);
require_once __DIR__ . '/helpers.php';
require_once __DIR__ . '/auth.php';
require_once __DIR__ . '/lang.php';
require_once __DIR__ . '/mikrotik_lib.php';

require_login();
if (function_exists('require_perm')) {
    require_perm('can_manage_subscribers');
}

$page_title = 'مزامنة سرعات PPPoE من MikroTik';

$conn = $GLOBALS['conn'] ?? null;
if (!($conn instanceof mysqli)) {
    die('خطأ: اتصال قاعدة البيانات غير جاهز');
}

/* -------------------- أدوات مساعدة -------------------- */

function detect_speed_label(array $p): ?string {
    $name = (string)($p['name'] ?? '');
    $rate = (string)($p['rate-limit'] ?? '');

    if (preg_match('~(\d{1,3})M~i', $name, $m)) {
        return (int)$m[1] . 'M';
    }

    if ($rate && preg_match('~\b(\d{1,3})M/(\d{1,3})M\b~i', $rate, $m)) {
        return (int)$m[1] . 'M';
    }

    return null;
}

function profile_is_pppoe_speed(array $p): bool {
    $rate = (string)($p['rate-limit'] ?? '');
    return $rate !== '' && stripos($rate, 'M') !== false;
}

function sort_speed_labels(array $labels): array {
    $labels = array_unique(array_filter($labels));
    usort($labels, function($a,$b){
        return (int)$a <=> (int)$b;
    });
    return $labels;
}

/* -------------------- التنفيذ -------------------- */

$msg = '';
$err = '';
$profiles = [];
$speed_labels = [];

try {

    $API = mt_connect();
    if (!$API) {
        throw new Exception('تعذر الاتصال بـ MikroTik');
    }

    $raw = mt_call($API, '/ppp/profile/print', ['detail' => '']);
    if (!is_array($raw)) $raw = [];

    foreach ($raw as $p) {

        if (!is_array($p)) continue;
        if (!profile_is_pppoe_speed($p)) continue;

        $label = detect_speed_label($p);

        $profiles[] = [
            'name'        => $p['name'] ?? '',
            'rate_limit'  => $p['rate-limit'] ?? '',
            'only_one'    => $p['only-one'] ?? '',
            'speed_label' => $label,
        ];

        if ($label) $speed_labels[] = $label;
    }

    $speed_labels = sort_speed_labels($speed_labels);

    if (isset($_POST['do_sync'])) {

        set_app_setting($conn, 'pppoe_speed_profiles_json', json_encode($profiles, JSON_UNESCAPED_UNICODE));
        set_app_setting($conn, 'pppoe_speed_options_json', json_encode($speed_labels, JSON_UNESCAPED_UNICODE));
        set_app_setting($conn, 'pppoe_profiles_synced_at', date('Y-m-d H:i:s'));

        $msg = 'تمت المزامنة بنجاح ✅';
    }

} catch (Throwable $e) {
    $err = $e->getMessage();
}

$last_synced_at = get_app_setting($conn, 'pppoe_profiles_synced_at', '');

$UA_FORCE_DESIGN_V2 = true;
include __DIR__ . '/header.php';
include __DIR__ . '/sidebar.php';
?>

<div class="content-wrapper ua-extracted-page">
<section class="content-header">
<div class="container-fluid d-flex justify-content-between align-items-center">
<h1><?= h($page_title) ?></h1>
<?php if($last_synced_at): ?>
<span class="badge badge-info">آخر مزامنة: <?= h($last_synced_at) ?></span>
<?php endif; ?>
</div>
</section>

<section class="content">
<div class="container-fluid">

<?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; ?>

<div class="card">
<div class="card-body">

<form method="post" class="mb-3">
<button type="submit" name="do_sync" value="1" class="btn btn-primary">
تنفيذ المزامنة الآن
</button>
</form>

<div class="row mb-3">
<div class="col-md-6">
<strong>عدد بروفايلات السرعة:</strong>
<?= count($profiles) ?>
</div>
<div class="col-md-6">
<strong>السرعات المكتشفة:</strong>
<?= h(implode(' , ', $speed_labels)) ?>
</div>
</div>

<div class="table-responsive">
<table class="table table-bordered table-striped">
<thead>
<tr>
<th>Profile</th>
<th>السرعة</th>
<th>rate-limit</th>
<th>only-one</th>
</tr>
</thead>
<tbody>

<?php if(!$profiles): ?>
<tr><td colspan="4" class="text-center text-muted">لا يوجد بروفايلات سرعة</td></tr>
<?php else: foreach($profiles as $p): ?>
<tr>
<td><code><?= h($p['name']) ?></code></td>
<td><?= h($p['speed_label']) ?></td>
<td><code><?= h($p['rate_limit']) ?></code></td>
<td><?= h($p['only_one']) ?></td>
</tr>
<?php endforeach; endif; ?>

</tbody>
</table>
</div>

</div>
</div>

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

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