<?php
require_once 'config/database.php';

echo "Debugging missing payment for transaction CJM6I74RX...\n\n";

// Get the specific transaction
$stmt = $pdo->prepare("
    SELECT bt.*, s.first_name, s.last_name, s.student_id as student_code, ba.bank_name, ba.branch_name
    FROM bank_transactions bt
    JOIN students s ON bt.student_id = s.id
    JOIN bank_accounts ba ON bt.bank_account_id = ba.id
    WHERE bt.transaction_id = ?
");
$stmt->execute(['CJM6I74RX']);
$transaction = $stmt->fetch();

if ($transaction) {
    echo "Transaction Details:\n";
    print_r($transaction);
    
    echo "\nChecking fees for this student...\n";
    $stmt = $pdo->prepare("
        SELECT *
        FROM fees
        WHERE student_id = ?
        ORDER BY due_date ASC
    ");
    $stmt->execute([$transaction['student_id']]);
    $fees = $stmt->fetchAll();
    
    echo "Found " . count($fees) . " fees for this student:\n";
    foreach ($fees as $fee) {
        $due_amount = $fee['amount'] - $fee['paid_amount'];
        echo "  - " . $fee['fee_type'] . " " . $fee['month'] . ", Amount: " . $fee['amount'] . ", Paid: " . $fee['paid_amount'] . ", Due: " . $due_amount . ", Status: " . $fee['status'] . "\n";
    }
    
    // Check if there are any fee_payments with this transaction_id
    echo "\nChecking for fee_payments with this transaction_id...\n";
    $stmt = $pdo->prepare("
        SELECT fp.*, f.fee_type, f.month
        FROM fee_payments fp
        JOIN fees f ON fp.fee_id = f.id
        WHERE fp.transaction_id = ?
    ");
    $stmt->execute([$transaction['transaction_id']]);
    $payments = $stmt->fetchAll();
    
    if (count($payments) > 0) {
        echo "Found " . count($payments) . " fee payment(s):\n";
        foreach ($payments as $payment) {
            echo "  - Fee: " . $payment['fee_type'] . " " . $payment['month'] . ", Amount: " . $payment['amount'] . ", Date: " . $payment['payment_date'] . "\n";
        }
    } else {
        echo "NO FEE PAYMENTS FOUND FOR THIS TRANSACTION!\n";
    }
} else {
    echo "Transaction not found!\n";
}

echo "\nDone.\n";
?>