<?php
declare(strict_types=1);

/**
 * pdf.php – Safari & iOS optimized PDF streaming
 */

// Disable ALL buffering and compression
@ini_set('zlib.output_compression', '0');
@ini_set('output_buffering', '0');
@ini_set('implicit_flush', '1');

if (function_exists('apache_setenv')) { 
    @apache_setenv('no-gzip', '1'); 
}

while (@ob_get_level()) { 
    @ob_end_clean(); 
}

$config = require __DIR__ . '/config.php';
$uploadsDir = $config['uploads_dir'] ?? (__DIR__ . '/uploads');

$rel = isset($_GET['f']) ? (string)$_GET['f'] : '';
if ($rel === '') {
    http_response_code(400);
    die('Missing parameter f');
}

if (!preg_match('/\.pdf$/i', $rel)) {
    http_response_code(400);
    die('Only .pdf files are allowed');
}

$uploadsReal = realpath($uploadsDir);
if ($uploadsReal === false) {
    http_response_code(500);
    die('Uploads dir not found');
}

// Resolve file path
$try1 = realpath($uploadsReal . DIRECTORY_SEPARATOR . ltrim($rel, '/'));
$try2 = realpath(__DIR__ . DIRECTORY_SEPARATOR . ltrim($rel, '/'));
$path = $try1 ?: $try2;

if ($path === false || !file_exists($path)) {
    http_response_code(404);
    die('File not found: ' . htmlspecialchars($rel));
}

// Security check
if (strpos($path, $uploadsReal) !== 0) {
    http_response_code(403);
    die('Forbidden');
}

$size = filesize($path);
if ($size === false || $size === 0) {
    http_response_code(500);
    die('Invalid file size');
}

$filename = basename($path);
$start = 0;
$end = $size - 1;
$isPartial = false;

// Handle Range requests (critical for Safari)
if (isset($_SERVER['HTTP_RANGE'])) {
    if (preg_match('/bytes=(\d*)-(\d*)/i', $_SERVER['HTTP_RANGE'], $m)) {
        $isPartial = true;
        if ($m[1] !== '') { $start = (int)$m[1]; }
        if ($m[2] !== '') { $end = min((int)$m[2], $size - 1); }
        
        if ($start > $end || $start >= $size) {
            http_response_code(416);
            header('Content-Range: bytes */' . $size);
            die();
        }
    }
}

$length = $end - $start + 1;

// CRITICAL: Safari-specific headers (order matters!)
if ($isPartial) {
    http_response_code(206);
    header('Content-Range: bytes ' . $start . '-' . $end . '/' . $size);
} else {
    http_response_code(200);
}

header('Content-Type: application/pdf');
header('Content-Length: ' . $length);
header('Accept-Ranges: bytes');

// Set the filename to "كشف الحساب-1.pdf" for all downloads
$customFilename = 'كشف الحساب-1.pdf';
// Safari requires inline without quotes - but we'll encode the Arabic filename properly
header('Content-Disposition: inline; filename="' . rawurlencode($customFilename) . '"; filename*=UTF-8\'\'' . rawurlencode($customFilename));

// Allow embedding in same origin (critical for Safari)
header('X-Frame-Options: SAMEORIGIN');

// Safari-friendly cache
header('Cache-Control: public, max-age=31536000, immutable');
header('Pragma: public');

// Remove problematic headers
if (function_exists('header_remove')) {
    @header_remove('X-Powered-By');
    @header_remove('Expires');
    @header_remove('Set-Cookie');
}

// Stream file
$fp = @fopen($path, 'rb');
if (!$fp) {
    http_response_code(500);
    die('Failed to open file');
}

if ($start > 0) {
    fseek($fp, $start);
}

// Safari works best with larger chunks
$chunkSize = 16384; // 16KB
$bytesRemaining = $length;

while (!feof($fp) && $bytesRemaining > 0 && connection_status() === CONNECTION_NORMAL) {
    $readSize = min($chunkSize, $bytesRemaining);
    $buffer = fread($fp, $readSize);
    
    if ($buffer === false) {
        break;
    }
    
    echo $buffer;
    
    if (@ob_get_length()) {
        @ob_flush();
    }
    flush();
    
    $bytesRemaining -= strlen($buffer);
}

fclose($fp);
exit;