<?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 UCHENNA'S TEST CUSTOMER
|--------------------------------------------------------------------------
*/

$stmt = $pdo->prepare("
    SELECT

        mva.id,
        mva.user_id,
        mva.customer_code,
        mva.validation_status,

        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 u.fullname = 'Uchenna Okoro'

    ORDER BY mva.id DESC

    LIMIT 1
");


$stmt->execute();


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


if (!$customer) {

    die(
        "Uchenna Okoro's Paystack Test customer could not be found."
    );

}


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

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

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

}


/*
|--------------------------------------------------------------------------
| HANDLE VALIDATION
|--------------------------------------------------------------------------
*/

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


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


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

        $_SESSION['error'] =
            "Invalid request. Please try again.";

        header(
            "Location: paystack-validate-customer.php"
        );

        exit();

    }


    /*
    |--------------------------------------------------------------------------
    | PAYSTACK OFFICIAL TEST IDENTITY
    |--------------------------------------------------------------------------
    |
    | Test Mode only.
    |
    */

    $validationData = [

        'country' =>
            'NG',

        'type' =>
            'bank_account',

        'account_number' =>
            '0111111111',

        'bvn' =>
            '22222222222',

        'bank_code' =>
            '007',

        'first_name' =>
            'Uchenna',

        'last_name' =>
            'Okoro'

    ];


    /*
    |--------------------------------------------------------------------------
    | SEND VALIDATION REQUEST
    |--------------------------------------------------------------------------
    */

    $url =
        $paystackBaseUrl
        .
        '/customer/'
        .
        rawurlencode(
            $customer[
                'customer_code'
            ]
        )
        .
        '/identification';


    $curl =
        curl_init();


    curl_setopt_array(
        $curl,
        [

            CURLOPT_URL =>
                $url,

            CURLOPT_POST =>
                true,

            CURLOPT_RETURNTRANSFER =>
                true,

            CURLOPT_HTTPHEADER => [

                'Authorization: Bearer '
                .
                $paystackSecretKey,

                'Content-Type: application/json',

                'Accept: application/json'

            ],

            CURLOPT_POSTFIELDS =>
                json_encode(
                    $validationData
                ),

            CURLOPT_TIMEOUT =>
                30

        ]
    );


    $response =
        curl_exec(
            $curl
        );


    $httpCode =
        curl_getinfo(
            $curl,
            CURLINFO_HTTP_CODE
        );


    $curlError =
        curl_error(
            $curl
        );


    curl_close(
        $curl
    );


    /*
    |--------------------------------------------------------------------------
    | CONNECTION ERROR
    |--------------------------------------------------------------------------
    */

    if ($curlError) {

        $_SESSION['error'] =
            "Unable to connect to Paystack: "
            .
            $curlError;

        header(
            "Location: paystack-validate-customer.php"
        );

        exit();

    }


    $responseData =
        json_decode(
            $response,
            true
        );


    /*
    |--------------------------------------------------------------------------
    | PAYSTACK ERROR
    |--------------------------------------------------------------------------
    */

    if (
        !in_array(
            $httpCode,
            [200, 202],
            true
        )
        ||
        empty(
            $responseData['status']
        )
    ) {

        $_SESSION['error'] =
            $responseData['message']
            ??
            "Paystack could not start customer validation.";

        header(
            "Location: paystack-validate-customer.php"
        );

        exit();

    }


    /*
    |--------------------------------------------------------------------------
    | MARK AS PENDING
    |--------------------------------------------------------------------------
    */

    $updateStmt =
        $pdo->prepare("
            UPDATE member_virtual_accounts

            SET
                validation_status = 'pending',
                consent_at = COALESCE(
                    consent_at,
                    NOW()
                )

            WHERE id = ?
        ");


    $updateStmt->execute([
        $customer['id']
    ]);


    $_SESSION['success'] =
        $responseData['message']
        ??
        "Customer identification started.";


    header(
        "Location: paystack-validate-customer.php"
    );

    exit();

}

?>

<!DOCTYPE html>

<html lang="en">

<head>

<meta charset="UTF-8">

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

<title>
    Paystack Customer Validation Test
</title>


<style>

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

.validation-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;
    font-size: 25px;
}

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

.details {
    margin: 20px 0;
    padding: 16px;
    border-radius: 10px;
    background: #f8fafc;
}

.details strong {
    display: block;
    margin-bottom: 5px;
}

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

.success {
    margin-bottom: 18px;
    padding: 14px;
    border-radius: 10px;
    color: #15803d;
    background: #ecfdf3;
}

.error {
    margin-bottom: 18px;
    padding: 14px;
    border-radius: 10px;
    color: #b42318;
    background: #fef3f2;
}

.warning {
    margin-top: 20px;
    padding: 14px;
    border-radius: 10px;
    color: #92400e;
    background: #fffbeb;
    font-size: 12px;
    line-height: 1.6;
}

</style>

</head>


<body>


<div class="validation-box">


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


    <h1>
        Validate Test Customer
    </h1>


    <p>
        This page uses Paystack's official Test Mode
        identity credentials for Uchenna Okoro.
        No real BVN or bank account is being used.
    </p>


    <?php if (
        isset($_SESSION['success'])
    ): ?>

        <div class="success">

            <?= htmlspecialchars(
                $_SESSION['success']
            ); ?>

        </div>

    <?php

    unset($_SESSION['success']);

    endif;

    ?>


    <?php if (
        isset($_SESSION['error'])
    ): ?>

        <div class="error">

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

        </div>

    <?php

    unset($_SESSION['error']);

    endif;

    ?>


    <div class="details">

        <strong>
            Complete Bliss Member
        </strong>

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


        <br><br>


        <strong>
            Paystack Customer Code
        </strong>

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


        <br><br>


        <strong>
            Current Validation Status
        </strong>

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

    </div>


    <form method="POST">

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

        <button type="submit">

            Start Test Customer Validation

        </button>

    </form>


    <div class="warning">

        Validation is asynchronous.
        A successful API response only means Paystack
        has started checking the identity.
        Final success or failure is normally delivered
        through a webhook.

    </div>


</div>


</body>

</html>