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

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

$transaction_id = $_GET['transaction_id'] ?? null;

if (!$transaction_id) {
    die("Invalid transaction");
}

/* VERIFY PAYMENT */
$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_key"
    ]
]);

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

$result = json_decode($response, true);

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

$data = $result['data'];

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

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

$receipt_no = "RCP-" . date("Y") . rand(1000,9999);

/* ================= GET STUDENT BALANCE ================= */
$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();

$new_paid = $student['fees_paid'] + $amount;
$new_balance = $student['fees_outstanding'] - $amount;

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

/* ================= INSERT INTO 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;

/* ================= RECEIPT TABLE ================= */
$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();

/* ================= INSTALLMENT LEDGER ================= */
$balance_after = $new_balance;
$payment_method = "Flutterwave";

$stmt = $conn->prepare("
INSERT INTO installment_payments 
(student_id, amount_paid, balance_after, payment_method, reference, receipt_no, created_at)
VALUES (?, ?, ?, ?, ?, ?, NOW())
");

$stmt->bind_param(
    "idssss",
    $student_id,
    $amount,
    $balance_after,
    $payment_method,
    $reference,
    $receipt_no
);

$stmt->execute();

?>

<!DOCTYPE html>
<html>
<head>
<title>Payment Success</title>
<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">

    <div class="alert alert-success text-center">
        <h3>Payment Successful 🎉</h3>
        <p>Receipt No: <b><?= $receipt_no ?></b></p>
        <p>Amount Paid: <b>₦<?= number_format($amount,2) ?></b></p>
        <p>Balance Left: <b>₦<?= number_format($balance_after,2) ?></b></p>
    </div>

    <div class="text-center">
        <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 Dashboard
        </a>
    </div>

</div>

</body>
</html>