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

// Only admins can access this page
if (!isset($_SESSION['user_id']) || $_SESSION['user_role'] !== 'admin') {
    header('Location: ../login.php');
    exit();
}

$error_message = '';
$success_message = '';

// Handle payment verification
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['verify_payment'])) {
    try {
        // Get payment data from POST
        $transaction_id = (int)($_POST['transaction_id'] ?? 0);
        $action = $_POST['verify_payment']; // 'approve' or 'reject' - get from button value
        $admin_notes = trim($_POST['admin_notes'] ?? '');
        
        if ($transaction_id <= 0) {
            throw new Exception("Invalid transaction data");
        }
        
        // 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 verified for any student
        if ($action === 'approve') {
            $stmt = $pdo->prepare("
                SELECT bt.id, 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.transaction_id = ? AND bt.status = 'verified'
            ");
            $stmt->execute([$transaction['transaction_id']]);
            $existing_verified = $stmt->fetch();
            
            if ($existing_verified) {
                throw new Exception("This transaction ID has already been verified for student " . 
                    $existing_verified['student_code'] . " (" . 
                    $existing_verified['first_name'] . " " . 
                    $existing_verified['last_name'] . "). " .
                    "The same transaction cannot be accepted multiple times.");
            }
        }
        
        if ($action === 'approve') {
            // Update fee records (distribute payment across due fees)
            $pdo->beginTransaction();
            
            try {
                // Get due fees for this student
                $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 transaction status
                $stmt = $pdo->prepare("
                    UPDATE bank_transactions 
                    SET status = 'verified', verified_at = NOW(), verified_by = ?, notes = ?
                    WHERE id = ?
                ");
                $stmt->execute([$_SESSION['user_id'], $admin_notes, $transaction_id]);
                
                $pdo->commit();
                
                $success_message = "Payment verified and applied successfully!";
                
                // Send SMS notification to student
                try {
                    $smsHelperPath = __DIR__ . '/../includes/sms_helper.php';
                    if (file_exists($smsHelperPath)) {
                        require_once $smsHelperPath;
                        
                        // Check if non-musking SMS service is enabled
                        $stmt = $pdo->prepare("SELECT setting_value FROM settings WHERE setting_key = 'non_musking_enabled'");
                        $stmt->execute();
                        $result = $stmt->fetch();
                        $nonMuskingEnabled = $result && $result['setting_value'] === '1';
                        
                        // Check if bank transaction notifications are enabled
                        $stmt = $pdo->prepare("SELECT setting_value FROM settings WHERE setting_key = 'sms_send_bank_transaction_notifications'");
                        $stmt->execute();
                        $result = $stmt->fetch();
                        $bankNotificationsEnabled = $result && $result['setting_value'] === '1';
                        
                        if ($nonMuskingEnabled && $bankNotificationsEnabled) {
                            $cfg = sms_config();
                            $numbers = [];
                            // Fetch student's phone numbers
                            $pStmt = $pdo->prepare('SELECT phone, guardian_phone, first_name, last_name FROM students WHERE id=?');
                            $pStmt->execute([$transaction['student_id']]);
                            $p = $pStmt->fetch();
                            if (!empty($p['phone'])) $numbers[] = $p['phone'];
                            if (($cfg['send_to_guardian'] ?? true) && !empty($p['guardian_phone'])) $numbers[] = $p['guardian_phone'];

                            if (!empty($numbers)) {
                                // Calculate total due after payment
                                $dueStmt = $pdo->prepare('SELECT COALESCE(SUM(amount-COALESCE(paid_amount,0)),0) AS due FROM fees WHERE student_id=?');
                                $dueStmt->execute([$transaction['student_id']]);
                                $due = (float)($dueStmt->fetch()['due'] ?? 0);
                                $vars = [
                                    'name' => trim(($p['first_name'] ?? '').' '.($p['last_name'] ?? '')),
                                    'paid_amount' => number_format($transaction['amount'], 2),
                                    'due_amount' => number_format($due, 2),
                                ];
                                
                                // Try to use non-musking template for bank transaction, fallback to hardcoded message
                                $result = non_musking_send_template($pdo, 'bank_transaction', $vars, $numbers);
                                
                                // If template doesn't exist, use hardcoded Bengali message
                                if (!$result['success'] && strpos($result['message'], 'Template not found') !== false) {
                                    $bankMessage = "\xE0\xA6\xAB\xE0\xA7\x87\xE0\xA6\xB8 \xE0\xA6\xAA\xE0\xA7\x8D\xE0\xA6\xB0\xE0\xA6\xA6\xE0\xA6\xBE\xE0\xA6\xA8 \xE0\xA6\x95\xE0\xA6\xB0\xE0\xA7\x87\xE0\xA6\xB0 \xE0\xA6\x86\xE0\xA6\xAA\xE0\xA6\xA8\xE0\xA6\xBE\xE0\xA6\xB0 \xE0\xA6\xAC\xE0\xA7\x8D\xE0\xA6\xAF\xE0\xA6\xBE\xE0\xA6\x82\xE0\xA6\x95 \xE0\xA6\x9F\xE0\xA7\x8D\xE0\xA6\xB0\xE0\xA6\xBE\xE0\xA6\xA8\xE0\xA6\x9C\xE0\xA7\x87\xE0\xA6\x95\xE0\xA6\xB6\xE0\xA6\xA8 \xE0\xA7\xBB\xE0\xA6\x93" . number_format($transaction['amount'], 2) . " \xE0\xA6\x9F\xE0\xA6\xBE\xE0\xA6\x95\xE0\xA6\xBE \xE0\xA6\x97\xE0\xA7\x83\xE0\xA6\xB9\xE0\xA7\x80\xE0\xA6\xA4 \xE0\xA6\xB9\xE0\xA6\AF\xE0\xA6\xBC\xE0\xA7\x87\xE0\xA6\xB0\xE0\xA7\x87\xE0\xA6\x9B\xE0\xA7\x87\xE0\xA5\xA4 \xE0\xA6\xAC\xE0\xA6\xB0\xE0\xA7\x8D\xE0\xA6\xA4\xE0\xA6\xAE\xE0\xA6\xBE\xE0\xA6\xA8 \xE0\xA6\xAC\xE0\xA6\x95\xE0\xA7\x87\xE0\xA6\xAF\xE0\xA6\xBC\xE0\xA6\xBE: " . number_format($due, 2) . " \xE0\xA6\x9F\xE0\xA6\xBE\xE0\xA6\x95\xE0\xA6\xBE\xE0\xA5\xA4 \xE0\xA6\xA7\xE0\xA6\xA8\xE0\xA7\x8D\xE0\xA6\xAF\xE0\xA6\xAC\xE0\xA6\xBE\xE0\xA6\xA6\xE0\xA5\xA4";
                                    non_musking_send($pdo, $numbers, $bankMessage, ['template'=>'bank_transaction']);
                                }
                            } else {
                                // Log that no phone numbers were found for the student
                                if (function_exists('sms_log')) sms_log('No phone numbers found for student ID: ' . $transaction['student_id']);
                            }
                        } else {
                            // Show why notifications were not sent
                            $reasons = [];
                            if (!$nonMuskingEnabled) {
                                $reasons[] = '\xE0\xA6\xA8\xE0\xA6\xA8-\xE0\xA6\xAE\xE0\xA6\xBE\xE0\xA6\xB8\xE0\xA7\x8D\xE0\xA6\x95\xE0\xA6\xBF\xE0\xA6\x82 \xE0\xA6\x8F\xE0\xA6\xB8\xE0\xA6\x8F\xE0\xA6\xAE\xE0\xA6\x8F\xE0\xA6\xB8 \xE0\xA6\xB8\xE0\xA6\xBE\xE0\xA6\xB0\xE0\xA7\x8D\xE0\xA6\xAD\xE0\xA6\xBF\xE0\xA6\xB8 \xE0\xA6\xA8\xE0\xA6\xBF\xE0\xA6\xB7\xE0\xA7\x8D\xE0\xA6\x95\xE0\xA7\x8D\xE0\xA6\xB0\xE0\xA6\xBF\xE0\xA6\xAF\xE0\xA6\xBC';
                            }
                            if (!$bankNotificationsEnabled) {
                                $reasons[] = '\xE0\xA6\xAC\xE0\xA7\x8D\xE0\xA6\xAF\xE0\xA6\xBE\xE0\xA6\x82\xE0\xA6\x95 \xE0\xA6\x9F\xE0\xA7\x8D\xE0\xA6\xB0\xE0\xA6\xBE\xE0\xA6\xA8\xE0\xA6\x9C\xE0\xA7\x87\xE0\xA6\x95\xE0\xA6\xB6\xE0\xA6\xA8 \xE0\xA6\xA8\xE0\xA7\x8B\xE0\xA6\x9F\xE0\xA6\xBF\xE0\xA6\xAB\xE0\xA6\xBF\xE0\xA6\x95\xE0\xA7\x87\xE0\xA6\B6\xE0\xA6\xA8 \xE0\xA6\xA8\xE0\xA6\xBF\xE0\xA6\xB7\xE0\xA7\x8D\xE0\xA6\x95\xE0\xA7\x8D\xE0\xA6\xB0\xE0\xA6\xBF\xE0\xA6\xAF\xE0\xA6\xBC';
                            }
                            if (function_exists('sms_log')) sms_log('BANK TRANSACTION SMS not sent to student ID: ' . $transaction['student_id'] . '. Reasons: ' . implode(', ', $reasons));
                        }
                    }
                } catch (Throwable $e) {
                    if (function_exists('sms_log')) sms_log('BANK TRANSACTION SMS error: '.$e->getMessage());
                }
            } catch (Exception $e) {
                $pdo->rollBack();
                throw new Exception("Failed to update fee records: " . $e->getMessage());
            }
        } else if ($action === 'reject') {
            // Reject the transaction
            $stmt = $pdo->prepare("UPDATE bank_transactions SET status = 'rejected', verified_at = NOW(), verified_by = ?, notes = ? WHERE id = ?");
            $stmt->execute([$_SESSION['user_id'], $admin_notes, $transaction_id]);
                        
            $success_message = "Payment rejected successfully!";
                        

                $smsHelperPath = __DIR__ . '/../includes/sms_helper.php';
                if (file_exists($smsHelperPath)) {
                    require_once $smsHelperPath;
                                
                    // Check if non-musking SMS service is enabled
                    $stmt = $pdo->prepare("SELECT setting_value FROM settings WHERE setting_key = 'non_musking_enabled'");
                    $stmt->execute();
                    $result = $stmt->fetch();
                    $nonMuskingEnabled = $result && $result['setting_value'] === '1';
                                
                    // Check if bank transaction notifications are enabled
                    $stmt = $pdo->prepare("SELECT setting_value FROM settings WHERE setting_key = 'sms_send_bank_transaction_notifications'");
                    $stmt->execute();
                    $result = $stmt->fetch();
                    $bankNotificationsEnabled = $result && $result['setting_value'] === '1';
                                
                    if ($nonMuskingEnabled && $bankNotificationsEnabled) {
                        $cfg = sms_config();
                        $numbers = [];
                        // Fetch student's phone numbers
                        $pStmt = $pdo->prepare('SELECT phone, guardian_phone, first_name, last_name FROM students WHERE id=?');
                        $pStmt->execute([$transaction['student_id']]);
                        $p = $pStmt->fetch();
                        if (!empty($p['phone'])) $numbers[] = $p['phone'];
                        if (($cfg['send_to_guardian'] ?? true) && !empty($p['guardian_phone'])) $numbers[] = $p['guardian_phone'];
            
                        if (!empty($numbers)) {
                            $vars = [
                                'name' => trim(($p['first_name'] ?? '').' '.($p['last_name'] ?? '')),
                                'amount' => number_format($transaction['amount'], 2),
                                'transaction_id' => $transaction['transaction_id'],
                                'notes' => $admin_notes,
                            ];
                                        
                            // Try to use non-musking template for bank transaction rejection, fallback to hardcoded message
                            $result = non_musking_send_template($pdo, 'bank_transaction_rejection', $vars, $numbers);
                                        
                            // If template doesn't exist, use hardcoded Bengali message
                            if (!$result['success'] && strpos($result['message'], 'Template not found') !== false) {
                                $rejectionMessage = "\xE0\xA6\x86\xE0\xA6\xAA\xE0\xA6\xA8\xE0\xA6\xBE\xE0\xA6\xB0 \xE0\xA6\xAC\xE0\xA7\x8D\xE0\xA6\xAF\xE0\xA6\xBE\xE0\xA6\x82\xE0\xA6\x95 \xE0\xA6\x9F\xE0\xA7\x8D\xE0\xA6\xB0\xE0\xA6\xBE\xE0\xA6\xA8\xE0\xA6\x9C\xE0\xA7\x87\xE0\xA6\x95\xE0\xA6\xB6\xE0\xA6\xA8 \xE0\xA7\xBB\xE0\xA6\x93" . number_format($transaction['amount'], 2) . " \xE0\xA6\x9F\xE0\xA6\xBE\xE0\xA6\x95\xE0\xA6\xBE \xE0\xA6\xAA\xE0\xA7\x8D\xE0\xA6\xB0\xE0\xA6\xA4\xE0\xA7\x8D\xE0\xA6\xAF\xE0\xA6\xBE\xE0\xA6\x96\xE0\xA7\x8D\xE0\xA6\xAF\xE0\xA6\xBE\xE0\xA6\A8 \xE0\xA6\xB9\xE0\xA6\AF\xE0\xA6\xBC\xE0\xA7\x87\xE0\xA6\x9B\xE0\xA7\x87\xE0\xA5\xA4 \xE0\xA6\x9F\xE0\A7\x8D\xE0\xA6\xB0\xE0\xA6\xBE\xE0\xA6\xA8\xE0\xA6\x9C\xE0\xA7\x87\xE0\xA6\x95\xE0\xA6\xB6\xE0\xA6\xA8 \xE0\xA6\x86\xE0\xA6\xBF\xE0\xA6\x9C\xE0\xA7\x87\xE0\xA6\xB0 \xE0\xA6\x95\xE0\xA6\xBE\xE0\xA6\xB0\xE0\xA6\xA3\xE0\xA7\x87: " . $admin_notes . " \xE0\xA5\xA4 \xE0\xA6\x85\xE0\xA6\xA8\xE0\xA7\x81\xE0\xA6\x97\xE0\xA7\x8D\xE0\xA6\xB0\xE0\xA6\xB9 \xE0\xA6\xAA\xE0\xA7\x81\xE0\xA6\xA8\xE0\xA6\B0\xE0\xA7\x8D\xE0\xA6\x86\xE0\xA6\xAF\xE0\xA6\xBC \xE0\xA6\xAA\xE0\xA7\x8D\xE0\xA6\xB0\xE0\xA6\xA6\xE0\xA6\xBE\xE0\xA6\xA8 \xE0\xA6\x95\xE0\xA6\xB0\xE0\xA7\x81\xE0\xA6\A8\xE0\xA5\xA4";
                                non_musking_send($pdo, $numbers, $rejectionMessage, ['template'=>'bank_transaction_rejection']);
                            }
                        } else {
                            // Log that no phone numbers were found for the student
                            if (function_exists('sms_log')) sms_log('No phone numbers found for student ID: ' . $transaction['student_id']);
                        }
                    } else {
                        // Show why notifications were not sent
                        $reasons = [];
                        if (!$nonMuskingEnabled) {
                            $reasons[] = '\xE0\xA6\xA8\xE0\xA6\xA8-\xE0\xA6\xAE\xE0\xA6\xBE\xE0\xA6\xB8\xE0\xA7\x8D\xE0\xA6\x95\xE0\xA6\xBF\xE0\xA6\x82 \xE0\xA6\x8F\xE0\xA6\xB8\xE0\xA6\x8F\xE0\xA6\xAE\xE0\xA6\x8F\xE0\xA6\xB8 \xE0\xA6\xB8\xE0\xA6\xBE\xE0\xA6\xB0\xE0\xA7\x8D\xE0\xA6\xAD\xE0\xA6\xBF\xE0\xA6\xB8 \xE0\xA6\xA8\xE0\xA6\xBF\xE0\xA6\xB7\xE0\xA7\x8D\xE0\xA6\x95\xE0\xA7\x8D\xE0\xA6\xB0\xE0\xA6\xBF\xE0\xA6\xAF\xE0\xA6\xBC';
                        }
                        if (!$bankNotificationsEnabled) {
                            $reasons[] = '\xE0\xA6\xAC\xE0\xA7\x8D\xE0\xA6\xAF\xE0\xA6\xBE\xE0\xA6\x82\xE0\xA6\x95 \xE0\xA6\x9F\xE0\xA7\x8D\xE0\xA6\xB0\xE0\xA6\xBE\xE0\xA6\xA8\xE0\xA6\x9C\xE0\xA7\x87\xE0\xA6\x95\xE0\xA6\xB6\xE0\xA6\xA8 \xE0\xA6\xA8\xE0\xA7\x8B\xE0\xA6\x9F\xE0\xA6\xBF\xE0\xA6\xAB\xE0\xA6\xBF\xE0\xA6\x95\xE0\xA7\x87\xE0\xA6\B6\xE0\xA6\xA8 \xE0\xA6\xA8\xE0\xA6\xBF\xE0\xA6\xB7\xE0\xA7\x8D\xE0\xA6\x95\xE0\xA7\x8D\xE0\xA6\xB0\xE0\xA6\xBF\xE0\xA6\xAF\xE0\xA6\xBC';
                        }
                        if (function_exists('sms_log')) sms_log('BANK TRANSACTION REJECTION SMS not sent to student ID: ' . $transaction['student_id'] . '. Reasons: ' . implode(', ', $reasons));
                    }
                }
            } catch (Throwable $e) {
                if (function_exists('sms_log')) sms_log('BANK TRANSACTION REJECTION SMS error: '.$e->getMessage());
            }
                        

                $smsHelperPath = __DIR__ . '/../includes/sms_helper.php';
                if (file_exists($smsHelperPath)) {
                    require_once $smsHelperPath;
                                
                    // Check if non-musking SMS service is enabled
                    $stmt = $pdo->prepare("SELECT setting_value FROM settings WHERE setting_key = 'non_musking_enabled'");
                    $stmt->execute();
                    $result = $stmt->fetch();
                    $nonMuskingEnabled = $result && $result['setting_value'] === '1';
                                
                    // Check if bank transaction notifications are enabled
                    $stmt = $pdo->prepare("SELECT setting_value FROM settings WHERE setting_key = 'sms_send_bank_transaction_notifications'");
                    $stmt->execute();
                    $result = $stmt->fetch();
                    $bankNotificationsEnabled = $result && $result['setting_value'] === '1';
                                
                    if ($nonMuskingEnabled && $bankNotificationsEnabled) {
                        $cfg = sms_config();
                        $numbers = [];
                        // Fetch student's phone numbers
                        $pStmt = $pdo->prepare('SELECT phone, guardian_phone, first_name, last_name FROM students WHERE id=?');
                        $pStmt->execute([$transaction['student_id']]);
                        $p = $pStmt->fetch();
                        if (!empty($p['phone'])) $numbers[] = $p['phone'];
                        if (($cfg['send_to_guardian'] ?? true) && !empty($p['guardian_phone'])) $numbers[] = $p['guardian_phone'];
            
                        if (!empty($numbers)) {
                            $vars = [
                                'name' => trim(($p['first_name'] ?? '').' '.($p['last_name'] ?? '')),
                                'amount' => number_format($transaction['amount'], 2),
                                'transaction_id' => $transaction['transaction_id'],
                                'notes' => $admin_notes,
                            ];
                                        
                            // Try to use non-musking template for bank transaction rejection, fallback to hardcoded message
                            $result = non_musking_send_template($pdo, 'bank_transaction_rejection', $vars, $numbers);
                                        
                            // If template doesn't exist, use hardcoded Bengali message
                            if (!$result['success'] && strpos($result['message'], 'Template not found') !== false) {
                                $rejectionMessage = "\xE0\xA6\x86\xE0\xA6\xAA\xE0\xA6\xA8\xE0\xA6\xBE\xE0\xA6\xB0 \xE0\xA6\xAC\xE0\xA7\x8D\xE0\xA6\xAF\xE0\xA6\xBE\xE0\xA6\x82\xE0\xA6\x95 \xE0\xA6\x9F\xE0\xA7\x8D\xE0\xA6\xB0\xE0\xA6\xBE\xE0\xA6\xA8\xE0\xA6\x9C\xE0\xA7\x87\xE0\xA6\x95\xE0\xA6\xB6\xE0\xA6\xA8 \xE0\xA7\xBB\xE0\xA6\x93" . number_format($transaction['amount'], 2) . " \xE0\xA6\x9F\xE0\xA6\xBE\xE0\xA6\x95\xE0\xA6\xBE \xE0\xA6\xAA\xE0\xA7\x8D\xE0\xA6\xB0\xE0\xA6\xA4\xE0\xA7\x8D\xE0\xA6\xAF\xE0\xA6\xBE\xE0\xA6\x96\xE0\xA7\x8D\xE0\xA6\xAF\xE0\xA6\xBE\xE0\xA6\A8 \xE0\xA6\xB9\xE0\xA6\AF\xE0\xA6\xBC\xE0\xA7\x87\xE0\xA6\x9B\xE0\xA7\x87\xE0\xA5\xA4 \xE0\xA6\x9F\xE0\xA7\x8D\xE0\xA6\xB0\xE0\xA6\xBE\xE0\xA6\xA8\xE0\xA6\x9C\xE0\xA7\x87\xE0\xA6\x95\xE0\xA6\xB6\xE0\xA6\xA8 \xE0\xA6\x86\xE0\xA6\xBF\xE0\xA6\x9C\xE0\xA7\x87\xE0\xA6\xB0 \xE0\xA6\x95\xE0\xA6\xBE\xE0\xA6\xB0\xE0\xA6\xA3\xE0\xA7\x87: " . $admin_notes . " \xE0\xA5\xA4 \xE0\xA6\x85\xE0\xA6\xA8\xE0\xA7\x81\xE0\xA6\x97\xE0\xA7\x8D\xE0\xA6\xB0\xE0\xA6\xB9 \xE0\xA6\xAA\xE0\xA7\x81\xE0\xA6\xA8\xE0\xA6\xB0\xE0\xA7\x8D\xE0\xA6\x86\xE0\xA6\xAF\xE0\xA6\xBC \xE0\xA6\xAA\xE0\xA7\x8D\xE0\xA6\xB0\xE0\xA6\xA6\xE0\xA6\xBE\xE0\xA6\xA8 \xE0\xA6\x95\xE0\xA6\xB0\xE0\xA7\x81\xE0\xA6\A8\xE0\xA5\xA4";
                                non_musking_send($pdo, $numbers, $rejectionMessage, ['template'=>'bank_transaction_rejection']);
                            }
                        } else {
                            // Log that no phone numbers were found for the student
                            if (function_exists('sms_log')) sms_log('No phone numbers found for student ID: ' . $transaction['student_id']);
                        }
                    } else {
                        // Show why notifications were not sent
                        $reasons = [];
                        if (!$nonMuskingEnabled) {
                            $reasons[] = '\xE0\xA6\xA8\xE0\xA6\xA8-\xE0\xA6\xAE\xE0\xA6\xBE\xE0\xA6\xB8\xE0\xA7\x8D\xE0\xA6\x95\xE0\xA6\xBF\xE0\xA6\x82 \xE0\xA6\x8F\xE0\xA6\xB8\xE0\xA6\x8F\xE0\xA6\xAE\xE0\xA6\x8F\xE0\xA6\xB8 \xE0\xA6\xB8\xE0\xA6\xBE\xE0\xA6\xB0\xE0\xA7\x8D\xE0\xA6\xAD\xE0\xA6\xBF\xE0\xA6\xB8 \xE0\xA6\xA8\xE0\xA6\xBF\xE0\xA6\xB7\xE0\xA7\x8D\xE0\xA6\x95\xE0\xA7\x8D\xE0\xA6\xB0\xE0\xA6\xBF\xE0\xA6\xAF\xE0\xA6\xBC';
                        }
                        if (!$bankNotificationsEnabled) {
                            $reasons[] = '\xE0\xA6\xAC\xE0\xA7\x8D\xE0\xA6\xAF\xE0\xA6\xBE\xE0\xA6\x82\xE0\xA6\x95 \xE0\xA6\x9F\xE0\xA7\x8D\xE0\xA6\xB0\xE0\xA6\xBE\xE0\xA6\xA8\xE0\xA6\x9C\xE0\xA7\x87\xE0\xA6\x95\xE0\xA6\xB6\xE0\xA6\xA8 \xE0\xA6\xA8\xE0\xA7\x8B\xE0\xA6\x9F\xE0\xA6\xBF\xE0\xA6\xAB\xE0\xA6\xBF\xE0\xA6\x95\xE0\xA7\x87\xE0\xA6\B6\xE0\xA6\xA8 \xE0\xA6\xA8\xE0\xA6\xBF\xE0\xA6\xB7\xE0\xA7\x8D\xE0\xA6\x95\xE0\xA7\x8D\xE0\xA6\xB0\xE0\xA6\xBF\xE0\xA6\xAF\xE0\xA6\xBC';
                        }
                        if (function_exists('sms_log')) sms_log('BANK TRANSACTION REJECTION SMS not sent to student ID: ' . $transaction['student_id'] . '. Reasons: ' . implode(', ', $reasons));
                    }
                }
            } catch (Throwable $e) {
                if (function_exists('sms_log')) sms_log('BANK TRANSACTION REJECTION SMS error: '.$e->getMessage());
            }
        }
        
    } catch (Exception $e) {
        $error_message = $e->getMessage();
    }
}

// Handle AJAX search requests
if (isset($_POST['ajax']) && $_POST['ajax'] == 'search_transactions') {
    header('Content-Type: application/json');
    
    $status = $_POST['status'] ?? '';
    $search_term = trim($_POST['search_term'] ?? '');
    
    if (!in_array($status, ['pending', 'verified', 'rejected'])) {
        echo json_encode(['success' => false, 'message' => 'Invalid status']);
        exit();
    }
    
    try {
        $where_clause = "bt.status = ?";
        $params = [$status];
        
        if (!empty($search_term)) {
            $where_clause .= " AND (bt.transaction_id LIKE ? OR s.first_name LIKE ? OR s.last_name LIKE ? OR s.student_id LIKE ? OR ba.bank_name LIKE ? OR ba.branch_name LIKE ? OR bt.amount LIKE ?";
            if ($status !== 'pending') { // verified and rejected have notes and verified_by fields
                $where_clause .= " OR u.username LIKE ? OR bt.notes LIKE ?";
                $search_param = "%{$search_term}%";
                $params = array_merge($params, array_fill(0, 9, $search_param));
            } else { // pending status
                $search_param = "%{$search_term}%";
                $params = array_merge($params, array_fill(0, 7, $search_param));
            }
            $where_clause .= ")";
        }
        
        $sql = "SELECT bt.*, s.first_name, s.last_name, s.student_id as student_code, ba.bank_name, ba.branch_name";
        
        if ($status !== 'pending') {
            $sql .= ", u.username as verified_by_name, bt.notes";
        }
        
        $sql .= "\n               FROM bank_transactions bt\n               JOIN students s ON bt.student_id = s.id\n               JOIN bank_accounts ba ON bt.bank_account_id = ba.id";
        
        if ($status !== 'pending') {
            $sql .= "\n               LEFT JOIN users u ON bt.verified_by = u.id";
        }
        
        $sql .= "\n               WHERE {$where_clause}";
        
        if ($status === 'pending') {
            $sql .= "\n               ORDER BY bt.submitted_at DESC";
        } else {
            $sql .= "\n               ORDER BY bt.verified_at DESC";
        }
        
        $stmt = $pdo->prepare($sql);
        $stmt->execute($params);
        $transactions = $stmt->fetchAll();
        
        echo json_encode(['success' => true, 'transactions' => $transactions]);
        exit();
    } catch (Exception $e) {
        echo json_encode(['success' => false, 'message' => $e->getMessage()]);
        exit();
    }
}

// Handle transaction editing
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['edit_transaction'])) {
    try {
        $transaction_id = (int)($_POST['transaction_id'] ?? 0);
        $transaction_id_value = trim($_POST['edit_transaction_id'] ?? '');
        $amount = (float)($_POST['edit_amount'] ?? 0);
        $status = trim($_POST['edit_status'] ?? 'pending');
        
        if ($transaction_id <= 0 || empty($transaction_id_value) || $amount <= 0) {
            throw new Exception("All fields are required");
        }
        
        // Validate status
        if (!in_array($status, ['pending', 'verified', 'rejected'])) {
            throw new Exception("Invalid status");
        }
        
        // If changing to verified, check if this transaction ID has already been verified
        if ($status === 'verified') {
            // Get the current transaction to get its transaction_id
            $stmt = $pdo->prepare("SELECT transaction_id FROM bank_transactions WHERE id = ?");
            $stmt->execute([$transaction_id]);
            $current_transaction = $stmt->fetch();
            
            if ($current_transaction) {
                $stmt = $pdo->prepare("
                    SELECT bt.id, 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.transaction_id = ? AND bt.status = 'verified' AND bt.id != ?
                ");
                $stmt->execute([$current_transaction['transaction_id'], $transaction_id]);
                $existing_verified = $stmt->fetch();
                
                if ($existing_verified) {
                    throw new Exception("This transaction ID has already been verified for student " . 
                        $existing_verified['student_code'] . " (" . 
                        $existing_verified['first_name'] . " " . 
                        $existing_verified['last_name'] . "). " .
                        "The same transaction cannot be accepted multiple times.");
                }
            }
        }
        
        // Update the transaction
        $stmt = $pdo->prepare("
            UPDATE bank_transactions 
            SET transaction_id = ?, amount = ?, status = ?
            WHERE id = ?
        ");
        $stmt->execute([$transaction_id_value, $amount, $status, $transaction_id]);
        
        $success_message = 'ট্রানজেকশন সফলভাবে আপডেট করা হয়েছে';
        
    } catch (Exception $e) {
        $error_message = $e->getMessage();
    }
}

// Get search parameters
$search_pending = isset($_GET['search_pending']) ? trim($_GET['search_pending']) : '';
$search_verified = isset($_GET['search_verified']) ? trim($_GET['search_verified']) : '';
$search_rejected = isset($_GET['search_rejected']) ? trim($_GET['search_rejected']) : '';

// Get all pending bank transactions with search filters
$where_clause = "bt.status = 'pending'";
$params = [];

if (!empty($search_pending)) {
    $where_clause .= " AND (bt.transaction_id LIKE ? OR s.first_name LIKE ? OR s.last_name LIKE ? OR s.student_id LIKE ? OR ba.bank_name LIKE ? OR ba.branch_name LIKE ? OR bt.amount LIKE ?)";
    $search_param = "%{$search_pending}%";
    $params = array_fill(0, 7, $search_param);
}

$sql = "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 {$where_clause}
       ORDER BY bt.submitted_at DESC";

$stmt = $pdo->prepare($sql);
$stmt->execute($params);
$pending_transactions = $stmt->fetchAll();

// Get all verified bank transactions with search filters
$where_clause_v = "bt.status = 'verified'";
$params_v = [];

if (!empty($search_verified)) {
    $where_clause_v .= " AND (bt.transaction_id LIKE ? OR s.first_name LIKE ? OR s.last_name LIKE ? OR s.student_id LIKE ? OR ba.bank_name LIKE ? OR ba.branch_name LIKE ? OR bt.amount LIKE ? OR u.username LIKE ?)";
    $search_param_v = "%{$search_verified}%";
    $params_v = array_fill(0, 8, $search_param_v);
}

$sql_v = "SELECT bt.*, s.first_name, s.last_name, s.student_id as student_code, ba.bank_name, ba.branch_name, 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 {$where_clause_v}
       ORDER BY bt.verified_at DESC";

$stmt = $pdo->prepare($sql_v);
$stmt->execute($params_v);
$verified_transactions = $stmt->fetchAll();

// Get all rejected bank transactions with search filters
$where_clause_r = "bt.status = 'rejected'";
$params_r = [];

if (!empty($search_rejected)) {
    $where_clause_r .= " AND (bt.transaction_id LIKE ? OR s.first_name LIKE ? OR s.last_name LIKE ? OR s.student_id LIKE ? OR ba.bank_name LIKE ? OR ba.branch_name LIKE ? OR bt.amount LIKE ? OR u.username LIKE ? OR bt.notes LIKE ?)";
    $search_param_r = "%{$search_rejected}%";
    $params_r = array_fill(0, 9, $search_param_r);
}

$sql_r = "SELECT bt.*, s.first_name, s.last_name, s.student_id as student_code, ba.bank_name, ba.branch_name, 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 {$where_clause_r}
       ORDER BY bt.verified_at DESC";

$stmt = $pdo->prepare($sql_r);
$stmt->execute($params_r);
$rejected_transactions = $stmt->fetchAll();

// Check for messages from session
if (isset($_SESSION['success_message'])) {
    $success_message = $_SESSION['success_message'];
    unset($_SESSION['success_message']);
}

if (isset($_SESSION['error_message'])) {
    $error_message = $_SESSION['error_message'];
    unset($_SESSION['error_message']);
}
?>

<!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;
        }
        .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;
            max-height: 200px;
            cursor: pointer;
        }
        .receipt-thumb {
            max-width: 60px;
            max-height: 60px;
            cursor: pointer;
        }
    </style>
</head>
<body>
<nav 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>
</nav>

<div class="container-fluid mt-4">
    <?php if ($success_message): ?>
        <div class="alert alert-success alert-dismissible fade show">
            <i class="fas fa-check-circle"></i> <?= htmlspecialchars($success_message) ?>
            <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
        </div>
    <?php endif; ?>
    
    <?php if ($error_message): ?>
        <div class="alert alert-danger alert-dismissible fade show">
            <i class="fas fa-exclamation-triangle"></i> <?= htmlspecialchars($error_message) ?>
            <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
        </div>
    <?php endif; ?>
    
    <div class="row">
        <div class="col-md-12">
            <h3><i class="fas fa-file-invoice-dollar"></i> ব্যাংক ট্রানজেকশন ভেরিফিকেশন</h3>
            
            <!-- Pending Transactions -->
            <?php if (!empty($pending_transactions)): ?>
                <div class="card mb-4">
                    <div class="card-header">
                        <div class="d-flex justify-content-between align-items-center">
                            <h5><i class="fas fa-clock"></i> মুলতুবি ট্রানজেকশন (<span data-status="pending"><?= count($pending_transactions) ?></span>)</h5>
                            <div class="input-group" style="max-width: 300px;">
                                <input type="text" class="form-control" id="searchPending" placeholder="খুঁজুন..." value="<?= htmlspecialchars($search_pending) ?>" onkeyup="realTimeSearch('pending')">
                                <span class="input-group-text">
                                    <i class="fas fa-search"></i>
                                </span>
                            </div>
                        </div>
                    </div>
                    <div class="card-body">
                        <div class="table-responsive">
                            <table id="pending-transactions-table" class="table table-striped">
                                <thead class="table-dark">
                                    <tr>
                                        <th>তারিখ</th>
                                        <th>ছাত্র/ছাত্রী</th>
                                        <th>ট্রানজেকশন আইডি</th>
                                        <th>ব্যাংক</th>
                                        <th>পরিমাণ</th>
                                        <th>রসিদ</th>
                                        <th>অ্যাকশন</th>
                                    </tr>
                                </thead>
                                <tbody>
                                    <?php foreach ($pending_transactions as $transaction): ?>
                                        <tr>
                                            <td><?= date('d/m/Y H:i', strtotime($transaction['submitted_at'])) ?></td>
                                            <td>
                                                <?= htmlspecialchars($transaction['first_name'] . ' ' . $transaction['last_name']) ?><br>
                                                <small><?= htmlspecialchars($transaction['student_code']) ?></small>
                                            </td>
                                            <td><?= htmlspecialchars($transaction['transaction_id']) ?></td>
                                            <td>
                                                <?= htmlspecialchars($transaction['bank_name']) ?><br>
                                                <small><?= htmlspecialchars($transaction['branch_name']) ?></small>
                                            </td>
                                            <td>৳<?= number_format((float)$transaction['amount'], 2) ?></td>
                                            <td>
                                                <?php if ($transaction['receipt_image']): ?>
                                                    <a href="../<?= htmlspecialchars($transaction['receipt_image']) ?>" target="_blank" data-bs-toggle="modal" data-bs-target="#receiptModal" data-img="../<?= htmlspecialchars($transaction['receipt_image']) ?>">
                                                        <img src="../<?= htmlspecialchars($transaction['receipt_image']) ?>" alt="Receipt" class="receipt-thumb img-thumbnail" style="cursor: pointer;">
                                                    </a>
                                                <?php else: ?>
                                                    N/A
                                                <?php endif; ?>
                                            </td>
                                            <td>
                                                <button class="btn btn-sm btn-primary" data-bs-toggle="modal" data-bs-target="#verifyModal" 
                                                        data-id="<?= $transaction['id'] ?>" 
                                                        data-student="<?= htmlspecialchars($transaction['first_name'] . ' ' . $transaction['last_name']) ?>"
                                                        data-transaction="<?= htmlspecialchars($transaction['transaction_id']) ?>"
                                                        data-amount="<?= $transaction['amount'] ?>">
                                                    <i class="fas fa-check"></i> ভেরিফাই
                                                </button>
                                                
                                                <button class="btn btn-sm btn-warning mt-1" data-bs-toggle="modal" data-bs-target="#editModal" 
                                                        data-id="<?= $transaction['id'] ?>" 
                                                        data-transaction="<?= htmlspecialchars($transaction['transaction_id']) ?>"
                                                        data-amount="<?= $transaction['amount'] ?>">
                                                    <i class="fas fa-edit"></i> এডিট
                                                </button>
                                            </td>
                                        </tr>
                                    <?php endforeach; ?>
                                </tbody>
                            </table>
                        </div>
                    </div>
                </div>
            <?php endif; ?>
            
            <!-- Verified Transactions -->
            <?php if (!empty($verified_transactions)): ?>
                <div class="card mb-4">
                    <div class="card-header">
                        <div class="d-flex justify-content-between align-items-center">
                            <h5><i class="fas fa-check-circle"></i> ভেরিফাইড ট্রানজেকশন (<span data-status="verified"><?= count($verified_transactions) ?></span>)</h5>
                            <div class="input-group" style="max-width: 300px;">
                                <input type="text" class="form-control" id="searchVerified" placeholder="খুঁজুন..." value="<?= htmlspecialchars($search_verified) ?>" onkeyup="realTimeSearch('verified')">
                                <span class="input-group-text">
                                    <i class="fas fa-search"></i>
                                </span>
                            </div>
                        </div>
                    </div>
                    <div class="card-body">
                        <div class="table-responsive">
                            <table id="verified-transactions-table" class="table table-striped">
                                <thead class="table-dark">
                                    <tr>
                                        <th>তারিখ</th>
                                        <th>ছাত্র/ছাত্রী</th>
                                        <th>ট্রানজেকশন আইডি</th>
                                        <th>ব্যাংক</th>
                                        <th>পরিমাণ</th>
                                        <th>রসিদ</th>
                                        <th>ভেরিফাই করেছেন</th>
                                    </tr>
                                </thead>
                                <tbody>
                                    <?php foreach ($verified_transactions as $transaction): ?>
                                        <tr>
                                            <td><?= date('d/m/Y H:i', strtotime($transaction['submitted_at'])) ?></td>
                                            <td>
                                                <?= htmlspecialchars($transaction['first_name'] . ' ' . $transaction['last_name']) ?><br>
                                                <small><?= htmlspecialchars($transaction['student_code']) ?></small>
                                            </td>
                                            <td><?= htmlspecialchars($transaction['transaction_id']) ?></td>
                                            <td>
                                                <?= htmlspecialchars($transaction['bank_name']) ?><br>
                                                <small><?= htmlspecialchars($transaction['branch_name']) ?></small>
                                            </td>
                                            <td>৳<?= number_format((float)$transaction['amount'], 2) ?></td>
                                            <td>
                                                <?php if ($transaction['receipt_image']): ?>
                                                    <a href="../<?= htmlspecialchars($transaction['receipt_image']) ?>" target="_blank" data-bs-toggle="modal" data-bs-target="#receiptModal" data-img="../<?= htmlspecialchars($transaction['receipt_image']) ?>">
                                                        <img src="../<?= htmlspecialchars($transaction['receipt_image']) ?>" alt="Receipt" class="receipt-thumb img-thumbnail" style="cursor: pointer;">
                                                    </a>
                                                <?php else: ?>
                                                    N/A
                                                <?php endif; ?>
                                            </td>
                                            <td>
                                                <?= htmlspecialchars($transaction['verified_by_name'] ?? 'N/A') ?><br>
                                                <small><?= $transaction['verified_at'] ? date('d/m/Y H:i', strtotime($transaction['verified_at'])) : 'N/A' ?></small>
                                            </td>
                                        </tr>
                                    <?php endforeach; ?>
                                </tbody>
                            </table>
                        </div>
                    </div>
                </div>
            <?php endif; ?>
            
            <!-- Rejected Transactions -->
            <?php if (!empty($rejected_transactions)): ?>
                <div class="card">
                    <div class="card-header">
                        <div class="d-flex justify-content-between align-items-center">
                            <h5><i class="fas fa-times-circle"></i> প্রত্যাখ্যাত ট্রানজেকশন (<span data-status="rejected"><?= count($rejected_transactions) ?></span>)</h5>
                            <div class="input-group" style="max-width: 300px;">
                                <input type="text" class="form-control" id="searchRejected" placeholder="খুঁজুন..." value="<?= htmlspecialchars($search_rejected) ?>" onkeyup="realTimeSearch('rejected')">
                                <span class="input-group-text">
                                    <i class="fas fa-search"></i>
                                </span>
                            </div>
                        </div>
                    </div>
                    <div class="card-body">
                        <div class="table-responsive">
                            <table id="rejected-transactions-table" class="table table-striped">
                                <thead class="table-dark">
                                    <tr>
                                        <th>তারিখ</th>
                                        <th>ছাত্র/ছাত্রী</th>
                                        <th>ট্রানজেকশন আইডি</th>
                                        <th>ব্যাংক</th>
                                        <th>পরিমাণ</th>
                                        <th>রসিদ</th>
                                        <th>ভেরিফাই করেছেন</th>
                                        <th>নোট</th>
                                    </tr>
                                </thead>
                                <tbody>
                                    <?php foreach ($rejected_transactions as $transaction): ?>
                                        <tr>
                                            <td><?= date('d/m/Y H:i', strtotime($transaction['submitted_at'])) ?></td>
                                            <td>
                                                <?= htmlspecialchars($transaction['first_name'] . ' ' . $transaction['last_name']) ?><br>
                                                <small><?= htmlspecialchars($transaction['student_code']) ?></small>
                                            </td>
                                            <td><?= htmlspecialchars($transaction['transaction_id']) ?></td>
                                            <td>
                                                <?= htmlspecialchars($transaction['bank_name']) ?><br>
                                                <small><?= htmlspecialchars($transaction['branch_name']) ?></small>
                                            </td>
                                            <td>৳<?= number_format((float)$transaction['amount'], 2) ?></td>
                                            <td>
                                                <?php if ($transaction['receipt_image']): ?>
                                                    <a href="../<?= htmlspecialchars($transaction['receipt_image']) ?>" target="_blank" data-bs-toggle="modal" data-bs-target="#receiptModal" data-img="../<?= htmlspecialchars($transaction['receipt_image']) ?>">
                                                        <img src="../<?= htmlspecialchars($transaction['receipt_image']) ?>" alt="Receipt" class="receipt-thumb img-thumbnail" style="cursor: pointer;">
                                                    </a>
                                                <?php else: ?>
                                                    N/A
                                                <?php endif; ?>
                                            </td>
                                            <td>
                                                <?= htmlspecialchars($transaction['verified_by_name'] ?? 'N/A') ?><br>
                                                <small><?= $transaction['verified_at'] ? date('d/m/Y H:i', strtotime($transaction['verified_at'])) : 'N/A' ?></small>
                                            </td>
                                            <td><?= htmlspecialchars($transaction['notes'] ?? 'N/A') ?></td>
                                        </tr>
                                    <?php endforeach; ?>
                                </tbody>
                            </table>
                        </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 endif; ?>
        </div>
    </div>
</div>

<!-- Verification Modal -->
<div class="modal fade" id="verifyModal" tabindex="-1" aria-labelledby="verifyModalLabel" aria-hidden="true">
    <div class="modal-dialog">
        <div class="modal-content">
            <form method="POST">
                <div class="modal-header">
                    <h5 class="modal-title" id="verifyModalLabel">ট্রানজেকশন ভেরিফাই করুন</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="verify_transaction_id">
                    
                    <div class="mb-3">
                        <label class="form-label"><i class="fas fa-user"></i> ছাত্র/ছাত্রী</label>
                        <div class="form-control-plaintext" id="verify_student_name"></div>
                    </div>
                    
                    <div class="mb-3">
                        <label class="form-label"><i class="fas fa-hashtag"></i> ট্রানজেকশন আইডি</label>
                        <div class="form-control-plaintext" id="verify_transaction_id_display"></div>
                    </div>
                    
                    <div class="mb-3">
                        <label class="form-label"><i class="fas fa-money-bill-wave"></i> পরিমাণ</label>
                        <div class="form-control-plaintext" id="verify_amount"></div>
                    </div>
                    
                    <div class="mb-3">
                        <label for="admin_notes" class="form-label"><i class="fas fa-sticky-note"></i> নোট (ঐচ্ছিক)</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="verify_payment" value="reject" class="btn btn-danger">
                        <i class="fas fa-times"></i> প্রত্যাখ্যান
                    </button>
                    <button type="submit" name="verify_payment" value="approve" class="btn btn-success">
                        <i class="fas fa-check"></i> অনুমদন
                    </button>
                </div>
            </form>
        </div>
    </div>
</div>

<!-- Edit Modal -->
<div class="modal fade" id="editModal" tabindex="-1" aria-labelledby="editModalLabel" aria-hidden="true">
    <div class="modal-dialog">
        <div class="modal-content">
            <form method="POST">
                <div class="modal-header">
                    <h5 class="modal-title" id="editModalLabel">ট্রানজেকশন এডিট করুন</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="edit_transaction_id">
                    
                    <div class="mb-3">
                        <label for="edit_transaction_id_field" class="form-label"><i class="fas fa-hashtag"></i> ট্রানজেকশন আইডি <span class="text-danger">*</span></label>
                        <input type="text" class="form-control" id="edit_transaction_id_field" name="edit_transaction_id" required>
                    </div>
                    
                    <div class="mb-3">
                        <label for="edit_amount" class="form-label"><i class="fas fa-money-bill-wave"></i> পরিমাণ (৳) <span class="text-danger">*</span></label>
                        <input type="number" class="form-control" id="edit_amount" name="edit_amount" step="0.01" min="0" required>
                    </div>
                    
                    <div class="mb-3">
                        <label for="edit_status" class="form-label"><i class="fas fa-tasks"></i> অবস্থা <span class="text-danger">*</span></label>
                        <select class="form-select" id="edit_status" name="edit_status" required>
                            <option value="pending">মুলতুবি</option>
                            <option value="verified">ভেরিফাইড</option>
                            <option value="rejected">প্রত্যাখ্যাত</option>
                        </select>
                    </div>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">বাতিল</button>
                    <button type="submit" name="edit_transaction" class="btn btn-primary">
                        <i class="fas fa-save"></i> আপডেট
                    </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>
    // Populate verification modal
    document.querySelectorAll('[data-bs-target="#verifyModal"]').forEach(button => {
        button.addEventListener('click', function() {
            document.getElementById('verify_transaction_id').value = this.dataset.id;
            document.getElementById('verify_student_name').textContent = this.dataset.student;
            document.getElementById('verify_transaction_id_display').textContent = this.dataset.transaction;
            document.getElementById('verify_amount').textContent = '৳' + parseFloat(this.dataset.amount).toFixed(2);
        });
    });
    
    // Populate edit modal
    document.querySelectorAll('[data-bs-target="#editModal"]').forEach(button => {
        button.addEventListener('click', function() {
            document.getElementById('edit_transaction_id').value = this.dataset.id;
            document.getElementById('edit_transaction_id_field').value = this.dataset.transaction;
            document.getElementById('edit_amount').value = this.dataset.amount;
            document.getElementById('edit_status').value = 'pending';
        });
    });
    
    // Real-time search with debouncing
    let searchTimeout;
    
    function realTimeSearch(status) {
        clearTimeout(searchTimeout);
        
        // Set timeout to delay the search for 500ms to reduce API calls
        searchTimeout = setTimeout(function() {
            performRealTimeSearch(status);
        }, 500);
    }
    
    function performRealTimeSearch(status) {
        const searchTerm = document.getElementById('search' + capitalizeFirstLetter(status)).value;
        
        // Create form data for AJAX request
        const formData = new FormData();
        formData.append('ajax', 'search_transactions');
        formData.append('status', status);
        formData.append('search_term', searchTerm);
        
        // Make AJAX request
        fetch(window.location.href, {
            method: 'POST',
            body: formData
        })
        .then(response => response.json())
        .then(data => {
            if (data.success) {
                updateTable(status, data.transactions);
            }
        })
        .catch(error => {
            console.error('Search error:', error);
        });
    }
    
    function capitalizeFirstLetter(string) {
        return string.charAt(0).toUpperCase() + string.slice(1);
    }
    
    function updateTable(status, transactions) {
        const tableBody = document.querySelector('#' + status + '-transactions-table tbody');
        if (!tableBody) return;
        
        if (transactions.length === 0) {
            const colSpan = status === 'rejected' ? 8 : 7;
            tableBody.innerHTML = `<tr><td colspan="` + colSpan + `" class="text-center">কোন ট্রানজেকশন পাওয়া যায়নি</td></tr>`;
            return;
        }
        
        let html = '';
        transactions.forEach(transaction => {
            html += `<tr>
                <td>` + formatDate(transaction.submitted_at || transaction.verified_at) + `</td>
                <td>
                    ` + transaction.first_name + ` ` + transaction.last_name + `<br>
                    <small>` + transaction.student_code + `</small>
                </td>
                <td>` + transaction.transaction_id + `</td>
                <td>
                    ` + transaction.bank_name + `<br>
                    <small>` + transaction.branch_name + `</small>
                </td>
                <td>৳` + parseFloat(transaction.amount).toFixed(2) + `</td>
                <td>
                    ` + (transaction.receipt_image ? 
                        `<a href="../` + transaction.receipt_image + `" target="_blank" data-bs-toggle="modal" data-bs-target="#receiptModal" data-img="../` + transaction.receipt_image + `">
                            <img src="../` + transaction.receipt_image + `" alt="Receipt" class="receipt-thumb img-thumbnail" style="cursor: pointer;">
                        </a>` : 
                        'N/A') + `
                </td>`;
                
            if (status === 'pending') {
                html += `<td>
                    <button class="btn btn-sm btn-primary" data-bs-toggle="modal" data-bs-target="#verifyModal" 
                            data-id="` + transaction.id + `" 
                            data-student="` + transaction.first_name + ` ` + transaction.last_name + `"
                            data-transaction="` + transaction.transaction_id + `"
                            data-amount="` + transaction.amount + `">
                        <i class="fas fa-check"></i> ভেরিফাই
                    </button>
                    
                    <button class="btn btn-sm btn-warning mt-1" data-bs-toggle="modal" data-bs-target="#editModal" 
                            data-id="` + transaction.id + `" 
                            data-transaction="` + transaction.transaction_id + `"
                            data-amount="` + transaction.amount + `">
                        <i class="fas fa-edit"></i> এডিট
                    </button>
                </td>`;
            } else if (status === 'verified') {
                html += `<td>
                    ` + (transaction.verified_by_name || 'N/A') + `<br>
                    <small>` + (transaction.verified_at ? formatDate(transaction.verified_at) : 'N/A') + `</small>
                </td>`;
            } else { // rejected
                html += `<td>
                    ` + (transaction.verified_by_name || 'N/A') + `<br>
                    <small>` + (transaction.verified_at ? formatDate(transaction.verified_at) : 'N/A') + `</small>
                </td>
                <td>` + (transaction.notes || 'N/A') + `</td>`;
            }
            
            html += '</tr>';
        });
        
        tableBody.innerHTML = html;
        
        // Update count in header
        const countElement = document.querySelector('[data-status="' + status + '"]');
        if (countElement) {
            countElement.textContent = transactions.length;
        }
    }
    
    function formatDate(dateString) {
        const date = new Date(dateString);
        return date.toLocaleDateString('bn-BD', { day: '2-digit', month: '2-digit', year: 'numeric', hour: '2-digit', minute: '2-digit' });
    }
    
    // Allow pressing Enter to trigger search - already handled by onkeyup
</script>

<!-- Receipt Modal -->
<div class="modal fade" id="receiptModal" tabindex="-1" aria-labelledby="receiptModalLabel" aria-hidden="true">
    <div class="modal-dialog modal-lg">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title" id="receiptModalLabel">রসিদের ছবি</h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
            </div>
            <div class="modal-body text-center">
                <img src="" alt="Receipt" class="img-fluid" id="modalReceiptImage">
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">বন্ধ</button>
            </div>
        </div>
    </div>
</div>

<script>
// Receipt modal functionality
var receiptModal = document.getElementById('receiptModal');
receiptModal.addEventListener('show.bs.modal', function (event) {
    var link = event.relatedTarget;
    var imgSrc = link.getAttribute('data-img');
    var modalImg = this.querySelector('.modal-body img');
    modalImg.src = imgSrc;
});
</script>
</body>
</html>