<?php
session_start();
require_once '../config/database.php';

// Check if user is admin
if (!isset($_SESSION['user_id']) || $_SESSION['user_role'] !== 'admin') {
    header('Location: ../login.php');
    exit();
}

$user_role = $_SESSION['user_role'] ?? 'guest';
$user_name = $_SESSION['username'] ?? 'Unknown';

// Handle transaction status updates
$message = '';
$message_type = '';

// Handle view parameter - show receipt
$view_transaction = null;
if (isset($_GET['view'])) {
    try {
        $transaction_id = (int)$_GET['view'];
        
        // Fetch transaction with student and bank details
        $stmt = $pdo->prepare("
            SELECT bt.*, s.first_name, s.last_name, s.student_id as student_code, 
                   ba.bank_name, ba.branch_name, ba.account_number,
                   u.username as verified_by_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
            LEFT JOIN users u ON bt.verified_by = u.id
            WHERE bt.id = ?
        ");
        $stmt->execute([$transaction_id]);
        $view_transaction = $stmt->fetch();
        
        if (!$view_transaction) {
            $message = 'ট্রানজেকশন খুঁজে পাওয়া যায়নি';
            $message_type = 'danger';
        }
    } catch (Exception $e) {
        $message = 'ত্রুটি: ' . $e->getMessage();
        $message_type = 'danger';
    }
}

// Update transaction status
if (isset($_POST['update_status'])) {
    try {
        $transaction_id = (int)$_POST['transaction_id'];
        $status = $_POST['status'];
        $admin_notes = trim($_POST['admin_notes']);
        
        // Validate status
        if (!in_array($status, ['pending', 'verified', 'rejected'])) {
            throw new Exception("Invalid status");
        }
        
        // When verifying a transaction, we need to update the related fees
        if ($status === 'verified') {
            // Begin transaction
            $pdo->beginTransaction();
            
            try {
                // Get transaction details
                $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.id = ? AND bt.status = 'pending'
                ");
                $stmt->execute([$transaction_id]);
                $transaction = $stmt->fetch();
                
                if (!$transaction) {
                    throw new Exception("Transaction not found or already processed");
                }
                
                // Check if this transaction ID has already been used for any student (both pending and verified)
                $stmt = $pdo->prepare("
                    SELECT bt.id, s.first_name, s.last_name, s.student_id as student_code, bt.status
                    FROM bank_transactions bt
                    JOIN students s ON bt.student_id = s.id
                    WHERE bt.transaction_id = ? AND bt.id != ?
                ");
                $stmt->execute([$transaction['transaction_id'], $transaction_id]);
                $existing_transactions = $stmt->fetchAll();
                
                if (!empty($existing_transactions)) {
                    $existing = $existing_transactions[0];
                    $status_text = ($existing['status'] === 'verified') ? 'verified' : 'pending';
                    throw new Exception("This transaction ID has already been used for student " . 
                        $existing['student_code'] . " (" . 
                        $existing['first_name'] . " " . 
                        $existing['last_name'] . ") with status '" . $status_text . "'. " .
                        "The same transaction cannot be accepted multiple times.");
                }
                
                // Check if there are specific fees selected for this transaction
                $stmt = $pdo->prepare("
                    SELECT fee_id FROM bank_transaction_selected_fees WHERE transaction_id = ?
                ");
                $stmt->execute([$transaction_id]);
                $selected_fees = $stmt->fetchAll(PDO::FETCH_COLUMN);
                
                if (!empty($selected_fees)) {
                    // Use only the selected fees
                    $placeholders = str_repeat('?,', count($selected_fees) - 1) . '?';
                    $stmt = $pdo->prepare("
                        SELECT id, amount, paid_amount 
                        FROM fees 
                        WHERE student_id = ? AND id IN ($placeholders) AND status IN ('pending', 'partial', 'overdue') 
                        ORDER BY FIELD(id, $placeholders)
                    ");
                    
                    // Prepare parameters for the query
                    $params = [$transaction['student_id']];
                    $params = array_merge($params, $selected_fees);
                    $params = array_merge($params, $selected_fees);
                    
                    $stmt->execute($params);
                    $due_fees = $stmt->fetchAll();
                } else {
                    // Use all due fees (fallback to original behavior)
                    $stmt = $pdo->prepare("
                        SELECT id, amount, paid_amount 
                        FROM fees 
                        WHERE student_id = ? AND status IN ('pending', 'partial', 'overdue') 
                        ORDER BY due_date ASC
                    ");
                    $stmt->execute([$transaction['student_id']]);
                    $due_fees = $stmt->fetchAll();
                }
                
                $remaining_amount = (float)$transaction['amount'];
                $updated_fees = [];
                
                foreach ($due_fees as $fee) {
                    if ($remaining_amount <= 0) break;
                    
                    $due_amount = $fee['amount'] - $fee['paid_amount'];
                    $payment_amount = min($remaining_amount, $due_amount);
                    
                    $new_paid_amount = $fee['paid_amount'] + $payment_amount;
                    $new_status = ($new_paid_amount >= $fee['amount']) ? 'paid' : 'partial';
                    
                    $stmt = $pdo->prepare("
                        UPDATE fees 
                        SET paid_amount = ?, status = ?, paid_date = IF(paid_date IS NULL, CURDATE(), paid_date)
                        WHERE id = ?
                    ");
                    $stmt->execute([$new_paid_amount, $new_status, $fee['id']]);
                    
                    // Insert payment record for this specific fee
                    $ins = $pdo->prepare("
                        INSERT INTO fee_payments (fee_id, amount, payment_date, payment_method, transaction_id, notes, created_by) 
                        VALUES (?, ?, NOW(), ?, ?, ?, ?)
                    ");
                    $ins->execute([
                        $fee['id'], 
                        $payment_amount, 
                        'bank', 
                        $transaction['transaction_id'], 
                        'Bank payment to ' . $transaction['bank_name'] . ' - ' . $transaction['branch_name'] . '. Verified by admin. Notes: ' . $admin_notes, 
                        $_SESSION['user_id'] ?? null
                    ]);
                    
                    $remaining_amount -= $payment_amount;
                    $updated_fees[] = [
                        'fee_id' => $fee['id'],
                        'paid_amount' => $payment_amount
                    ];
                }
                
                // Update the transaction
                $stmt = $pdo->prepare("
                    UPDATE bank_transactions 
                    SET status = ?, verified_at = NOW(), verified_by = ?, notes = ?
                    WHERE id = ?
                ");
                $stmt->execute([$status, $_SESSION['user_id'], $admin_notes, $transaction_id]);
                
                $pdo->commit();
                
                $message = 'ট্রানজেকশন সফলভাবে আপডেট করা হয়েছে এবং পেমেন্ট হিস্টোরীতে যুক্ত করা হয়েছে';
                $message_type = 'success';
            } catch (Exception $e) {
                $pdo->rollBack();
                throw new Exception("Failed to update fee records: " . $e->getMessage());
            }
        } else {
            // For pending or rejected status, just update the transaction
            $stmt = $pdo->prepare("
                UPDATE bank_transactions 
                SET status = ?, verified_at = NOW(), verified_by = ?, notes = ?
                WHERE id = ?
            ");
            $stmt->execute([$status, $_SESSION['user_id'], $admin_notes, $transaction_id]);
            
            $message = 'ট্রানজেকশন সফলভাবে আপডেট করা হয়েছে';
            $message_type = 'success';
        }
    } catch (Exception $e) {
        $message = 'ত্রুটি: ' . $e->getMessage();
        $message_type = 'danger';
    }
}

// Delete transaction
if (isset($_GET['delete'])) {
    try {
        $transaction_id = (int)$_GET['delete'];
        
        // Delete the transaction
        $stmt = $pdo->prepare("DELETE FROM bank_transactions WHERE id = ?");
        $stmt->execute([$transaction_id]);
        
        $message = 'ট্রানজেকশন সফলভাবে মুছে ফেলা হয়েছে';
        $message_type = 'success';
    } catch (Exception $e) {
        $message = 'ত্রুটি: ' . $e->getMessage();
        $message_type = 'danger';
    }
}

// Fetch all bank transactions with student and bank details (only if not viewing a specific transaction)
$transactions = [];
if (!$view_transaction) {
    try {
        // Handle search parameters
        $search_student = isset($_GET['search_student']) ? trim($_GET['search_student']) : '';
        $search_transaction_id = isset($_GET['search_transaction_id']) ? trim($_GET['search_transaction_id']) : '';
        $search_status = isset($_GET['search_status']) ? $_GET['search_status'] : '';
        $search_date_from = isset($_GET['search_date_from']) ? $_GET['search_date_from'] : '';
        $search_date_to = isset($_GET['search_date_to']) ? $_GET['search_date_to'] : '';
        
        // Build query with search conditions
        $sql = "SELECT bt.*, s.first_name, s.last_name, s.student_id as student_code, 
                ba.bank_name, ba.branch_name, ba.account_number,
                u.username as verified_by_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
                LEFT JOIN users u ON bt.verified_by = u.id";
        
        $where_conditions = [];
        $params = [];
        
        if (!empty($search_student)) {
            $where_conditions[] = "(s.first_name LIKE :student_name OR s.last_name LIKE :student_name OR s.student_id LIKE :student_id)";
            $params[':student_name'] = "%$search_student%";
            $params[':student_id'] = "%$search_student%";
        }
        
        if (!empty($search_transaction_id)) {
            $where_conditions[] = "bt.transaction_id LIKE :transaction_id";
            $params[':transaction_id'] = "%$search_transaction_id%";
        }
        
        if (!empty($search_status)) {
            $where_conditions[] = "bt.status = :status";
            $params[':status'] = $search_status;
        }
        
        if (!empty($search_date_from)) {
            $where_conditions[] = "DATE(bt.submitted_at) >= :date_from";
            $params[':date_from'] = $search_date_from;
        }
        
        if (!empty($search_date_to)) {
            $where_conditions[] = "DATE(bt.submitted_at) <= :date_to";
            $params[':date_to'] = $search_date_to;
        }
        
        if (!empty($where_conditions)) {
            $sql .= " WHERE " . implode(' AND ', $where_conditions);
        }
        
        $sql .= " ORDER BY bt.submitted_at DESC";
        
        $stmt = $pdo->prepare($sql);
        foreach ($params as $key => $value) {
            $stmt->bindValue($key, $value);
        }
        $stmt->execute();
        $transactions = $stmt->fetchAll();
    } catch (Exception $e) {
        $transactions = [];
        $message = 'ত্রুটি: ' . $e->getMessage();
        $message_type = 'danger';
    }
}

// Group transactions by status
$pending_transactions = [];
$verified_transactions = [];
$rejected_transactions = [];

foreach ($transactions as $transaction) {
    switch ($transaction['status']) {
        case 'pending':
            $pending_transactions[] = $transaction;
            break;
        case 'verified':
            $verified_transactions[] = $transaction;
            break;
        case 'rejected':
            $rejected_transactions[] = $transaction;
            break;
    }
}
?>

<!DOCTYPE html>
<html lang="bn">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>ব্যাংক ট্রানজেকশন ম্যানেজমেন্ট - অনুসন্ধান</title>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/css/bootstrap.min.css" rel="stylesheet">
    <link href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.0.0/css/all.min.css" rel="stylesheet">
    <link href="https://fonts.googleapis.com/css2?family=Hind+Siliguri:wght@300;400;500;600;700&display=swap" rel="stylesheet">
    <style>
        body {
            font-family: 'Hind Siliguri', sans-serif;
            background-color: #f8f9fa;
            overflow-x: hidden;
        }
        .card {
            box-shadow: 0 0.125rem 0.25rem rgba(0, 0, 0, 0.075);
            border: 1px solid rgba(0, 0, 0, 0.125);
            border-radius: 0.5rem;
        }
        .card-header {
            background-color: #fff;
            border-bottom: 1px solid rgba(0, 0, 0, 0.125);
            font-weight: 600;
        }
        .table th {
            font-weight: 600;
        }
        .status-pending {
            background-color: #fff3cd;
            color: #856404;
        }
        .status-verified {
            background-color: #d4edda;
            color: #155724;
        }
        .status-rejected {
            background-color: #f8d7da;
            color: #721c24;
        }
        .form-control, .form-select {
            border-radius: 0.375rem;
        }
        .btn {
            border-radius: 0.375rem;
        }
        .navbar {
            box-shadow: 0 0.125rem 0.25rem rgba(0, 0, 0, 0.075);
        }
        .receipt-image {
            max-width: 200px;
            height: auto;
        }
        .receipt-view-container {
            max-width: 800px;
            margin: 0 auto;
        }
        .back-button {
            margin-bottom: 20px;
        }
        .search-highlight {
            background-color: #fff3cd;
            border: 1px solid #ffc107;
            border-radius: 0.375rem;
        }
        .btn-action {
            margin-right: 5px;
            margin-bottom: 5px;
        }
        

    </style>
</head>
<body>
    <div class="container-fluid">
        <header class="navbar navbar-expand-lg navbar-dark bg-primary">
            <div class="container-fluid">
                <a class="navbar-brand" href="../index.php">
                    <i class="fas fa-graduation-cap"></i> ব্যাংক ট্রানজেকশন ম্যানেজমেন্ট
                </a>
                <div class="navbar-nav ms-auto">
                    <a class="nav-link" href="../index.php"><i class="fas fa-home"></i> হোম</a>
                    <a class="nav-link" href="../logout.php"><i class="fas fa-sign-out-alt"></i> লগআউট</a>
                </div>
            </div>
        </header>

<div class="container-fluid mt-4">
    <div class="row">
        <div class="col-md-12">
            <?php if ($view_transaction): ?>
                <!-- View Receipt -->
                <div class="receipt-view-container">
                    <div class="d-flex justify-content-between align-items-center mb-3">
                        <h3><i class="fas fa-receipt"></i> রসিদ দেখুন</h3>
                        <a href="bank_transactions.php" class="btn btn-secondary"><i class="fas fa-arrow-left"></i> ট্রানজেকশন লিস্টে ফিরে যান</a>
                    </div>
                    
                    <?php if ($message): ?>
                        <div class="alert alert-<?php echo $message_type; ?> alert-dismissible fade show">
                            <?php echo htmlspecialchars($message); ?>
                            <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
                        </div>
                    <?php endif; ?>
                    
                    <div class="card">
                        <div class="card-header">
                            <h5>ট্রানজেকশন বিস্তারিত</h5>
                        </div>
                        <div class="card-body">
                            <div class="row">
                                <div class="col-md-6">
                                    <table class="table table-borderless">
                                        <tr>
                                            <th>ছাত্র/ছাত্রী:</th>
                                            <td><?php echo htmlspecialchars($view_transaction['first_name'] . ' ' . $view_transaction['last_name']); ?> (<?php echo htmlspecialchars($view_transaction['student_code']); ?>)</td>
                                        </tr>
                                        <tr>
                                            <th>ট্রানজেকশন আইডি:</th>
                                            <td><?php echo htmlspecialchars($view_transaction['transaction_id']); ?></td>
                                        </tr>
                                        <tr>
                                            <th>তারিখ:</th>
                                            <td><?php echo date('d/m/Y H:i', strtotime($view_transaction['submitted_at'])); ?></td>
                                        </tr>
                                        <tr>
                                            <th>পরিমাণ:</th>
                                            <td>৳<?php echo number_format((float)$view_transaction['amount'], 2); ?></td>
                                        </tr>
                                        <tr>
                                            <th>অবস্থা:</th>
                                            <td>
                                                <?php if ($view_transaction['status'] == 'pending'): ?>
                                                    <span class="badge status-pending">মুলতুবি</span>
                                                <?php elseif ($view_transaction['status'] == 'verified'): ?>
                                                    <span class="badge status-verified">ভেরিফাইড</span>
                                                <?php else: ?>
                                                    <span class="badge status-rejected">প্রত্যাখ্যাত</span>
                                                <?php endif; ?>
                                            </td>
                                        </tr>
                                        <?php if ($view_transaction['status'] != 'pending' && $view_transaction['verified_at']): ?>
                                            <tr>
                                                <th>ভেরিফাই করেছেন:</th>
                                                <td><?php echo htmlspecialchars($view_transaction['verified_by_name'] ?? 'N/A'); ?> (<?php echo date('d/m/Y H:i', strtotime($view_transaction['verified_at'])); ?>)</td>
                                            </tr>
                                        <?php endif; ?>
                                        <?php if ($view_transaction['notes']): ?>
                                            <tr>
                                                <th>নোট:</th>
                                                <td><?php echo htmlspecialchars($view_transaction['notes']); ?></td>
                                            </tr>
                                        <?php endif; ?>
                                    </table>
                                </div>
                                <div class="col-md-6">
                                    <table class="table table-borderless">
                                        <tr>
                                            <th>ব্যাংক:</th>
                                            <td><?php echo htmlspecialchars($view_transaction['bank_name']); ?></td>
                                        </tr>
                                        <tr>
                                            <th>শাখা:</th>
                                            <td><?php echo htmlspecialchars($view_transaction['branch_name']); ?></td>
                                        </tr>
                                        <tr>
                                            <th>অ্যাকাউন্ট নম্বর:</th>
                                            <td><?php echo htmlspecialchars($view_transaction['account_number']); ?></td>
                                        </tr>
                                    </table>
                                </div>
                            </div>
                            
                            <?php if ($view_transaction['receipt_image']): ?>
                                <hr>
                                <h5 class="mt-4">আপলোডকৃত রসিদ:</h5>
                                <div class="text-center mt-3">
                                    <a href="../<?php echo htmlspecialchars($view_transaction['receipt_image']); ?>" target="_blank">
                                        <img src="../<?php echo htmlspecialchars($view_transaction['receipt_image']); ?>" alt="Student Receipt" class="receipt-image img-fluid border">
                                    </a>
                                    <div class="mt-2">
                                        <a href="../<?php echo htmlspecialchars($view_transaction['receipt_image']); ?>" target="_blank" class="btn btn-primary">
                                            <i class="fas fa-search-plus"></i> বড় সাইজে দেখুন
                                        </a>
                                    </div>
                                </div>
                            <?php else: ?>
                                <div class="alert alert-info mt-3">
                                    <i class="fas fa-info-circle"></i> কোন রসিদ আপলোড করা হয়নি।
                                </div>
                            <?php endif; ?>
                        </div>
                    </div>
                </div>
            <?php else: ?>
                <!-- Show all transactions -->
                <h3><i class="fas fa-file-invoice-dollar"></i> ব্যাংক ট্রানজেকশন ম্যানেজমেন্ট - অনুসন্ধান</h3>
                
                <!-- Search Form -->
                <div class="card mb-4">
                    <div class="card-header">
                        <h5><i class="fas fa-search"></i> ট্রানজেকশন অনুসন্ধান</h5>
                    </div>
                    <div class="card-body">
                        <form method="GET" class="row g-3">
                            <div class="col-md-3">
                                <label class="form-label">শিক্ষার্থী/আইডি</label>
                                <input type="text" class="form-control" name="search_student" placeholder="নাম বা আইডি" value="<?php echo isset($_GET['search_student']) ? htmlspecialchars($_GET['search_student']) : ''; ?>">
                            </div>
                            <div class="col-md-3">
                                <label class="form-label">ট্রানজেকশন আইডি</label>
                                <input type="text" class="form-control" name="search_transaction_id" placeholder="ট্রানজেকশন আইডি" value="<?php echo isset($_GET['search_transaction_id']) ? htmlspecialchars($_GET['search_transaction_id']) : ''; ?>">
                            </div>
                            <div class="col-md-2">
                                <label class="form-label">অবস্থা</label>
                                <select class="form-select" name="search_status">
                                    <option value="">সব অবস্থা</option>
                                    <option value="pending" <?php echo (isset($_GET['search_status']) && $_GET['search_status'] == 'pending') ? 'selected' : ''; ?>>মুলতুবি</option>
                                    <option value="verified" <?php echo (isset($_GET['search_status']) && $_GET['search_status'] == 'verified') ? 'selected' : ''; ?>>ভেরিফাইড</option>
                                    <option value="rejected" <?php echo (isset($_GET['search_status']) && $_GET['search_status'] == 'rejected') ? 'selected' : ''; ?>>প্রত্যাখ্যাত</option>
                                </select>
                            </div>
                            <div class="col-md-2">
                                <label class="form-label">তারিখ হইতে</label>
                                <input type="date" class="form-control" name="search_date_from" value="<?php echo isset($_GET['search_date_from']) ? htmlspecialchars($_GET['search_date_from']) : ''; ?>">
                            </div>
                            <div class="col-md-2">
                                <label class="form-label">তারিখ পর্যন্ত</label>
                                <input type="date" class="form-control" name="search_date_to" value="<?php echo isset($_GET['search_date_to']) ? htmlspecialchars($_GET['search_date_to']) : ''; ?>">
                            </div>
                            <div class="col-12">
                                <button type="submit" class="btn btn-primary">
                                    <i class="fas fa-search"></i> অনুসন্ধান
                                </button>
                                <a href="bank_transactions.php" class="btn btn-secondary">
                                    <i class="fas fa-refresh"></i> রিসেট
                                </a>
                            </div>
                        </form>
                    </div>
                </div>
                
                <?php if ($message): ?>
                    <div class="alert alert-<?php echo $message_type; ?> alert-dismissible fade show">
                        <?php echo htmlspecialchars($message); ?>
                        <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
                    </div>
                <?php endif; ?>
                
                <!-- Pending & Verified Transactions Side by Side -->
                <div class="row">
                    <!-- Pending Transactions -->
                    <?php if (!empty($pending_transactions)): ?>
                        <div class="col-md-6">
                            <div class="card mb-4">
                                <div class="card-header">
                                    <h5><i class="fas fa-clock"></i> মুলতুবি ট্রানজেকশন (<?php echo count($pending_transactions); ?>)</h5>
                                </div>
                                <div class="card-body">
                                    <div class="table-responsive">
                                        <table class="table table-striped">
                                            <thead class="table-dark">
                                                <tr>
                                                    <th>তারিখ</th>
                                                    <th>ট্রানজেকশন আইডি</th>
                                                    <th>পরিমাণ</th>
                                                    <th>কার্যক্রম</th>
                                                </tr>
                                            </thead>
                                            <tbody>
                                                <?php foreach ($pending_transactions as $transaction): ?>
                                                    <tr>
                                                        <td><?php echo date('d/m/Y', strtotime($transaction['submitted_at'])); ?></td>
                                                        <td><?php echo htmlspecialchars($transaction['transaction_id']); ?></td>
                                                        <td>৳<?php echo number_format((float)$transaction['amount'], 2); ?></td>
                                                        <td class="action-cell">
                                                            <a href="bank_transactions.php?view=<?php echo $transaction['id']; ?>" class="btn btn-sm btn-info btn-action" title="দেখুন" data-bs-toggle="tooltip" data-bs-placement="top">
                                                                <i class="fas fa-eye"></i>
                                                            </a>
                                                            <a href="#" class="btn btn-sm btn-success btn-action" title="ভেরিফাই" data-bs-toggle="modal" data-bs-target="#updateModal" 
                                                               data-id="<?php echo $transaction['id']; ?>" data-status="verified" data-bs-toggle="tooltip" data-bs-placement="top">
                                                                <i class="fas fa-check"></i>
                                                            </a>
                                                            <a href="#" class="btn btn-sm btn-danger btn-action" title="প্রত্যাখ্যান" data-bs-toggle="modal" data-bs-target="#updateModal" 
                                                               data-id="<?php echo $transaction['id']; ?>" data-status="rejected" data-bs-toggle="tooltip" data-bs-placement="top">
                                                                <i class="fas fa-times"></i>
                                                            </a>
                                                        </td>
                                                    </tr>
                                                <?php endforeach; ?>
                                            </tbody>
                                        </table>
                                    </div>
                                </div>
                            </div>
                        </div>
                    <?php endif; ?>
                    
                    <!-- Verified Transactions -->
                    <?php if (!empty($verified_transactions)): ?>
                        <div class="col-md-6">
                            <div class="card mb-4">
                                <div class="card-header">
                                    <h5><i class="fas fa-check-circle"></i> ভেরিফাইড ট্রানজেকশন (<?php echo count($verified_transactions); ?>)</h5>
                                </div>
                                <div class="card-body">
                                    <div class="table-responsive">
                                        <table class="table table-striped">
                                            <thead class="table-dark">
                                                <tr>
                                                    <th>তারিখ</th>
                                                    <th>ট্রানজেকশন আইডি</th>
                                                    <th>পরিমাণ</th>
                                                    <th>কার্যক্রম</th>
                                                </tr>
                                            </thead>
                                            <tbody>
                                                <?php foreach ($verified_transactions as $transaction): ?>
                                                    <tr>
                                                        <td><?php echo date('d/m/Y', strtotime($transaction['submitted_at'])); ?></td>
                                                        <td><?php echo htmlspecialchars($transaction['transaction_id']); ?></td>
                                                        <td>৳<?php echo number_format((float)$transaction['amount'], 2); ?></td>
                                                        <td class="action-cell">
                                                            <a href="bank_transactions.php?view=<?php echo $transaction['id']; ?>" class="btn btn-sm btn-info btn-action" title="দেখুন" data-bs-toggle="tooltip" data-bs-placement="top">
                                                                <i class="fas fa-eye"></i>
                                                            </a>
                                                            <a href="#" class="btn btn-sm btn-warning btn-action" title="মুলতুবি" data-bs-toggle="modal" data-bs-target="#updateModal" 
                                                               data-id="<?php echo $transaction['id']; ?>" data-status="pending" data-bs-toggle="tooltip" data-bs-placement="top">
                                                                <i class="fas fa-clock"></i>
                                                            </a>
                                                            <a href="bank_transactions.php?delete=<?php echo $transaction['id']; ?>" class="btn btn-sm btn-danger btn-action" title="মুছুন" 
                                                               onclick="return confirm('আপনি কি নিশ্চিত যে এই ট্রানজেকশনটি মুছে ফেলতে চান?')" data-bs-toggle="tooltip" data-bs-placement="top">
                                                                <i class="fas fa-trash"></i>
                                                            </a>
                                                        </td>
                                                    </tr>
                                                <?php endforeach; ?>
                                            </tbody>
                                        </table>
                                    </div>
                                </div>
                            </div>
                        </div>
                    <?php endif; ?>
                </div> <!-- End row for pending and verified -->
                

                
                <!-- Rejected Transactions in Row Layout -->
                <?php if (!empty($rejected_transactions)): ?>
                    <div class="row">
                        <div class="col-md-12">
                            <div class="card">
                                <div class="card-header">
                                    <h5><i class="fas fa-times-circle"></i> প্রত্যাখ্যাত ট্রানজেকশন (<?php echo count($rejected_transactions); ?>)</h5>
                                </div>
                                <div class="card-body">
                                    <div class="table-responsive">
                                        <table class="table table-striped">
                                            <thead class="table-dark">
                                                <tr>
                                                    <th>তারিখ</th>
                                                    <th>ট্রানজেকশন আইডি</th>
                                                    <th>পরিমাণ</th>
                                                    <th>নোট</th>
                                                    <th>কার্যক্রম</th>
                                                </tr>
                                            </thead>
                                            <tbody>
                                                <?php foreach ($rejected_transactions as $transaction): ?>
                                                    <tr>
                                                        <td><?php echo date('d/m/Y', strtotime($transaction['submitted_at'])); ?></td>
                                                        <td><?php echo htmlspecialchars($transaction['transaction_id']); ?></td>
                                                        <td>৳<?php echo number_format((float)$transaction['amount'], 2); ?></td>
                                                        <td><?php echo htmlspecialchars($transaction['notes'] ?? 'N/A'); ?></td>
                                                        <td class="action-cell">
                                                            <a href="bank_transactions.php?view=<?php echo $transaction['id']; ?>" class="btn btn-sm btn-info btn-action" title="দেখুন">
                                                                <i class="fas fa-eye"></i>
                                                            </a>
                                                            <a href="#" class="btn btn-sm btn-warning btn-action" title="মুলতুবি" data-bs-toggle="modal" data-bs-target="#updateModal" 
                                                               data-id="<?php echo $transaction['id']; ?>" data-status="pending">
                                                                <i class="fas fa-clock"></i>
                                                            </a>
                                                            <a href="bank_transactions.php?delete=<?php echo $transaction['id']; ?>" class="btn btn-sm btn-danger btn-action" title="মুছুন" 
                                                               onclick="return confirm('আপনি কি নিশ্চিত যে এই ট্রানজেকশনটি মুছে ফেলতে চান?')">
                                                                <i class="fas fa-trash"></i>
                                                            </a>
                                                        </td>
                                                    </tr>
                                                <?php endforeach; ?>
                                            </tbody>
                                        </table>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>
                <?php endif; ?>
                
                <?php if (empty($pending_transactions) && empty($verified_transactions) && empty($rejected_transactions)): ?>
                    <div class="alert alert-info">
                        <i class="fas fa-info-circle"></i> কোন ট্রানজেকশন রেকর্ড পাওয়া যায়নি।
                    </div>
                <?php else: ?>
                    <div class="mt-3">
                        <p class="text-muted">
                            <?php 
                            $total_count = count($transactions);
                            echo "মোট " . $total_count . " টি ট্রানজেকশন পাওয়া গেছে।";
                            
                            // Show search criteria if any
                            $search_student = isset($_GET['search_student']) ? trim($_GET['search_student']) : '';
                            $search_transaction_id = isset($_GET['search_transaction_id']) ? trim($_GET['search_transaction_id']) : '';
                            $search_status = isset($_GET['search_status']) ? $_GET['search_status'] : '';
                            $search_date_from = isset($_GET['search_date_from']) ? $_GET['search_date_from'] : '';
                            $search_date_to = isset($_GET['search_date_to']) ? $_GET['search_date_to'] : '';
                            
                            if (!empty($search_student) || !empty($search_transaction_id) || !empty($search_status) || !empty($search_date_from) || !empty($search_date_to)) {
                                echo " (অনুসন্ধান মানদণ্ড: ";
                                $criteria = [];
                                if (!empty($search_student)) $criteria[] = "শিক্ষার্থী: " . htmlspecialchars($search_student);
                                if (!empty($search_transaction_id)) $criteria[] = "ট্রানজেকশন আইডি: " . htmlspecialchars($search_transaction_id);
                                if (!empty($search_status)) {
                                    $status_labels = ['pending' => 'মুলতুবি', 'verified' => 'ভেরিফাইড', 'rejected' => 'প্রত্যাখ্যাত'];
                                    $criteria[] = "অবস্থা: " . ($status_labels[$search_status] ?? $search_status);
                                }
                                if (!empty($search_date_from)) $criteria[] = "তারিখ হইতে: " . htmlspecialchars($search_date_from);
                                if (!empty($search_date_to)) $criteria[] = "তারিখ পর্যন্ত: " . htmlspecialchars($search_date_to);
                                echo implode(", ", $criteria) . ")";
                            }
                            ?>
                        </p>
                    </div>
                <?php endif; ?>
            <?php endif; ?>
        </div>
    </div>
</div>

<!-- Update Status Modal -->
<div class="modal fade" id="updateModal" tabindex="-1" aria-labelledby="updateModalLabel" aria-hidden="true">
    <div class="modal-dialog">
        <div class="modal-content">
            <form method="POST">
                <div class="modal-header">
                    <h5 class="modal-title" id="updateModalLabel">ট্রানজেকশন স্ট্যাটাস আপডেট</h5>
                    <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
                </div>
                <div class="modal-body">
                    <input type="hidden" name="transaction_id" id="transactionId">
                    <input type="hidden" name="status" id="transactionStatus">
                    
                    <div class="mb-3">
                        <label for="admin_notes" class="form-label">নোট (ঐচ্ছিক)</label>
                        <textarea class="form-control" id="admin_notes" name="admin_notes" rows="3" placeholder="ট্রানজেকশন সম্পর্কে কোন বিশেষ তথ্য..."></textarea>
                    </div>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">বাতিল</button>
                    <button type="submit" name="update_status" class="btn btn-primary">আপডেট করুন</button>
                </div>
            </form>
        </div>
    </div>
</div>

<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/js/bootstrap.bundle.min.js"></script>
<script>
    // Handle modal data population
    var updateModal = document.getElementById('updateModal');
    updateModal.addEventListener('show.bs.modal', function (event) {
        var button = event.relatedTarget;
        var transactionId = button.getAttribute('data-id');
        var status = button.getAttribute('data-status');
        
        var modal = this;
        modal.querySelector('#transactionId').value = transactionId;
        modal.querySelector('#transactionStatus').value = status;
    });
</script>
</div> <!-- Close container-fluid -->
</body>
</html>