<?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' => 'Database unavailable.'], 500);
ua_update_ensure_schema($conn);
$data = json_decode((string)file_get_contents('php://input'), true);
if (!is_array($data)) $data = $_POST;
try {
    $request = ua_update_authenticate_request($conn, (string)($data['instance_id'] ?? ''), trim((string)($data['secret'] ?? '')));
    if ((string)($request['connection_mode'] ?? 'local') === 'internet' && !ua_update_request_is_https()) {
        api_json_out(['ok' => false, 'message' => 'HTTPS required.'], 426);
    }
    $release = ua_update_release_by_key($conn, preg_replace('/[^A-Za-z0-9._-]/', '', (string)($data['release_id'] ?? '')) ?? '');
    if (!$release) api_json_out(['ok' => false, 'message' => 'Release not found.'], 404);
    $status = strtolower(trim((string)($data['status'] ?? '')));
    if (!in_array($status, ['deferred', 'installed', 'failed'], true)) api_json_out(['ok' => false, 'message' => 'Invalid status.'], 400);
    $error = substr(trim((string)($data['error'] ?? '')), 0, 2000);
    $releaseId = (int)$release['id'];
    $requestId = (int)$request['id'];
    $installedAt = $status === 'installed' ? date('Y-m-d H:i:s') : null;
    $deferUntil = $status === 'deferred' ? date('Y-m-d H:i:s', time() + 3600) : null;
    $stmt = $conn->prepare("INSERT INTO ua_update_deployments
      (release_id,request_id,status,current_version,target_version,error_message,defer_until,installed_at,offered_at)
      VALUES (?,?,?,?,?,?,?,?,NOW())
      ON DUPLICATE KEY UPDATE status=VALUES(status), error_message=VALUES(error_message),
        defer_until=VALUES(defer_until), installed_at=VALUES(installed_at)");
    $currentVersion = trim((string)($data['current_version'] ?? ''));
    $targetVersion = (string)$release['version'];
    $stmt->bind_param('iissssss', $releaseId, $requestId, $status, $currentVersion, $targetVersion, $error, $deferUntil, $installedAt);
    $stmt->execute();
    $stmt->close();
    api_json_out(['ok' => true]);
} catch (RuntimeException $e) {
    $code = in_array($e->getCode(), [400, 403], true) ? $e->getCode() : 500;
    api_json_out(['ok' => false, 'message' => $e->getMessage()], $code);
}
