<?php
session_start();
require 'db_connection.php';

$secret = "FLWSECK-e24cc29ecd485a60ab7ac51272c71cf0-19974cfc5bfvt-X";

/* GET FLUTTERWAVE DATA */
$transaction_id = $_GET['transaction_id'] ?? null;
$status = $_GET['status'] ?? null;
$tx_ref = $_GET['tx_ref'] ?? null;

if (!$transaction_id) {
    die("Invalid payment reference (missing transaction_id)");
}

/* CALL FLUTTERWAVE VERIFY API */
$url = "https://api.flutterwave.com/v3/transactions/$transaction_id/verify";

$curl = curl_init();

curl_setopt_array($curl, [
    CURLOPT_URL => $url,
    CURLOPT_RETURNTRANSFER => true,
    CURLOPT_HTTPHEADER => [
        "Authorization: Bearer $secret"
    ]
]);

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

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

$result = json_decode($response, true);

/* DEBUG (IMPORTANT) */
// Uncomment this if error continues
// echo "<pre>"; print_r($result); exit;

/* VALIDATE RESPONSE */
if (!isset($result['status'])) {
    die("Invalid API response from Flutterwave");
}

if ($result['status'] !== 'success') {
    die("Payment verification failed (API rejected)");
}

/* GET PAYMENT DATA */
$data = $result['data'];

if ($data['status'] !== 'successful') {
    die("Transaction not successful");
}

/* ================= DATA ================= */
$student_id = $data['meta']['student_id'];
$parent_id  = $data['meta']['parent_id'];
$amount     = $data['amount'];

$receipt_no = "RCP-" . time();

/* ================= GET STUDENT ================= */
$stmt = $conn->prepare("
SELECT fees_paid, fees_outstanding 
FROM students 
WHERE student_id=?
");
$stmt->bind_param("i", $student_id);
$stmt->execute();
$student = $stmt->get_result()->fetch_assoc();

/* ================= UPDATE BALANCE ================= */
$new_paid = $student['fees_paid'] + $amount;
$new_outstanding = max(0, $student['fees_outstanding'] - $amount);

$stmt = $conn->prepare("
UPDATE students 
SET fees_paid=?, fees_outstanding=? 
WHERE student_id=?
");
$stmt->bind_param("ddi", $new_paid, $new_outstanding, $student_id);
$stmt->execute();

/* ================= PAYMENTS ================= */
$stmt = $conn->prepare("
INSERT INTO payments (student_id, amount, purpose, date, receipt_no, created_at)
VALUES (?, ?, 'School Fees', NOW(), ?, NOW())
");
$stmt->bind_param("ids", $student_id, $amount, $receipt_no);
$stmt->execute();

$payment_id = $stmt->insert_id;

/* ================= RECEIPTS ================= */
$stmt = $conn->prepare("
INSERT INTO receipts (student_id, payment_id, receipt_no, date, created_at)
VALUES (?, ?, ?, NOW(), NOW())
");
$stmt->bind_param("iis", $student_id, $payment_id, $receipt_no);
$stmt->execute();

/* ================= SUCCESS ================= */
?>

<!DOCTYPE html>
<html>
<head>
<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css" rel="stylesheet">
</head>

<body class="bg-light">

<div class="container mt-5 text-center">

<div class="alert alert-success">
<h3>Payment Successful 🎉</h3>

<p><b>Receipt:</b> <?= $receipt_no ?></p>
<p><b>Amount:</b> ₦<?= number_format($amount) ?></p>
<p><b>New Balance:</b> ₦<?= number_format($new_outstanding) ?></p>
</div>

<a href="receipt.php?receipt_no=<?= $receipt_no ?>" class="btn btn-primary">
Download Receipt
</a>

<a href="parent_dashboard.php" class="btn btn-secondary">
Back
</a>

</div>

</body>
</html>