<?php

declare(strict_types=1);

require DENTAL_ROOT . '/app/bootstrap.php';
require_once DENTAL_ROOT . '/app/doctor_photo.php';
$type = (string) ($_GET['type'] ?? '');
$pdo = db();
$path = null;
$name = 'file';
$mime = 'application/octet-stream';
$dentistUserId = 0;
$publicAllowed = false;

if ($type === 'document') {
    require_login();
    require_doctor_workflow_schema();
    $id = (int) ($_GET['id'] ?? 0);
    $stmt = $pdo->prepare('SELECT * FROM `' . table('dentist_documents') . '` WHERE id=?');
    $stmt->execute([$id]);
    $row = $stmt->fetch();
    if ($row) {
        $dentistUserId = (int) $row['dentist_user_id'];
        $path = $row['file_path'];
        $name = $row['original_name'];
        $mime = $row['mime_type'] ?: $mime;
    }
} elseif (in_array($type, ['photo','signature','prescription_signature'], true)) {
    $dentistUserId = (int) ($_GET['user_id'] ?? 0);
    $profile = dentist_profile($dentistUserId);
    if ($profile) {
        $variant = $type === 'photo' ? strtolower(trim((string)($_GET['variant'] ?? 'square'))) : '';
        if ($type === 'photo') {
            if (!in_array($variant, ['original','square','portrait','thumbnail','legacy'], true)) $variant = 'square';
            $path = doctor_photo_profile_path($profile, $variant);
        } else {
            $column = $type === 'signature' ? 'signature_path' : 'prescription_signature_path';
            $path = $profile[$column] ?? null;
        }
        $extension = strtolower(pathinfo((string) $path, PATHINFO_EXTENSION));
        $name = $type . ($variant !== '' ? '_' . $variant : '') . ($extension !== '' ? '.' . $extension : '');
        $mime = match ($extension) {
            'jpg', 'jpeg' => 'image/jpeg',
            'png' => 'image/png',
            'webp' => 'image/webp',
            default => 'application/octet-stream',
        };
        $publicAllowed = $type === 'photo'
            && $variant !== 'original'
            && !empty($profile['public_profile_enabled'])
            && ($profile['profile_status'] ?? '') === 'active'
            && ($profile['user_status'] ?? '') === 'active';
    }
}

if (!$path) {
    http_response_code(404);
    exit('File not found.');
}

if (!$publicAllowed) {
    require_login();
    if (task_preview_mode() && active_role() === 'dentist' && in_array($type, ['document','signature','prescription_signature'], true)) {
        http_response_code(403);
        exit('Private dentist credentials and signatures are not available in Dentist Task View preview. Return to Administrator or Superuser Task View.');
    }
    $canOpen = can_manage_dentist_profile($dentistUserId);
    if ($type === 'photo') {
        $canOpen = $canOpen || can('clinical.view', ['dentist','dental_assistant']);
    }
    if (!$canOpen) {
        http_response_code(403);
        exit('Access denied.');
    }
}

$privateRoot = realpath(DENTAL_ROOT . '/storage/private');
$candidate = DENTAL_ROOT . '/storage/private/' . ltrim((string) $path, '/');
$full = realpath($candidate);
if ($privateRoot === false || $full === false || !str_starts_with($full, $privateRoot . DIRECTORY_SEPARATOR) || !is_file($full) || !is_readable($full)) {
    http_response_code(404);
    exit('File not found.');
}

header('Content-Type: ' . $mime);
header('Content-Length: ' . filesize($full));
$disposition = $type === 'document' ? 'attachment' : 'inline';
header('Content-Disposition: ' . $disposition . '; filename="' . str_replace(['"', "\r", "\n"], '', (string) $name) . '"');
header('X-Content-Type-Options: nosniff');
header('Cache-Control: ' . ($publicAllowed ? 'public, max-age=3600' : 'private, no-store'));
readfile($full);
