<?php
include('includes/session.php');
error_reporting(0);
include('includes/dbconnection.php');
require_once 'vendor/autoload.php';

// Check if the reference and other details are present
if (!isset($_GET['reference']) || !isset($_GET['studentno']) || !isset($_GET['email']) || !isset($_GET['studentName']) || !isset($_GET['stdid'])) {
    echo "Invalid request. Missing parameters.";
    exit;
}

$reference = $_GET['reference'];
$studentno = $_GET['studentno'];
$email =$_GET['email'];
$studentName = $_GET['studentName'];
$stdid = $_GET['stdid'];

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

$paystackSecretKey = $_ENV['PAYSTACK_SECRET_KEY']; // Secret key for Paystack API

// Verify payment via Paystack API
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, "https://api.paystack.co/transaction/verify/" . $reference);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_HTTPHEADER, [
    "Authorization: Bearer $paystackSecretKey",
    "Content-Type: application/json"
]);
$response = curl_exec($ch);
curl_close($ch);

$responseData = json_decode($response, true);

// Check if the transaction was successful
if ($responseData['status'] && $responseData['data']['status'] === 'success') {
    $amountPaid = $responseData['data']['amount'] / 100; // Convert from kobo to NGN
    $feeType = $responseData['data']['metadata']['custom_fields'][0]['value']; // Fee type metadata

    // Payment query to be retried in case of failure
    $paymentQuery = "INSERT INTO payments (student_id,studentno, studentName, email, reference, amount, status, fee_type, payment_date) 
                     VALUES ('$stdid','$studentno', '$studentName','$email', '$reference', $amountPaid, 'approved', '$feeType', NOW())";

    $retryLimit = 5;
    $attempt = 0;
    $success = false;

    do {
        $attempt++;
        $result = mysqli_query($con, $paymentQuery);
        if ($result) {
            $success = true;
            // Display success message as an alert
            echo "<script>
                alert('Payment successful. Reference: $reference');
                window.location.href = 'confirmpaymentold1.php'; // Redirect after alert
            </script>";
            exit;
        } else {
            $errorMsg = mysqli_error($con);
            error_log('Payment save error: ' . $errorMsg); // Log the error for further investigation
        }

        if ($attempt >= $retryLimit) {
            // Display error saving payment as an alert after retries exhausted
            echo "<script>
                alert('Error saving payment after $retryLimit attempts: $errorMsg');
                window.history.back(); // Go back to the previous page
            </script>";
            exit;
        }
    } while (!$result);
} else {
    // Display payment verification error as an alert
    $errorMessage = isset($responseData['message']) ? $responseData['message'] : "Transaction failed.";
    echo "<script>
        alert('Payment verification failed: $errorMessage');
        window.history.back(); // Go back to the previous page
    </script>";
    exit;
}
?>
