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

if (!isset($_SESSION['user_id'])) {
    header("Location: parent_login.php");
    exit();
}

$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'];

/* INPUT */
$student_id = $_POST['student_id'];
$amount = $_POST['amount'];

/* VALIDATE STUDENT */
$stmt = $conn->prepare("SELECT * FROM students WHERE student_id=? AND parent_id=?");
$stmt->bind_param("ii", $student_id, $parent_id);
$stmt->execute();
$student = $stmt->get_result()->fetch_assoc();

if (!$student) {
    die("Invalid student");
}

/* TX REF */
$tx_ref = "FEE_" . time() . "_" . $student_id;

/* STORE SESSION */
$_SESSION['tx_ref'] = $tx_ref;
$_SESSION['amount'] = $amount;

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

$data = [
    "tx_ref" => $tx_ref,
    "amount" => $amount,
    "currency" => "NGN",
    "redirect_url" => "http://localhost/CSMS/parent/flutterwave_verify.php",
    "customer" => [
        "email" => "parent@email.com",
        "name" => $student['name']
    ],
    "meta" => [
        "student_id" => $student_id,
        "parent_id" => $parent_id
    ]
];

$curl = curl_init();

curl_setopt_array($curl, [
    CURLOPT_URL => "https://api.flutterwave.com/v3/payments",
    CURLOPT_RETURNTRANSFER => true,
    CURLOPT_POST => true,
    CURLOPT_POSTFIELDS => json_encode($data),
    CURLOPT_HTTPHEADER => [
        "Authorization: Bearer $secret",
        "Content-Type: application/json"
    ]
]);

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

$res = json_decode($response, true);

if ($res['status'] === 'success') {
    header("Location: " . $res['data']['link']);
    exit();
}

die("Payment initialization failed");