<?php
include('includes/session.php');
error_reporting();
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'];
$paymentMethod = "Paystack"; // Payment method
$status = "approved"; // Payment status
$tabSessionID = $_GET['tab_id']; // Tab ID
$term = $_GET['term'];
$session = $_GET['session'];


// 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
    $metadata = $responseData['data']['metadata']['custom_fields'];

    $feeType = '';
    $discountUsed = 'No';
    $discountAmount = 0;
    $discountPercent = 0;

    foreach ($metadata as $field) {
        if ($field['display_name'] === 'Fees Type') {
            $feeType = $field['value'];
        } elseif ($field['display_name'] === 'Used Discount') {
            $discountUsed = $field['value'];
        } elseif ($field['display_name'] === 'Discount Amount') {
            $discountAmount = $field['value'];
        } elseif ($field['display_name'] === 'Discount Percent') {
            $discountPercent = $field['value'];
        }
    }

    $retryLimit = 5; // Maximum retry attempts
    $attempt = 0;
    $success = false;
do {
    $attempt++;

    // Check if payment with this reference already exists
    $checkQuery = "SELECT id FROM payments WHERE reference = '$reference' LIMIT 1";
    $checkResult = mysqli_query($con, $checkQuery);

    if (mysqli_num_rows($checkResult) > 0) {
        // UPDATE the existing payment
        $paymentQuery = "UPDATE payments SET 
            student_id = '$stdid',
            studentno = '$studentno',
            studentName = '$studentName',
            email = '$email',
            amount = $amountPaid,
            status = 'approved',
            fee_type = '$feeType',
            payment_date = NOW(),
            discount_used = '$discountUsed',
            discount_amount = '$discountAmount',
            discount_percent = '$discountPercent',
            payment_method = '$paymentMethod',
            term_id = '$term',
            session_id = '$session'
        WHERE reference = '$reference'";
    } else {
        // INSERT new payment record
        $paymentQuery = "INSERT INTO payments 
            (student_id, studentno, studentName, email, reference, amount, status, fee_type, payment_date, 
            discount_used, discount_amount, discount_percent, payment_method, term_id, session_id) 
        VALUES 
            ('$stdid', '$studentno', '$studentName', '$email', '$reference', $amountPaid, 'approved', '$feeType', NOW(), 
            '$discountUsed', '$discountAmount', '$discountPercent', '$paymentMethod', '$term', '$session')";
    }

    if (mysqli_query($con, $paymentQuery)) {
        // Store payment details in session
        $_SESSION['payment_details'] = [
            'transaction_id' => $reference,
            'amount' => $amountPaid,
            'email' => $email,
            'payment_method' => $paymentMethod,
            'status' => 'approved',
            'student_no' => $studentno,
            'student_name' => $studentName,
            'fee_type' => $feeType,
            'tab_id' => $tabSessionID,
            'term' => $term,
            'session' => $session,
            'discount_used' => $discountUsed,
            'discount_amount' => $discountAmount,
            'discount_percent' => $discountPercent
        ];

        header("Location: confirmpaymentoldboard.php?tab_id=$tabSessionID"); exit;
        $success = true;
        exit;
    } else {
        $errorMsg = mysqli_error($con);
        error_log("Database error on attempt $attempt: $errorMsg");
        if ($attempt >= $retryLimit) {
            echo "<script>
                alert('Error saving payment: $errorMsg');
                window.history.back();
            </script>";
            exit;
        }
    }
} while (!$success);

} 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;
}
