<?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 LATEST TEST CHARGE EVENT
|--------------------------------------------------------------------------
*/

$stmt = $pdo->query("
    SELECT
        id,
        provider_reference,
        payload
    FROM payment_events
    WHERE
        provider = 'paystack'
        AND environment = 'test'
        AND event_type = 'charge.success'
    ORDER BY id DESC
    LIMIT 1
");


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


if (!$paymentEvent) {

    die(
        "No Paystack test charge event exists yet."
    );

}


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

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

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

}


$result = null;


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

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


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


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

        die(
            "Invalid request."
        );

    }


    /*
    |--------------------------------------------------------------------------
    | ORIGINAL RAW PAYLOAD
    |--------------------------------------------------------------------------
    */

    $payload =
        $paymentEvent['payload'];


    /*
    |--------------------------------------------------------------------------
    | VALID SIGNATURE
    |--------------------------------------------------------------------------
    */

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


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

    $countStmt =
        $pdo->prepare("
            SELECT COUNT(*)
            FROM payment_events
            WHERE
                provider = 'paystack'
                AND environment = 'test'
                AND provider_reference = ?
        ");


    $countStmt->execute([
        $paymentEvent[
            'provider_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';


    /*
    |--------------------------------------------------------------------------
    | RESEND EXACT SAME EVENT
    |--------------------------------------------------------------------------
    */

    $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);


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

    $countStmt->execute([
        $paymentEvent[
            'provider_reference'
        ]
    ]);


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


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

    $duplicateProtected =
        (
            $httpCode === 200
            &&
            $countBefore === $countAfter
        );


    $result = [

        'protected' =>
            $duplicateProtected,

        'reference' =>
            $paymentEvent[
                'provider_reference'
            ],

        'before' =>
            $countBefore,

        'after' =>
            $countAfter,

        '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 Duplicate 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: #1d4ed8;
    background: #eff6ff;
    font-size: 11px;
    font-weight: 700;
}

h1 {
    margin: 0 0 8px;
}

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

.reference {
    margin: 20px 0;
    padding: 14px;
    border-radius: 10px;
    background: #f8fafc;
    word-break: break-word;
}

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;
}

.line {
    margin-top: 8px;
}

</style>

</head>


<body>


<div class="test-box">


    <span class="badge">
        DUPLICATE PROTECTION TEST
    </span>


    <h1>
        Resend Existing Webhook
    </h1>


    <p>
        This will resend the exact same signed
        Paystack test event already received by
        Complete Bliss.
    </p>


    <div class="reference">

        <strong>
            Existing Reference:
        </strong>

        <br>

        <?= htmlspecialchars(
            $paymentEvent[
                'provider_reference'
            ]
        ); ?>

    </div>


    <form method="POST">

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

        <button type="submit">

            Resend Same Webhook

        </button>

    </form>


    <?php if ($result): ?>


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


            <div class="success">

                ✅ Duplicate protection working.


                <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">

                ❌ Duplicate protection test failed.


                <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>


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

                    <div class="line">

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

                    </div>

                <?php endif; ?>


            </div>


        <?php endif; ?>


    <?php endif; ?>


</div>


</body>

</html>