<?php
// Load Composer Autoloader
require_once 'vendor/autoload.php';

// Load Environment Variables
$dotenv = Dotenv\Dotenv::createImmutable(__DIR__);
$dotenv->load();

// Retrieve Paystack Secret Key
$paystackSecretKey = getenv('PAYSTACK_SECRET_KEY');
$paystackUrl = getenv('PAYSTACK_PAYMENT_URL');

// Check if reference is provided
if (isset($_GET['reference'])) {
    $reference = $_GET['reference'];

    // Verify the transaction
    $curl = curl_init();
    curl_setopt_array($curl, [
        CURLOPT_URL => "$paystackUrl/transaction/verify/$reference",
        CURLOPT_RETURNTRANSFER => true,
        CURLOPT_HTTPHEADER => [
            "Authorization: Bearer $paystackSecretKey",
            "Content-Type: application/json",
        ],
    ]);

    $response = curl_exec($curl);
    $err = curl_error($curl);
    curl_close($curl);

    if ($err) {
        die("Error verifying transaction: " . $err);
    }

    // Decode the Paystack response
    $transaction = json_decode($response, true);

    if (!$transaction || !isset($transaction['status'])) {
        die("Invalid response from Paystack: " . $response);
    }

    if ($transaction['status'] && $transaction['data']['status'] === 'success') {
        // Payment was successful
        echo "<h1>Payment Successful</h1>";
        echo "<p>Reference: " . $transaction['data']['reference'] . "</p>";
        echo "<p>Amount Paid: ₦" . ($transaction['data']['amount'] / 100) . "</p>";
        echo "<p>Status: " . $transaction['data']['status'] . "</p>";

        // Update your database here (e.g., save $transaction['data'] details)
    } else {
        // Payment failed
        echo "<h1>Payment Failed</h1>";
        echo "<p>Error Message: " . $transaction['message'] . "</p>";
    }
} else {
    echo "<h1>Invalid Request</h1>";
}
?>
