<?php
require __DIR__ . '/../app/bootstrap.php';
auth_require();
require __DIR__ . '/../app/pages/_common.php';

$id = intval($_GET['id'] ?? 0);
if ($id<=0) { http_response_code(404); die('Not found'); }

$row = db_one("SELECT * FROM attachments WHERE id=?", [$id]);
if (!$row) { http_response_code(404); die('Not found'); }

$ownerType = (string)$row['owner_type'];
$ownerId = intval($row['owner_id']);

$can = false;
if ($ownerType === 'asset') $can = auth_can('view_assets');
if ($ownerType === 'farm')  $can = auth_can('view_farms');

if (!$can) { http_response_code(403); die('Forbidden'); }

$base = realpath(__DIR__ . '/../storage/uploads');
$rel  = (string)$row['stored_name'];
$full = realpath(__DIR__ . '/../storage/uploads/' . $rel);

if (!$base || !$full || strpos($full, $base) !== 0 || !is_file($full)) {
  http_response_code(404);
  die('File missing');
}

$mime = (string)$row['mime'];
$orig = (string)$row['original_name'];

header('Content-Type: ' . $mime);
header('Content-Disposition: attachment; filename="' . rawurlencode($orig) . '"');
header('Content-Length: ' . filesize($full));
readfile($full);
exit;
