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

echo "Checking verified transactions and their corresponding fee payments...\n\n";

// Get verified bank transactions
$stmt = $pdo->query("
    SELECT bt.*, s.first_name, s.last_name, s.student_id as student_code
    FROM bank_transactions bt
    JOIN students s ON bt.student_id = s.id
    WHERE bt.status = 'verified'
    ORDER BY bt.verified_at DESC
    LIMIT 5
");
$transactions = $stmt->fetchAll();

echo "Found " . count($transactions) . " verified transactions:\n\n";

foreach ($transactions as $transaction) {
    echo "Transaction ID: " . $transaction['transaction_id'] . "\n";
    echo "Student: " . $transaction['first_name'] . " " . $transaction['last_name'] . " (" . $transaction['student_code'] . ")\n";
    echo "Amount: " . $transaction['amount'] . "\n";
    echo "Verified at: " . $transaction['verified_at'] . "\n";
    
    // Check if there are fee_payments with this transaction_id
    $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 = ?
        ORDER BY fp.created_at DESC
    ");
    $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";
    }
    
    // Also check fees for this student to see if they were updated
    $stmt = $pdo->prepare("
        SELECT *
        FROM fees
        WHERE student_id = ?
        ORDER BY updated_at DESC
        LIMIT 5
    ");
    $stmt->execute([$transaction['student_id']]);
    $fees = $stmt->fetchAll();
    
    echo "Recent fees for this student:\n";
    foreach ($fees as $fee) {
        echo "  - " . $fee['fee_type'] . " " . $fee['month'] . ", Amount: " . $fee['amount'] . ", Paid: " . $fee['paid_amount'] . ", Status: " . $fee['status'] . "\n";
    }
    
    echo str_repeat("-", 50) . "\n\n";
}

echo "Done.\n";
?>