<?php

declare(strict_types=1);

require DENTAL_ROOT . '/app/bootstrap.php';
require_once DENTAL_ROOT . '/app/transaction_integrity.php';

$id = (int) ($_GET['id'] ?? 0);
$staff = current_user();
$portal = patient_portal_user();
$preview = isset($_GET['preview']);

if (!$staff && !$portal) {
    header('Location: login.php');
    exit;
}

require_documentation_schema();
$stmt = db()->prepare(
    'SELECT d.*,p.branch_id patient_branch_id FROM `' . table('documents') . '` d '
    . 'JOIN `' . table('patients') . '` p ON p.id=d.patient_id WHERE d.id=? LIMIT 1'
);
$stmt->execute([$id]);
$document = $stmt->fetch();
if (!$document) {
    http_response_code(404);
    exit('Document not found.');
}

if ($portal) {
    $allowed = (int) $portal['patient_id'] === (int) $document['patient_id']
        && (string) $document['access_level'] === 'patient';
    if (!$allowed) {
        audit('clinical_document_access_denied','document',$id,[
            'viewer_type'=>'patient_portal',
            'patient_id'=>(int)($portal['patient_id']??0),
            'preview'=>$preview,
            'reason'=>'Patient or access-level mismatch',
        ]);
        http_response_code(403);
        exit('Access denied.');
    }
} else {
    $decision = integrity_document_staff_decision($document);
    if (!$decision['allowed']) {
        audit('clinical_document_access_denied','document',$id,[
            'viewer_type'=>'staff',
            'active_role'=>active_role(),
            'patient_id'=>(int)$document['patient_id'],
            'branch_id'=>(int)($document['branch_id']??0),
            'category'=>(string)$document['category'],
            'access_level'=>(string)$document['access_level'],
            'preview'=>$preview,
            'reason'=>$decision['reason'],
        ]);
        http_response_code(403);
        exit('Access denied.');
    }
}

$path = private_document_directory() . '/' . basename((string) $document['stored_name']);
if (!is_file($path)) {
    http_response_code(404);
    exit('Stored file is missing.');
}

audit($preview ? 'clinical_document_previewed' : 'clinical_document_opened','document',$id,[
    'viewer_type'=>$portal ? 'patient_portal' : 'staff',
    'active_role'=>$staff ? active_role() : null,
    'patient_id'=>(int)$document['patient_id'],
    'branch_id'=>(int)($document['branch_id']??0),
    'category'=>(string)$document['category'],
    'access_level'=>(string)$document['access_level'],
]);

header('X-Content-Type-Options: nosniff');
header('Content-Security-Policy: default-src \'none\'; sandbox');
header('Cache-Control: private, max-age=' . ($preview ? '300' : '0') . ', must-revalidate');
header('Content-Type: ' . $document['mime_type']);
header('Content-Disposition: inline; filename="' . str_replace('"','',basename((string)$document['file_name'])) . '"');
header('Content-Length: ' . filesize($path));
readfile($path);
