<?php
session_start();
require_once '../config/database.php';
require_once '../includes/sms_helper.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();
}

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

function bill_submission_rollback(PDO $pdo): void {
    if (!$pdo->inTransaction()) {
        return;
    }
    try {
        $pdo->rollBack();
    } catch (PDOException $e) {
        // Ignore: transaction may already be committed implicitly
    }
}

// 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 bill submission
if ($_SERVER['REQUEST_METHOD'] == 'POST' && isset($_POST['submit_bill'])) {
    $student_id = (int)$_POST['student_id'];
    $bill_type = trim($_POST['bill_type']);
    $bill_amount = (float)$_POST['bill_amount'];
    $bill_description = trim($_POST['bill_description']);
    $due_date = $_POST['due_date'];
    $send_sms = isset($_POST['send_sms']) ? true : false;
    
    if ($student_id > 0 && $bill_type && $bill_amount > 0) {
        try {
            // Check if fee already exists for this student and fee type
            $check_stmt = $pdo->prepare(
                "SELECT id FROM fees WHERE student_id = ? AND fee_type = ? AND status IN ('pending', 'partial', 'overdue', 'paid') LIMIT 1"
            );
            $check_stmt->execute([$student_id, $bill_type]);
            $existing_fee = $check_stmt->fetch();

            if ($existing_fee) {
                $error_message = "এই ধরনের ফি ইতিমধ্যে বিদ্যমান: " . $bill_type;
            } else {
            // Insert bill record
            $stmt = $pdo->prepare(
                "INSERT INTO fees (student_id, fee_type, amount, due_date, remarks, status)
                VALUES (?, ?, ?, ?, ?, 'pending')"
            );
            $stmt->execute([$student_id, $bill_type, $bill_amount, $due_date, $bill_description]);

            $success_message = "বিল সফলভাবে সাবমিট করা হয়েছে";

            // Send SMS if requested
            if ($send_sms) {
                try {
                    $stmt = $pdo->prepare("
                        SELECT s.first_name, s.last_name, s.phone, s.guardian_phone, s.student_id, s.roll_number,
                               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 = ?
                    ");
                    $stmt->execute([$student_id]);
                    $student = $stmt->fetch();
                    
                    if ($student) {
                        $numbers = [];
                        if (!empty($student['phone'])) $numbers[] = $student['phone'];
                        if (!empty($student['guardian_phone'])) $numbers[] = $student['guardian_phone'];
                        
                        if (!empty($numbers)) {
                            $vars = [
                                'name' => $student['first_name'] . ' ' . $student['last_name'],
                                'student_id' => $student['student_id'],
                                'class' => $student['class_name'],
                                'section' => $student['class_section'],
                                'roll' => $student['roll_number'],
                                'bill_type' => $bill_type,
                                'bill_amount' => number_format($bill_amount, 2),
                                'due_date' => date('d/m/Y', strtotime($due_date)),
                                'description' => $bill_description
                            ];
                            
                            $result = sms_send_template($pdo, 'bill_submission', $vars, $numbers);
                            
                            if ($result['success']) {
                                $success_message .= " এবং SMS পাঠানো হয়েছে";
                            } else {
                                $error_message .= " (SMS পাঠাতে সমস্যা: " . $result['message'] . ")";
                            }
                        }
                    }
                } catch (Exception $e) {
                    $error_message .= " (SMS পাঠাতে সমস্যা: " . $e->getMessage() . ")";
                }
            }
            }
        } catch (Exception $e) {
            $error_message = 'বিল সাবমিট করতে সমস্যা হয়েছে: ' . $e->getMessage();
        }
    } else {
        $error_message = 'সকল প্রয়োজনীয় তথ্য পূরণ করুন';
    }
}

// Handle quick payment collection (simple earliest-first allocation)
if ($_SERVER['REQUEST_METHOD'] == 'POST' && isset($_POST['quick_pay'])) {
    $student_id = (int)$_POST['student_id'];
    $pay_amount = (float)($_POST['quick_pay_amount'] ?? 0);
    $payment_method = $_POST['payment_method'] ?? 'cash';
    $payment_note = trim($_POST['payment_note'] ?? '');

    if ($student_id > 0 && $pay_amount > 0) {
        try {
            $pdo->beginTransaction();

            // Fetch due fees in chronological order
            $stmt = $pdo->prepare("\n                SELECT f.*,(f.amount-COALESCE(f.paid_amount,0)) AS due_amount\n                FROM fees f\n                WHERE f.student_id = ? AND (f.amount-COALESCE(f.paid_amount,0)) > 0\n                ORDER BY f.due_date ASC, f.created_at ASC, f.id ASC\n            ");
            $stmt->execute([$student_id]);
            $fees = $stmt->fetchAll();

            $total_due_before = 0;
            foreach ($fees as $fee) {
                $due = (float)$fee['amount'] - (float)$fee['paid_amount'];
                $total_due_before += $due;
            }

            $remaining = $pay_amount;
            $total_collected = 0;

            foreach ($fees as $fee) {
                if ($remaining <= 0) break;
                $due = (float)$fee['amount'] - (float)$fee['paid_amount'];
                if ($due <= 0) continue;
                $pay = min($due, $remaining);
                $new_paid = (float)$fee['paid_amount'] + $pay;
                $new_status = $new_paid >= (float)$fee['amount'] ? 'paid' : 'partial';

                // Update fee
                $stmt = $pdo->prepare("\n                    UPDATE fees\n                    SET paid_amount = ?, status = ?, paid_date = CURDATE(), updated_at = NOW()\n                    WHERE id = ?\n                ");
                $stmt->execute([$new_paid, $new_status, $fee['id']]);

                // Insert payment record
                $stmt = $pdo->prepare("\n                    INSERT INTO fee_payments (fee_id, amount, payment_date, payment_method, transaction_id, notes, created_by)\n                    VALUES (?, ?, NOW(), ?, NULL, ?, NULL)\n                ");
                $stmt->execute([$fee['id'], $pay, $payment_method, $payment_note]);

                $remaining -= $pay;
                $total_collected += $pay;
            }

            $remaining_due = $total_due_before - $total_collected;

            $pdo->commit();

            if ($total_collected > 0) {
                // Send SMS notification
                try {
                    // Get student details for SMS
                    $stmt = $pdo->prepare("
                        SELECT s.first_name, s.last_name, s.phone, s.guardian_phone, s.student_id, s.roll_number,
                               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 = ?
                    ");
                    $stmt->execute([$student_id]);
                    $student = $stmt->fetch();
                    
                    if ($student) {
                        $numbers = [];
                        if (!empty($student['phone'])) $numbers[] = $student['phone'];
                        if (!empty($student['guardian_phone'])) $numbers[] = $student['guardian_phone'];
                        
                        if (!empty($numbers)) {
                            $vars = [
                                'name' => $student['first_name'] . ' ' . $student['last_name'],
                                'student_id' => $student['student_id'],
                                'roll' => $student['roll_number'],
                                'class' => $student['class_name'] . ' - ' . $student['class_section'],
                                'paid_amount' => number_format($total_collected, 2),
                                'payment_method' => ucfirst($payment_method),
                                'transaction_id' => 'BILL_' . time(),
                                'due_amount' => number_format($remaining_due, 2)
                            ];
                            
                            $result = sms_send_template($pdo, 'bill_payment_success', $vars, $numbers);
                            
                            if ($result['success']) {
                                // SMS sent successfully
                            } else {
                                // SMS failed but continue with payment
                                error_log('SMS failed: ' . $result['message']);
                            }
                        }
                    }
                } catch (Exception $e) {
                    // SMS failed but continue with payment
                    error_log('SMS error: ' . $e->getMessage());
                }
                
                // Store payment info in session for success page
                $_SESSION['payment_student_id'] = $student_id;
                $_SESSION['payment_amount'] = $total_collected;
                $_SESSION['payment_method'] = $payment_method;
                $_SESSION['payment_tran_id'] = 'BILL_' . time();
                
                // Redirect to bill payment success message page
                header('Location: bill_payment_success_message.php');
                exit();
            } else {
                $error_message = 'কোন ডিউ পাওয়া যায়নি বা পেমেন্ট প্রক্রিয়া করা যায়নি';
            }
        } catch (Exception $e) {
            bill_submission_rollback($pdo);
            $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,
            c.name as class_name,
            c.section as class_section,
            COALESCE(SUM(f.amount), 0) as total_payable,
            COALESCE(SUM(f.paid_amount), 0) as total_paid,
            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 AND (f.academic_year = ? OR f.academic_year IS NULL OR f.academic_year = '')
        WHERE $where_clause
        GROUP BY s.id, s.student_id, s.first_name, s.last_name, s.roll_number, s.session, s.group_name, c.name, c.section
        ORDER BY s.roll_number
    ";
    
    array_unshift($params, $session);

    $stmt = $pdo->prepare($sql);
    $stmt->execute($params);
    $students = $stmt->fetchAll();
    
    echo json_encode($students);
    exit();
}

// AJAX handler for getting a student's due fees (for auto-prefill)
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) {
        $stmt = $pdo->prepare("\n            SELECT \n                f.*,\n                (f.amount - COALESCE(f.paid_amount,0)) as due_amount\n            FROM fees f\n            WHERE f.student_id = ? AND (f.amount - COALESCE(f.paid_amount,0)) > 0\n            ORDER BY f.due_date ASC, f.created_at ASC\n        ");
        $stmt->execute([$student_id]);
        $fees = $stmt->fetchAll();
        echo json_encode($fees ?: []);
    } else {
        echo json_encode([]);
    }
    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>
        :root{--indigo:#4fc3f7;--pink:#e83e8c;--teal:#4dd0e1;--orange:#ffb74d}
        body{font-family:'Hind Siliguri',sans-serif;background:linear-gradient(135deg,#0a1929,#11294a);min-height:100vh;color:#e0e0e0;font-size:.85rem}
        .top-bar{background:linear-gradient(135deg,#0d2137,#1a3a5c);padding:8px 20px;display:flex;align-items:center;justify-content:space-between;box-shadow:0 2px 20px rgba(0,0,0,.4)}
        .top-bar .brand{color:#4fc3f7;font-weight:700;font-size:.9rem;text-decoration:none;display:flex;align-items:center;gap:8px}
        .top-bar .brand i{font-size:1.2rem}
        .top-bar .nav-links{display:flex;gap:12px}
        .top-bar .nav-links a{color:rgba(255,255,255,.7);text-decoration:none;font-size:.75rem;font-weight:500;padding:4px 10px;border-radius:6px;transition:.2s}
        .top-bar .nav-links a:hover{color:#fff;background:rgba(255,255,255,.08)}
        .filter-card{background:rgba(255,255,255,.06);border:1px solid rgba(255,255,255,.08);border-radius:10px;padding:10px 14px;margin-bottom:12px}
        .filter-card .form-label{font-size:.75rem;font-weight:700;color:#90caf9;margin-bottom:2px}
        .filter-card .form-select,.filter-card .form-control{font-size:.8rem;padding:4px 8px;border-radius:6px;border:1px solid rgba(255,255,255,.15);background:rgba(0,0,0,.35);color:#e0e0e0}
        .filter-card .form-select:focus,.filter-card .form-control:focus{border-color:#4fc3f7;box-shadow:0 0 0 3px rgba(79,195,247,.15)}
        .filter-card select option{background:#11294a;color:#e0e0e0}
        .card{border:none;border-radius:10px;background:rgba(255,255,255,.04);border:1px solid rgba(255,255,255,.06);margin-bottom:1rem}
        .card .card-header{background:linear-gradient(135deg,#0d2137,#1a3a5c);color:#4fc3f7;border-bottom:1px solid rgba(255,255,255,.06);padding:8px 12px;font-weight:600;font-size:.9rem}
        .card .card-header h5{margin:0;font-size:.9rem;font-weight:600;color:#4fc3f7}
        .card .card-body{padding:10px 14px;background:rgba(255,255,255,.02)}
        .form-control,.form-select{font-size:.82rem;padding:5px 10px;border-radius:6px;border:1px solid rgba(255,255,255,.15);background:rgba(0,0,0,.35);color:#e0e0e0}
        .form-control:focus,.form-select:focus{border-color:#4fc3f7;box-shadow:0 0 0 3px rgba(79,195,247,.15)}
        .form-select option{background:#11294a;color:#e0e0e0}
        .form-control::placeholder{color:rgba(255,255,255,.3)}
        label.form-label{font-size:.78rem;font-weight:600;color:#90caf9;margin-bottom:2px}
        .btn{font-size:.78rem;border-radius:6px;padding:5px 14px;font-weight:600}
        .btn-light{background:rgba(255,255,255,.1);border:1px solid rgba(255,255,255,.15);color:#e0e0e0}
        .btn-light:hover{background:rgba(255,255,255,.18);color:#fff}
        .btn-outline-primary{color:#4fc3f7;border-color:#4fc3f7}
        .btn-outline-primary:hover{background:#4fc3f7;border-color:#4fc3f7;color:#0a1929}
        .btn-outline-secondary{color:rgba(255,255,255,.6);border-color:rgba(255,255,255,.2)}
        .btn-outline-secondary:hover{background:rgba(255,255,255,.1);color:#fff}
        .student-card{border:1px solid rgba(255,255,255,.08);border-radius:8px;padding:8px 10px;margin-bottom:5px;cursor:pointer;transition:.15s;background:rgba(255,255,255,.04)}
        .student-card:hover{border-color:#4fc3f7;box-shadow:0 2px 12px rgba(79,195,247,.12)}
        .student-card.selected{border-color:#4fc3f7;background:rgba(79,195,247,.1)}
        .student-card .text-muted,.bill-form .text-muted{color:rgba(255,255,255,.5)!important}
        .student-card .text-primary{color:#4fc3f7!important}
        .student-card .text-success{color:#66bb6a!important}
        .student-card .text-danger{color:#ef5350!important}
        .bill-form{background:rgba(255,255,255,.04);border:1px solid rgba(255,255,255,.06);border-radius:10px;padding:12px 14px}
        .bill-form h5{color:#4fc3f7;font-weight:700}
        .search-box{border:1px solid rgba(255,255,255,.15);border-radius:6px;background:rgba(0,0,0,.35);color:#e0e0e0}
        .search-box:focus{border-color:#4fc3f7;box-shadow:0 0 0 3px rgba(79,195,247,.15)}
        .input-group-text{background:rgba(0,0,0,.3);border:1px solid rgba(255,255,255,.12);color:#90caf9}
        .btn-submit{background:linear-gradient(135deg,#1565c0,#1e88e5);border:none;border-radius:6px;padding:8px 16px;font-weight:700;font-size:.82rem;color:#fff;width:100%}
        .btn-submit:hover{background:linear-gradient(135deg,#1976d2,#42a5f5);color:#fff}
        .alert{font-size:.8rem;border-radius:8px;padding:8px 12px}
        .alert-dismissible .btn-close{filter:invert(1)}
        .alert-success{background:rgba(46,125,50,.2);border:1px solid rgba(46,125,50,.3);color:#a5d6a7}
        .alert-danger{background:rgba(198,40,40,.2);border:1px solid rgba(198,40,40,.3);color:#ef9a9a}
        .alert-info{background:rgba(21,101,192,.2);border:1px solid rgba(21,101,192,.3);color:#90caf9}
        .form-check-label{font-size:.78rem;color:rgba(255,255,255,.7)}
        .form-check-input{background:rgba(0,0,0,.35);border:1px solid rgba(255,255,255,.15)}
        .form-check-input:checked{background:#4fc3f7;border-color:#4fc3f7}
        mark{background:rgba(79,195,247,.25);color:#fff;padding:1px 4px;border-radius:3px}
        .badge.bg-light{background:rgba(255,255,255,.1)!important}
        .text-dark{color:#e0e0e0!important}
        .bg-success{background:#2e7d32!important}
        .search-highlight{border-left:3px solid #4fc3f7}
        .pay-card{border:1px solid rgba(255,255,255,.08);border-radius:8px;padding:8px 10px;margin-bottom:5px;background:rgba(255,255,255,.04);cursor:pointer;transition:.15s}
        .pay-card:hover{border-color:#4fc3f7}
        .pay-card.selected{border-color:#4fc3f7;background:rgba(79,195,247,.1)}
        .pay-card .pay-label{font-size:.72rem;color:rgba(255,255,255,.5)}
        .pay-card .pay-amount{font-size:.85rem;font-weight:700;color:#fff}
        .pay-card .pay-check{width:16px;height:16px;border-radius:50%;border:2px solid rgba(255,255,255,.2);display:flex;align-items:center;justify-content:center;flex-shrink:0}
        .pay-card.selected .pay-check{border-color:#4fc3f7;background:#4fc3f7}
        .pay-card.selected .pay-check::after{content:"\2713";color:#0a1929;font-size:10px;font-weight:700}
        #quick-pay-area{display:none;margin-top:10px;padding-top:10px;border-top:1px solid rgba(255,255,255,.08)}
    </style>
</head>
<body>
    <div class="top-bar">
        <a href="../index.php" class="brand"><i class="fas fa-graduation-cap"></i> স্কুল ম্যানেজমেন্ট</a>
        <div class="nav-links">
            <a href="../index.php"><i class="fas fa-home"></i> হোম</a>
            <a href="manage.php"><i class="fas fa-wrench"></i> ফি ম্যানেজ</a>
            <a href="student_fees.php"><i class="fas fa-money-bill-wave"></i> ফি সংগ্রহ</a>
            <a href="management_dashboard.php"><i class="fas fa-cog"></i> ফি ড্যাশবোর্ড</a>
            <a href="bill_submission.php"><i class="fas fa-file-invoice"></i> বিল সাবমিট</a>
            <a href="../logout.php"><i class="fas fa-sign-out-alt"></i> লগআউট</a>
        </div>
    </div>

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

        <div class="filter-card">
            <div class="row g-1 align-items-end">
                <div class="col-md-3"><label class="form-label"><i class="fas fa-calendar-alt me-1" style="color:var(--indigo)"></i>সেশন</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 class="form-label"><i class="fas fa-chalkboard me-1" style="color:var(--teal)"></i>ক্লাস</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 class="form-label"><i class="fas fa-users me-1" style="color:var(--orange)"></i>গ্রুপ</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 d-flex align-items-end"><button type="button" class="btn w-100" style="background:linear-gradient(135deg,#1565c0,#1e88e5);color:#fff;border:none;padding:5px;font-weight:700;font-size:.8rem;border-radius:6px" onclick="loadStudents()"><i class="fas fa-search me-1"></i>খুঁজুন</button></div>
            </div>
        </div>

        <div class="row">
            <!-- Students List -->
            <div class="col-md-6">
                <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">
                        <!-- Student Search -->
                        <div class="mb-3">
                            <div class="input-group">
                                <span class="input-group-text">
                                    <i class="fas fa-search"></i>
                                </span>
                                <input type="text" class="form-control search-box" id="student-search" 
                                       placeholder="নাম, আইডি, রোল নম্বর বা ক্লাস দিয়ে খুঁজুন..." 
                                       onkeyup="filterStudents()"
                                       autocomplete="off">
                                <button class="btn btn-outline-secondary" type="button" onclick="clearSearch()">
                                    <i class="fas fa-times"></i>
                                </button>
                            </div>
                        </div>
                        
                        <!-- Students List Container -->
                        <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>
                    </div>
                </div>
            </div>

            <!-- Bill Submission Form -->
            <div class="col-md-6">
                <div class="card">
                    <div class="card-header">
                        <h5><i class="fas fa-file-invoice"></i> বিল সাবমিশন</h5>
                    </div>
                    <div class="card-body">
                        <div id="bill-form-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 = [];

        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
            });

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

        function displayStudents(students) {
            allStudents = students;
            const container = document.getElementById('students-list');
            
            if (students.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;
            }

            renderStudentList(students);
        }

        function generateStudentCards(students, searchTerm = '') {
            let html = '';
            
            students.forEach(student => {
                const totalDue = parseFloat(student.total_due) || 0;
                const totalPaid = parseFloat(student.total_paid) || 0;
                const totalPayable = parseFloat(student.total_payable) || 0;

                // Highlight search term
                let displayName = student.first_name + ' ' + student.last_name;
                let displayRoll = student.roll_number;
                let displayClass = student.class_name + ' - ' + student.class_section;
                let displayStudentId = student.student_id || '';
                
                if (searchTerm) {
                    const regex = new RegExp(`(${searchTerm})`, 'gi');
                    displayName = displayName.replace(regex, '<mark>$1</mark>');
                    displayRoll = displayRoll.toString().replace(regex, '<mark>$1</mark>');
                    displayClass = displayClass.replace(regex, '<mark>$1</mark>');
                    displayStudentId = displayStudentId.toString().replace(regex, '<mark>$1</mark>');
                }

                const cardClass = searchTerm ? 'student-card search-highlight' : 'student-card';

                html += `
                    <div class="${cardClass} p-3 mb-2" data-student-id="${student.id}" data-student-name="${student.first_name} ${student.last_name}" onclick="selectStudent(${student.id}, '${student.first_name} ${student.last_name}', this)">
                        <div class="d-flex justify-content-between align-items-start">
                            <div>
                                <h6 class="mb-1">${displayName}</h6>
                                <small class="text-muted">
                                    ${displayStudentId ? `আইডি: ${displayStudentId} | ` : ''}রোল: ${displayRoll} | 
                                    ক্লাস: ${displayClass}
                                    ${student.group_name ? ` | গ্রুপ: ${student.group_name}` : ''}
                                </small>
                            </div>
                            <div class="text-end">
                                <div class="fw-bold text-primary">৳${totalPayable.toFixed(2)}</div>
                                <small class="text-muted">মোট পে</small>
                            </div>
                        </div>
                        <div class="row mt-2">
                            <div class="col-6">
                                <div class="text-success fw-bold">৳${totalPaid.toFixed(2)}</div>
                                <small class="text-muted">পরিশোধিত</small>
                            </div>
                            <div class="col-6 text-end">
                                <div class="text-danger fw-bold">৳${totalDue.toFixed(2)}</div>
                                <small class="text-muted">বকেয়া</small>
                            </div>
                        </div>
                    </div>
                `;
            });

            return html;
        }

        function renderStudentList(students, searchTerm = '') {
            const container = document.getElementById('students-list');
            const countElement = document.getElementById('student-count');
            
            countElement.textContent = `${students.length} জন`;
            countElement.className = students.length > 0 ? 'badge bg-success' : 'badge bg-light text-dark';
            
            const html = generateStudentCards(students, searchTerm);
            container.innerHTML = html;
        }

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

        function displayBillForm(studentId, studentName) {
            const container = document.getElementById('bill-form-area');
            container.innerHTML = `
                <div style="font-size:.82rem;font-weight:700;color:#4fc3f7;margin-bottom:6px"><i class="fas fa-user me-1" style="color:var(--teal)"></i>${studentName}</div>
                <div class="d-flex justify-content-between align-items-center mb-3 px-3 py-2" style="background:rgba(79,195,247,.08);border:1px solid rgba(79,195,247,.2);border-radius:8px">
                    <span style="color:#90caf9;font-size:.82rem;font-weight:600">মোট বকেয়া</span>
                    <span id="total-due" style="color:#fff;font-size:1rem;font-weight:800">লোড হচ্ছে...</span>
                </div>
                <form method="POST" action="">
                    <input type="hidden" name="student_id" value="${studentId}">
                    <div class="row g-2 mb-2">
                        <div class="col-6"><label class="form-label">বিলের ধরন</label><select class="form-select" name="bill_type" required><option value="">নির্বাচন করুন</option><option value="মাসিক বেতন">মাসিক বেতন</option><option value="পরীক্ষার ফি">পরীক্ষার ফি</option><option value="লাইব্রেরি ফি">লাইব্রেরি ফি</option><option value="ল্যাব ফি">ল্যাব ফি</option><option value="স্পোর্টস ফি">স্পোর্টস ফি</option><option value="অন্যান্য">অন্যান্য</option></select></div>
                        <div class="col-3"><label class="form-label">পরিমাণ (৳)</label><input type="number" class="form-control" name="bill_amount" step="0.01" min="1" required placeholder="0"></div>
                        <div class="col-3"><label class="form-label">শেষ তারিখ</label><input type="date" class="form-control" name="due_date" required></div>
                    </div>
                    <textarea class="form-control mb-2" name="bill_description" rows="1" placeholder="বিবরণ (ঐচ্ছিক)" style="font-size:.78rem"></textarea>
                    <div class="d-flex gap-2 align-items-center mb-2">
                        <div class="form-check form-switch mb-0"><input class="form-check-input" type="checkbox" name="send_sms" checked id="sms_switch"><label class="form-check-label" for="sms_switch"><i class="fas fa-sms me-1"></i>SMS</label></div>
                        <button type="button" class="btn ms-auto" style="background:rgba(255,255,255,.06);border:1px solid rgba(255,255,255,.1);color:rgba(255,255,255,.6);font-size:.7rem;padding:3px 10px;border-radius:6px" onclick="toggleQuickPay()"><i class="fas fa-bolt me-1"></i>দ্রুত পেমেন্ট</button>
                    </div>
                    <button type="submit" name="submit_bill" class="btn w-100" style="background:linear-gradient(135deg,#1565c0,#1e88e5);border:none;border-radius:6px;padding:6px;font-weight:700;font-size:.82rem;color:#fff"><i class="fas fa-paper-plane me-1"></i>বিল সাবমিট করুন</button>
                    <div id="quick-pay-area">
                        <div class="row g-2 mb-2">
                            <div class="col-5"><label class="form-label" style="font-size:.7rem">পেমেন্ট (৳)</label><input type="number" class="form-control" name="quick_pay_amount" step="0.01" min="1" placeholder="০"></div>
                            <div class="col-4"><label class="form-label" style="font-size:.7rem">পদ্ধতি</label><select class="form-select" name="payment_method"><option value="cash">নগদ</option><option value="bank">ব্যাংক</option><option value="online">অনলাইন</option><option value="cheque">চেক</option></select></div>
                            <div class="col-3 d-flex align-items-end"><button type="submit" name="quick_pay" class="btn w-100" style="background:linear-gradient(135deg,#e65100,#ef6c00);border:none;border-radius:6px;padding:5px;font-weight:700;font-size:.75rem;color:#fff"><i class="fas fa-bolt me-1"></i>পে</button></div>
                        </div>
                        <textarea class="form-control" name="payment_note" rows="1" placeholder="নোট..." style="font-size:.72rem"></textarea>
                    </div>
                </form>
            `;
            const today = new Date();
            const nextMonth = new Date(today.getFullYear(), today.getMonth() + 1, 10);
            const dueEl = document.querySelector('[name="due_date"]');
            if (dueEl) dueEl.value = nextMonth.toISOString().split('T')[0];
            prefillFromDueFees(studentId);
        }

        let quickPayVisible = false;
        function toggleQuickPay() {
            quickPayVisible = !quickPayVisible;
            document.getElementById('quick-pay-area').style.display = quickPayVisible ? 'block' : 'none';
        }

        async function prefillFromDueFees(studentId) {
            try {
                const resp = await fetch('?ajax=get_student_fees&student_id=' + studentId);
                const fees = await resp.json();
                const dueLabel = document.getElementById('total-due');
                if (!Array.isArray(fees) || fees.length === 0) {
                    if (dueLabel) dueLabel.textContent = '৳0.00';
                    return;
                }
                const totalDue = fees.reduce((s,f)=> s + Math.max(0, parseFloat(f.amount||0) - parseFloat(f.paid_amount||0)), 0);
                if (dueLabel) dueLabel.textContent = '৳' + totalDue.toFixed(2);
            } catch (e) {
                console.error('Prefill error', e);
            }
        }

        function filterStudents() {
            const searchTerm = document.getElementById('student-search').value.toLowerCase().trim();
            
            if (searchTerm === '') {
                renderStudentList(allStudents);
                return;
            }
            
            const filteredStudents = allStudents.filter(student => {
                const fullName = (student.first_name + ' ' + student.last_name).toLowerCase();
                const rollNumber = student.roll_number.toString().toLowerCase();
                const className = (student.class_name + ' ' + student.class_section).toLowerCase();
                const groupName = (student.group_name || '').toLowerCase();
                const studentId = student.student_id ? student.student_id.toString().toLowerCase() : '';
                
                return fullName.includes(searchTerm) || 
                       studentId.includes(searchTerm) || 
                       rollNumber.includes(searchTerm) || 
                       className.includes(searchTerm) || 
                       groupName.includes(searchTerm);
            });
            
            if (filteredStudents.length === 0) {
                document.getElementById('students-list').innerHTML = `
                    <div class="text-center text-muted py-4">
                        <i class="fas fa-search fa-3x mb-3"></i>
                        <p>"${document.getElementById('student-search').value}" এর জন্য কোন শিক্ষার্থী পাওয়া যায়নি</p>
                        <button class="btn btn-sm btn-outline-primary mt-2" onclick="clearSearch()">
                            <i class="fas fa-times"></i> সার্চ ক্লিয়ার করুন
                        </button>
                    </div>
                `;
            } else {
                renderStudentList(filteredStudents, searchTerm);
            }
        }

        function clearSearch() {
            document.getElementById('student-search').value = '';
            renderStudentList(allStudents);
        }

        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>
            `;
            
            const container = document.querySelector('.container-fluid');
            container.insertAdjacentHTML('afterbegin', alertHtml);
            
            setTimeout(() => {
                const alert = container.querySelector('.alert');
                if (alert) {
                    alert.remove();
                }
            }, 5000);
        }

        // Load students on page load if filters are set
        document.addEventListener('DOMContentLoaded', function() {
            const hasFilters = document.getElementById('filter_session').value || 
                              document.getElementById('filter_class').value || 
                              document.getElementById('filter_group').value;
            
            if (hasFilters) {
                loadStudents();
            }
            
            // Add Enter key support for search
            document.getElementById('student-search').addEventListener('keypress', function(e) {
                if (e.key === 'Enter') {
                    filterStudents();
                }
            });
        });
    </script>
</body>
</html>
