<?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 VALIDATED CUSTOMER
|--------------------------------------------------------------------------
*/

$stmt = $pdo->prepare("
    SELECT

        mva.id,
        mva.user_id,
        mva.customer_code,
        mva.validation_status,
        mva.dedicated_account_id,
        mva.bank_name,
        mva.account_name,
        mva.account_number,
        mva.assigned,
        mva.active,

        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."
    );

}


/*
|--------------------------------------------------------------------------
| MUST BE VALIDATED FIRST
|--------------------------------------------------------------------------
*/

if (
    $customer['validation_status']
    !== 'validated'
) {

    die(
        "This customer has not been validated yet."
    );

}


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

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

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

}


/*
|--------------------------------------------------------------------------
| HANDLE DVA CREATION
|--------------------------------------------------------------------------
*/

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


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

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


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

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

        header(
            "Location: paystack-create-dva.php"
        );

        exit();

    }


    /*
    |--------------------------------------------------------------------------
    | PREVENT DUPLICATE CREATION
    |--------------------------------------------------------------------------
    */

    if (
        !empty(
            $customer[
                'account_number'
            ]
        )
    ) {

        $_SESSION['error'] =
            "This customer already has a Paystack Test virtual account.";

        header(
            "Location: paystack-create-dva.php"
        );

        exit();

    }


    /*
    |--------------------------------------------------------------------------
    | REQUEST DATA
    |--------------------------------------------------------------------------
    */

    $requestData = [

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

        'preferred_bank' =>
            'test-bank'

    ];


    /*
    |--------------------------------------------------------------------------
    | CALL PAYSTACK
    |--------------------------------------------------------------------------
    */

    $curl =
        curl_init();


    curl_setopt_array(
        $curl,
        [

            CURLOPT_URL =>
                $paystackBaseUrl
                .
                '/dedicated_account',

            CURLOPT_POST =>
                true,

            CURLOPT_RETURNTRANSFER =>
                true,

            CURLOPT_HTTPHEADER => [

                'Authorization: Bearer '
                .
                $paystackSecretKey,

                'Content-Type: application/json',

                'Accept: application/json'

            ],

            CURLOPT_POSTFIELDS =>
                json_encode(
                    $requestData
                ),

            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-create-dva.php"
        );

        exit();

    }


    $responseData =
        json_decode(
            $response,
            true
        );


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

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

        $_SESSION['error'] =
            $responseData['message']
            ??
            "Paystack could not create the virtual account.";

        header(
            "Location: paystack-create-dva.php"
        );

        exit();

    }


    /*
    |--------------------------------------------------------------------------
    | DVA RESPONSE
    |--------------------------------------------------------------------------
    */

    $dva =
        $responseData['data'];


    $dedicatedAccountId =
        $dva['id']
        ?? null;


    $accountNumber =
        $dva['account_number']
        ?? null;


    $accountName =
        $dva['account_name']
        ?? null;


    $currency =
        $dva['currency']
        ?? 'NGN';


    $assigned =
        !empty(
            $dva['assigned']
        )
            ? 1
            : 0;


    $active =
        !empty(
            $dva['active']
        )
            ? 1
            : 0;


    $bankName =
        $dva['bank']['name']
        ?? null;


    $bankSlug =
        $dva['bank']['slug']
        ?? null;


    /*
    |--------------------------------------------------------------------------
    | ENSURE REQUIRED DATA EXISTS
    |--------------------------------------------------------------------------
    */

    if (
        !$dedicatedAccountId
        ||
        !$accountNumber
        ||
        !$bankName
    ) {

        $_SESSION['error'] =
            "Paystack created the account but returned incomplete virtual account information.";

        header(
            "Location: paystack-create-dva.php"
        );

        exit();

    }


    /*
    |--------------------------------------------------------------------------
    | SAVE DVA TO COMPLETE BLISS
    |--------------------------------------------------------------------------
    */

    try {


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

                SET

                    dedicated_account_id = ?,

                    bank_name = ?,

                    bank_slug = ?,

                    account_name = ?,

                    account_number = ?,

                    currency = ?,

                    assigned = ?,

                    active = ?,

                    consent_at = COALESCE(
                        consent_at,
                        NOW()
                    )

                WHERE id = ?
            ");


        $updateStmt->execute([

            $dedicatedAccountId,

            $bankName,

            $bankSlug,

            $accountName,

            $accountNumber,

            $currency,

            $assigned,

            $active,

            $customer['id']

        ]);


    } catch (Exception $e) {


        $_SESSION['error'] =
            "Paystack created the virtual account, but Complete Bliss could not save it. Do not create another one yet.";

        header(
            "Location: paystack-create-dva.php"
        );

        exit();

    }


    /*
    |--------------------------------------------------------------------------
    | SUCCESS
    |--------------------------------------------------------------------------
    */

    $_SESSION['dva_success'] = [

        'message' =>
            $responseData['message']
            ??
            'Virtual account created successfully.',

        'bank' =>
            $bankName,

        'account_name' =>
            $accountName,

        'account_number' =>
            $accountNumber

    ];


    header(
        "Location: paystack-create-dva.php"
    );

    exit();

}


/*
|--------------------------------------------------------------------------
| REFRESH CUSTOMER AFTER POSSIBLE CREATION
|--------------------------------------------------------------------------
*/

$stmt = $pdo->prepare("
    SELECT

        mva.*,

        u.fullname,
        u.email,
        u.phone

    FROM member_virtual_accounts mva

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

    WHERE mva.id = ?

    LIMIT 1
");


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


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

?>

<!DOCTYPE html>

<html lang="en">

<head>

<meta charset="UTF-8">

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

<title>
    Create Paystack Test Virtual Account
</title>


<style>

body {

    margin: 0;

    padding: 40px 20px;

    font-family: Arial, sans-serif;

    background: #f5f7fb;

    color: #101828;

}


.dva-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;

}


.subtitle {

    margin: 0 0 25px;

    color: #667085;

    font-size: 13px;

    line-height: 1.7;

}


.customer-details {

    margin: 20px 0;

    padding: 17px;

    border-radius: 11px;

    background: #f8fafc;

}


.customer-details span {

    display: block;

    margin-bottom: 4px;

    color: #667085;

    font-size: 10px;

}


.customer-details strong {

    display: block;

    margin-bottom: 16px;

}


.validated {

    color: #15803d;

}


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: 20px;

    padding: 17px;

    border-radius: 11px;

    color: #166534;

    background: #ecfdf3;

}


.error {

    margin-bottom: 20px;

    padding: 14px;

    border-radius: 10px;

    color: #b42318;

    background: #fef3f2;

}


.account-card {

    margin-top: 20px;

    padding: 20px;

    border-radius: 14px;

    color: #ffffff;

    background:
        linear-gradient(
            135deg,
            #1d4ed8,
            #2563eb
        );

}


.account-card small {

    display: block;

    margin-bottom: 5px;

    opacity: .75;

}


.account-number {

    margin: 8px 0 18px;

    font-size: 28px;

    font-weight: 800;

    letter-spacing: 2px;

}


.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="dva-box">


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


    <h1>
        Create Test Virtual Account
    </h1>


    <p class="subtitle">

        We are now creating a Dedicated Virtual
        Account for the validated Paystack Test
        customer.

    </p>



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


        <?php

        $dvaSuccess =
            $_SESSION['dva_success'];

        ?>


        <div class="success">

            ✅

            <?= htmlspecialchars(
                $dvaSuccess['message']
            ); ?>

        </div>


        <div class="account-card">


            <small>
                BANK
            </small>


            <strong>

                <?= htmlspecialchars(
                    $dvaSuccess['bank']
                ); ?>

            </strong>


            <div class="account-number">

                <?= htmlspecialchars(
                    $dvaSuccess[
                        'account_number'
                    ]
                ); ?>

            </div>


            <small>
                ACCOUNT NAME
            </small>


            <strong>

                <?= htmlspecialchars(
                    $dvaSuccess[
                        'account_name'
                    ]
                ); ?>

            </strong>


        </div>


    <?php

    unset(
        $_SESSION['dva_success']
    );

    endif;

    ?>



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


        <div class="error">

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

        </div>


    <?php

    unset($_SESSION['error']);

    endif;

    ?>



    <div class="customer-details">


        <span>
            MEMBER
        </span>


        <strong>

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

        </strong>



        <span>
            PAYSTACK CUSTOMER
        </span>


        <strong>

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

        </strong>



        <span>
            VALIDATION
        </span>


        <strong class="validated">

            ✅

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

        </strong>


    </div>



    <?php if (
        empty(
            $customer[
                'account_number'
            ]
        )
    ): ?>


        <form method="POST">


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


            <button type="submit">

                Create Test Virtual Account

            </button>


        </form>


    <?php else: ?>


        <div class="account-card">


            <small>
                TEST BANK
            </small>


            <strong>

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

            </strong>


            <div class="account-number">

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

            </div>


            <small>
                ACCOUNT NAME
            </small>


            <strong>

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

            </strong>


        </div>


    <?php endif; ?>



    <div class="warning">

        This is a Paystack Test Mode virtual
        account. It cannot receive real money.

    </div>


</div>


</body>

</html>