<?php
require_once '../models/db_connection.php';

if (isset($_GET['studentID'])) {
    $studentID = $_GET['studentID'];

    // Fetch the course price based on student enrollment
    $courseQuery = mysqli_query($conn, "SELECT fees.ammount  
                                        FROM student_course 
                                        JOIN fees ON student_course.course_id = fees.id 
                                        WHERE student_course.s_id = '$studentID'");

    // Fetch the course price from the query
    $courseData = mysqli_fetch_assoc($courseQuery);
    $coursePrice = $courseData['ammount'];

    // Fetch total payments made by the student
    $paymentsQuery = mysqli_query($conn, "SELECT SUM(student_payments.amount) as totalPaid
                                          FROM student_payments 
                                          JOIN students ON student_payments.st_id = students.student_id 
                                          WHERE students.en_id = '$studentID'");
    $paymentsData = mysqli_fetch_assoc($paymentsQuery);
    $totalPaid = $paymentsData['totalPaid'] ?? 0; // Handle case if no payment exists

    // Calculate remaining balance
    $remainingBalance = $coursePrice - $totalPaid;

    // Send response back as JSON
    echo json_encode([
        'coursePrice' => $coursePrice,
        'totalPaid' => $totalPaid,
        'remainingBalance' => $remainingBalance
    ]);
}
