<?php

define('SECURE_ACCESS', true);

require_once __DIR__ . '/includes/config.php';

/*
|--------------------------------------------------------------------------
| Paystack API Request
|--------------------------------------------------------------------------
*/
function paystackRequest(string $endpoint, string $method = 'GET', ?array $data = null): array
{
    $url = PAYSTACK_BASE_URL . $endpoint;

    $ch = curl_init($url);

    $headers = [
        'Authorization: Bearer ' . PAYSTACK_SECRET_KEY,
        'Content-Type: application/json',
        'Cache-Control: no-cache'
    ];

    curl_setopt_array($ch, [
        CURLOPT_RETURNTRANSFER => true,
        CURLOPT_HTTPHEADER => $headers,
        CURLOPT_CUSTOMREQUEST => $method,
        CURLOPT_TIMEOUT => 30,
    ]);

    if ($data !== null) {
        curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($data));
    }

    $response = curl_exec($ch);
    $curlError = curl_error($ch);
    $httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);

    curl_close($ch);

    if ($curlError) {
        throw new Exception('cURL Error: ' . $curlError);
    }

    $decoded = json_decode($response, true);

    if (!is_array($decoded)) {
        throw new Exception(
            "Invalid Paystack response. HTTP {$httpCode}: " . $response
        );
    }

    if (empty($decoded['status'])) {
        $message = $decoded['message'] ?? 'Unknown Paystack error';

        throw new Exception(
            "Paystack error (HTTP {$httpCode}): {$message}"
        );
    }

    return $decoded;
}


/*
|--------------------------------------------------------------------------
| Select a PPay Customer
|--------------------------------------------------------------------------
|
| For this first test, we simply select the first active customer.
| Later, this will use the logged-in PPay customer.
|
*/
$stmt = $pdo->query("
    SELECT *
    FROM customers
    WHERE status = 'active'
    ORDER BY id ASC
    LIMIT 1
");

$customer = $stmt->fetch();

if (!$customer) {
    die('No active customer found in the customers table.');
}


/*
|--------------------------------------------------------------------------
| Create Paystack Customer
|--------------------------------------------------------------------------
*/

try {

    /*
     * If this PPay customer doesn't already have
     * a Paystack customer code, create one.
     */
    if (empty($customer['paystack_customer_code'])) {

        $nameParts = preg_split(
            '/\s+/',
            trim($customer['full_name']),
            2
        );

        $firstName = $nameParts[0] ?? $customer['full_name'];
        $lastName  = $nameParts[1] ?? $firstName;

        $customerData = [
            'email'      => $customer['email'],
            'first_name' => $firstName,
            'last_name'  => $lastName,
            'phone'      => $customer['phone'],
        ];

        $paystackCustomer = paystackRequest(
            '/customer',
            'POST',
            $customerData
        );

        $paystackCustomerCode =
            $paystackCustomer['data']['customer_code'] ?? null;

        if (!$paystackCustomerCode) {
            throw new Exception(
                'Paystack did not return a customer code.'
            );
        }

        /*
         * Save Paystack customer code.
         */
        $update = $pdo->prepare("
            UPDATE customers
            SET paystack_customer_code = ?
            WHERE id = ?
        ");

        $update->execute([
            $paystackCustomerCode,
            $customer['id']
        ]);

        $customer['paystack_customer_code'] =
            $paystackCustomerCode;
    }


    /*
    |--------------------------------------------------------------------------
    | Check if DVA already exists
    |--------------------------------------------------------------------------
    */

    if (!empty($customer['paystack_account_number'])) {

        echo '<h2>Virtual Account Already Exists</h2>';

        echo '<p><strong>Customer:</strong> ' .
            htmlspecialchars($customer['full_name']) .
            '</p>';

        echo '<p><strong>Account Name:</strong> ' .
            htmlspecialchars($customer['paystack_account_name']) .
            '</p>';

        echo '<p><strong>Account Number:</strong> ' .
            htmlspecialchars($customer['paystack_account_number']) .
            '</p>';

        echo '<p><strong>Bank:</strong> ' .
            htmlspecialchars($customer['paystack_bank_name']) .
            '</p>';

        exit;
    }


    /*
    |--------------------------------------------------------------------------
    | Create TEST Dedicated Virtual Account
    |--------------------------------------------------------------------------
    */

    $dvaData = [
        'customer'      => $customer['paystack_customer_code'],
        'preferred_bank' => 'test-bank'
    ];

    $dvaResponse = paystackRequest(
        '/dedicated_account',
        'POST',
        $dvaData
    );

    $dva = $dvaResponse['data'] ?? null;

    if (!$dva) {
        throw new Exception(
            'Paystack did not return DVA information.'
        );
    }


    /*
    |--------------------------------------------------------------------------
    | Extract DVA Details
    |--------------------------------------------------------------------------
    */

    $dvaId = $dva['id'] ?? null;
    $accountNumber = $dva['account_number'] ?? null;
    $accountName = $dva['account_name'] ?? null;

    $bankName = $dva['bank']['name'] ?? null;
    $bankCode = $dva['bank']['slug'] ?? null;


    if (!$accountNumber) {
        throw new Exception(
            'Paystack did not return an account number.'
        );
    }


    /*
    |--------------------------------------------------------------------------
    | Save DVA Information
    |--------------------------------------------------------------------------
    */

    $update = $pdo->prepare("
        UPDATE customers
        SET
            paystack_dva_id = ?,
            paystack_account_number = ?,
            paystack_account_name = ?,
            paystack_bank_name = ?,
            paystack_bank_code = ?
        WHERE id = ?
    ");

    $update->execute([
        $dvaId,
        $accountNumber,
        $accountName,
        $bankName,
        $bankCode,
        $customer['id']
    ]);


    /*
    |--------------------------------------------------------------------------
    | Display Result
    |--------------------------------------------------------------------------
    */

    echo '<h2>Paystack Test DVA Created Successfully</h2>';

    echo '<p><strong>PPay Customer:</strong> ' .
        htmlspecialchars($customer['full_name']) .
        '</p>';

    echo '<p><strong>Paystack Customer Code:</strong> ' .
        htmlspecialchars($customer['paystack_customer_code']) .
        '</p>';

    echo '<hr>';

    echo '<p><strong>DVA ID:</strong> ' .
        htmlspecialchars((string)$dvaId) .
        '</p>';

    echo '<p><strong>Account Name:</strong> ' .
        htmlspecialchars((string)$accountName) .
        '</p>';

    echo '<p><strong>Account Number:</strong> ' .
        htmlspecialchars((string)$accountNumber) .
        '</p>';

    echo '<p><strong>Bank:</strong> ' .
        htmlspecialchars((string)$bankName) .
        '</p>';

    echo '<p><strong>Bank Code:</strong> ' .
        htmlspecialchars((string)$bankCode) .
        '</p>';


} catch (Throwable $e) {

    http_response_code(500);

    echo '<h2>Paystack DVA Test Failed</h2>';

    echo '<p style="color:red;">' .
        htmlspecialchars($e->getMessage()) .
        '</p>';
}