<?php
require_once __DIR__ . '/api_common.php';
require_once __DIR__ . '/../db_bootstrap.php';
require_once __DIR__ . '/../install_link_lib.php';

$conn = api_ensure_db(true);
if (!($conn instanceof mysqli)) {
  api_json_out(['ok' => false, 'message' => 'الخادم غير جاهز للربط.'], 503);
}

$raw = file_get_contents('php://input');
$data = json_decode((string)$raw, true);
if (!is_array($data)) $data = $_POST;
$mode = ua_link_connection_mode((string)($data['connection_mode'] ?? 'local'));
$remoteAddr = trim((string)($_SERVER['REMOTE_ADDR'] ?? ''));
if (!ua_link_rate_limit($conn, 'probe', $remoteAddr !== '' ? $remoteAddr : 'unknown', 60, 60)) {
  api_json_out(['ok' => false, 'message' => 'طلبات فحص كثيرة. حاول لاحقاً.'], 429);
}

$isHttps = (!empty($_SERVER['HTTPS']) && strtolower((string)$_SERVER['HTTPS']) !== 'off')
  || strtolower((string)($_SERVER['HTTP_X_FORWARDED_PROTO'] ?? '')) === 'https';
if ($mode === 'internet' && !$isHttps) {
  api_json_out(['ok' => false, 'message' => 'المسار الخارجي يجب أن يعمل عبر HTTPS.'], 400);
}

api_json_out([
  'ok' => true,
  'service' => 'network-customers-link',
  'api_version' => 1,
  'connection_mode' => $mode,
  'https' => $isHttps,
  'server_time' => gmdate('c'),
]);
