<?php

/*
|--------------------------------------------------------------------------
| WINGS STOCK TRANSFER FORM — PNPKI DIGITAL SIGNING
|--------------------------------------------------------------------------
| PHP 7.4 compatible
|
| Process:
| 1. Load Stock Transfer Form
| 2. Generate the original PDF using BIRT
| 3. Temporarily upload the approver's PNPKI P12/PFX
| 4. Sign the PDF using Python 3.11 and pyHanko
| 5. Delete the temporary certificate immediately
| 6. Update the Stock Transfer Form and audit log
| 7. Redirect directly to the signed PDF
|--------------------------------------------------------------------------
*/

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

require_once("include/dbcommon.php");


/*
|--------------------------------------------------------------------------
| BIRT CONFIGURATION
|--------------------------------------------------------------------------
*/

$BIRT_HOST =
    "https://reporting.8boxsystems.com";

$BIRT_REPORT =
    "SuppyTransferForm_DSWD.rptdesign";

$BIRT_EA =
    "wims_db2";


/*
|--------------------------------------------------------------------------
| PYTHON / PYHANKO CONFIGURATION
|--------------------------------------------------------------------------
*/

$PYTHON_BIN =
    "/home/nboxsy5/pnpki_signer/venv/bin/python";

$PYTHON_SIGNER_SCRIPT =
    "/home/nboxsy5/pnpki_signer/pdf_cli_signing.py";

$PYTHON_WORKING_DIRECTORY =
    "/home/nboxsy5/pnpki_signer";

$PNPKI_TEMP_DIRECTORY =
    "/home/nboxsy5/pnpki_temp";


/*
|--------------------------------------------------------------------------
| VISIBLE SIGNATURE PLACEMENT
|--------------------------------------------------------------------------
| Format:
| left,top,width,height
|
| Adjust these values after checking the first signed PDF.
|--------------------------------------------------------------------------
*/

$SIGNATURE_PAGE = "1";

$SIGNATURE_COORDINATES =
    "60,80,420,120";


/*
|--------------------------------------------------------------------------
| HELPER FUNCTIONS
|--------------------------------------------------------------------------
*/

function h($value)
{
    return htmlspecialchars(
        (string)$value,
        ENT_QUOTES,
        "UTF-8"
    );
}


function sqlq($value)
{
    return db_prepare_string(
        (string)$value
    );
}


function ensureDir($directory)
{
    if (!is_dir($directory)) {
        mkdir(
            $directory,
            0775,
            true
        );
    }
}


function safeDelete($filePath)
{
    if (
        $filePath !== "" &&
        file_exists($filePath)
    ) {
        @unlink($filePath);
    }
}


function looksLikePdf($content)
{
    if (!$content) {
        return false;
    }

    $trimmed = ltrim($content);

    if (substr($trimmed, 0, 4) === "%PDF") {
        return true;
    }

    return strpos(
        substr($content, 0, 1024),
        "%PDF"
    ) !== false;
}


function getCurrentUserId()
{
    if (
        isset($_SESSION["user_id"]) &&
        is_numeric($_SESSION["user_id"])
    ) {
        return (int)$_SESSION["user_id"];
    }

    if (
        isset($_SESSION["platform_user_id"]) &&
        is_numeric($_SESSION["platform_user_id"])
    ) {
        return (int)$_SESSION["platform_user_id"];
    }

    if (
        isset($_SESSION["UserID"]) &&
        is_numeric($_SESSION["UserID"])
    ) {
        return (int)$_SESSION["UserID"];
    }

    return 0;
}


function getCurrentUserName()
{
    if (!empty($_SESSION["display_name"])) {
        return (string)$_SESSION["display_name"];
    }

    if (!empty($_SESSION["user_email"])) {
        return (string)$_SESSION["user_email"];
    }

    if (!empty($_SESSION["UserName"])) {
        return (string)$_SESSION["UserName"];
    }

    if (!empty($_SESSION["UserID"])) {
        return (string)$_SESSION["UserID"];
    }

    return "Approver";
}


/*
|--------------------------------------------------------------------------
| DOWNLOAD BIRT PDF
|--------------------------------------------------------------------------
*/

function downloadBirtPdf(
    $transferFormId,
    $safeNo,
    &$errorMessage,
    &$debugInfo
) {
    global $BIRT_HOST;
    global $BIRT_REPORT;
    global $BIRT_EA;

    $debugInfo = array();

    /*
     * Try /frameset first because this is the working sample URL.
     * Try /run second as fallback.
     */
    $baseUrls = array(
        rtrim($BIRT_HOST, "/") . "/frameset",
        rtrim($BIRT_HOST, "/") . "/run"
    );

    foreach ($baseUrls as $baseUrl) {

        $query = http_build_query(
            array(
                "__report" => $BIRT_REPORT,
                "txnid" => $transferFormId,
                "ea" => $BIRT_EA,
                "__dpi" => "96",
                "__format" => "pdf",
                "__pageoverflow" => "2",
                "__overwrite" => "false"
            )
        );

        $url =
            $baseUrl
            . "?"
            . $query;

        $curl = curl_init();

        curl_setopt_array(
            $curl,
            array(
                CURLOPT_URL => $url,
                CURLOPT_RETURNTRANSFER => true,
                CURLOPT_FOLLOWLOCATION => true,
                CURLOPT_TIMEOUT => 180,

                /*
                 * Testing configuration.
                 * Enable SSL verification once certificates are confirmed.
                 */
                CURLOPT_SSL_VERIFYPEER => false,
                CURLOPT_SSL_VERIFYHOST => false,

                CURLOPT_ENCODING => "",
                CURLOPT_USERAGENT =>
                    "WINGS-PNPKI-Signer/1.0",

                CURLOPT_HTTPHEADER => array(
                    "Accept: application/pdf,*/*"
                )
            )
        );

        $content =
            curl_exec($curl);

        $curlError =
            curl_error($curl);

        $httpCode =
            curl_getinfo(
                $curl,
                CURLINFO_HTTP_CODE
            );

        $contentType =
            curl_getinfo(
                $curl,
                CURLINFO_CONTENT_TYPE
            );

        curl_close($curl);

        $debugInfo[] = array(
            "url" => $url,
            "http_code" => $httpCode,
            "content_type" => $contentType,
            "curl_error" => $curlError,
            "size" =>
                $content
                    ? strlen($content)
                    : 0
        );

        if (
            $httpCode == 200 &&
            $content &&
            looksLikePdf($content)
        ) {
            return $content;
        }

        /*
         * Save an HTML/error response for troubleshooting.
         */
        $debugDirectory =
            __DIR__
            . "/files/birt_debug/stf/";

        ensureDir($debugDirectory);

        if ($content) {
            file_put_contents(
                $debugDirectory
                . $safeNo
                . "_"
                . time()
                . "_failed_response.html",
                $content
            );
        }
    }

    $last =
        end($debugInfo);

    $lastHttpCode = "N/A";
    $lastContentType = "N/A";
    $lastCurlError = "";

    if (is_array($last)) {

        if (isset($last["http_code"])) {
            $lastHttpCode =
                $last["http_code"];
        }

        if (isset($last["content_type"])) {
            $lastContentType =
                $last["content_type"];
        }

        if (isset($last["curl_error"])) {
            $lastCurlError =
                $last["curl_error"];
        }
    }

    $errorMessage =
        "Failed to generate BIRT PDF. "
        . "HTTP Code: "
        . $lastHttpCode
        . ". Content-Type: "
        . $lastContentType
        . ". cURL Error: "
        . $lastCurlError;

    return false;
}


/*
|--------------------------------------------------------------------------
| RUN PYTHON SIGNER
|--------------------------------------------------------------------------
*/

function runPythonSigner(
    $command,
    $workingDirectory
) {
    $result = array(
        "started" => false,
        "return_code" => null,
        "stdout" => "",
        "stderr" => ""
    );

    if (!function_exists("proc_open")) {
        $result["stderr"] =
            "proc_open is disabled.";

        return $result;
    }

    $descriptors = array(
        0 => array("pipe", "r"),
        1 => array("pipe", "w"),
        2 => array("pipe", "w")
    );

    $process = proc_open(
        $command,
        $descriptors,
        $pipes,
        $workingDirectory
    );

    if (!is_resource($process)) {
        $result["stderr"] =
            "Unable to start the Python process.";

        return $result;
    }

    $result["started"] = true;

    fclose($pipes[0]);

    $result["stdout"] =
        stream_get_contents($pipes[1]);

    fclose($pipes[1]);

    $result["stderr"] =
        stream_get_contents($pipes[2]);

    fclose($pipes[2]);

    $result["return_code"] =
        proc_close($process);

    return $result;
}


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

if (function_exists("isLogged")) {

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


/*
|--------------------------------------------------------------------------
| GET STOCK TRANSFER FORM
|--------------------------------------------------------------------------
*/

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

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

$sql = "
    SELECT
        transfer_form_id,
        transfer_form_no,
        transfer_form_date,
        status,
        approval_status,
        digital_signature_status,
        signed_pdf_path,
        signed_at,
        signed_by_name
    FROM stock_transfer_form
    WHERE transfer_form_id = "
    . $transferFormId
    . "
    LIMIT 1
";

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

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

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

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


/*
|--------------------------------------------------------------------------
| VERIFY SERVER COMPONENTS
|--------------------------------------------------------------------------
*/

if (!file_exists($PYTHON_BIN)) {
    die(
        "Python executable was not found: "
        . h($PYTHON_BIN)
    );
}

if (!is_executable($PYTHON_BIN)) {
    die(
        "Python executable is not executable: "
        . h($PYTHON_BIN)
    );
}

if (!file_exists($PYTHON_SIGNER_SCRIPT)) {
    die(
        "Python signer script was not found: "
        . h($PYTHON_SIGNER_SCRIPT)
    );
}

if (!is_readable($PYTHON_SIGNER_SCRIPT)) {
    die(
        "Python signer script is not readable: "
        . h($PYTHON_SIGNER_SCRIPT)
    );
}

if (!function_exists("proc_open")) {
    die(
        "PHP proc_open is disabled. "
        . "Python signing cannot run."
    );
}

if (!is_dir($PNPKI_TEMP_DIRECTORY)) {
    die(
        "PNPKI temporary directory was not found: "
        . h($PNPKI_TEMP_DIRECTORY)
    );
}

if (!is_writable($PNPKI_TEMP_DIRECTORY)) {
    die(
        "PNPKI temporary directory is not writable: "
        . h($PNPKI_TEMP_DIRECTORY)
    );
}


/*
|--------------------------------------------------------------------------
| CREATE PDF DIRECTORIES
|--------------------------------------------------------------------------
*/

$originalPdfDirectory =
    __DIR__
    . "/files/birt_original/stf/";

$signedPdfDirectory =
    __DIR__
    . "/files/pnpki_signed/stf/";

$debugDirectory =
    __DIR__
    . "/files/birt_debug/stf/";

ensureDir($originalPdfDirectory);
ensureDir($signedPdfDirectory);
ensureDir($debugDirectory);

if (!is_writable($originalPdfDirectory)) {
    die(
        "Original PDF directory is not writable: "
        . h($originalPdfDirectory)
    );
}

if (!is_writable($signedPdfDirectory)) {
    die(
        "Signed PDF directory is not writable: "
        . h($signedPdfDirectory)
    );
}


/*
|--------------------------------------------------------------------------
| TEST BIRT PDF
|--------------------------------------------------------------------------
*/

if (
    isset($_GET["test_birt"]) &&
    $_GET["test_birt"] == "1"
) {
    $errorMessage = "";
    $debugInfo = array();

    $pdfContent = downloadBirtPdf(
        $transferFormId,
        $safeNo,
        $errorMessage,
        $debugInfo
    );

    if (!$pdfContent) {

        echo "<h3>BIRT PDF Test Failed</h3>";

        echo "<p>"
            . h($errorMessage)
            . "</p>";

        echo "<pre>"
            . h(
                print_r(
                    $debugInfo,
                    true
                )
            )
            . "</pre>";

        exit();
    }

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

    header(
        "Content-Disposition: inline; filename=\""
        . $safeNo
        . ".pdf\""
    );

    echo $pdfContent;
    exit();
}


/*
|--------------------------------------------------------------------------
| ALREADY SIGNED PAGE
|--------------------------------------------------------------------------
*/

if (
    $data["digital_signature_status"] ===
    "SIGNED"
) {
    ?>
    <!DOCTYPE html>
    <html lang="en">
    <head>
        <meta charset="UTF-8">

        <meta
            name="viewport"
            content="width=device-width, initial-scale=1"
        >

        <title>Already PNPKI Signed</title>

        <style>
            body {
                margin: 30px;
                background: #f5f6f8;
                font-family: Arial, sans-serif;
            }

            .box {
                max-width: 700px;
                margin: 0 auto;
                padding: 22px;
                background: #fff;
                border: 1px solid #ddd;
                border-radius: 8px;
            }

            .btn {
                display: inline-block;
                padding: 10px 16px;
                color: #fff;
                background: #2e3192;
                border-radius: 5px;
                text-decoration: none;
            }
        </style>
    </head>

    <body>

    <div class="box">

        <h2>
            This Stock Transfer Form is already
            PNPKI signed.
        </h2>

        <p>
            <strong>STF No:</strong>
            <?php echo h($data["transfer_form_no"]); ?>
        </p>

        <p>
            <strong>Signed By:</strong>
            <?php echo h($data["signed_by_name"]); ?>
        </p>

        <p>
            <strong>Signed At:</strong>
            <?php echo h($data["signed_at"]); ?>
        </p>

        <?php if (!empty($data["signed_pdf_path"])) { ?>

            <p>
                <a
                    class="btn"
                    target="_blank"
                    href="<?php
                        echo h(
                            $data["signed_pdf_path"]
                            . "?v="
                            . time()
                        );
                    ?>"
                >
                    Open Signed PDF
                </a>
            </p>

        <?php } ?>

        <p>
            <a href="stock_transfer_form_view.php?editid1=<?php
                echo (int)$transferFormId;
            ?>">
                Back to Stock Transfer Form
            </a>
        </p>

    </div>

    </body>
    </html>

    <?php

    exit();
}


/*
|--------------------------------------------------------------------------
| POST: GENERATE AND SIGN PDF
|--------------------------------------------------------------------------
*/

if (
    $_SERVER["REQUEST_METHOD"] === "POST"
) {
    $p12Password =
        isset($_POST["p12_password"])
            ? (string)$_POST["p12_password"]
            : "";

    $remarks =
        isset($_POST["approval_remarks"])
            ? trim(
                (string)$_POST["approval_remarks"]
            )
            : "";

    if ($p12Password === "") {
        die("P12 password is required.");
    }

    if (
        !isset($_FILES["p12_file"]) ||
        $_FILES["p12_file"]["error"] !==
            UPLOAD_ERR_OK
    ) {
        die("PNPKI P12/PFX file is required.");
    }

    $originalUploadName =
        $_FILES["p12_file"]["name"];

    $extension = strtolower(
        pathinfo(
            $originalUploadName,
            PATHINFO_EXTENSION
        )
    );

    if (
        $extension !== "p12" &&
        $extension !== "pfx"
    ) {
        die(
            "Invalid certificate file. "
            . "Upload a .p12 or .pfx file."
        );
    }

    /*
     * Generate a random temporary filename.
     */
    $uniqueToken =
        bin2hex(
            random_bytes(12)
        );

    $tempP12Path =
        rtrim(
            $PNPKI_TEMP_DIRECTORY,
            "/"
        )
        . "/"
        . $safeNo
        . "_"
        . $uniqueToken
        . "."
        . $extension;

    $originalPdfPath =
        $originalPdfDirectory
        . $safeNo
        . ".pdf";

    $signedPdfPath =
        $signedPdfDirectory
        . $safeNo
        . "_SIGNED.pdf";

    /*
     * Delete a stale signed file from a previous failed attempt.
     */
    safeDelete($signedPdfPath);

    if (
        !move_uploaded_file(
            $_FILES["p12_file"]["tmp_name"],
            $tempP12Path
        )
    ) {
        die(
            "Failed to save the temporary "
            . "PNPKI certificate."
        );
    }

    @chmod(
        $tempP12Path,
        0600
    );


    /*
    |--------------------------------------------------------------------------
    | STEP A: GENERATE BIRT PDF
    |--------------------------------------------------------------------------
    */

    $errorMessage = "";
    $debugInfo = array();

    $pdfContent = downloadBirtPdf(
        $transferFormId,
        $safeNo,
        $errorMessage,
        $debugInfo
    );

    if (!$pdfContent) {

        safeDelete($tempP12Path);

        DB::Exec("
            UPDATE stock_transfer_form
            SET
                digital_signature_status = 'FAILED',
                approval_remarks = "
            . sqlq(
                $remarks
                . "\n"
                . $errorMessage
            )
            . "
            WHERE transfer_form_id = "
            . $transferFormId
        );

        echo "<h3>Failed to generate BIRT PDF.</h3>";

        echo "<p>"
            . h($errorMessage)
            . "</p>";

        echo "<pre>"
            . h(
                print_r(
                    $debugInfo,
                    true
                )
            )
            . "</pre>";

        exit();
    }

    $writeResult =
        file_put_contents(
            $originalPdfPath,
            $pdfContent
        );

    if ($writeResult === false) {

        safeDelete($tempP12Path);

        die(
            "Unable to save the original "
            . "BIRT PDF."
        );
    }


    /*
    |--------------------------------------------------------------------------
    | STEP B: SIGN PDF USING PYTHON + PYHANKO
    |--------------------------------------------------------------------------
    */

    $userName =
        getCurrentUserName();

    /*
     * Positional argument order required by pdf_cli_signing.py:
     *
     * 1. pdf_file
     * 2. p12_file
     * 3. p12_password
     * 4. digital_signature_image
     * 5. page_number
     * 6. coordinates
     * 7. platform
     * 8. document_reference_number
     * 9. rotation
     */
    $command = array(
        $PYTHON_BIN,
        $PYTHON_SIGNER_SCRIPT,
        $originalPdfPath,
        $tempP12Path,
        $p12Password,

        /*
         * Blank image path means the Python script
         * generates its own text-based appearance.
         */
        "",

        $SIGNATURE_PAGE,
        $SIGNATURE_COORDINATES,
        "ePIRMA",
        $data["transfer_form_no"],
        "0",

        "--output_pdf",
        $signedPdfPath,

        "--reason",
        "Stock Transfer Form Approval",

        "--location",
        "DSWD WINGS",

        "--contact",
        $userName
    );

    $signerResult = runPythonSigner(
        $command,
        $PYTHON_WORKING_DIRECTORY
    );

    /*
     * Delete the P12/PFX immediately after the signing attempt.
     */
    safeDelete($tempP12Path);


    /*
    |--------------------------------------------------------------------------
    | VALIDATE PYTHON SIGNING RESULT
    |--------------------------------------------------------------------------
    */

    $signingSucceeded =
        $signerResult["started"] &&
        $signerResult["return_code"] === 0 &&
        file_exists($signedPdfPath) &&
        filesize($signedPdfPath) > 1000;

    if (!$signingSucceeded) {

        $technicalError =
            "PyHanko signing failed."
            . "\nStarted: "
            . (
                $signerResult["started"]
                    ? "YES"
                    : "NO"
            )
            . "\nReturn code: "
            . (
                $signerResult["return_code"] === null
                    ? "N/A"
                    : $signerResult["return_code"]
            )
            . "\nOutput:\n"
            . $signerResult["stdout"]
            . "\nError:\n"
            . $signerResult["stderr"];

        DB::Exec("
            UPDATE stock_transfer_form
            SET
                digital_signature_status = 'FAILED',
                approval_remarks = "
            . sqlq(
                $remarks
                . "\n"
                . $technicalError
            )
            . "
            WHERE transfer_form_id = "
            . $transferFormId
        );

        echo "<h3>PNPKI PDF signing failed.</h3>";

        echo "<p><strong>Process started:</strong> "
            . (
                $signerResult["started"]
                    ? "YES"
                    : "NO"
            )
            . "</p>";

        echo "<p><strong>Return code:</strong> "
            . h(
                $signerResult["return_code"] === null
                    ? "N/A"
                    : $signerResult["return_code"]
            )
            . "</p>";

        echo "<h4>Python output</h4>";

        echo "<pre>"
            . h($signerResult["stdout"])
            . "</pre>";

        echo "<h4>Python error</h4>";

        echo "<pre>"
            . h($signerResult["stderr"])
            . "</pre>";

        exit();
    }


    /*
    |--------------------------------------------------------------------------
    | VALIDATE SIGNED PDF
    |--------------------------------------------------------------------------
    */

    $signedPdfContent =
        file_get_contents(
            $signedPdfPath
        );

    if (
        !$signedPdfContent ||
        !looksLikePdf($signedPdfContent)
    ) {
        safeDelete($signedPdfPath);

        DB::Exec("
            UPDATE stock_transfer_form
            SET
                digital_signature_status = 'FAILED',
                approval_remarks = "
            . sqlq(
                $remarks
                . "\nSigned output is not "
                . "a valid PDF."
            )
            . "
            WHERE transfer_form_id = "
            . $transferFormId
        );

        die(
            "The signed output was created "
            . "but is not a valid PDF."
        );
    }


    /*
    |--------------------------------------------------------------------------
    | CALCULATE DOCUMENT HASHES
    |--------------------------------------------------------------------------
    */

    $originalHash =
        hash_file(
            "sha256",
            $originalPdfPath
        );

    $signedHash =
        hash_file(
            "sha256",
            $signedPdfPath
        );

    $userId =
        getCurrentUserId();

    $relativeOriginalPath =
        "files/birt_original/stf/"
        . $safeNo
        . ".pdf";

    $relativeSignedPath =
        "files/pnpki_signed/stf/"
        . $safeNo
        . "_SIGNED.pdf";


    /*
    |--------------------------------------------------------------------------
    | UPDATE STOCK TRANSFER FORM
    |--------------------------------------------------------------------------
    */

    DB::Exec("
        UPDATE stock_transfer_form
        SET
            approval_status = 'APPROVED',

            digital_signature_status = 'SIGNED',

            original_pdf_path = "
            . sqlq($relativeOriginalPath)
            . ",

            signed_pdf_path = "
            . sqlq($relativeSignedPath)
            . ",

            original_pdf_hash = "
            . sqlq($originalHash)
            . ",

            signed_pdf_hash = "
            . sqlq($signedHash)
            . ",

            signed_by = "
            . (int)$userId
            . ",

            signed_by_name = "
            . sqlq($userName)
            . ",

            signed_at = NOW(),

            approved_by = "
            . (int)$userId
            . ",

            approved_by_name = "
            . sqlq($userName)
            . ",

            approved_date = CURDATE(),

            approval_remarks = "
            . sqlq($remarks)
            . ",

            status = 'ISSUED'

        WHERE transfer_form_id = "
        . $transferFormId
    );


    /*
    |--------------------------------------------------------------------------
    | INSERT DIGITAL SIGNATURE AUDIT LOG
    |--------------------------------------------------------------------------
    */

    DB::Exec("
        INSERT INTO digital_signature_log
        (
            transaction_type,
            transaction_id,
            document_no,
            original_pdf_path,
            signed_pdf_path,
            original_pdf_hash,
            signed_pdf_hash,
            signer_user_id,
            signer_name,
            signed_at,
            signing_status,
            remarks
        )
        VALUES
        (
            'STOCK_TRANSFER_FORM',

            "
            . $transferFormId
            . ",

            "
            . sqlq(
                $data["transfer_form_no"]
            )
            . ",

            "
            . sqlq($relativeOriginalPath)
            . ",

            "
            . sqlq($relativeSignedPath)
            . ",

            "
            . sqlq($originalHash)
            . ",

            "
            . sqlq($signedHash)
            . ",

            "
            . (int)$userId
            . ",

            "
            . sqlq($userName)
            . ",

            NOW(),

            'SIGNED',

            "
            . sqlq($remarks)
            . "
        )
    ");


    /*
    |--------------------------------------------------------------------------
    | VERIFY SIGNED FILE BEFORE REDIRECT
    |--------------------------------------------------------------------------
    */

    if (
        !file_exists($signedPdfPath) ||
        filesize($signedPdfPath) < 1000
    ) {
        die(
            "Signing was recorded, but the signed "
            . "PDF file could not be found."
        );
    }


    /*
    |--------------------------------------------------------------------------
    | REDIRECT DIRECTLY TO THE SIGNED PDF
    |--------------------------------------------------------------------------
    | The cache-busting parameter ensures the latest file is displayed.
    |--------------------------------------------------------------------------
    */

    header(
        "Location: "
        . $relativeSignedPath
        . "?v="
        . time()
    );

    exit();
}


/*
|--------------------------------------------------------------------------
| SIGNING FORM PAGE
|--------------------------------------------------------------------------
*/

$testBirtUrl =
    "pnpki_sign_stf.php?id="
    . $transferFormId
    . "&test_birt=1";

?>
<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">

    <meta
        name="viewport"
        content="width=device-width, initial-scale=1"
    >

    <title>Approve and PNPKI Sign STF</title>

    <style>
        * {
            box-sizing: border-box;
        }

        body {
            margin: 0;
            padding: 30px;
            background: #f5f6f8;
            color: #222;
            font-family: Arial, sans-serif;
        }

        .box {
            width: 100%;
            max-width: 760px;
            margin: 0 auto;
            padding: 24px;
            background: #fff;
            border: 1px solid #dce1e7;
            border-radius: 10px;
            box-shadow:
                0 3px 12px
                rgba(0, 0, 0, 0.06);
        }

        h2 {
            margin-top: 0;
            color: #2e3192;
        }

        .row {
            margin-bottom: 8px;
        }

        label {
            display: block;
            margin-top: 16px;
            font-weight: bold;
        }

        input,
        textarea {
            width: 100%;
            margin-top: 6px;
            padding: 10px;
            border: 1px solid #cbd1d8;
            border-radius: 5px;
        }

        textarea {
            resize: vertical;
        }

        .buttons {
            margin-top: 18px;
        }

        .btn {
            display: inline-block;
            margin-right: 8px;
            margin-top: 8px;
            padding: 10px 17px;
            border: none;
            border-radius: 5px;
            color: #fff;
            cursor: pointer;
            text-decoration: none;
        }

        .btn-primary {
            background: #2e3192;
        }

        .btn-success {
            background: #198754;
        }

        .btn-secondary {
            background: #6c757d;
        }

        .note {
            margin-top: 16px;
            padding: 13px;
            background: #fff7d6;
            border: 1px solid #ead47c;
            border-radius: 6px;
        }

        .security-note {
            margin-top: 16px;
            padding: 13px;
            background: #eaf4ff;
            border: 1px solid #9bc7eb;
            border-radius: 6px;
        }

        @media (max-width: 600px) {
            body {
                padding: 14px;
            }

            .box {
                padding: 18px;
            }

            .btn {
                display: block;
                width: 100%;
                text-align: center;
            }
        }
    </style>
</head>

<body>

<div class="box">

    <h2>Approve and PNPKI Sign</h2>

    <div class="row">
        <strong>STF No:</strong>
        <?php echo h($data["transfer_form_no"]); ?>
    </div>

    <div class="row">
        <strong>Date:</strong>
        <?php echo h($data["transfer_form_date"]); ?>
    </div>

    <div class="row">
        <strong>Status:</strong>
        <?php echo h($data["status"]); ?>
    </div>

    <div class="row">
        <strong>Approval Status:</strong>
        <?php echo h($data["approval_status"]); ?>
    </div>

    <div class="row">
        <strong>Signature Status:</strong>
        <?php
        echo h(
            $data["digital_signature_status"]
        );
        ?>
    </div>

    <div class="note">
        First click <strong>Test BIRT PDF</strong>.
        When the STF PDF opens correctly, proceed with
        PNPKI signing.
    </div>

    <div class="security-note">
        The uploaded P12/PFX certificate is stored only
        temporarily and is deleted immediately after
        the signing attempt. The password is never saved.
    </div>

    <div class="buttons">

        <a
            class="btn btn-secondary"
            target="_blank"
            href="<?php echo h($testBirtUrl); ?>"
        >
            Test BIRT PDF
        </a>

        <a
            class="btn btn-primary"
            href="stock_transfer_form_view.php?editid1=<?php
                echo (int)$transferFormId;
            ?>"
        >
            Back to STF
        </a>

    </div>

    <form
        method="post"
        enctype="multipart/form-data"
        autocomplete="off"
    >

        <label for="p12_file">
            PNPKI P12/PFX File
        </label>

        <input
            id="p12_file"
            type="file"
            name="p12_file"
            accept=".p12,.pfx"
            required
        >

        <label for="p12_password">
            P12 Password
        </label>

        <input
            id="p12_password"
            type="password"
            name="p12_password"
            autocomplete="new-password"
            required
        >

        <label for="approval_remarks">
            Approval Remarks
        </label>

        <textarea
            id="approval_remarks"
            name="approval_remarks"
            rows="4"
        ></textarea>

        <button
            type="submit"
            class="btn btn-success"
        >
            Approve and Sign PDF
        </button>

    </form>

</div>

</body>
</html>