<?php
include('includes/session2.php');
error_reporting(0);
require_once 'vendor/autoload.php';
include('includes/dbconnection.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'])|| !isset($_GET['cls']) || !isset($_GET['school_type'])) {
    echo "Invalid request. Missing parameters.";
    exit;
}

$reference = $_GET['reference'];
$studentno = $_GET['studentno'];
$email = $_GET['email'];
$studentName = $_GET['studentName'];
$stdid = $_GET['stdid'];
$cls = $_GET['cls'];
$school_type = $_GET['school_type'];
$session = $_GET['session'];
$paymentMethod = "Paystack";
$tabSessionID = $_GET['tab_id']; // Tab ID


// 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

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

    do {
        $attempt++;

        // Check if payment with the same 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 existing record
            $paymentQuery = "UPDATE payments SET 
                student_id = '$stdid',
                studentno = '$studentno',
                studentName = '$studentName',
                email = '$email',
                amount = $amountPaid,
                status = 'approved',
                fee_type = '$feeType',
                payment_date = NOW(),
                payment_method = '$paymentMethod',
                session_id = '$session'
            WHERE reference = '$reference'";
        } else {
            // INSERT new payment
            $paymentQuery = "INSERT INTO payments 
                (student_id, studentno, studentName, email, reference, amount, status, fee_type, payment_date, payment_method, session_id) 
            VALUES 
                ('$stdid', '$studentno', '$studentName', '$email', '$reference', $amountPaid, 'approved', '$feeType', NOW(), '$paymentMethod', '$session')";
        }

        $result = mysqli_query($con, $paymentQuery);

        if ($result) {
            // 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,
                'class' => $cls,
                'school_type' => $school_type,
                'session' => $session,
                'tab_id' => $tabSessionID
            ];

            header("Location: confirmpaymententrancecert.php?tab_id=$tabSessionID"); exit;
            $success = true;
            exit;
        } else {
            $errorMsg = mysqli_error($con);
            error_log('Payment save error: ' . $errorMsg); // Log the error
        }

        if ($attempt >= $retryLimit) {
            echo "<script>
                alert('Error saving payment after $retryLimit attempts: $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;
}
?>
