<?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);
$instanceId = (string)($_POST['instance_id'] ?? $_GET['instance_id'] ?? '');
$secret = trim((string)($_POST['secret'] ?? $_GET['secret'] ?? ''));
$releaseKey = preg_replace('/[^A-Za-z0-9._-]/', '', (string)($_POST['release_id'] ?? $_GET['release_id'] ?? '')) ?? '';
$remote = (string)($_SERVER['REMOTE_ADDR'] ?? '');
if (!ua_link_rate_limit($conn, 'update-download', $instanceId . '|' . $remote, 12, 60)) api_json_out(['ok' => false, 'message' => 'Too many downloads.'], 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 required.'], 426);
    }
    $release = ua_update_release_by_key($conn, $releaseKey);
    if (!$release) api_json_out(['ok' => false, 'message' => 'Release not found.'], 404);
    $roles = json_decode((string)$release['roles_json'], true);
    if (!is_array($roles) || !in_array((string)$request['install_type'], $roles, true)) api_json_out(['ok' => false, 'message' => 'Release is not allowed for this client.'], 403);
    $path = (string)$release['package_path'];
    if (!is_file($path) || !hash_equals((string)$release['package_sha256'], (string)hash_file('sha256', $path))) api_json_out(['ok' => false, 'message' => 'Stored release is invalid.'], 500);
    $releaseId = (int)$release['id'];
    $requestId = (int)$request['id'];
    @$conn->query("UPDATE ua_update_deployments SET status='downloading', downloaded_at=NOW() WHERE release_id=$releaseId AND request_id=$requestId");
    $size = filesize($path);
    header('Content-Type: application/zip');
    header('Content-Disposition: attachment; filename="networkcustomers-update-' . rawurlencode((string)$release['version']) . '.zip"');
    header('Content-Length: ' . (string)$size);
    header('Cache-Control: no-store, private');
    header('X-Content-Type-Options: nosniff');
    readfile($path);
    exit;
} catch (RuntimeException $e) {
    $code = in_array($e->getCode(), [400, 403], true) ? $e->getCode() : 500;
    api_json_out(['ok' => false, 'message' => $e->getMessage()], $code);
}
