<?php
$page_title = 'الربط الشبكي';
$UA_FORCE_DESIGN_V2 = true;
$uaAndroidServerLinks = ((string)($_GET['ua_android'] ?? '') === '1')
  || stripos((string)($_SERVER['HTTP_USER_AGENT'] ?? ''), 'NetworkCustomersAndroid/') !== false;
$UA_PAGE_CSS = $uaAndroidServerLinks
  ? ['assets/css/android_server_links.css']
  : ['assets/css/server_links.css'];

require_once __DIR__ . '/header.php';
require_once __DIR__ . '/sidebar.php';
require_once __DIR__ . '/auth.php';
require_once __DIR__ . '/helpers.php';
require_once __DIR__ . '/ui_settings.php';
require_once __DIR__ . '/install_link_lib.php';

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

// The same menu entry serves both roles: the main installation manages all
// requests, while branch/agent installations manage their own connection.
if (!ua_is_server_install()) {
  header('Location: install_link.php');
  exit;
}

$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;
}

ua_link_ensure_schema($conn);
ua_ensure_settings_table($conn);

$active_tab = 'link';
$msg = '';
$err = '';

if (($_SERVER['REQUEST_METHOD'] ?? '') === 'POST') {
  $action = (string)($_POST['action'] ?? '');
  if (function_exists('ua_csrf_verify') && !ua_csrf_verify()) {
    $err = 'انتهت صلاحية النموذج. أعد المحاولة.';
  } elseif ($action === 'save_parent_settings') {
    ua_set_setting($conn, 'link_parent_name', trim((string)($_POST['parent_name'] ?? '')));
    ua_set_setting($conn, 'link_db_host', trim((string)($_POST['db_host'] ?? '')));
    ua_set_setting($conn, 'link_db_port', (string)max(1, min(65535, (int)($_POST['db_port'] ?? 3306))));
    ua_set_setting($conn, 'link_db_name', trim((string)($_POST['db_name'] ?? '')));
    ua_set_setting($conn, 'link_db_user', trim((string)($_POST['db_user'] ?? '')));
    ua_set_setting($conn, 'link_db_pass', (string)($_POST['db_pass'] ?? ''));
    ua_set_setting($conn, 'link_db_charset', trim((string)($_POST['db_charset'] ?? 'utf8mb4')));
    $msg = 'تم حفظ إعدادات النسخة الرئيسية وقاعدة البيانات.';
  } elseif ($action === 'save_endpoint') {
    $id = (int)($_POST['endpoint_id'] ?? 0);
    $label = trim((string)($_POST['label'] ?? ''));
    $baseUrl = ua_link_normalize_url((string)($_POST['base_url'] ?? ''));
    $addressType = (string)($_POST['address_type'] ?? 'internal');
    if (!in_array($addressType, ['internal', 'external'], true)) $addressType = 'internal';
    $allowBranch = isset($_POST['allow_branch']) ? 1 : 0;
    $allowAgent = isset($_POST['allow_agent']) ? 1 : 0;
    $isEnabled = isset($_POST['is_enabled']) ? 1 : 0;
    $notes = trim((string)($_POST['notes'] ?? ''));
    if ($label === '' || $baseUrl === '') {
      $err = 'أدخل اسم العنوان والرابط بشكل صحيح.';
    } elseif ($addressType === 'external' && strtolower((string)parse_url($baseUrl, PHP_URL_SCHEME)) !== 'https') {
      $err = 'العنوان الخارجي يجب أن يستخدم HTTPS لحماية بيانات الربط.';
    } elseif (!$allowBranch && !$allowAgent) {
      $err = 'حدد مهمة واحدة على الأقل لهذا العنوان.';
    } elseif ($id > 0) {
      $stmt = @$conn->prepare("UPDATE ua_link_endpoints SET label=?, base_url=?, address_type=?, allow_branch=?, allow_agent=?, is_enabled=?, notes=?, updated_at=NOW() WHERE id=?");
      if ($stmt) {
        $stmt->bind_param('sssiiisi', $label, $baseUrl, $addressType, $allowBranch, $allowAgent, $isEnabled, $notes, $id);
        $stmt->execute();
        $stmt->close();
        $msg = 'تم تحديث العنوان.';
      }
    } else {
      $stmt = @$conn->prepare("INSERT INTO ua_link_endpoints (label, base_url, address_type, allow_branch, allow_agent, is_enabled, notes) VALUES (?,?,?,?,?,?,?)");
      if ($stmt) {
        $stmt->bind_param('sssiiis', $label, $baseUrl, $addressType, $allowBranch, $allowAgent, $isEnabled, $notes);
        $stmt->execute();
        $stmt->close();
        $msg = 'تم إضافة العنوان.';
      }
    }
  } elseif ($action === 'delete_endpoint') {
    $id = (int)($_POST['endpoint_id'] ?? 0);
    if ($id > 0) {
      @$conn->query("DELETE FROM ua_link_endpoints WHERE id=$id");
      $msg = 'تم حذف العنوان.';
    }
  } elseif (in_array($action, ['approve_request', 'reject_request', 'block_request'], true)) {
    $id = (int)($_POST['request_id'] ?? 0);
    $adminId = (int)($_SESSION['admin_id'] ?? ($_SESSION['admin_user_id'] ?? 0));
    $status = $action === 'approve_request' ? 'approved' : ($action === 'block_request' ? 'blocked' : 'rejected');
    if ($id > 0) {
      if ($status === 'approved') {
        $stmt = @$conn->prepare("UPDATE ua_link_requests SET status=?, approved_by=?, approved_at=NOW(), updated_at=NOW() WHERE id=?");
        if ($stmt) {
          $stmt->bind_param('sii', $status, $adminId, $id);
          $stmt->execute();
          $stmt->close();
        }
      } else {
        $stmt = @$conn->prepare("UPDATE ua_link_requests SET status=?, approved_by=NULL, approved_at=NULL, updated_at=NOW() WHERE id=?");
        if ($stmt) {
          $stmt->bind_param('si', $status, $id);
          $stmt->execute();
          $stmt->close();
        }
      }
      $msg = 'تم تحديث حالة طلب الربط.';
    }
  }
}

$currentDb = ua_link_parent_db_profile($conn);
$parentName = (string)ua_get_setting($conn, 'link_parent_name', 'النسخة الرئيسية');
$endpoints = [];
$rs = @$conn->query("SELECT * FROM ua_link_endpoints ORDER BY id DESC");
if ($rs) while ($row = $rs->fetch_assoc()) $endpoints[] = $row;
$requests = [];
$rs = @$conn->query("SELECT r.*, e.label endpoint_label FROM ua_link_requests r LEFT JOIN ua_link_endpoints e ON e.id=r.endpoint_id ORDER BY FIELD(r.status,'pending','approved','rejected','blocked'), r.updated_at DESC, r.id DESC");
if ($rs) while ($row = $rs->fetch_assoc()) $requests[] = $row;
$currentUrl = ua_link_current_public_url();
$externalEndpoints = array_values(array_filter($endpoints, static function(array $endpoint): bool {
  return ($endpoint['address_type'] ?? '') === 'external' && !empty($endpoint['is_enabled']);
}));
$enabledEndpoints = array_values(array_filter($endpoints, static function(array $endpoint): bool {
  return !empty($endpoint['is_enabled']);
}));
$pendingRequests = array_values(array_filter($requests, static function(array $request): bool {
  return ($request['status'] ?? '') === 'pending';
}));
$approvedRequests = array_values(array_filter($requests, static function(array $request): bool {
  return ($request['status'] ?? '') === 'approved';
}));
if ($uaAndroidServerLinks) {
  require __DIR__ . '/android_server_links.php';
  require_once __DIR__ . '/footer.php';
  exit;
}
?>
<div class="content-wrapper ua-extracted-page ua-u-text-right" dir="rtl">
  <section class="content">
    <div class="container-fluid ua-network-page">
      <?php require __DIR__ . '/settings_tabs.php'; ?>

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

      <header class="ua-network-hero">
        <div class="ua-network-hero__main">
          <span class="ua-network-hero__icon" aria-hidden="true"><i class="fa fa-sitemap"></i></span>
          <div>
            <span class="ua-network-kicker">إدارة الاتصالات</span>
            <h1>الربط الشبكي</h1>
            <p>إدارة اتصال النسخ الفرعية ونسخ المعتمدين بالنسخة الرئيسية داخل الشبكة أو عبر الإنترنت.</p>
          </div>
        </div>
        <div class="ua-network-connection <?= $externalEndpoints ? 'is-online' : 'is-warning' ?>">
          <span class="ua-network-connection__icon" aria-hidden="true"><i class="fa <?= $externalEndpoints ? 'fa-globe' : 'fa-exclamation-triangle' ?>"></i></span>
          <div>
            <small>الاتصال عبر الإنترنت</small>
            <strong><?= $externalEndpoints ? 'مهيأ وآمن' : 'يحتاج إلى إعداد' ?></strong>
            <span><?= $externalEndpoints ? count($externalEndpoints) . ' عنوان HTTPS نشط' : 'أضف عنوان HTTPS خارجياً لتفعيله' ?></span>
          </div>
        </div>
      </header>

      <div class="ua-network-stats" aria-label="ملخص الربط الشبكي">
        <div class="ua-network-stat"><i class="fa fa-link" aria-hidden="true"></i><div><strong><?= count($endpoints) ?></strong><span>عناوين الوصول</span></div></div>
        <div class="ua-network-stat"><i class="fa fa-check-circle" aria-hidden="true"></i><div><strong><?= count($enabledEndpoints) ?></strong><span>عناوين نشطة</span></div></div>
        <div class="ua-network-stat"><i class="fa fa-clock-o" aria-hidden="true"></i><div><strong><?= count($pendingRequests) ?></strong><span>طلبات قيد المراجعة</span></div></div>
        <div class="ua-network-stat"><i class="fa fa-random" aria-hidden="true"></i><div><strong><?= count($approvedRequests) ?></strong><span>نسخ معتمدة</span></div></div>
      </div>

      <div class="ua-network-grid">
        <section class="ua-network-card">
          <div class="ua-network-card__head">
            <span class="ua-network-card__icon"><i class="fa fa-database"></i></span>
            <div><h2>النسخة الرئيسية</h2><p>بيانات قاعدة البيانات التي تعتمد عليها النسخ المرتبطة.</p></div>
          </div>
          <form method="post" class="ua-network-form">
            <?php if (function_exists('ua_csrf_field')) ua_csrf_field(); ?>
            <input type="hidden" name="action" value="save_parent_settings">
            <div class="ua-network-form-grid">
              <div class="ua-network-span"><label>اسم النسخة الرئيسية</label><input class="form-control" name="parent_name" value="<?= h($parentName) ?>"></div>
              <div><label>DB Host للنسخ المرتبطة</label><input class="form-control" name="db_host" value="<?= h((string)$currentDb['host']) ?>" dir="ltr"></div>
              <div><label>Port</label><input class="form-control" type="number" name="db_port" value="<?= h((string)$currentDb['port']) ?>" min="1" max="65535" dir="ltr"></div>
              <div><label>Database</label><input class="form-control" name="db_name" value="<?= h((string)$currentDb['name']) ?>" dir="ltr"></div>
              <div><label>User</label><input class="form-control" name="db_user" value="<?= h((string)$currentDb['user']) ?>" dir="ltr"></div>
              <div><label>Password</label><input class="form-control" type="password" name="db_pass" value="<?= h((string)$currentDb['pass']) ?>" dir="ltr"></div>
              <div><label>Charset</label><input class="form-control" name="db_charset" value="<?= h((string)$currentDb['charset']) ?>" dir="ltr"></div>
            </div>
            <div class="ua-network-form__actions"><button class="btn btn-primary" type="submit"><i class="fa fa-floppy-o"></i><span>حفظ الإعدادات</span></button></div>
          </form>
        </section>

        <section class="ua-network-card" id="network-endpoint-form">
          <div class="ua-network-card__head">
            <span class="ua-network-card__icon"><i class="fa fa-map-marker"></i></span>
            <div><h2>إضافة عنوان وصول</h2><p>حدد عنواناً داخلياً أو خارجياً يمكن للنسخ الاتصال من خلاله.</p></div>
          </div>
          <form method="post" class="ua-network-form">
            <?php if (function_exists('ua_csrf_field')) ua_csrf_field(); ?>
            <input type="hidden" name="action" value="save_endpoint">
            <div class="ua-network-form-grid">
              <div><label>اسم العنوان</label><input class="form-control" name="label" value="عنوان الربط"></div>
              <div><label>نوع العنوان</label><select class="form-control" name="address_type"><option value="internal">داخلي</option><option value="external">خارجي (HTTPS)</option></select></div>
              <div class="ua-network-span"><label>رابط الوصول</label><input class="form-control" name="base_url" value="<?= h($currentUrl) ?>" placeholder="https://portal.example.com/mikrotik" dir="ltr"></div>
              <div class="ua-network-span"><label>ملاحظات</label><input class="form-control" name="notes" value="" placeholder="وصف اختياري لهذا العنوان"></div>
            </div>
            <div class="ua-network-checks">
              <label class="ua-network-check"><input type="checkbox" name="allow_branch" checked><span><i class="fa fa-code-fork"></i> للنسخ الفرعية</span></label>
              <label class="ua-network-check"><input type="checkbox" name="allow_agent" checked><span><i class="fa fa-users"></i> لنسخ المعتمدين</span></label>
              <label class="ua-network-check"><input type="checkbox" name="is_enabled" checked><span><i class="fa fa-power-off"></i> مفعل</span></label>
            </div>
            <div class="ua-network-form__actions"><button class="btn btn-primary" type="submit"><i class="fa fa-plus"></i><span>إضافة العنوان</span></button></div>
          </form>
        </section>
      </div>

      <section class="ua-network-card ua-network-card--table">
        <div class="ua-network-card__head ua-network-card__head--row">
          <div class="ua-network-card__title"><span class="ua-network-card__icon"><i class="fa fa-globe"></i></span><div><h2>عناوين الوصول</h2><p>المسارات المتاحة للاتصال بالنسخة الرئيسية.</p></div></div>
          <a class="ua-network-secondary-action" href="#network-endpoint-form"><i class="fa fa-plus"></i><span>عنوان جديد</span></a>
        </div>
        <?php if (!$endpoints): ?>
          <div class="ua-network-empty"><span><i class="fa fa-map-o"></i></span><h3>لا توجد عناوين وصول بعد</h3><p>أضف أول عنوان داخلي أو خارجي لبدء ربط النسخ.</p><a href="#network-endpoint-form">إضافة عنوان</a></div>
        <?php else: ?>
          <div class="ua-network-table-wrap"><table class="ua-network-table">
            <thead><tr><th>العنوان</th><th>النطاق</th><th>الاستخدام</th><th>الحالة</th><th>إجراء</th></tr></thead>
            <tbody><?php foreach ($endpoints as $e): ?><tr>
              <td><strong><?= h((string)$e['label']) ?></strong><small dir="ltr"><?= h((string)$e['base_url']) ?></small></td>
              <td><span class="ua-network-type <?= ($e['address_type'] ?? '') === 'external' ? 'is-external' : '' ?>"><i class="fa <?= ($e['address_type'] ?? '') === 'external' ? 'fa-globe' : 'fa-building-o' ?>"></i><?= ($e['address_type'] ?? '') === 'external' ? 'خارجي' : 'داخلي' ?></span></td>
              <td><span class="ua-network-use"><?= !empty($e['allow_branch']) ? 'نسخ فرعية' : '' ?><?= !empty($e['allow_branch']) && !empty($e['allow_agent']) ? ' • ' : '' ?><?= !empty($e['allow_agent']) ? 'نسخ معتمدين' : '' ?></span></td>
              <td><span class="ua-network-badge <?= !empty($e['is_enabled']) ? 'approved' : 'blocked' ?>"><i class="fa fa-circle"></i><?= !empty($e['is_enabled']) ? 'مفعل' : 'متوقف' ?></span></td>
              <td><form method="post" onsubmit="return confirm('حذف هذا العنوان؟')"><?php if (function_exists('ua_csrf_field')) ua_csrf_field(); ?><input type="hidden" name="action" value="delete_endpoint"><input type="hidden" name="endpoint_id" value="<?= (int)$e['id'] ?>"><button class="btn btn-sm btn-outline-danger ua-network-icon-btn" type="submit" title="حذف العنوان"><i class="fa fa-trash-o"></i><span>حذف</span></button></form></td>
            </tr><?php endforeach; ?></tbody>
          </table></div>
        <?php endif; ?>
      </section>

      <section class="ua-network-card ua-network-card--table">
        <div class="ua-network-card__head ua-network-card__head--row">
          <div class="ua-network-card__title"><span class="ua-network-card__icon"><i class="fa fa-exchange"></i></span><div><h2>طلبات الربط</h2><p>مراجعة واعتماد طلبات النسخ المتصلة.</p></div></div>
          <?php if ($pendingRequests): ?><span class="ua-network-count"><?= count($pendingRequests) ?> بانتظار المراجعة</span><?php endif; ?>
        </div>
        <?php if (!$requests): ?>
          <div class="ua-network-empty"><span><i class="fa fa-inbox"></i></span><h3>لا توجد طلبات ربط</h3><p>ستظهر هنا الطلبات الواردة من النسخ الفرعية ونسخ المعتمدين.</p></div>
        <?php else: ?>
          <?php $statusLabels = ['pending' => 'قيد المراجعة', 'approved' => 'معتمد', 'rejected' => 'مرفوض', 'blocked' => 'محظور']; ?>
          <div class="ua-network-table-wrap"><table class="ua-network-table ua-network-table--requests">
            <thead><tr><th>النسخة</th><th>بيانات الاتصال</th><th>عنوان الوصول</th><th>الحالة</th><th>آخر اتصال</th><th>الإجراءات</th></tr></thead>
            <tbody><?php foreach ($requests as $r): ?><?php $st = (string)$r['status']; ?><tr>
              <td><strong><?= h((string)$r['instance_name']) ?></strong><small><?= h(ua_link_install_type_label((string)$r['install_type'])) ?> • <?= ($r['connection_mode'] ?? 'local') === 'internet' ? 'عبر الإنترنت' : 'شبكة محلية' ?></small></td>
              <td><small dir="ltr"><?= h((string)$r['reported_url']) ?></small><small dir="ltr"><?= h((string)$r['remote_addr']) ?></small></td>
              <td><strong><?= h((string)($r['endpoint_label'] ?? 'غير محد')) ?></strong><small dir="ltr"><?= h((string)$r['server_url']) ?></small></td>
              <td><span class="ua-network-badge <?= h($st) ?>"><i class="fa fa-circle"></i><?= h($statusLabels[$st] ?? $st) ?></span></td>
              <td><span class="ua-network-date"><?= h((string)($r['last_seen_at'] ?? 'لا يوجد')) ?></span></td>
              <td><div class="ua-network-actions">
                <form method="post"><?php if (function_exists('ua_csrf_field')) ua_csrf_field(); ?><input type="hidden" name="request_id" value="<?= (int)$r['id'] ?>"><button class="btn btn-sm btn-success" name="action" value="approve_request" type="submit"><i class="fa fa-check"></i><span>موافقة</span></button></form>
                <form method="post"><?php if (function_exists('ua_csrf_field')) ua_csrf_field(); ?><input type="hidden" name="request_id" value="<?= (int)$r['id'] ?>"><button class="btn btn-sm btn-outline-warning" name="action" value="reject_request" type="submit"><i class="fa fa-times"></i><span>رفض</span></button></form>
                <form method="post"><?php if (function_exists('ua_csrf_field')) ua_csrf_field(); ?><input type="hidden" name="request_id" value="<?= (int)$r['id'] ?>"><button class="btn btn-sm btn-outline-danger" name="action" value="block_request" type="submit"><i class="fa fa-ban"></i><span>حظر</span></button></form>
              </div></td>
            </tr><?php endforeach; ?></tbody>
          </table></div>
        <?php endif; ?>
      </section>
    </div>
  </section>
</div>
<?php require_once __DIR__ . '/footer.php'; ?>
