<?php
// admin/install_link.php
// First-run main-instance link page for branch/agent installations.

require_once __DIR__ . '/security.php';
require_once __DIR__ . '/helpers.php';
require_once __DIR__ . '/install_link_lib.php';

$config = ua_install_config();
$installType = ua_install_type();
$link = ua_install_link_config();
$msg = '';
$err = '';

if (!ua_install_link_required()) {
  header('Location: index.php');
  exit;
}

$instanceId = trim((string)($link['instance_id'] ?? ''));
$secret = trim((string)($link['secret'] ?? ''));
if ($instanceId === '') $instanceId = 'ua_' . ua_link_random_token(16);
if ($secret === '') $secret = ua_link_random_token(32);

$serverUrl = (string)($link['server_url'] ?? ($config['server_url'] ?? ''));
if (trim($serverUrl) === '') $serverUrl = 'http://127.0.0.1:8080/mikrotik/admin';
$connectionMode = ua_link_connection_mode((string)($link['connection_mode'] ?? ($config['connection_mode'] ?? 'local')));
$instanceName = (string)($link['instance_name'] ?? (ua_link_install_type_label($installType) . ' - ' . substr($instanceId, -6)));
$status = ua_install_link_status();

function ua_install_link_save_local(array $patch, string &$error): bool {
  return ua_save_install_config($patch, $error);
}

function ua_install_link_payload(string $installType, string $instanceId, string $secret, string $serverUrl, string $instanceName, string $connectionMode): array {
  return [
    'instance_id' => $instanceId,
    'secret' => $secret,
    'install_type' => $installType,
    'server_url' => $serverUrl,
    'connection_mode' => $connectionMode,
    'reported_url' => ua_link_current_public_url(),
    'instance_name' => $instanceName,
    'version' => function_exists('app_version') ? app_version() : '',
    'build' => function_exists('app_build') ? app_build() : '',
  ];
}

if (($_SERVER['REQUEST_METHOD'] ?? '') === 'POST') {
  if (function_exists('ua_csrf_verify') && !ua_csrf_verify()) {
    $err = 'انتهت صلاحية النموذج. أعد المحاولة.';
  } else {
    $action = (string)($_POST['action'] ?? 'register');
    $serverUrl = ua_link_normalize_url((string)($_POST['server_url'] ?? $serverUrl));
    $connectionMode = ua_link_connection_mode((string)($_POST['connection_mode'] ?? $connectionMode));
    $instanceName = trim((string)($_POST['instance_name'] ?? $instanceName));
    if ($instanceName === '') $instanceName = ua_link_install_type_label($installType) . ' - ' . substr($instanceId, -6);

    if ($serverUrl === '') {
      $err = 'أدخل رابط النسخة الرئيسية بشكل صحيح.';
    } elseif ($connectionMode === 'internet' && strtolower((string)parse_url($serverUrl, PHP_URL_SCHEME)) !== 'https') {
      $err = 'الاتصال عبر الإنترنت يتطلب رابط HTTPS خارجياً.';
    } else {
      $localPatch = [
        'install_type' => $installType,
        'connection_mode' => $connectionMode,
        'server_url' => $serverUrl,
        'link' => [
          'instance_id' => $instanceId,
          'secret' => $secret,
          'server_url' => $serverUrl,
          'connection_mode' => $connectionMode,
          'instance_name' => $instanceName,
          'status' => $status,
          'checked_at' => date('Y-m-d H:i:s'),
        ],
      ];

      $apiPath = $action === 'check' ? 'api/link_status.php' : 'api/link_register.php';
      $apiErr = '';
      $res = ua_link_http_json($serverUrl, $apiPath, ua_install_link_payload($installType, $instanceId, $secret, $serverUrl, $instanceName, $connectionMode), $apiErr, 12);
      if (!is_array($res)) {
        $localPatch['link']['status'] = 'error';
        $localPatch['connection_verified'] = false;
        $tmpErr = '';
        ua_install_link_save_local($localPatch, $tmpErr);
        $status = 'error';
        $err = $apiErr !== '' ? $apiErr : 'تعذر الاتصال بالنسخة الرئيسية.';
      } elseif (empty($res['ok'])) {
        $localPatch['link']['status'] = (string)($res['status'] ?? 'error');
        $localPatch['connection_verified'] = false;
        $tmpErr = '';
        ua_install_link_save_local($localPatch, $tmpErr);
        $status = $localPatch['link']['status'];
        $err = (string)($res['message'] ?? 'رفضت النسخة الرئيسية الطلب.');
      } else {
        $status = (string)($res['status'] ?? 'pending');
        $localPatch['link']['status'] = $status;
        $localPatch['connection_verified'] = $status === 'approved';
        $localPatch['link']['request_id'] = (int)($res['request_id'] ?? 0);
        $localPatch['link']['portal_url'] = (string)($res['portal_url'] ?? ua_link_admin_url($serverUrl));
        if ($status === 'approved' && $connectionMode === 'local' && isset($res['database']) && is_array($res['database'])) {
          $db = $res['database'];
          $localPatch['database'] = [
            'host' => trim((string)($db['host'] ?? '')),
            'port' => (int)($db['port'] ?? 3306),
            'name' => trim((string)($db['name'] ?? '')),
            'user' => trim((string)($db['user'] ?? '')),
            'pass' => (string)($db['pass'] ?? ''),
            'charset' => trim((string)($db['charset'] ?? 'utf8mb4')),
          ];
        }
        $saveErr = '';
        if (!ua_install_link_save_local($localPatch, $saveErr)) {
          $err = $saveErr;
        } else {
          $msg = (string)($res['message'] ?? 'تم تحديث حالة الربط.');
          $link = ua_install_link_config();
          if ($status === 'approved') {
            $msg = 'تم اعتماد الربط وحفظ إعداد الاتصال بقاعدة النسخة الرئيسية. يمكنك تسجيل الدخول الآن.';
          }
        }
      }
    }
  }
}

$statusLabels = [
  'unlinked' => 'غير مربوط',
  'pending' => 'بانتظار موافقة المدير',
  'approved' => 'معتمد',
  'rejected' => 'مرفوض',
  'blocked' => 'محظور',
  'error' => 'خطأ اتصال',
];
$statusClass = $status === 'approved' ? 'ok' : ($status === 'pending' ? 'wait' : 'bad');
$programLogo = function_exists('ua_media_url') ? ua_media_url('sidebar_program_logo', 'assets/img/sidebar_program_logo.png') : 'assets/img/sidebar_program_logo.png';
?>
<!doctype html>
<html lang="ar" dir="rtl">
<head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <title>الربط الشبكي</title>
  <?= function_exists('ua_asset_tag_css') ? ua_asset_tag_css('bootstrap_462_css') : '' ?>
  <style>
    *{box-sizing:border-box}
    body{margin:0;min-height:100vh;font-family:Tahoma,Arial,sans-serif;background:#eef8fb;color:#083a53;display:grid;place-items:center;padding:18px}
    .ua-link-window{width:min(940px,100%);min-height:560px;background:#f8fcfe;border:1px solid rgba(14,83,108,.16);box-shadow:0 26px 80px rgba(3,10,20,.25);display:grid;grid-template-columns:42% 58%;overflow:hidden}
    .ua-link-side{background:linear-gradient(145deg,#dff2f7,#bfe2ef);display:flex;align-items:center;justify-content:center;padding:32px;position:relative}
    .ua-link-side img{width:92px;height:92px;object-fit:contain;background:#fff;border-radius:18px;padding:14px;box-shadow:0 18px 40px rgba(3,42,65,.16)}
    .ua-link-main{padding:42px 46px;display:flex;flex-direction:column;justify-content:center}
    .ua-link-kicker{font-size:13px;font-weight:900;color:#0f7fd8;margin-bottom:8px}
    h1{font-size:30px;line-height:1.25;margin:0 0 10px;font-weight:900}
    .ua-link-copy{color:#60758a;font-size:14px;line-height:1.8;margin:0 0 20px}
    .ua-status{display:inline-flex;align-items:center;gap:8px;width:max-content;max-width:100%;padding:7px 11px;border-radius:999px;font-size:13px;font-weight:900;margin-bottom:18px}
    .ua-status.ok{background:#dcfce7;color:#166534}.ua-status.wait{background:#fef3c7;color:#92400e}.ua-status.bad{background:#fee2e2;color:#991b1b}
    .ua-alert{padding:10px 12px;border-radius:10px;margin-bottom:12px;font-size:13px;line-height:1.7}
    .ua-alert.ok{background:#ecfdf5;color:#166534;border:1px solid #bbf7d0}.ua-alert.bad{background:#fff1f2;color:#991b1b;border:1px solid #fecaca}
    label{display:block;font-weight:900;font-size:13px;margin:0 0 7px;color:#243244}
    input{width:100%;height:42px;border:1px solid #dbe5ee;border-radius:10px;background:#fff;color:#0f172a;padding:0 12px;font-size:14px;outline:0}
    input:focus{border-color:#0f7fd8;box-shadow:0 0 0 3px rgba(15,127,216,.12)}
    .ua-field{margin-bottom:14px}
    .ua-mode-grid{display:grid;grid-template-columns:1fr 1fr;gap:10px;margin-bottom:16px}.ua-mode-option{display:flex;align-items:center;gap:9px;padding:12px;border:1px solid #dbe5ee;border-radius:10px;background:#fff;cursor:pointer}.ua-mode-option:has(input:checked){border-color:#0f7fd8;background:#eff8ff;box-shadow:0 0 0 2px rgba(15,127,216,.10)}.ua-mode-option input{width:18px;height:18px;box-shadow:none}.ua-mode-option span{font-weight:900;font-size:13px}
    .ua-actions{display:flex;gap:10px;flex-wrap:wrap;margin-top:6px}
    .ua-btn{height:42px;border:0;border-radius:10px;padding:0 18px;font-weight:900;cursor:pointer;text-decoration:none;display:inline-flex;align-items:center;justify-content:center}
    .ua-btn.primary{background:linear-gradient(180deg,#0f7fd8,#0967b3);color:#fff}.ua-btn.secondary{background:#e7eef5;color:#143247}.ua-btn.success{background:#16a34a;color:#fff}
    .ua-note{margin-top:16px;color:#64748b;font-size:12px;line-height:1.8}
    @media(max-width:780px){body{padding:10px}.ua-link-window{grid-template-columns:1fr;min-height:0}.ua-link-side{display:none}.ua-link-main{padding:26px 18px}.ua-actions{flex-direction:column}.ua-btn{width:100%}}
  </style>
</head>
<body>
  <main class="ua-link-window" role="main">
    <aside class="ua-link-side" aria-hidden="true">
      <img src="<?= h($programLogo) ?>" alt="">
    </aside>
    <section class="ua-link-main">
      <div class="ua-link-kicker"><?= h(ua_link_install_type_label($installType)) ?></div>
      <h1>الربط الشبكي</h1>
      <p class="ua-link-copy">أدخل عنوان النسخة الرئيسية، ثم أرسل طلب الربط. بعد موافقة المدير من النسخة الرئيسية سيتم حفظ اتصال قاعدة البيانات ومتابعة تشغيل البرنامج.</p>
      <div class="ua-status <?= h($statusClass) ?>"><?= h($statusLabels[$status] ?? $status) ?></div>

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

      <form method="post">
        <?php if (function_exists('ua_csrf_field')) ua_csrf_field(); ?>
        <label>طريقة الاتصال</label>
        <div class="ua-mode-grid">
          <label class="ua-mode-option"><input type="radio" name="connection_mode" value="local" <?= $connectionMode === 'local' ? 'checked' : '' ?>><span>شبكة محلية</span></label>
          <label class="ua-mode-option"><input type="radio" name="connection_mode" value="internet" <?= $connectionMode === 'internet' ? 'checked' : '' ?>><span>عبر الإنترنت (HTTPS)</span></label>
        </div>
        <div class="ua-field">
          <label>اسم هذه النسخة</label>
          <input name="instance_name" value="<?= h($instanceName) ?>" autocomplete="off">
        </div>
        <div class="ua-field">
          <label>رابط النسخة الرئيسية</label>
          <input name="server_url" value="<?= h($serverUrl) ?>" placeholder="http://SERVER-IP:PORT/mikrotik/admin" dir="ltr" autocomplete="off">
        </div>
        <div class="ua-actions">
          <button class="ua-btn primary" name="action" value="register" type="submit">إرسال طلب الربط</button>
          <button class="ua-btn secondary" name="action" value="check" type="submit">فحص الموافقة</button>
          <?php if ($status === 'approved'): ?>
            <a class="ua-btn success" href="<?= h($connectionMode === 'internet' ? ua_link_admin_url($serverUrl) . '/index.php?login=1' : 'index.php') ?>">متابعة تسجيل الدخول</a>
          <?php endif; ?>
        </div>
      </form>
      <div class="ua-note">رقم النسخة: <?= h($instanceId) ?>. الموافقة تتم فقط من صفحة إدارة الربط في النسخة الرئيسية.</div>
    </section>
  </main>
</body>
</html>
