<?php

declare(strict_types=1);

require dirname(__DIR__) . '/app/bootstrap.php';
require_login();
require_permission('inventory.manage',['super_admin','clinic_admin','inventory_officer']);
require_once DENTAL_ROOT . '/app/inventory_integrity.php';

$documentId=max(0,(int)($_GET['id']??0));
if($documentId<1){http_response_code(404);exit('Inventory evidence not found.');}
$pdo=db();
$stmt=$pdo->prepare('SELECT id,branch_id,destination_branch_id,evidence_file_path,evidence_original_name FROM `' . table('inventory_documents') . '` WHERE id=? LIMIT 1');
$stmt->execute([$documentId]);$row=$stmt->fetch();
if(!$row||empty($row['evidence_file_path'])){http_response_code(404);exit('Inventory evidence not found.');}
if(!superuser_primary_workspace()){
    $branchId=inventory_user_branch_id();
    if($branchId<=0||($branchId!==(int)$row['branch_id']&&$branchId!==(int)($row['destination_branch_id']??0))){http_response_code(403);exit('Access denied.');}
}
$base=realpath(DENTAL_ROOT.'/storage/private');
$file=realpath(DENTAL_ROOT.'/storage/private/'.ltrim((string)$row['evidence_file_path'],'/'));
if(!$base||!$file||!str_starts_with($file,$base.DIRECTORY_SEPARATOR)||!is_file($file)){http_response_code(404);exit('Inventory evidence file is unavailable.');}
$mime=(new finfo(FILEINFO_MIME_TYPE))->file($file)?:'application/octet-stream';
$name=basename((string)($row['evidence_original_name']?:basename($file)));
audit('inventory_evidence_downloaded','inventory_document',$documentId);
header('Content-Type: '.$mime);
header('Content-Length: '.filesize($file));
header('Content-Disposition: inline; filename="'.str_replace(['"',"\r","\n"],'',$name).'"');
header('X-Content-Type-Options: nosniff');
readfile($file);
