<?php
define('INDEX_AUTH', 1);

require 'sysconfig.inc.php';
require LIB . 'ip_based_access.inc.php';

do_checkIP('opac');
do_checkIP('opac-member');

require LIB . 'member_session.inc.php';

use SLiMS\DB;

if (empty($_SESSION['mid'])) {
    header('Location: index.php?p=member');
    exit;
}

$id = (int)($_GET['id'] ?? 0);

$db = DB::getInstance();

$sql = $db->prepare("
    SELECT surat_no, file_path
    FROM bebas_pustaka_history
    WHERE id = ?
      AND member_id = ?
      AND status = 'printed'
");

$sql->execute([$id, $_SESSION['mid']]);

$data = $sql->fetch(PDO::FETCH_ASSOC);

if (!$data) {
    http_response_code(404);
    exit('Data tidak ditemukan');
}

$file = trim($data['file_path']);

if (!is_file($file)) {
    http_response_code(404);
    exit('File tidak ditemukan');
}

/* bersihkan semua output */
while (ob_get_level() > 0) {
    ob_end_clean();
}

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

@ini_set('zlib.output_compression', 'Off');

header('Content-Description: File Transfer');
header('Content-Type: application/pdf');
header('Content-Disposition: attachment; filename="' . basename($file) . '"');
header('Content-Transfer-Encoding: binary');
header('Expires: 0');
header('Cache-Control: must-revalidate');
header('Pragma: public');
header('Content-Length: ' . filesize($file));

flush();

$fp = fopen($file, 'rb');
fpassthru($fp);
fclose($fp);

exit;