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

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

// Get classes for dropdown
$stmt = $pdo->query("SELECT id, name, section FROM classes WHERE status = 'active' ORDER BY name, section");
$classes = $stmt->fetchAll();

// Get academic sessions for dropdown
$stmt = $pdo->query("SELECT session_name FROM academic_sessions WHERE status = 'active' ORDER BY session_name DESC");
$sessions = $stmt->fetchAll();

// Get student groups for dropdown
$stmt = $pdo->query("SELECT group_name, group_code FROM student_groups WHERE status = 'active' ORDER BY group_name");
$groups = $stmt->fetchAll();

// Handle fee payment
$success_message = '';
$error_message = '';

if ($_SERVER['REQUEST_METHOD'] == 'POST' && isset($_POST['collect_fee'])) {
    $student_id = (int)$_POST['student_id'];
    $fee_payments = $_POST['fee_payments'] ?? [];
    $payment_method = $_POST['payment_method'] ?? 'cash';
    $payment_note = trim($_POST['payment_note'] ?? '');
    
    if ($student_id > 0 && !empty($fee_payments)) {
        try {
            $pdo->beginTransaction();
            
            $total_collected = 0;
            $processed_payments = [];
            
            foreach ($fee_payments as $fee_id => $payment_amount) {
                $payment_amount = (float)$payment_amount;
                if ($payment_amount <= 0) continue;
                
                $stmt = $pdo->prepare("SELECT * FROM fees WHERE id = ? AND student_id = ?");
                $stmt->execute([$fee_id, $student_id]);
                $fee = $stmt->fetch();
                
                if (!$fee) continue;
                
                $current_due = $fee['amount'] - $fee['paid_amount'];
                if ($current_due <= 0) continue;
                
                $actual_payment = min($payment_amount, $current_due);
                $new_paid_amount = $fee['paid_amount'] + $actual_payment;
                
                $new_status = ($new_paid_amount >= $fee['amount']) ? 'paid' : 'partial';
                
                $stmt = $pdo->prepare("UPDATE fees SET paid_amount = ?, status = ?, paid_date = CURDATE() WHERE id = ?");
                $stmt->execute([$new_paid_amount, $new_status, $fee_id]);
                
                $stmt = $pdo->prepare("
                    INSERT INTO fee_payments (fee_id, amount, payment_date, payment_method, notes, created_by)
                    VALUES (?, ?, NOW(), ?, ?, ?)
                ");
                $stmt->execute([$fee_id, $actual_payment, $payment_method, $payment_note, $_SESSION['user_id'] ?? null]);
                
                // Generate and update transaction ID
                $payment_id = $pdo->lastInsertId();
                if ($payment_id) {
                    $transaction_id = 'TXN-' . date('Ymd') . '-' . $payment_id;
                    $update_txn_stmt = $pdo->prepare("UPDATE fee_payments SET transaction_id = ? WHERE id = ?");
                    $update_txn_stmt->execute([$transaction_id, $payment_id]);

                    // Store info for success message
                    $processed_payments[] = [
                        'payment_id' => $payment_id,
                        'transaction_id' => $transaction_id,
                        'fee_type' => $fee['fee_type'],
                        'amount' => $actual_payment
                    ];
                }
                
                $total_collected += $actual_payment;
            }
            
            $pdo->commit();
            
            if ($total_collected > 0) {
                $success_message = "সফলভাবে ৳" . number_format($total_collected, 2) . " টাকা সংগ্রহ করা হয়েছে।";
                if (!empty($processed_payments)) {
                    $success_message .= "<hr class='my-2'><strong>প্রসেসকৃত পেমেন্ট:</strong><ul class='list-unstyled mt-2'>";
                    foreach ($processed_payments as $p) {
                        $success_message .= "<li class='d-flex justify-content-between align-items-center mb-1'>" . htmlspecialchars($p['fee_type']) . ": ৳" . number_format($p['amount'], 2);
                        $success_message .= " <span>(ID: {$p['payment_id']}) ";
                        $success_message .= "<a href='receipt.php?id={$p['payment_id']}' target='_blank' class='btn btn-sm btn-outline-success ms-2'><i class='fas fa-print'></i> রসিদ</a></span></li>";
                    }
                    $success_message .= "</ul>";
                }
            } else {
                $error_message = "কোন পেমেন্ট প্রক্রিয়া করা হয়নি";
            }
            
        } catch (Exception $e) {
            $pdo->rollBack();
            $error_message = 'পেমেন্ট প্রক্রিয়ায় সমস্যা হয়েছে: ' . $e->getMessage();
        }
    } else {
        $error_message = 'সকল প্রয়োজনীয় তথ্য পূরণ করুন';
    }
}

// AJAX handler for getting students
if (isset($_GET['ajax']) && $_GET['ajax'] == 'get_students') {
    header('Content-Type: application/json');
    
    $class_id = $_GET['class_id'] ?? '';
    $session = $_GET['session'] ?? '';
    $group_name = $_GET['group_name'] ?? '';
    
    $where_conditions = ["s.status = 'active'"];
    $params = [];
    
    if (!empty($class_id)) {
        $where_conditions[] = "s.class_id = ?";
        $params[] = $class_id;
    }
    
    if (!empty($session)) {
        $where_conditions[] = "s.session = ?";
        $params[] = $session;
    }
    
    if ($group_name !== '') {
        $where_conditions[] = "COALESCE(s.group_name, '') = ?";
        $params[] = $group_name;
    }
    
    $where_clause = implode(' AND ', $where_conditions);
    
    $sql = "
        SELECT s.id, s.student_id, s.first_name, s.last_name, s.roll_number, s.session, s.group_name, s.scholarship, c.name as class_name, c.section as class_section,
               COALESCE(SUM(f.amount - f.paid_amount), 0) as total_due
        FROM students s
        JOIN classes c ON s.class_id = c.id
        LEFT JOIN fees f ON s.id = f.student_id
        WHERE $where_clause
        GROUP BY s.id
        ORDER BY s.roll_number
    ";
    
    $stmt = $pdo->prepare($sql);
    $stmt->execute($params);
    $students = $stmt->fetchAll();
    
    echo json_encode($students);
    exit();
}

// AJAX handler for getting student fee details
if (isset($_GET['ajax']) && $_GET['ajax'] == 'get_student_fees') {
    header('Content-Type: application/json');
    
    $student_id = (int)($_GET['student_id'] ?? 0);
    
    if ($student_id > 0) {
        // First check if student has scholarship
        $stmt = $pdo->prepare("SELECT scholarship FROM students WHERE id = ?");
        $stmt->execute([$student_id]);
        $student = $stmt->fetch();
        
        $stmt = $pdo->prepare("SELECT *, (amount - paid_amount) as due_amount FROM fees WHERE student_id = ? AND (amount - paid_amount) > 0 ORDER BY due_date ASC");
        $stmt->execute([$student_id]);
        $fees = $stmt->fetchAll();
        
        // If student has scholarship, filter out salary fees
        if ($student && $student['scholarship'] === 'yes') {
            // Filter fees to exclude salary fees (both "বেতন" and "মাসিক বেতন")
            $filtered_fees = array_filter($fees, function($fee) {
                return $fee['fee_type'] !== 'বেতন' && $fee['fee_type'] !== 'মাসিক বেতন';
            });
            
            // If all fees were salary fees, return scholarship exemption
            if (empty($filtered_fees)) {
                echo json_encode(['scholarship' => true, 'message' => 'বেতন উপবৃত্তির কারণে মওকুত']);
            } else {
                // Return only non-salary fees
                echo json_encode(array_values($filtered_fees));
            }
        } else {
            echo json_encode($fees);
        }
    } else {
        echo json_encode([]);
    }
    exit();
}

// AJAX handler for merchant payment initiation
if (isset($_GET['ajax']) && $_GET['ajax'] == 'initiate_merchant_payment') {
    header('Content-Type: application/json');
    
    $student_id = (int)($_POST['student_id'] ?? 0);
    $amount = (float)($_POST['amount'] ?? 0);
    $payment_method = $_POST['payment_method'] ?? 'bkash';
    $phone_number = $_POST['phone_number'] ?? '';
    
    if ($student_id <= 0 || $amount <= 0 || empty($phone_number)) {
        echo json_encode(['success' => false, 'message' => 'Invalid payment data']);
        exit();
    }
    
    // Get student details
    $stmt = $pdo->prepare("
        SELECT s.*, c.name as class_name, c.section 
        FROM students s 
        JOIN classes c ON s.class_id = c.id 
        WHERE s.id = ?
    ");
    $stmt->execute([$student_id]);
    $student = $stmt->fetch();
    
    if (!$student) {
        echo json_encode(['success' => false, 'message' => 'Student not found']);
        exit();
    }
    
    // Generate merchant invoice number
    $merchant_invoice = 'FEE_' . date('Ymd') . '_' . uniqid();
    
    // Store payment request in database
    $stmt = $pdo->prepare("
        INSERT INTO merchant_payment_requests 
        (merchant_invoice, student_id, amount, payment_method, phone_number, status, created_at) 
        VALUES (?, ?, ?, ?, ?, 'pending', NOW())
    ");
    $stmt->execute([$merchant_invoice, $student_id, $amount, $payment_method, $phone_number]);
    $payment_request_id = $pdo->lastInsertId();
    
    // Prepare response based on payment method
    $response = [
        'success' => true,
        'merchant_invoice' => $merchant_invoice,
        'payment_request_id' => $payment_request_id,
        'student_name' => $student['first_name'] . ' ' . $student['last_name'],
        'student_id' => $student['student_id'],
        'class' => $student['class_name'] . ' - ' . $student['section'],
        'amount' => $amount
    ];
    
    // Handle different payment methods
    switch ($payment_method) {
        case 'bkash':
            // Manual bKash payment instructions
            $response['type'] = 'manual';
            $response['instructions'] = 'bKash এ পেমেন্ট করতে নিচের ধাপগুলো অনুসরণ করুন:<br>
            1. bKash অ্যাপ খুলুন বা *247# ডায়াল করুন<br>
            2. "Send Money" অপশন সিলেক্ট করুন<br>
            3. রিসিভার নাম্বার: 017XXXXXXXX<br>
            4. পরিমাণ: ' . number_format($amount, 2) . ' টাকা<br>
            5. রেফারেন্স: ' . $merchant_invoice . '<br>
            6. PIN দিয়ে পেমেন্ট সম্পন্ন করুন<br>
            7. ট্রানজেকশন আইডি নোট করুন';
            break;
            
        case 'nagad':
            // Manual Nagad payment instructions
            $response['type'] = 'manual';
            $response['instructions'] = 'Nagad এ পেমেন্ট করতে নিচের ধাপগুলো অনুসরণ করুন:<br>
            1. Nagad অ্যাপ খুলুন<br>
            2. "Send Money" অপশন সিলেক্ট করুন<br>
            3. রিসিভার নাম্বার: 018XXXXXXXX<br>
            4. পরিমাণ: ' . number_format($amount, 2) . ' টাকা<br>
            5. রেফারেন্স: ' . $merchant_invoice . '<br>
            6. PIN দিয়ে পেমেন্ট সম্পন্ন করুন<br>
            7. ট্রানজেকশন আইডি নোট করুন';
            break;
            
        case 'rocket':
            // Manual Rocket payment instructions
            $response['type'] = 'manual';
            $response['instructions'] = 'Rocket এ পেমেন্ট করতে নিচের ধাপগুলো অনুসরণ করুন:<br>
            1. *322# ডায়াল করুন<br>
            2. "Send Money" অপশন সিলেক্ট করুন<br>
            3. রিসিভার নাম্বার: 019XXXXXXXX<br>
            4. পরিমাণ: ' . number_format($amount, 2) . ' টাকা<br>
            5. রেফারেন্স: ' . $merchant_invoice . '<br>
            6. PIN দিয়ে পেমেন্ট সম্পন্ন করুন<br>
            7. ট্রানজেকশন আইডি নোট করুন';
            break;
            
        default:
            $response['type'] = 'manual';
            $response['instructions'] = 'পেমেন্ট করতে নিচের ধাপগুলো অনুসরণ করুন:<br>
            1. ' . ucfirst($payment_method) . ' এ পেমেন্ট করুন<br>
            2. মার্চেন্ট নাম্বার: 01XXXXXXXXX<br>
            3. পরিমাণ: ' . number_format($amount, 2) . ' টাকা<br>
            4. রেফারেন্স: ' . $merchant_invoice . '<br>
            5. ট্রানজেকশন আইডি নোট করুন';
    }
    
    echo json_encode($response);
    exit();
}

// AJAX handler for collecting payment
if (isset($_POST['action'])) {
    $action = trim($_POST['action']);
    if ($action === 'collect_payment') {
        $student_id = intval($_POST['student_id'] ?? 0);
        $payments_json = $_POST['payments'] ?? '[]';
        $payment_method = trim($_POST['payment_method'] ?? 'Cash');
        $note = trim($_POST['note'] ?? '');
        $payments = json_decode($payments_json, true);
        if (!is_array($payments)) $payments = [];

        if ($student_id <= 0 || empty($payments)) {
            echo json_encode(['success'=>false, 'message'=>'Invalid data']);
            exit();
        }

        try {
            $pdo->beginTransaction();
            $total_paid = 0.0;
            $receipt_items = [];

            // Lock rows to avoid race (best effort)
            foreach ($payments as $p) {
                $fee_id = intval($p['fee_id'] ?? 0);
                $pay_amount = floatval($p['pay_amount'] ?? 0);
                if ($fee_id <= 0 || $pay_amount <= 0) continue;

                // Get current fee row
                $stmt = $pdo->prepare("SELECT id, student_id, fee_type, amount, COALESCE(paid_amount,0) AS paid_amount, academic_year, month, due_date, status FROM fees WHERE id=? AND student_id=? FOR UPDATE");
                $stmt->execute([$fee_id, $student_id]);
                $fee = $stmt->fetch();
                if (!$fee) continue;

                $due = floatval($fee['amount']) - floatval($fee['paid_amount']);
                if ($due <= 0) continue;

                $apply = min($due, $pay_amount);
                if ($apply <= 0) continue;

                // Update fee row
                $new_paid = floatval($fee['paid_amount']) + $apply;
                $new_status = ($new_paid + 0.0001 >= floatval($fee['amount'])) ? 'paid' : 'pending';
                $upd = $pdo->prepare("UPDATE fees SET paid_amount = ?, status = ? WHERE id = ?");
                $upd->execute([$new_paid, $new_status, $fee_id]);

                // Record payment into fee_payments for unified ledger
                $ins = $pdo->prepare("INSERT INTO fee_payments (fee_id, amount, payment_date, payment_method, transaction_id, notes, created_by) VALUES (?, ?, NOW(), ?, NULL, ?, ?)");
                $ins->execute([$fee_id, $apply, $payment_method, $note, $_SESSION['user_id'] ?? null]);

                $total_paid += $apply;
                $receipt_items[] = [
                    'fee_type' => $fee['fee_type'],
                    'academic_year' => $fee['academic_year'],
                    'month' => $fee['month'],
                    'amount' => floatval($fee['amount']),
                    'paid_now' => $apply,
                ];
            }

            // Fetch student info for receipt
            $sStmt = $pdo->prepare("SELECT s.student_id, s.first_name, s.last_name, s.roll_number, s.session, COALESCE(s.group_name,'') AS group_name, c.name AS class_name, c.section AS class_section FROM students s JOIN classes c ON s.class_id=c.id WHERE s.id=?");
            $sStmt->execute([$student_id]);
            $stu = $sStmt->fetch();

            $pdo->commit();

            // Store payment info in session for success page
            $_SESSION['payment_student_id'] = $student_id;
            $_SESSION['payment_amount'] = $total_paid;
            $_SESSION['payment_method'] = $payment_method;
            $_SESSION['payment_tran_id'] = 'CASH_' . time();

            echo json_encode([
                'success'=>true,
                'message'=>'Payment successfully saved',
                'total_paid'=>$total_paid,
                'redirect_url'=>'payment_success_message.php',
                'receipt'=>[
                    'student'=>$stu,
                    'items'=>$receipt_items,
                    'payment_method'=>$payment_method,
                    'note'=>$note,
                    'datetime'=>date('Y-m-d H:i:s')
                ]
            ]);
            exit();
        } catch (Exception $e) {
            $pdo->rollBack();
            echo json_encode(['success'=>false, 'message'=>'Payment processing error: '.$e->getMessage()]);
            exit();
        }
    }
}
?>

<!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; 
        }
        .header-section {
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            color: white;
            padding: 2rem 0;
            margin-bottom: 2rem;
        }
        .card {
            border: none;
            border-radius: 15px;
            box-shadow: 0 0 20px rgba(0,0,0,0.1);
            margin-bottom: 1.5rem;
        }
        .card-header {
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            color: white;
            border-radius: 15px 15px 0 0 !important;
            padding: 1rem 1.5rem;
        }
        .filter-section {
            background: linear-gradient(135deg, #f093fb 0%, #f5576c 100%);
            border-radius: 15px;
            padding: 1.5rem;
            margin-bottom: 2rem;
        }
        .filter-section .form-label {
            color: white;
            font-weight: 600;
        }
        .student-card {
            border: 1px solid #e9ecef;
            border-radius: 10px;
            transition: all 0.3s ease;
            cursor: pointer;
            margin-bottom: 0.5rem;
        }
        .student-card:hover {
            transform: translateY(-2px);
            box-shadow: 0 5px 15px rgba(0,0,0,0.1);
        }
        .student-card.selected {
            border-color: #007bff;
            background-color: #f0f8ff;
        }
        .fee-item {
            border: 1px solid #dee2e6;
            border-radius: 8px;
            padding: 1rem;
            margin-bottom: 0.5rem;
            background: white;
        }
        .fee-item.overdue {
            border-left: 4px solid #dc3545;
            background-color: #fff5f5;
        }
        .amount-display {
            font-size: 1.1rem;
            font-weight: 600;
        }
        .total-due {
            color: #dc3545;
        }
        .btn-collect {
            background: linear-gradient(135deg, #28a745 0%, #20c997 100%);
            border: none;
            border-radius: 25px;
            padding: 0.75rem 2rem;
            font-weight: 600;
        }
        .step-instructions {
            background-color: #e8f4f8;
            border-left: 4px solid #17a2b8;
            padding: 1rem;
            border-radius: 0 8px 8px 0;
            margin-bottom: 1.5rem;
        }
        .step-number {
            display: inline-block;
            width: 30px;
            height: 30px;
            background: #17a2b8;
            color: white;
            border-radius: 50%;
            text-align: center;
            line-height: 30px;
            font-weight: bold;
            margin-right: 10px;
        }
        .student-card.no-dues {
            border: 1px solid #28a745;
            background-color: #e8f5e9;
        }
        .student-card.no-dues:hover {
            background-color: #dcfce7;
        }
    </style>
</head>
<body>
    <!-- Header Section -->
    <div class="header-section">
        <div class="container">
            <div class="row">
                <div class="col-12 text-center">
                    <h1><i class="fas fa-money-bill-wave"></i> ফি পেমেন্ট ড্যাশবোর্ড</h1>
                    <p class="lead">স্কুল ম্যানেজমেন্ট সিস্টেম</p>
                </div>
            </div>
        </div>
    </div>

    <div class="container">
        <!-- Step-by-Step Instructions -->
        <div class="step-instructions">
            <h5><i class="fas fa-info-circle"></i> কিভাবে ফি সংগ্রহ করবেন:</h5>
            <div class="mt-2">
                <p><span class="step-number">1</span> নিচের ফিল্টার ব্যবহার করে শিক্ষার্থী খুঁজুন (সেশন, ক্লাস, গ্রুপ)</p>
                <p><span class="step-number">2</span> শিক্ষার্থী তালিকা থেকে যে শিক্ষার্থীর ফি সংগ্রহ করতে চান তার উপর ক্লিক করুন</p>
                <p><span class="step-number">3</span> বকেয়া ফি সমূহের পরিমাণ দিন এবং পেমেন্ট পদ্ধতি নির্বাচন করুন</p>
                <p><span class="step-number">4</span> "ফি সংগ্রহ করুন" বাটনে ক্লিক করুন</p>
                <p><span class="step-number">5</span> পেমেন্ট সফল হলে রসিদ প্রিন্ট করুন</p>
            </div>
        </div>

        <?php if ($success_message): ?>
            <div class="alert alert-success alert-dismissible fade show" role="alert">
                <?php echo $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" role="alert">
                <?php echo $error_message; ?>
                <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
            </div>
        <?php endif; ?>

        <div class="row">
            <!-- Filter Section -->
            <div class="col-12">
                <div class="filter-section">
                    <h4 class="text-white mb-3"><i class="fas fa-filter"></i> শিক্ষার্থী খুঁজুন</h4>
                    <div class="row g-3">
                        <div class="col-md-3">
                            <label for="filter_session" class="form-label">সেশন</label>
                            <select class="form-select" id="filter_session">
                                <option value="">সব সেশন</option>
                                <?php foreach ($sessions as $session): ?>
                                    <option value="<?php echo htmlspecialchars($session['session_name']); ?>">
                                        <?php echo htmlspecialchars($session['session_name']); ?>
                                    </option>
                                <?php endforeach; ?>
                            </select>
                        </div>
                        <div class="col-md-3">
                            <label for="filter_class" class="form-label">ক্লাস</label>
                            <select class="form-select" id="filter_class">
                                <option value="">সব ক্লাস</option>
                                <?php foreach ($classes as $class): ?>
                                    <option value="<?php echo $class['id']; ?>">
                                        <?php echo $class['name'] . ' - ' . $class['section']; ?>
                                    </option>
                                <?php endforeach; ?>
                            </select>
                        </div>
                        <div class="col-md-3">
                            <label for="filter_group" class="form-label">গ্রুপ</label>
                            <select class="form-select" id="filter_group">
                                <option value="">সব গ্রুপ</option>
                                <option value="">কোন গ্রুপ নেই</option>
                                <?php foreach ($groups as $group): ?>
                                    <option value="<?php echo htmlspecialchars($group['group_name']); ?>">
                                        <?php echo htmlspecialchars($group['group_name']); ?>
                                    </option>
                                <?php endforeach; ?>
                            </select>
                        </div>
                        <div class="col-md-3">
                            <label class="form-label">&nbsp;</label>
                            <button type="button" class="btn btn-light w-100" onclick="loadStudents()">
                                <i class="fas fa-search"></i> খুঁজুন
                            </button>
                        </div>
                    </div>
                </div>
            </div>
        </div>

        <div class="row">
            <!-- Student List -->
            <div class="col-md-5">
                <div class="card">
                    <div class="card-header">
                        <div class="d-flex justify-content-between align-items-center">
                            <h5 class="mb-0"><i class="fas fa-users"></i> শিক্ষার্থী তালিকা</h5>
                            <span class="badge bg-light text-dark" id="student-count">0 জন</span>
                        </div>
                    </div>
                    <div class="card-body">
                        <div class="mb-3">
                            <div class="input-group">
                                <input type="text" class="form-control" id="student-search" placeholder="নাম, আইডি বা রোল দিয়ে খুঁজুন...">
                                <button class="btn btn-outline-secondary" type="button" id="search-button">
                                    <i class="fas fa-search"></i> খুঁজুন
                                </button>
                            </div>
                        </div>
                        <div style="max-height: 550px; overflow-y: auto;">
                            <div id="students-list">
                                <div class="text-center text-muted py-4">
                                    <i class="fas fa-search fa-3x mb-3"></i>
                                    <p>শিক্ষার্থী খুঁজতে উপরের ফিল্টার ব্যবহার করুন</p>
                                </div>
                            </div>
                        </div>
                        <nav class="mt-3">
                            <ul class="pagination justify-content-center pagination-sm" id="pagination-controls"></ul>
                        </nav>
                    </div>
                </div>
            </div>
            
            <!-- Fee Collection Area -->
            <div class="col-md-7">
                <div class="card">
                    <div class="card-header">
                        <h5><i class="fas fa-money-bill-wave"></i> ফি কালেকশন</h5>
                    </div>
                    <div class="card-body">
                        <div id="fee-collection-area">
                            <div class="text-center text-muted py-4">
                                <i class="fas fa-hand-point-left fa-3x mb-3"></i>
                                <p>একজন শিক্ষার্থী নির্বাচন করুন</p>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>

    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/js/bootstrap.bundle.min.js"></script>
    <script>
        let selectedStudentId = null;
        
        let allStudents = [];
        let filteredStudents = [];
        const studentsPerPage = 15;
        let currentPage = 1;

        function loadStudents() {
            const session = document.getElementById('filter_session').value;
            const classId = document.getElementById('filter_class').value;
            const groupName = document.getElementById('filter_group').value;

            const params = new URLSearchParams({ 
                ajax: 'get_students', 
                session: session, 
                class_id: classId, 
                group_name: groupName 
            });

            document.getElementById('students-list').innerHTML = '<div class="text-center text-muted py-4"><div class="spinner-border text-primary" role="status"></div><p class="mt-2">লোড হচ্ছে...</p></div>';

            return fetch(`?${params}`)
                .then(response => response.json())
                .then(students => {
                    allStudents = students;
                    filterStudents();
                })
                .catch(error => {
                    console.error('Error:', error);
                    showAlert('শিক্ষার্থী লোড করতে সমস্যা হয়েছে', 'danger');
                });
        }

        function filterStudents() {
            const searchTerm = document.getElementById('student-search').value.toLowerCase().trim();
            filteredStudents = (searchTerm === '') ? allStudents : allStudents.filter(s => 
                (s.first_name + ' ' + s.last_name).toLowerCase().includes(searchTerm) ||
                s.roll_number.toString().toLowerCase().includes(searchTerm) ||
                (s.student_id || '').toString().toLowerCase().includes(searchTerm)
            );
            currentPage = 1;
            renderPage(currentPage);
            setupPagination();
        }

        function renderPage(page) {
            currentPage = page;
            const container = document.getElementById('students-list');
            const countElement = document.getElementById('student-count');
            
            countElement.textContent = `${filteredStudents.length} জন`;

            if (filteredStudents.length === 0) {
                container.innerHTML = '<div class="text-center text-muted py-4"><i class="fas fa-user-slash fa-3x mb-3"></i><p>কোন শিক্ষার্থী পাওয়া যায়নি</p></div>';
                return;
            }

            const startIndex = (page - 1) * studentsPerPage;
            const endIndex = startIndex + studentsPerPage;
            container.innerHTML = generateStudentCards(filteredStudents.slice(startIndex, endIndex));
        }

        function setupPagination() {
            const paginationContainer = document.getElementById('pagination-controls');
            if (!paginationContainer) return;
            paginationContainer.innerHTML = '';
            
            const pageCount = Math.ceil(filteredStudents.length / studentsPerPage);
            if (pageCount <= 1) return;

            const createPageItem = (text, pageNum, isDisabled = false, isActive = false) => {
                const li = document.createElement('li');
                li.className = `page-item ${isDisabled ? 'disabled' : ''} ${isActive ? 'active' : ''}`;
                const a = document.createElement('a');
                a.className = 'page-link';
                a.href = '#';
                a.innerHTML = text;
                if (!isDisabled) {
                    a.addEventListener('click', (e) => { 
                        e.preventDefault(); 
                        renderPage(pageNum); 
                    });
                }
                li.appendChild(a);
                return li;
            };

            paginationContainer.appendChild(createPageItem('&laquo;', currentPage - 1, currentPage === 1));
            for (let i = 1; i <= pageCount; i++) {
                paginationContainer.appendChild(createPageItem(i, i, false, i === currentPage));
            }
            paginationContainer.appendChild(createPageItem('&raquo;', currentPage + 1, currentPage === pageCount));
        }

        function generateStudentCards(students) {
            let html = '';
            students.forEach(student => {
                const totalDue = parseFloat(student.total_due) || 0;
                const hasScholarship = student.scholarship === 'yes';
                
                // Determine if student has no dues
                const hasNoDues = totalDue === 0 && !hasScholarship;
                
                html += `
                    <div class="student-card p-3 mb-2 ${selectedStudentId == student.id ? 'selected' : ''} ${hasNoDues ? 'no-dues' : ''}" 
                         onclick="selectStudent(event, ${student.id}, '${student.first_name} ${student.last_name}')">
                        <div class="d-flex justify-content-between align-items-start">
                            <div>
                                <h6 class="mb-1">${student.first_name} ${student.last_name}</h6>
                                <small class="text-muted">রোল: ${student.roll_number} | আইডি: ${student.student_id || 'N/A'}</small>
                                ${hasScholarship ? '<span class="badge bg-success mt-1">উপবৃত্তি</span>' : ''}
                                ${hasNoDues ? '<span class="badge bg-success mt-1">বকেয়া নেই</span>' : ''}
                            </div>
                            <div class="text-end">
                                ${hasScholarship ? 
                                    '<div class="text-success"><small>বেতন মওকুত</small></div>' : 
                                    hasNoDues ?
                                    '<div class="text-success"><small>সব পরিশোধিত</small></div>' :
                                    `<div class="amount-display total-due">৳${totalDue.toFixed(2)}</div>
                                    <small class="text-muted">বকেয়া</small>`}
                            </div>
                        </div>
                    </div>
                `;
            });
            return html;
        }

        function selectStudent(event, studentId, studentName) {
            selectedStudentId = studentId;
            document.querySelectorAll('.student-card').forEach(card => card.classList.remove('selected'));
            event.currentTarget.classList.add('selected');
            loadStudentFees(studentId, studentName);
        }

        function loadStudentFees(studentId, studentName) {
            const params = new URLSearchParams({ ajax: 'get_student_fees', student_id: studentId });
            fetch(`?${params}`)
                .then(response => response.json())
                .then(fees => displayFeeCollection(studentId, studentName, fees))
                .catch(error => {
                    console.error('Error:', error);
                    showAlert('ফি তথ্য লোড করতে সমস্যা হয়েছে', 'danger');
                });
        }

        function displayFeeCollection(studentId, studentName, fees) {
            const container = document.getElementById('fee-collection-area');
            
            // Check if student has scholarship exemption
            if (fees.scholarship === true) {
                container.innerHTML = `
                    <div class="text-center text-success py-4">
                        <i class="fas fa-graduation-cap fa-3x mb-3"></i>
                        <h5>${studentName}</h5>
                        <div class="alert alert-success">
                            <i class="fas fa-check-circle"></i> এই শিক্ষার্থী উপবৃত্তি পেয়েছেন। বেতন মওকুত করা হয়েছে।
                        </div>
                    </div>
                `;
                return;
            }
            
            if (fees.length === 0) {
                container.innerHTML = `
                    <div class="text-center text-success py-4">
                        <i class="fas fa-check-circle fa-3x mb-3"></i>
                        <h5>${studentName}</h5>
                        <p>সব ফি পরিশোধিত</p>
                    </div>
                `;
                return;
            }

            let totalDue = 0;
            let feesHtml = fees.map(fee => {
                const dueAmount = parseFloat(fee.due_amount);
                totalDue += dueAmount;
                // Check if this is a salary fee
                const isSalaryFee = (fee.fee_type === 'বেতন' || fee.fee_type === 'মাসিক বেতন');
                return `
                    <div class="fee-item ${new Date(fee.due_date) < new Date() ? 'overdue' : ''}">
                        <div class="d-flex justify-content-between align-items-start mb-2">
                            <div>
                                <h6 class="mb-1">${fee.fee_type}</h6>
                                <small class="text-muted">${fee.month ? fee.month + ' ' : ''}${fee.academic_year || ''} | শেষ তারিখ: ${fee.due_date}</small>
                                ${isSalaryFee ? '<span class="badge bg-success mt-1">উপবৃত্তি মওকুত</span>' : ''}
                            </div>
                            <div class="text-end">
                                <div class="amount-display">৳${dueAmount.toFixed(2)}</div>
                                <small class="text-muted">বকেয়া</small>
                            </div>
                        </div>
                        ${!isSalaryFee ? 
                        `<div class="input-group input-group-sm">
                            <span class="input-group-text">৳</span>
                            <input type="number" class="form-control payment-input" name="fee_payments[${fee.id}]" 
                                   max="${dueAmount}" min="0" step="0.01" placeholder="পেমেন্ট" 
                                   onchange="updateTotalPayment()">
                        </div>` : 
                        '<div class="text-success"><i class="fas fa-check-circle"></i> মওকুত</div>'}
                    </div>
                `;
            }).join('');

            container.innerHTML = `
                <div class="mb-3">
                    <h5>${studentName}</h5>
                    <div class="alert alert-info">
                        <strong>মোট বকেয়া: ৳${totalDue.toFixed(2)}</strong>
                    </div>
                </div>
                <form method="POST" action="" id="feeCollectionForm">
                    <input type="hidden" name="student_id" value="${studentId}">
                    <div class="mb-3">
                        <h6>বকেয়া ফি সমূহ:</h6>
                        ${feesHtml}
                    </div>
                    <div class="row mb-3">
                        <div class="col-md-6">
                            <label class="form-label">পেমেন্ট পদ্ধতি</label>
                            <select class="form-select" name="payment_method" id="paymentMethod">
                                <option value="cash">নগদ</option>
                                <option value="bank">ব্যাংক</option>
                                <option value="mobile">মোবাইল ব্যাংকিং</option>
                                <option value="bkash">bKash</option>
                                <option value="nagad">Nagad</option>
                                <option value="rocket">Rocket</option>
                            </select>
                        </div>
                        <div class="col-md-6">
                            <label class="form-label">মোট পেমেন্ট</label>
                            <div class="form-control" id="total-payment-display">৳0.00</div>
                        </div>
                    </div>
                    <div class="mb-3" id="mobileNumberField" style="display: none;">
                        <label class="form-label">মোবাইল নাম্বার</label>
                        <input type="tel" class="form-control" id="mobileNumber" placeholder="01XXXXXXXXX">
                        <div class="form-text">মার্চেন্ট অ্যাকাউন্টে পেমেন্টের জন্য মোবাইল নাম্বার প্রয়োজন</div>
                    </div>
                    <div class="mb-3">
                        <label class="form-label">নোট (ঐচ্ছিক)</label>
                        <textarea class="form-control" name="payment_note" rows="2" 
                                  placeholder="পেমেন্ট সম্পর্কে কোন বিশেষ তথ্য..."></textarea>
                    </div>
                    <div class="d-grid gap-2">
                        <button type="button" class="btn btn-collect" onclick="processPayment()">
                            <i class="fas fa-money-bill-wave"></i> ফি সংগ্রহ করুন
                        </button>
                    </div>
                </form>
                <div id="merchantPaymentModal" class="modal fade" tabindex="-1">
                    <div class="modal-dialog">
                        <div class="modal-content">
                            <div class="modal-header">
                                <h5 class="modal-title">মার্চেন্ট পেমেন্ট</h5>
                                <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
                            </div>
                            <div class="modal-body" id="merchantPaymentContent">
                                <!-- Payment instructions will be loaded here -->
                            </div>
                            <div class="modal-footer">
                                <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">বন্ধ</button>
                                <button type="button" class="btn btn-primary" onclick="verifyPayment()">পেমেন্ট ভেরিফাই করুন</button>
                            </div>
                        </div>
                    </div>
                </div>
            `;
            
            // Add event listener for payment method change
            document.getElementById('paymentMethod').addEventListener('change', function() {
                const mobileField = document.getElementById('mobileNumberField');
                const selectedMethod = this.value;
                if (['bkash', 'nagad', 'rocket'].includes(selectedMethod)) {
                    mobileField.style.display = 'block';
                } else {
                    mobileField.style.display = 'none';
                }
            });
        }

        function updateTotalPayment() {
            let total = 0;
            document.querySelectorAll('.payment-input').forEach(input => { 
                total += parseFloat(input.value) || 0; 
            });
            const display = document.getElementById('total-payment-display');
            if (display) display.textContent = `৳${total.toFixed(2)}`;
        }

        function processPayment() {
            const paymentMethod = document.getElementById('paymentMethod').value;
            
            // If it's a merchant payment method, handle differently
            if (['bkash', 'nagad', 'rocket'].includes(paymentMethod)) {
                initiateMerchantPayment();
            } else {
                // Submit the form for traditional payment methods
                document.getElementById('feeCollectionForm').submit();
            }
        }

        function initiateMerchantPayment() {
            const studentId = document.querySelector('input[name="student_id"]').value;
            const paymentMethod = document.getElementById('paymentMethod').value;
            const mobileNumber = document.getElementById('mobileNumber').value;
            const totalAmount = document.getElementById('total-payment-display').textContent.replace('৳', '').trim();
            
            if (!mobileNumber) {
                showAlert('মোবাইল নাম্বার প্রয়োজন', 'danger');
                return;
            }
            
            if (!/^(01[3-9]\d{8})$/.test(mobileNumber)) {
                showAlert('সঠিক মোবাইল নাম্বার দিন', 'danger');
                return;
            }
            
            const formData = new FormData();
            formData.append('ajax', 'initiate_merchant_payment');
            formData.append('student_id', studentId);
            formData.append('amount', totalAmount);
            formData.append('payment_method', paymentMethod);
            formData.append('phone_number', mobileNumber);
            
            fetch('fee_payment_dashboard.php', {
                method: 'POST',
                body: formData
            })
            .then(response => response.json())
            .then(data => {
                if (data.success) {
                    // Show payment instructions in modal
                    document.getElementById('merchantPaymentContent').innerHTML = `
                        <div class="text-center">
                            <h5>${data.student_name}</h5>
                            <p>স্টুডেন্ট আইডি: ${data.student_id}</p>
                            <p>ক্লাস: ${data.class}</p>
                            <p>পরিমাণ: ৳${data.amount.toFixed(2)}</p>
                            <p>রেফারেন্স: ${data.merchant_invoice}</p>
                            <hr>
                            <div class="text-start">
                                <p><strong>পেমেন্ট নির্দেশাবলী:</strong></p>
                                <p>${data.instructions}</p>
                            </div>
                            <input type="hidden" id="paymentRequestId" value="${data.payment_request_id}">
                        </div>
                    `;
                    const modal = new bootstrap.Modal(document.getElementById('merchantPaymentModal'));
                    modal.show();
                } else {
                    showAlert(data.message || 'পেমেন্ট শুরু করতে সমস্যা হয়েছে', 'danger');
                }
            })
            .catch(error => {
                console.error('Error:', error);
                showAlert('নেটওয়ার্ক সমস্যা', 'danger');
            });
        }

        function verifyPayment() {
            const paymentRequestId = document.getElementById('paymentRequestId').value;
            const transactionId = prompt('ট্রানজেকশন আইডি দিন:');
            
            if (!transactionId) {
                showAlert('ট্রানজেকশন আইডি প্রয়োজন', 'danger');
                return;
            }
            
            const formData = new FormData();
            formData.append('ajax', 'verify_payment');
            formData.append('payment_request_id', paymentRequestId);
            formData.append('transaction_id', transactionId);
            
            fetch('fee_payment_dashboard.php', {
                method: 'POST',
                body: formData
            })
            .then(response => response.json())
            .then(data => {
                if (data.success) {
                    showAlert('পেমেন্ট সফলভাবে ভেরিফাই হয়েছে', 'success');
                    // Close modal
                    const modal = bootstrap.Modal.getInstance(document.getElementById('merchantPaymentModal'));
                    modal.hide();
                    // Reload the page to show updated status
                    setTimeout(() => location.reload(), 2000);
                } else {
                    showAlert(data.message || 'পেমেন্ট ভেরিফাই করতে সমস্যা হয়েছে', 'danger');
                }
            })
            .catch(error => {
                console.error('Error:', error);
                showAlert('নেটওয়ার্ক সমস্যা', 'danger');
            });
        }

        function showAlert(message, type = 'info') {
            const alertHtml = `<div class="alert alert-${type} alert-dismissible fade show" role="alert">${message}<button type="button" class="btn-close" data-bs-dismiss="alert"></button></div>`;
            document.querySelector('.container').insertAdjacentHTML('afterbegin', alertHtml);
        }

        document.addEventListener('DOMContentLoaded', function() {
            document.getElementById('student-search').addEventListener('keyup', filterStudents);
            
            // Add event listener for the search button
            document.getElementById('search-button').addEventListener('click', filterStudents);
            
            // Also trigger search when pressing Enter in the search box
            document.getElementById('student-search').addEventListener('keypress', function(e) {
                if (e.key === 'Enter') {
                    filterStudents();
                }
            });
        });
    </script>
</body>
</html>