<?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' => 'قاعدة البيانات غير جاهزة.'], 500);
ua_link_ensure_schema($conn);

$raw = file_get_contents('php://input');
$data = json_decode((string)$raw, true);
if (!is_array($data)) $data = $_POST;

$instanceId = preg_replace('/[^a-zA-Z0-9_\-]/', '', (string)($data['instance_id'] ?? ''));
$secret = trim((string)($data['secret'] ?? ''));
$deviceId = preg_replace('/[^a-zA-Z0-9_\-]/', '', (string)($data['device_id'] ?? ''));
$deviceSecret = trim((string)($data['device_secret'] ?? ''));
$installType = strtolower(trim((string)($data['install_type'] ?? '')));
$instanceName = trim((string)($data['instance_name'] ?? ''));
$serverUrl = ua_link_normalize_url((string)($data['server_url'] ?? ''));
$reportedUrl = ua_link_normalize_url((string)($data['reported_url'] ?? ''));
$clientPlatform = strtolower(trim((string)($data['client_platform'] ?? '')));
$connectionMode = ua_link_connection_mode((string)($data['connection_mode'] ?? 'local'));
$remoteAddr = trim((string)($_SERVER['REMOTE_ADDR'] ?? ''));

if (!ua_link_rate_limit($conn, 'register', $remoteAddr !== '' ? $remoteAddr : 'unknown', 20, 60)) {
  api_json_out(['ok' => false, 'message' => 'طلبات ربط كثيرة. حاول مجدداً بعد دقيقة.'], 429);
}

if ($instanceId === '' || strlen($instanceId) < 12 || $secret === '') {
  api_json_out(['ok' => false, 'message' => 'بيانات طلب الربط ناقصة.'], 400);
}
if (($deviceId !== '' || $deviceSecret !== '') && (strlen($deviceId) < 32 || strlen($deviceSecret) < 32)) {
  api_json_out(['ok' => false, 'message' => 'هوية الجهاز الدائمة غير مكتملة.'], 400);
}
if (!in_array($installType, ['branch', 'agent'], true)) {
  api_json_out(['ok' => false, 'message' => 'نوع النسخة غير مسموح للربط.'], 400);
}
if ($serverUrl === '') {
  $serverUrl = ua_link_current_public_url();
}
if ($instanceName === '') {
  $instanceName = ua_link_install_type_label($installType) . ' - ' . substr($instanceId, 0, 8);
}

$secretHash = ua_link_secret_hash($secret);
$hasDeviceIdentity = strlen($deviceId) >= 32 && strlen($deviceSecret) >= 32;
$deviceIdHash = $hasDeviceIdentity ? ua_link_secret_hash($deviceId) : null;
$deviceSecretHash = $hasDeviceIdentity ? ua_link_secret_hash($deviceSecret) : null;
$endpoint = ua_link_match_endpoint($conn, $serverUrl, $installType, $connectionMode);
$serverScheme = strtolower((string)(parse_url($serverUrl, PHP_URL_SCHEME) ?: ''));
if ($connectionMode === 'internet' && $serverScheme !== 'https') {
  api_json_out(['ok' => false, 'message' => 'الاتصال عبر الإنترنت يتطلب رابط HTTPS.'], 400);
}
if ($connectionMode === 'internet' && !$endpoint) {
  api_json_out(['ok' => false, 'message' => 'الرابط الخارجي غير مسجل أو غير مفعل في النسخة الرئيسية.'], 403);
}
$endpointId = $endpoint ? (int)$endpoint['id'] : 0;
$metadata = [
  'version' => (string)($data['version'] ?? ''),
  'build' => (string)($data['build'] ?? ''),
  'client_platform' => $clientPlatform,
  'device_model' => substr(trim((string)($data['device_model'] ?? '')), 0, 160),
  'user_agent' => (string)($_SERVER['HTTP_USER_AGENT'] ?? ''),
  'matched_endpoint' => $endpoint ? (string)($endpoint['label'] ?? '') : '',
  'connection_mode' => $connectionMode,
];
$metadataJson = json_encode($metadata, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES);
if (!is_string($metadataJson)) $metadataJson = '{}';

$idEsc = $conn->real_escape_string($instanceId);
$rs = @$conn->query("SELECT * FROM ua_link_requests WHERE instance_id='$idEsc' LIMIT 1");
$existing = ($rs && $rs->num_rows) ? $rs->fetch_assoc() : null;
$matchedByDevice = false;

// A reinstall receives a new request identity, but keeps this device identity
// outside the application directory. Match both hashes: an address or device
// name alone must never be enough to inherit an approval.
if (!$existing && $hasDeviceIdentity) {
  $stmt = @$conn->prepare("SELECT * FROM ua_link_requests
    WHERE device_id_hash=? AND device_secret_hash=? AND install_type=?
    ORDER BY id ASC LIMIT 1");
  if ($stmt) {
    $stmt->bind_param('sss', $deviceIdHash, $deviceSecretHash, $installType);
    $stmt->execute();
    $deviceResult = $stmt->get_result();
    $existing = ($deviceResult && $deviceResult->num_rows) ? $deviceResult->fetch_assoc() : null;
    $stmt->close();
    $matchedByDevice = is_array($existing);
  }
}

if ($existing) {
  $sameDeviceIdentity = $hasDeviceIdentity
    && hash_equals((string)($existing['device_id_hash'] ?? ''), (string)$deviceIdHash)
    && hash_equals((string)($existing['device_secret_hash'] ?? ''), (string)$deviceSecretHash);
  if (!hash_equals((string)($existing['request_secret_hash'] ?? ''), $secretHash) && !$sameDeviceIdentity) {
    api_json_out(['ok' => false, 'message' => 'سر طلب الربط لا يطابق الطلب المسجل.'], 403);
  }
  $existingType = strtolower(trim((string)($existing['install_type'] ?? '')));
  if ($existingType !== '' && $existingType !== $installType) {
    api_json_out([
      'ok' => false,
      'message' => 'لا يمكن تغيير نوع نسخة جهاز مسجل. ألغِ الربط من التطبيق وأرسل طلب اعتماد جديد.',
    ], 409);
  }
  $status = (string)($existing['status'] ?? 'pending');
  if (!in_array($status, ['approved', 'blocked'], true)) $status = 'pending';
  $existingId = (int)($existing['id'] ?? 0);
  $rememberedDevice = $matchedByDevice && $status === 'approved';
  $stmt = @$conn->prepare("UPDATE ua_link_requests
    SET instance_id=?, instance_name=?, install_type=?, connection_mode=?, server_url=?, reported_url=?, endpoint_id=?,
        request_secret_hash=?, device_id_hash=COALESCE(device_id_hash, ?), device_secret_hash=COALESCE(device_secret_hash, ?),
        remote_addr=?, metadata_json=?, status=?, last_seen_at=NOW(), updated_at=NOW()
    WHERE id=?");
  if ($stmt) {
    $endpointParam = $endpointId > 0 ? $endpointId : null;
    $stmt->bind_param('ssssssissssssi', $instanceId, $instanceName, $installType, $connectionMode, $serverUrl, $reportedUrl, $endpointParam, $secretHash, $deviceIdHash, $deviceSecretHash, $remoteAddr, $metadataJson, $status, $existingId);
    $stmt->execute();
    $stmt->close();
  }
} else {
  $status = 'pending';
  $rememberedDevice = false;
  $stmt = @$conn->prepare("INSERT INTO ua_link_requests
    (instance_id, instance_name, install_type, connection_mode, server_url, reported_url, endpoint_id, request_secret_hash, device_id_hash, device_secret_hash, status, remote_addr, metadata_json, last_seen_at)
    VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?,NOW())");
  if (!$stmt) api_json_out(['ok' => false, 'message' => 'تعذر إنشاء طلب الربط.'], 500);
  $endpointParam = $endpointId > 0 ? $endpointId : null;
  $stmt->bind_param('ssssssissssss', $instanceId, $instanceName, $installType, $connectionMode, $serverUrl, $reportedUrl, $endpointParam, $secretHash, $deviceIdHash, $deviceSecretHash, $status, $remoteAddr, $metadataJson);
  $stmt->execute();
  $stmt->close();
}

$rs = @$conn->query("SELECT * FROM ua_link_requests WHERE instance_id='$idEsc' LIMIT 1");
$row = ($rs && $rs->num_rows) ? $rs->fetch_assoc() : ['status' => 'pending'];
$response = $clientPlatform === 'android'
  ? ua_link_mobile_request_payload($row)
  : ua_link_request_payload($row, true, $conn);
$response['remembered_device'] = $rememberedDevice;
if ($rememberedDevice) {
  $response['message'] = 'تم التعرف على هذا الجهاز والموافقة على الربط تلقائياً.';
}
api_json_out($response);
