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

$conn = api_ensure_db(true);
if (!($conn instanceof mysqli)) api_json_out(['ok' => false, 'message' => 'قاعدة البيانات غير جاهزة.'], 500);
ua_update_ensure_schema($conn);
ua_update_import_inbox($conn);
$data = json_decode((string)file_get_contents('php://input'), true);
if (!is_array($data)) $data = $_POST;
$instanceId = (string)($data['instance_id'] ?? '');
$secret = trim((string)($data['secret'] ?? ''));
$currentVersion = trim((string)($data['current_version'] ?? ''));
$remote = (string)($_SERVER['REMOTE_ADDR'] ?? '');
if (!ua_link_rate_limit($conn, 'update-status', $instanceId . '|' . $remote, 30, 60)) api_json_out(['ok' => false, 'message' => 'طلبات تحديث كثيرة.'], 429);
try {
    $request = ua_update_authenticate_request($conn, $instanceId, $secret);
    if ((string)($request['connection_mode'] ?? 'local') === 'internet' && !ua_update_request_is_https()) {
        api_json_out(['ok' => false, 'message' => 'التحديث عبر الإنترنت يتطلب HTTPS.'], 426);
    }
    $offer = ua_update_find_offer($conn, $request, $currentVersion);
    api_json_out(['ok' => true, 'update_available' => $offer !== null, 'offer' => $offer]);
} catch (RuntimeException $e) {
    $code = in_array($e->getCode(), [400, 403], true) ? $e->getCode() : 500;
    api_json_out(['ok' => false, 'message' => $e->getMessage()], $code);
}
