<?php
error_reporting(E_ALL);
ini_set('display_errors', 1);
session_start();
include "../include/config.php";



// Check if student ID is provided
if (!isset($_POST['studentid']) || empty($_POST['studentid'])) {
    echo json_encode(['error' => 'No student ID provided']);
    exit();
}

$studentId = mysqli_real_escape_string($conn, $_POST['studentid']);

// Get student details
$studentQuery = "SELECT * FROM students WHERE studentid = '$studentId'";
$studentResult = mysqli_query($conn, $studentQuery);

if (!$studentResult || mysqli_num_rows($studentResult) === 0) {
    echo json_encode(['error' => 'Student not found']);
    exit();
}

$student = mysqli_fetch_assoc($studentQuery);

// Check fee clearance status
function checkFeeClearance($conn, $studentid) {
    // Get total fees required
    $feeQuery = "SELECT SUM(amount) as total_fees FROM balances WHERE intake = (SELECT intake FROM students WHERE studentid = '$studentid' LIMIT 1)";
    $feeResult = mysqli_query($conn, $feeQuery);
    $feeData = mysqli_fetch_assoc($feeResult);
    $totalFees = $feeData['total_fees'] ?? 0;
    
    // Get total payments made
    $paymentQuery = "SELECT SUM(amount) as total_paid FROM payments WHERE studentid = '$studentid' AND status = 'paid'";
    $paymentResult = mysqli_query($conn, $paymentQuery);
    $paymentData = mysqli_fetch_assoc($paymentResult);
    $totalPaid = $paymentData['total_paid'] ?? 0;
    
    // Calculate percentage paid
    $percentagePaid = 0;
    if ($totalFees > 0) {
        $percentagePaid = ($totalPaid / $totalFees) * 100;
    }
    
    return [
        'fee_cleared' => $percentagePaid >= 75,
        'percentage' => round($percentagePaid, 2),
        'total_fees' => $totalFees,
        'total_paid' => $totalPaid,
        'balance' => $totalFees - $totalPaid
    ];
}

$feeStatus = checkFeeClearance($conn, $studentId);

// Combine student data with fee status
$response = array_merge($student, $feeStatus);

// Return JSON response
header('Content-Type: application/json');
echo json_encode($response);
?>