<?php
require_once 'functions.php';
// Brak checkAuth() - plik musi być dostępny publicznie przez ważny token 24H.

$hash = $_GET['h'] ?? '';
if (!preg_match('/^(?:[a-f0-9]{12}|[a-f0-9]{32})$/', $hash)) die('Błędny lub wygasły link.');
$db = getDb();

if (!isset($db['shares'][$hash])) die('Błędny lub wygasły link.');

$share = $db['shares'][$hash];
$expires = (int)($share['expires'] ?? 0);
if (time() > $expires) die('Ten link tymczasowy wygasł (minęły 24h).');

$resolved = resolveAllowedFile($share['folder'] ?? '', $share['path'] ?? '', $share['file'] ?? '');
if ($resolved === false) die('Plik usunięty, przeniesiony lub znajduje się poza dozwolonym folderem.');

$megaPath = $resolved['mega'];
$localPath = $resolved['full'];
$fileName = $resolved['file'];
$fileSize = is_file($localPath) ? (int)@filesize($localPath) : 0;
$action = $_GET['action'] ?? '';

// Zachowanie zgodności z dotychczasowym otwieraniem linku bezpośrednio w VLC.
if ($action === '' && stripos($_SERVER['HTTP_USER_AGENT'] ?? '', 'vlc') !== false) {
    $action = 'view';
}

if ($action === 'view' || $action === 'download' || $action === 'media') {
    if ($action !== 'media') recordDownload($megaPath);

    $encodedFileName = rawurlencode($fileName);
    $safeHeaderFileName = str_replace(["\r", "\n", '"'], ['', '', "'"], $fileName);
    $ext = strtolower(pathinfo($fileName, PATHINFO_EXTENSION));

    $mimeTypes = [
        'jpg' => 'image/jpeg', 'jpeg' => 'image/jpeg', 'png' => 'image/png', 'gif' => 'image/gif', 'webp' => 'image/webp',
        'mp4' => 'video/mp4', 'webm' => 'video/webm', 'mkv' => 'video/x-matroska', 'avi' => 'video/x-msvideo', 'ts' => 'video/mp2t', 'mts' => 'video/mp2t',
        'mp3' => 'audio/mpeg', 'wav' => 'audio/wav', 'ogg' => 'audio/ogg', 'oga' => 'audio/ogg', 'flac' => 'audio/flac', 'm4a' => 'audio/mp4', 'aac' => 'audio/aac',
        'pdf' => 'application/pdf', 'txt' => 'text/plain; charset=utf-8', 'json' => 'application/json; charset=utf-8', 'xml' => 'application/xml; charset=utf-8', 'csv' => 'text/csv; charset=utf-8',
        // HTML, SVG, CSS i JS są pokazywane jako zwykły tekst, aby publiczny link nie wykonywał aktywnej zawartości w domenie panelu.
        'html' => 'text/plain; charset=utf-8', 'htm' => 'text/plain; charset=utf-8', 'svg' => 'text/plain; charset=utf-8', 'css' => 'text/plain; charset=utf-8', 'js' => 'text/plain; charset=utf-8'
    ];
    $mime = $mimeTypes[$ext] ?? 'application/octet-stream';

    header('Content-Type: ' . $mime);
    header('X-Content-Type-Options: nosniff');
    header('Cache-Control: private, no-store, no-cache, must-revalidate, max-age=0');
    header('Pragma: no-cache');

    if ($action === 'download') {
        header('Content-Disposition: attachment; filename="' . $safeHeaderFileName . '"; filename*=UTF-8\'\'' . $encodedFileName);
    } else {
        header('Content-Disposition: inline; filename="' . $safeHeaderFileName . '"; filename*=UTF-8\'\'' . $encodedFileName);
    }

    header('X-Sendfile: ' . $localPath);
    exit;
}

header('Cache-Control: private, no-store, no-cache, must-revalidate, max-age=0');
header('Pragma: no-cache');
header('X-Content-Type-Options: nosniff');
header("Content-Security-Policy: default-src 'none'; style-src 'unsafe-inline'; img-src 'self' data:; base-uri 'none'; form-action 'none'; frame-ancestors 'none'");

$videoExtensions = ['mp4', 'webm', 'mkv', 'avi', 'ts', 'mts'];
$isVideo = in_array(strtolower(pathinfo($fileName, PATHINFO_EXTENSION)), $videoExtensions, true);
$viewUrl = $isVideo
    ? 'play.php?h=' . urlencode($hash)
    : 'share.php?h=' . urlencode($hash) . '&action=view';
$downloadUrl = 'share.php?h=' . urlencode($hash) . '&action=download';
$expiresText = date('d.m.Y H:i', $expires);
?>
<!doctype html>
<html lang="pl">
<head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <title>Udostępniony plik</title>
    <style>
        * { box-sizing: border-box; }
        html, body { min-height: 100%; }
        body { margin: 0; padding: 20px; display: flex; align-items: center; justify-content: center; background: #f4f6f9; color: #333; font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, sans-serif; }
        .share-box { width: 100%; max-width: 560px; background: #fff; border: 1px solid #e0e0e0; border-radius: 14px; padding: 28px; text-align: center; box-shadow: 0 10px 30px rgba(0,0,0,0.10); }
        .share-icon { font-size: 58px; line-height: 1; margin-bottom: 18px; }
        .share-title { margin: 0 0 12px; font-size: 22px; }
        .share-name { margin: 0; overflow-wrap: anywhere; word-break: break-word; font-size: 17px; line-height: 1.4; }
        .share-meta { margin: 16px 0 22px; color: #777; font-size: 14px; line-height: 1.7; }
        .share-actions { display: flex; gap: 12px; justify-content: center; flex-wrap: wrap; }
        .share-btn { min-width: 160px; padding: 13px 20px; border-radius: 8px; color: #fff; text-decoration: none; font-size: 16px; font-weight: 600; }
        .share-view { background: #28a745; }
        .share-download { background: #007bff; }
        .share-btn:hover { opacity: 0.88; }
        .share-note { margin: 22px 0 0; color: #999; font-size: 12px; }
        @media (max-width: 480px) {
            body { padding: 12px; }
            .share-box { padding: 22px 16px; }
            .share-btn { width: 100%; }
        }
    </style>
</head>
<body>
    <main class="share-box">
        <div class="share-icon">&#128196;</div>
        <h1 class="share-title">Udostępniony plik</h1>
        <p class="share-name"><?=htmlspecialchars($fileName, ENT_QUOTES, 'UTF-8')?></p>
        <div class="share-meta">
            Rozmiar: <?=htmlspecialchars(formatSize($fileSize), ENT_QUOTES, 'UTF-8')?><br>
            Link ważny do: <?=htmlspecialchars($expiresText, ENT_QUOTES, 'UTF-8')?>
        </div>
        <div class="share-actions">
            <a class="share-btn share-view" href="<?=htmlspecialchars($viewUrl, ENT_QUOTES, 'UTF-8')?>" target="_blank" rel="noopener">&#128065; Zobacz</a>
            <a class="share-btn share-download" href="<?=htmlspecialchars($downloadUrl, ENT_QUOTES, 'UTF-8')?>">&#11015; Pobierz</a>
        </div>
        <p class="share-note"><?=$isVideo ? 'Film zostanie otwarty w odtwarzaczu Moja Chmura.' : 'Plik zostanie otwarty w przeglądarce, jeżeli jego format jest obsługiwany.'?></p>
    </main>
</body>
</html>
