<?php

include "../includes/admin_auth.php";
include "../config/database.php";
include "../config/paystack.php";


/*
|--------------------------------------------------------------------------
| TEST MODE ONLY
|--------------------------------------------------------------------------
*/

if (!paystackIsConfigured()) {

    die(
        "Paystack Test Mode is not configured correctly."
    );

}


/*
|--------------------------------------------------------------------------
| GET TEST CUSTOMER
|--------------------------------------------------------------------------
*/

$stmt = $pdo->query("
    SELECT
        mva.user_id,
        mva.customer_code,
        u.fullname,
        u.email

    FROM member_virtual_accounts mva

    INNER JOIN users u
        ON u.id = mva.user_id

    WHERE
        mva.provider = 'paystack'
        AND mva.environment = 'test'
        AND mva.customer_code IS NOT NULL

    ORDER BY mva.id DESC

    LIMIT 1
");


$customer =
    $stmt->fetch(
        PDO::FETCH_ASSOC
    );


if (!$customer) {

    die(
        "No Paystack Test customer was found."
    );

}


/*
|--------------------------------------------------------------------------
| CSRF
|--------------------------------------------------------------------------
*/

if (
    empty(
        $_SESSION[
            'paystack_fake_signature_csrf'
        ]
    )
) {

    $_SESSION[
        'paystack_fake_signature_csrf'
    ] =
        bin2hex(
            random_bytes(32)
        );

}


$result = null;


/*
|--------------------------------------------------------------------------
| RUN TEST
|--------------------------------------------------------------------------
*/

if ($_SERVER['REQUEST_METHOD'] === 'POST') {


    $csrfToken =
        $_POST['csrf_token']
        ?? '';


    if (
        !hash_equals(
            $_SESSION[
                'paystack_fake_signature_csrf'
            ],
            $csrfToken
        )
    ) {

        die(
            "Invalid request."
        );

    }


    /*
    |--------------------------------------------------------------------------
    | UNIQUE FAKE PAYMENT REFERENCE
    |--------------------------------------------------------------------------
    */

    $reference =
        'CB_FAKE_'
        .
        date('YmdHis')
        .
        '_'
        .
        random_int(
            1000,
            9999
        );


    /*
    |--------------------------------------------------------------------------
    | CREATE FAKE PAYSTACK-LIKE EVENT
    |--------------------------------------------------------------------------
    */

    $event = [

        'event' =>
            'charge.success',

        'data' => [

            'id' =>
                random_int(
                    1000000,
                    9999999
                ),

            'domain' =>
                'test',

            'status' =>
                'success',

            'reference' =>
                $reference,

            'amount' =>
                500000,

            'currency' =>
                'NGN',

            'channel' =>
                'dedicated_nuban',

            'customer' => [

                'customer_code' =>
                    $customer[
                        'customer_code'
                    ],

                'email' =>
                    $customer[
                        'email'
                    ]

            ]

        ]

    ];


    $payload =
        json_encode(
            $event,
            JSON_UNESCAPED_SLASHES
        );


    /*
    |--------------------------------------------------------------------------
    | IMPORTANT:
    | THIS SIGNATURE IS DELIBERATELY WRONG
    |--------------------------------------------------------------------------
    */

    $fakeSignature =
        hash(
            'sha512',
            'THIS_IS_NOT_A_VALID_PAYSTACK_SIGNATURE_'
            .
            random_bytes(16)
        );


    /*
    |--------------------------------------------------------------------------
    | COUNT BEFORE
    |--------------------------------------------------------------------------
    */

    $countStmt =
        $pdo->prepare("
            SELECT COUNT(*)

            FROM payment_events

            WHERE
                provider = 'paystack'
                AND environment = 'test'
                AND provider_reference = ?
        ");


    $countStmt->execute([
        $reference
    ]);


    $countBefore =
        (int)$countStmt->fetchColumn();


    /*
    |--------------------------------------------------------------------------
    | BUILD WEBHOOK URL
    |--------------------------------------------------------------------------
    */

    $isHttps =
        (
            !empty($_SERVER['HTTPS'])
            &&
            $_SERVER['HTTPS'] !== 'off'
        );


    $protocol =
        $isHttps
            ? 'https'
            : 'http';


    $host =
        $_SERVER['HTTP_HOST']
        ?? 'localhost';


    $adminDirectory =
        dirname(
            $_SERVER[
                'SCRIPT_NAME'
            ]
            ?? ''
        );


    $projectDirectory =
        dirname(
            $adminDirectory
        );


    if (
        $projectDirectory === '/'
        ||
        $projectDirectory === '.'
    ) {

        $projectDirectory = '';

    }


    $webhookUrl =
        $protocol
        .
        '://'
        .
        $host
        .
        $projectDirectory
        .
        '/paystack-webhook.php';


    /*
    |--------------------------------------------------------------------------
    | SEND FAKE WEBHOOK
    |--------------------------------------------------------------------------
    */

    $curl =
        curl_init();


    curl_setopt_array(
        $curl,
        [

            CURLOPT_URL =>
                $webhookUrl,

            CURLOPT_POST =>
                true,

            CURLOPT_RETURNTRANSFER =>
                true,

            CURLOPT_HTTPHEADER => [

                'Content-Type: application/json',

                'x-paystack-signature: '
                .
                $fakeSignature

            ],

            CURLOPT_POSTFIELDS =>
                $payload,

            CURLOPT_TIMEOUT =>
                20

        ]
    );


    $response =
        curl_exec($curl);


    $httpCode =
        curl_getinfo(
            $curl,
            CURLINFO_HTTP_CODE
        );


    $curlError =
        curl_error($curl);


    curl_close($curl);


    /*
    |--------------------------------------------------------------------------
    | COUNT AFTER
    |--------------------------------------------------------------------------
    */

    $countStmt->execute([
        $reference
    ]);


    $countAfter =
        (int)$countStmt->fetchColumn();


    /*
    |--------------------------------------------------------------------------
    | EXPECTED:
    |
    | HTTP 401
    | 0 rows before
    | 0 rows after
    |--------------------------------------------------------------------------
    */

    $fakeRejected =
        (
            $httpCode === 401
            &&
            $countBefore === 0
            &&
            $countAfter === 0
        );


    $result = [

        'rejected' =>
            $fakeRejected,

        'reference' =>
            $reference,

        'http_code' =>
            $httpCode,

        'before' =>
            $countBefore,

        'after' =>
            $countAfter,

        'response' =>
            $response,

        'error' =>
            $curlError

    ];

}

?>

<!DOCTYPE html>

<html lang="en">

<head>

<meta charset="UTF-8">

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

<title>
    Fake Paystack Webhook Test
</title>


<style>

body {
    margin: 0;
    padding: 40px 20px;
    font-family: Arial, sans-serif;
    background: #f5f7fb;
    color: #101828;
}

.test-box {
    width: 100%;
    max-width: 650px;
    margin: auto;
    padding: 30px;
    box-sizing: border-box;
    border-radius: 16px;
    background: #ffffff;
}

.badge {
    display: inline-block;
    margin-bottom: 10px;
    padding: 6px 10px;
    border-radius: 999px;
    color: #b42318;
    background: #fef3f2;
    font-size: 11px;
    font-weight: 700;
}

h1 {
    margin: 0 0 8px;
}

p {
    color: #667085;
    font-size: 13px;
    line-height: 1.7;
}

button {
    width: 100%;
    min-height: 48px;
    margin-top: 15px;
    border: 0;
    border-radius: 9px;
    cursor: pointer;
    color: #ffffff;
    background: #dc2626;
    font-weight: 700;
}

.success {
    margin-top: 20px;
    padding: 16px;
    border-radius: 11px;
    color: #15803d;
    background: #ecfdf3;
}

.error {
    margin-top: 20px;
    padding: 16px;
    border-radius: 11px;
    color: #b42318;
    background: #fef3f2;
}

.line {
    margin-top: 8px;
    word-break: break-word;
}

</style>

</head>


<body>


<div class="test-box">


    <span class="badge">
        SECURITY TEST
    </span>


    <h1>
        Fake Webhook Signature
    </h1>


    <p>
        This sends a fake payment event with an
        invalid Paystack signature.
        Complete Bliss should reject it before
        anything reaches the payment database.
    </p>


    <form method="POST">


        <input
            type="hidden"
            name="csrf_token"
            value="<?= htmlspecialchars(
                $_SESSION[
                    'paystack_fake_signature_csrf'
                ]
            ); ?>"
        >


        <button type="submit">

            Send Fake Webhook

        </button>


    </form>



    <?php if ($result): ?>


        <?php if (
            $result['rejected']
        ): ?>


            <div class="success">

                ✅ Fake webhook rejected successfully.


                <div class="line">

                    <strong>
                        HTTP:
                    </strong>

                    <?= (int)$result[
                        'http_code'
                    ]; ?>

                </div>


                <div class="line">

                    <strong>
                        Rows before:
                    </strong>

                    <?= (int)$result[
                        'before'
                    ]; ?>

                </div>


                <div class="line">

                    <strong>
                        Rows after:
                    </strong>

                    <?= (int)$result[
                        'after'
                    ]; ?>

                </div>


                <div class="line">

                    <strong>
                        Response:
                    </strong>

                    <?= htmlspecialchars(
                        $result[
                            'response'
                        ]
                    ); ?>

                </div>

            </div>


        <?php else: ?>


            <div class="error">

                ❌ Security test did not behave as expected.


                <div class="line">

                    HTTP:
                    <?= (int)$result[
                        'http_code'
                    ]; ?>

                </div>


                <div class="line">

                    Rows before:
                    <?= (int)$result[
                        'before'
                    ]; ?>

                </div>


                <div class="line">

                    Rows after:
                    <?= (int)$result[
                        'after'
                    ]; ?>

                </div>


                <div class="line">

                    Response:
                    <?= htmlspecialchars(
                        $result[
                            'response'
                        ]
                    ); ?>

                </div>

            </div>


        <?php endif; ?>


    <?php endif; ?>


</div>


</body>

</html>