<?php
include('includes/dbconnection.php');
require_once __DIR__ . '/includes/session_term_helper.php';

$stResult = resolveCurrentSessionTerm($con);
$currentSessionId = $stResult['session_id'];
$currentSessionName = $stResult['session_name'];
$currentTermId = $stResult['term_id'];
$currentTermName = $stResult['term_name'];

// Process POST request
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $student_id = $_POST['student_id'];
    $studentno = $_POST['studentno'];
    $studentName = $_POST['studentName'];
    $email = $_POST['email'];
    $amount = floatval($_POST['amount']);
    $fee_type = $_POST['feeType'];
    $term_id = $_POST['term_id'] ?? $currentTermId;
    $session_id = $_POST['session_id'] ?? $currentSessionId;
    $discount_used = $_POST['discount_used'];
    $discount_amount = floatval($_POST['discount_amount']);
    $discount_percent = floatval($_POST['discount_percent']);
    $status = $_POST['status'];
    $class = $_POST['class'];
    $school_type = $_POST['school_type'] ?? 'Day';
    $payment_date = date('Y-m-d H:i:s');

    $query = "INSERT INTO initiate_paymentsss 
        (student_id, studentno, studentName, email, amount, fee_type, class, school_type, 
         term_id, session_id, discount_used, discount_amount, discount_percent, status, payment_date) 
        VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)";

    $stmt = $con->prepare($query);
    $stmt->bind_param(
        "issssdssssddsss",
        $student_id,
        $studentno,
        $studentName,
        $email,
        $amount,
        $fee_type,
        $class,
        $school_type,
        $term_id,
        $session_id,
        $discount_used,
        $discount_amount,
        $discount_percent,
        $status,
        $payment_date
    );

    if ($stmt->execute()) {
        echo json_encode(["success" => true]);
    } else {
        http_response_code(500);
        echo json_encode(["error" => "Failed to insert payment record."]);
    }

    $stmt->close();
}
?>