<?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 ONE TEST PAYSTACK CUSTOMER
|--------------------------------------------------------------------------
*/

$stmt = $pdo->query("
    SELECT

        mva.user_id,
        mva.customer_code,

        u.fullname,
        u.email,
        u.phone

    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_webhook_test_csrf'
        ]
    )
) {

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

}


/*
|--------------------------------------------------------------------------
| RESULT
|--------------------------------------------------------------------------
*/

$result = null;


/*
|--------------------------------------------------------------------------
| HANDLE TEST
|--------------------------------------------------------------------------
*/

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


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

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


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

        die(
            "Invalid request."
        );

    }


    /*
    |--------------------------------------------------------------------------
    | UNIQUE TEST REFERENCE
    |--------------------------------------------------------------------------
    */

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


    /*
    |--------------------------------------------------------------------------
    | FAKE TEST PAYSTACK EVENT
    |--------------------------------------------------------------------------
    |
    | Amount is in KOBO.
    |
    | 250000 = ₦2,500.00
    |
    */

    $event = [

        'event' =>
            'charge.success',

        'data' => [

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

            'domain' =>
                'test',

            'status' =>
                'success',

            'reference' =>
                $reference,

            'amount' =>
                250000,

            'currency' =>
                'NGN',

            'channel' =>
                'dedicated_nuban',

            'customer' => [

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

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

            ],

            'authorization' => [

                'channel' =>
                    'dedicated_nuban',

                'receiver_bank_account_number' =>
                    '9999999999'

            ]

        ]

    ];


    /*
    |--------------------------------------------------------------------------
    | RAW JSON
    |--------------------------------------------------------------------------
    */

    $payload =
        json_encode(
            $event,
            JSON_UNESCAPED_SLASHES
        );


    /*
    |--------------------------------------------------------------------------
    | GENERATE VALID PAYSTACK SIGNATURE
    |--------------------------------------------------------------------------
    */

    $signature =
        hash_hmac(
            'sha512',
            $payload,
            $paystackSecretKey
        );


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

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


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


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


    /*
    |--------------------------------------------------------------------------
    | Example:
    |
    | Current:
    | /complete-bliss/admin/paystack-webhook-simulator.php
    |
    | Project:
    | /complete-bliss
    |
    */

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


    $projectDirectory =
        dirname(
            $adminDirectory
        );


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

        $projectDirectory = '';

    }


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


    /*
    |--------------------------------------------------------------------------
    | SEND EVENT TO OUR 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: '
                .
                $signature

            ],

            CURLOPT_POSTFIELDS =>
                $payload,

            CURLOPT_TIMEOUT =>
                20

        ]
    );


    $response =
        curl_exec(
            $curl
        );


    $httpCode =
        curl_getinfo(
            $curl,
            CURLINFO_HTTP_CODE
        );


    $curlError =
        curl_error(
            $curl
        );


    curl_close(
        $curl
    );


    /*
    |--------------------------------------------------------------------------
    | RESULT
    |--------------------------------------------------------------------------
    */

    $result = [

        'reference' =>
            $reference,

        'amount' =>
            2500,

        'webhook_url' =>
            $webhookUrl,

        'http_code' =>
            $httpCode,

        '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>
    Paystack Webhook Simulator
</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: #1d4ed8;

    background: #eff6ff;

    font-size: 11px;

    font-weight: 700;

}


h1 {

    margin: 0 0 8px;

}


.subtitle {

    color: #667085;

    font-size: 13px;

    line-height: 1.7;

}


.details {

    margin: 20px 0;

    padding: 16px;

    border-radius: 10px;

    background: #f8fafc;

}


.details span {

    display: block;

    margin-bottom: 4px;

    color: #98a2b3;

    font-size: 10px;

}


.details strong {

    display: block;

    margin-bottom: 15px;

}


button {

    width: 100%;

    min-height: 48px;

    border: 0;

    border-radius: 9px;

    cursor: pointer;

    color: #ffffff;

    background: #2563eb;

    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;

}


.result-line {

    margin-top: 8px;

    word-break: break-word;

}

</style>

</head>


<body>


<div class="test-box">


    <span class="badge">
        LOCAL PAYSTACK TEST
    </span>


    <h1>
        Webhook Simulator
    </h1>


    <p class="subtitle">

        This sends a signed fake Paystack
        <strong>charge.success</strong>
        event to your local webhook receiver.

        No money or wallet balance is changed.

    </p>



    <div class="details">


        <span>
            TEST MEMBER
        </span>


        <strong>

            <?= htmlspecialchars(
                $customer[
                    'fullname'
                ]
            ); ?>

        </strong>



        <span>
            PAYSTACK CUSTOMER
        </span>


        <strong>

            <?= htmlspecialchars(
                $customer[
                    'customer_code'
                ]
            ); ?>

        </strong>



        <span>
            SIMULATED PAYMENT
        </span>


        <strong>
            ₦2,500.00
        </strong>


    </div>



    <form method="POST">


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


        <button type="submit">

            Send Valid Test Webhook

        </button>


    </form>



    <?php if ($result): ?>


        <?php if (
            empty(
                $result['error']
            )
            &&
            $result[
                'http_code'
            ] === 200
        ): ?>


            <div class="success">

                ✅ Webhook accepted successfully.


                <div class="result-line">

                    <strong>
                        HTTP:
                    </strong>

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

                </div>


                <div class="result-line">

                    <strong>
                        Reference:
                    </strong>

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

                </div>


                <div class="result-line">

                    <strong>
                        Response:
                    </strong>

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

                </div>

            </div>


        <?php else: ?>


            <div class="error">

                ❌ Webhook test failed.


                <div class="result-line">

                    <strong>
                        HTTP:
                    </strong>

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

                </div>


                <?php if (
                    !empty(
                        $result['error']
                    )
                ): ?>

                    <div class="result-line">

                        <strong>
                            Error:
                        </strong>

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

                    </div>

                <?php endif; ?>


                <div class="result-line">

                    <strong>
                        Response:
                    </strong>

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

                </div>

            </div>


        <?php endif; ?>


    <?php endif; ?>


</div>


</body>

</html>