<?php

ini_set("display_errors", "1");
ini_set("display_startup_errors", "1");
error_reporting(E_ALL);

require_once("include/dbcommon.php");

/*
|--------------------------------------------------------------------------
| LOGIN CHECK
|--------------------------------------------------------------------------
*/

if (function_exists("isLogged")) {
    if (!isLogged()) {
        HeaderRedirect("login");
        exit();
    }
}

/*
|--------------------------------------------------------------------------
| GET STF ID
|--------------------------------------------------------------------------
*/

$transferFormId = isset($_GET["id"])
    ? (int)$_GET["id"]
    : 0;

if ($transferFormId <= 0) {
    http_response_code(400);
    die("Invalid Stock Transfer Form ID.");
}

/*
|--------------------------------------------------------------------------
| LOAD SIGNED PDF DETAILS
|--------------------------------------------------------------------------
*/

$sql = "
    SELECT
        transfer_form_id,
        transfer_form_no,
        digital_signature_status,
        signed_pdf_path
    FROM stock_transfer_form
    WHERE transfer_form_id = " . $transferFormId . "
    LIMIT 1
";

$rs = DB::Query($sql);

$data = $rs
    ? $rs->fetchAssoc()
    : false;

if (!$data) {
    http_response_code(404);
    die("Stock Transfer Form was not found.");
}

if ($data["digital_signature_status"] !== "SIGNED") {
    http_response_code(403);
    die("This Stock Transfer Form is not yet digitally signed.");
}

if (empty($data["signed_pdf_path"])) {
    http_response_code(404);
    die("Signed PDF path is missing.");
}

/*
|--------------------------------------------------------------------------
| RESOLVE AND VALIDATE PDF PATH
|--------------------------------------------------------------------------
*/

$baseDirectory = realpath(
    __DIR__ . "/files/pnpki_signed/stf"
);

if ($baseDirectory === false) {
    http_response_code(500);
    die("Signed PDF directory was not found.");
}

/*
 * Use only the filename stored in signed_pdf_path.
 * This prevents directory traversal.
 */
$pdfFilename = basename(
    $data["signed_pdf_path"]
);

$pdfPath = realpath(
    $baseDirectory
    . DIRECTORY_SEPARATOR
    . $pdfFilename
);

if ($pdfPath === false || !is_file($pdfPath)) {
    http_response_code(404);
    die("Signed PDF file was not found.");
}

/*
 * Confirm that the resolved file remains inside
 * the approved signed-PDF directory.
 */
$allowedPrefix =
    $baseDirectory
    . DIRECTORY_SEPARATOR;

if (strpos($pdfPath, $allowedPrefix) !== 0) {
    http_response_code(403);
    die("Invalid signed PDF path.");
}

if (!is_readable($pdfPath)) {
    http_response_code(403);
    die("The signed PDF is not readable.");
}

$fileSize = filesize($pdfPath);

if ($fileSize === false || $fileSize < 1000) {
    http_response_code(500);
    die("The signed PDF is empty or invalid.");
}

/*
|--------------------------------------------------------------------------
| SEND PDF TO BROWSER
|--------------------------------------------------------------------------
*/

$safeDocumentNo = preg_replace(
    '/[^A-Za-z0-9_\-]/',
    "_",
    $data["transfer_form_no"]
);

$downloadFilename =
    $safeDocumentNo
    . "_SIGNED.pdf";

while (ob_get_level() > 0) {
    ob_end_clean();
}

header("Content-Type: application/pdf");

header(
    'Content-Disposition: inline; filename="'
    . $downloadFilename
    . '"'
);

header(
    "Content-Length: "
    . $fileSize
);

header("X-Content-Type-Options: nosniff");
header("Cache-Control: no-store, no-cache, must-revalidate");
header("Pragma: no-cache");
header("Expires: 0");

readfile($pdfPath);
exit();