<?php
session_start();
include '../../includes/db_connection.php';
header('Content-Type: application/json');

if (!isset($_SESSION['user_id'])) {
    echo json_encode(['status' => 'error', 'message' => 'Unauthorized']);
    exit();
}

if (isset($_GET['payment_id'])) {
    $payment_id = $_GET['payment_id'];
    
    $sql = "SELECT f.student_id, f.amount, f.payment_date, f.payment_method, f.fee_month, s.first_name, s.last_name, c.class_name, ic.category_name
            FROM fees f
            JOIN students s ON f.student_id = s.student_id
            JOIN classes c ON s.class_id = c.class_id
            JOIN income_categories ic ON f.category_id = ic.category_id
            WHERE f.payment_id = ?";
            
    $stmt = $conn->prepare($sql);
    $stmt->bind_param("i", $payment_id);
    $stmt->execute();
    $result = $stmt->get_result();
    
    if ($result->num_rows > 0) {
        $data = $result->fetch_assoc();
        $data['student_name'] = $data['first_name'] . ' ' . $data['last_name'];
        unset($data['first_name'], $data['last_name']);
        
        echo json_encode(['status' => 'success', 'data' => $data]);
    } else {
        echo json_encode(['status' => 'error', 'message' => 'Fee record not found.']);
    }
    
    $stmt->close();
} else {
    echo json_encode(['status' => 'error', 'message' => 'Invalid request.']);
}

$conn->close();
?>