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

if (!isset($_SESSION['user_id'])) {
    die("Unauthorized access");
}

$user_id = $_SESSION['user_id'];

/* ================= GET PARENT ================= */
$stmt = $conn->prepare("SELECT parent_id FROM parents WHERE user_id=?");
$stmt->bind_param("i", $user_id);
$stmt->execute();
$parent_id = $stmt->get_result()->fetch_assoc()['parent_id'] ?? 0;

if (!$parent_id) {
    die("Parent not found");
}

/* ================= FLUTTERWAVE RESPONSE ================= */
$transaction_id = $_GET['transaction_id'] ?? null;
$tx_ref         = $_GET['tx_ref'] ?? null;

if (!$transaction_id || !$tx_ref) {
    die("Invalid payment reference.");
}

/* ================= VERIFY PAYMENT ================= */
$secret_key = "FLWSECK-e24cc29ecd485a60ab7ac51272c71cf0-19974cfc5bfvt-X";

$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",
        "Content-Type: application/json"
    ]
]);

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

$result = json_decode($response, true);

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

$data = $result['data'];

/* ================= CONFIRM STATUS ================= */
if ($data['status'] !== 'successful') {
    die("Payment not successful.");
}

$amount = $data['amount'];
$currency = $data['currency'];

/* ================= GENERATE RECEIPT ================= */
$receipt_no = "RC-" . date("Y") . rand(100000, 999999);

/* ================= GET STUDENT ================= */
/* IMPORTANT: tx_ref should contain student_id */
$student_id = intval($data['meta']['student_id'] ?? 0);

if (!$student_id) {
    die("Student not found in transaction metadata.");
}

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

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

/* ================= UPDATE STUDENT BALANCE ================= */
$conn->query("
UPDATE students 
SET fees_paid = fees_paid + $amount,
    fees_outstanding = fees_outstanding - $amount
WHERE student_id = $student_id
");

?>

<!DOCTYPE html>
<html>
<head>
<title>Payment Successful</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: <strong><?= $receipt_no ?></strong></p>
        <p>Amount Paid: <strong>₦<?= number_format($amount, 2) ?></strong></p>
    </div>

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

        <a href="dashboard.php" class="btn btn-secondary">
            Back to Dashboard
        </a>
    </div>
</div>

</body>
</html>