<?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 filter parameters
$student_id = $_GET['student_id'] ?? '';
$class_id = $_GET['class_id'] ?? '';
$session = $_GET['session'] ?? '';
$date_from = $_GET['date_from'] ?? '';
$date_to = $_GET['date_to'] ?? '';
$search_text = $_GET['search_text'] ?? '';
$search_by = $_GET['search_by'] ?? 'name';

// Get dropdown data
$classes = $pdo->query("SELECT id, name, section FROM classes WHERE status = 'active' ORDER BY name, section")->fetchAll();
$sessions = $pdo->query("SELECT session_name FROM academic_sessions WHERE status = 'active' ORDER BY session_name DESC")->fetchAll();

// Get students for dropdown
$students = [];
if (!empty($class_id) || !empty($search_text)) {
    $sql = "
        SELECT s.id, s.student_id, s.first_name, s.last_name, s.roll_number, 
               c.name as class_name, c.section as class_section, s.session
        FROM students s
        JOIN classes c ON s.class_id = c.id
        WHERE s.status = 'active'
    ";
    $params = [];
    
    if (!empty($class_id)) {
        $sql .= " AND s.class_id = ?";
        $params[] = $class_id;
    }
    
    if (!empty($session)) {
        $sql .= " AND s.session = ?";
        $params[] = $session;
    }
    
    if (!empty($search_text)) {
        switch ($search_by) {
            case 'name':
                $sql .= " AND (s.first_name LIKE ? OR s.last_name LIKE ?)";
                $params[] = "%$search_text%";
                $params[] = "%$search_text%";
                break;
            case 'roll':
                $sql .= " AND s.roll_number LIKE ?";
                $params[] = "%$search_text%";
                break;
            case 'student_id':
                $sql .= " AND s.student_id LIKE ?";
                $params[] = "%$search_text%";
                break;
            case 'phone':
                $sql .= " AND (s.phone LIKE ? OR s.parent_phone LIKE ?)";
                $params[] = "%$search_text%";
                $params[] = "%$search_text%";
                break;
        }
    }
    
    $sql .= " ORDER BY s.roll_number LIMIT 50";
    
    $stmt = $pdo->prepare($sql);
    $stmt->execute($params);
    $students = $stmt->fetchAll();
}

// Check if fee_payments table exists
try {
    $pdo->query("SELECT 1 FROM fee_payments LIMIT 1");
} catch (PDOException $e) {
    if ($e->getCode() == '42S02' || strpos($e->getMessage(), "doesn't exist") !== false) { // Table doesn't exist
        ?>
        <!DOCTYPE html>
        <html lang="bn">
        <head>
            <meta charset="UTF-8">
            <title>ডাটাবেস সেটআপ প্রয়োজন</title>
            <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/css/bootstrap.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; }</style>
        </head>
        <body class="bg-light">
            <div class="container mt-5">
                <div class="row justify-content-center">
                    <div class="col-md-8">
                        <div class="card">
                            <div class="card-header bg-warning text-dark">
                                <h4><i class="fas fa-exclamation-triangle"></i> ডাটাবেস সেটআপ প্রয়োজন</h4>
                            </div>
                            <div class="card-body">
                                <p>ইনভয়েজ সিস্টেম ব্যবহার করার জন্য প্রথমে ডাটাবেস সেটআপ করতে হবে।</p>
                                <p><strong>সমস্যা:</strong> fee_payments টেবিল খুঁজে পাওয়া যায়নি।</p>
                                <div class="d-grid gap-2">
                                    <a href="fix_database_now.php" class="btn btn-primary btn-lg">
                                        <i class="fas fa-database"></i> এখনই সেটআপ করুন
                                    </a>
                                    <a href="dashboard.php" class="btn btn-secondary">
                                        <i class="fas fa-arrow-left"></i> ড্যাশবোর্ডে ফিরুন
                                    </a>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </body>
        </html>
        <?php
        exit();
    }
}

// Get invoice data if student is selected
$invoice_data = [];
$student_info = null;
$total_amount = 0;
$total_paid = 0;
$total_due = 0;
$has_payments_table = true;

if (!empty($student_id)) {
    // Get student information
    $stmt = $pdo->prepare("
        SELECT s.*, 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_info = $stmt->fetch();
    
    if ($student_info) {
        // Build query conditions
        $where_conditions = ["f.student_id = ?"];
        $params = [$student_id];
        
        if (!empty($date_from)) {
            $where_conditions[] = "f.created_at >= ?";
            $params[] = $date_from . ' 00:00:00';
        }
        
        if (!empty($date_to)) {
            $where_conditions[] = "f.created_at <= ?";
            $params[] = $date_to . ' 23:59:59';
        }
        
        $where_clause = implode(' AND ', $where_conditions);
        
        // Check if fee_payments table exists and get fee transactions
        try {
            $pdo->query("SELECT 1 FROM fee_payments LIMIT 1");
        } catch (PDOException $e) {
            $has_payments_table = false;
        }
        
        if ($has_payments_table) {
            // Get fee transactions with payments
            $sql = "
                SELECT 
                    f.*,
                    fp.id as payment_id,
                    fp.amount as payment_amount,
                    fp.payment_date,
                    fp.payment_method,
                    fp.transaction_id,
                    fp.notes as payment_notes
                FROM fees f
                LEFT JOIN fee_payments fp ON f.id = fp.fee_id
                WHERE $where_clause
                ORDER BY f.created_at DESC, fp.payment_date DESC
            ";
        } else {
            // Fallback: Get only fees data
            $sql = "
                SELECT 
                    f.*,
                    NULL as payment_id,
                    f.paid_amount as payment_amount,
                    f.created_at as payment_date,
                    'cash' as payment_method,
                    CONCAT('TXN-', DATE_FORMAT(f.created_at, '%Y%m%d'), '-', f.id) as transaction_id,
                    'Payment record' as payment_notes
                FROM fees f
                WHERE $where_clause AND f.paid_amount > 0
                ORDER BY f.created_at DESC
            ";
        }
        
        $stmt = $pdo->prepare($sql);
        $stmt->execute($params);
        $results = $stmt->fetchAll();
        
        // Process data
        foreach ($results as $row) {
            $fee_id = $row['id'];
            
            if (!isset($invoice_data[$fee_id])) {
                $invoice_data[$fee_id] = [
                    'fee_info' => [
                        'id' => $row['id'],
                        'fee_type' => $row['fee_type'],
                        'amount' => $row['amount'],
                        'paid_amount' => $row['paid_amount'],
                        'due_amount' => $row['amount'] - $row['paid_amount'],
                        'due_date' => $row['due_date'],
                        'status' => $row['status'],
                        'academic_year' => $row['academic_year'],
                        'month' => $row['month'],
                        'created_at' => $row['created_at']
                    ],
                    'payments' => []
                ];
                
                $total_amount += $row['amount'];
                $total_paid += $row['paid_amount'];
                $total_due += ($row['amount'] - $row['paid_amount']);
            }
            
            if ($row['payment_id']) {
                $invoice_data[$fee_id]['payments'][] = [
                    'id' => $row['payment_id'],
                    'amount' => $row['payment_amount'],
                    'payment_date' => $row['payment_date'],
                    'payment_method' => $row['payment_method'],
                    'transaction_id' => $row['transaction_id'],
                    'notes' => $row['payment_notes']
                ];
            }
        }
    }
}
?>

<!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 {
            border: none;
            border-radius: 15px;
            box-shadow: 0 0 20px rgba(0,0,0,0.1);
        }
        .card-header {
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            color: white;
            border-radius: 15px 15px 0 0 !important;
            padding: 1.5rem;
        }
        .filter-section {
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            padding: 2rem;
            border-radius: 15px;
            margin-bottom: 2rem;
            color: white;
        }
        .invoice-header {
            background: linear-gradient(135deg, #2c3e50 0%, #34495e 100%);
            color: white;
            padding: 2rem;
            border-radius: 15px 15px 0 0;
            text-align: center;
        }
        .invoice-body {
            padding: 2rem;
        }
        .payment-row {
            background-color: #e8f5e8;
            border-left: 4px solid #28a745;
        }
        .fee-row {
            background-color: #fff3cd;
            border-left: 4px solid #ffc107;
        }
        
        .search-highlight {
            background-color: #fff3cd;
            padding: 2px 4px;
            border-radius: 3px;
        }
        
        .quick-access-panel {
            background: linear-gradient(135deg, #f8f9fa 0%, #e9ecef 100%);
            border-left: 4px solid #007bff;
        }
        
        .student-option {
            font-size: 14px;
        }
        
        .student-option:hover {
            background-color: #e3f2fd;
        }
        
        #student_search_results {
            position: absolute;
            background-color: white;
            border: 1px solid #ccc;
            border-radius: 5px;
            max-height: 300px;
            overflow-y: auto;
            width: 95%;
            z-index: 1000;
            color: black;
        }

        .student-result-item {
            padding: 10px;
            cursor: pointer;
            border-bottom: 1px solid #eee;
        }

        .student-result-item:hover {
            background-color: #f0f0f0;
        }

        .student-result-item:last-child {
            border-bottom: none;
        }
        
        /* Professional Compact Print Style - Based on provided image */
        .compact-invoice {
            display: none;
            background: white;
            font-family: 'Hind Siliguri', sans-serif;
            max-width: 800px;
            margin: 0 auto;
            border: 1px solid #ddd;
        }
        
        .compact-invoice.show {
            display: block;
        }
        
        /* Header Section - Dark Blue */
        .compact-invoice .invoice-header-compact {
            background: #2c3e50;
            color: white;
            padding: 15px 20px;
            display: flex;
            justify-content: space-between;
            align-items: center;
        }
        
        .compact-invoice .invoice-header-compact .left-section h4 {
            margin: 0;
            font-size: 16px;
            font-weight: bold;
        }
        
        .compact-invoice .invoice-header-compact .left-section p {
            margin: 2px 0;
            font-size: 14px;
        }
        
        .compact-invoice .invoice-header-compact .right-section {
            text-align: right;
            font-size: 12px;
        }
        
        /* Student Info Section - Slightly lighter blue */
        .compact-invoice .student-info-compact {
            background: #34495e;
            color: white;
            padding: 15px 20px;
            display: grid;
            grid-template-columns: 1fr 1fr;
            gap: 20px;
        }
        
        .compact-invoice .info-column {
            display: flex;
            flex-direction: column;
            gap: 8px;
        }
        
        .compact-invoice .info-row {
            display: flex;
            justify-content: space-between;
            font-size: 13px;
        }
        
        .compact-invoice .info-label {
            font-weight: bold;
            min-width: 100px;
        }
        
        .compact-invoice .info-value {
            text-align: right;
            flex: 1;
        }
        
        /* Fee Details Section */
        .compact-invoice .fee-details-compact {
            margin: 0;
            background: white;
        }
        
        .compact-invoice .fee-details-compact h5 {
            background: #2c3e50;
            color: white;
            padding: 12px 20px;
            margin: 0;
            font-size: 14px;
            font-weight: bold;
        }
        
        .compact-invoice .table-compact {
            width: 100%;
            border-collapse: collapse;
            font-size: 11px;
            margin: 0;
        }
        
        .compact-invoice .table-compact th {
            background: #34495e;
            color: white;
            padding: 10px 8px;
            text-align: center;
            font-weight: bold;
            border: 1px solid #2c3e50;
            font-size: 11px;
        }
        
        .compact-invoice .table-compact td {
            padding: 8px;
            border: 1px solid #ddd;
            text-align: left;
            font-size: 11px;
        }
        
        .compact-invoice .table-compact .amount-cell {
            text-align: right;
            font-weight: 500;
        }
        
        .compact-invoice .table-compact .center-cell {
            text-align: center;
        }
        
        .compact-invoice .table-compact .status-paid {
            background: #27ae60;
            color: white;
            padding: 2px 6px;
            border-radius: 3px;
            font-size: 10px;
            display: inline-block;
        }
        
        .compact-invoice .table-compact .status-due {
            background: #e74c3c;
            color: white;
            padding: 2px 6px;
            border-radius: 3px;
            font-size: 10px;
            display: inline-block;
        }
        
        .compact-invoice .table-compact .status-partial {
            background: #f39c12;
            color: white;
            padding: 2px 6px;
            border-radius: 3px;
            font-size: 10px;
            display: inline-block;
        }
        
        .compact-invoice .total-row {
            background: #ecf0f1 !important;
            font-weight: bold;
        }
        
        .compact-invoice .total-row td {
            font-weight: bold;
            background: #ecf0f1;
        }
        
        /* Footer Section */
        .compact-invoice .footer-compact {
            padding: 15px 20px;
            background: white;
            border-top: 1px solid #ddd;
            display: grid;
            grid-template-columns: 1fr 1fr;
            gap: 20px;
            font-size: 11px;
        }
        
        .compact-invoice .footer-compact .notes-section ul {
            margin: 5px 0;
            padding-left: 15px;
        }
        
        .compact-invoice .footer-compact .notes-section li {
            margin-bottom: 3px;
        }
        
        .compact-invoice .footer-compact .contact-info {
            text-align: right;
        }
        
        .compact-invoice .footer-compact .contact-info p {
            margin: 2px 0;
        }

        /* Print Styles */
        @media print {
            body {
                background: white !important;
                font-size: 12px;
                color: black !important;
            }
            
            .no-print {
                display: none !important;
            }
            
            .card {
                border: 1px solid #ddd !important;
                box-shadow: none !important;
                page-break-inside: avoid;
            }
            
            .invoice-header {
                background: #f8f9fa !important;
                color: black !important;
                border-bottom: 2px solid #000;
                text-align: center;
                padding: 1rem;
            }

            .invoice-header h1 {
                font-size: 20px;
                margin-bottom: 5px;
            }

            .invoice-header h3 {
                font-size: 16px;
                margin-bottom: 10px;
            }
            
            .table {
                font-size: 11px;
            }
            
            .table th,
            .table td {
                border: 1px solid #dee2e6 !important;
                padding: 6px 4px !important;
            }
            
            .table thead th {
                background-color: #e9ecef !important;
                font-weight: bold;
                color: #212529;
            }
            
            /* Compact Print Styles */
            .compact-invoice .invoice-header-compact {
                background: #2c3e50 !important;
                color: white !important;
                -webkit-print-color-adjust: exact;
                print-color-adjust: exact;
            }
            
            .compact-invoice .student-info-compact {
                background: #34495e !important;
                color: white !important;
                -webkit-print-color-adjust: exact;
                print-color-adjust: exact;
            }
            
            .compact-invoice .fee-details-compact h5 {
                background: #2c3e50 !important;
                color: white !important;
                -webkit-print-color-adjust: exact;
                print-color-adjust: exact;
            }
            
            .compact-invoice .table-compact th {
                background: #2c3e50 !important;
                color: white !important;
                -webkit-print-color-adjust: exact;
                print-color-adjust: exact;
            }
            
            .compact-invoice .status-paid {
                background: #27ae60 !important;
                color: white !important;
                -webkit-print-color-adjust: exact;
                print-color-adjust: exact;
            }
            
            .compact-invoice .status-due {
                background: #e74c3c !important;
                color: white !important;
                -webkit-print-color-adjust: exact;
                print-color-adjust: exact;
            }
            
            .payment-row {
                background-color: #f0fff0 !important;
            }
            
            .fee-row {
                background-color: #fff9e6 !important;
            }

            .table-bordered {
                border: 1px solid #dee2e6;
            }

            @page {
                size: A4;
                margin: 15mm;
            }
            
            /* Compact invoice specific print styles - No Background */
            .compact-invoice.show {
                display: block !important;
            }
            
            .compact-invoice {
                border: 2px solid #000 !important;
                background: white !important;
            }
            
            /* Regular invoice half-page print (top half) */
            body.half-page-print #regularInvoice {
                height: 133.5mm; /* Half of A4 printable area (approx) */
                overflow: hidden;
                box-shadow: none !important;
                page-break-after: avoid;
            }
            body.half-page-print .compact-invoice {
                display: none !important;
            }
            body.half-page-print #regularInvoice .invoice-header {
                padding: 8mm 10mm !important;
            }
            body.half-page-print #regularInvoice .invoice-body {
                padding: 8mm 10mm !important;
            }
            body.half-page-print #regularInvoice h1 { font-size: 18px !important; margin: 0 0 4px 0 !important; }
            body.half-page-print #regularInvoice h3 { font-size: 14px !important; margin: 0 0 4px 0 !important; }
            body.half-page-print #regularInvoice h4 { font-size: 13px !important; margin: 0 0 6px 0 !important; }
            body.half-page-print #regularInvoice table { font-size: 11px !important; }
            body.half-page-print #regularInvoice .table td,
            body.half-page-print #regularInvoice .table th { padding: 4px 6px !important; }
            
            .compact-invoice .invoice-header-compact {
                background: white !important;
                color: black !important;
                border-bottom: 2px solid #000 !important;
                -webkit-print-color-adjust: exact !important;
                print-color-adjust: exact !important;
            }
            
            .compact-invoice .student-info-compact {
                background: white !important;
                color: black !important;
                border-bottom: 1px solid #000 !important;
                -webkit-print-color-adjust: exact !important;
                print-color-adjust: exact !important;
            }
            
            .compact-invoice .fee-details-compact h5 {
                background: white !important;
                color: black !important;
                border-bottom: 1px solid #000 !important;
                -webkit-print-color-adjust: exact !important;
                print-color-adjust: exact !important;
            }
            
            .compact-invoice .table-compact {
                width: 100% !important;
                border-collapse: collapse !important;
            }
            
            .compact-invoice .table-compact th {
                background: white !important;
                color: black !important;
                border: 1px solid #000 !important;
                font-weight: bold !important;
                -webkit-print-color-adjust: exact !important;
                print-color-adjust: exact !important;
            }
            
            .compact-invoice .table-compact td {
                background: white !important;
                color: black !important;
                border: 1px solid #000 !important;
                padding: 6px !important;
                font-size: 11px !important;
            }
            
            .compact-invoice .total-row td {
                background: #f5f5f5 !important;
                font-weight: bold !important;
                -webkit-print-color-adjust: exact !important;
                print-color-adjust: exact !important;
            }
            
            .compact-invoice .status-paid,
            .compact-invoice .status-due,
            .compact-invoice .status-partial {
                background: white !important;
                color: black !important;
                border: 1px solid #000 !important;
                padding: 2px 4px !important;
                -webkit-print-color-adjust: exact !important;
                print-color-adjust: exact !important;
            }
            
            .compact-invoice .info-row {
                margin-bottom: 3px !important;
                font-size: 12px !important;
            }
            
            .compact-invoice .info-label {
                font-weight: bold !important;
            }
            
            .compact-invoice .footer-compact {
                background: white !important;
                color: black !important;
                border-top: 1px solid #000 !important;
            }
        }
    </style>
</head>
<body>
    <!-- Navigation -->
    <nav class="navbar navbar-expand-lg navbar-dark bg-primary no-print">
        <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="dashboard.php">
                    <i class="fas fa-tachometer-alt"></i> ড্যাশবোর্ড
                </a>
                <a class="nav-link" href="student_fees.php">
                    <i class="fas fa-money-bill-wave"></i> ফি কালেক্ট
                </a>
                <a class="nav-link" href="reports.php">
                    <i class="fas fa-chart-bar"></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">
        <!-- Quick Access Panel -->
        <div class="row mb-3 no-print">
            <div class="col-md-12">
                <div class="card">
                    <div class="card-body py-2">
                        <div class="row align-items-center">
                            <div class="col-md-8">
                                <h6 class="mb-0"><i class="fas fa-info-circle text-primary"></i> দ্রুত টিপস</h6>
                                <small class="text-muted">
                                    • নাম দিয়ে সার্চ করতে ২+ অক্ষর লিখুন • রোল/আইডি দিয়ে সরাসরি খুঁজুন • ফোন নম্বর দিয়েও খোঁজা যায়
                                </small>
                            </div>
                            <div class="col-md-4 text-end">
                                <button class="btn btn-sm btn-outline-primary" onclick="showKeyboardShortcuts()">
                                    <i class="fas fa-keyboard"></i> শর্টকাট
                                </button>
                                <button class="btn btn-sm btn-outline-success" onclick="showRecentStudents()">
                                    <i class="fas fa-history"></i> সাম্প্রতিক
                                </button>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </div>

        <!-- Filter Section -->
        <div class="filter-section no-print">
            <h4 class="text-white mb-3"><i class="fas fa-receipt"></i> ইনভয়েজ তৈরি করুন</h4>
            <form method="GET" action="">
                <div class="row g-3">
                    <!-- First Row -->
                    <div class="col-md-2">
                        <label for="session" class="form-label">সেশন</label>
                        <select class="form-select" name="session" id="session" onchange="loadStudents()">
                            <option value="">সব সেশন</option>
                            <?php foreach ($sessions as $s): ?>
                                <option value="<?php echo htmlspecialchars($s['session_name']); ?>" 
                                        <?php echo $session == $s['session_name'] ? 'selected' : ''; ?>>
                                    <?php echo htmlspecialchars($s['session_name']); ?>
                                </option>
                            <?php endforeach; ?>
                        </select>
                    </div>
                    <div class="col-md-2">
                        <label for="class_id" class="form-label">ক্লাস</label>
                        <select class="form-select" name="class_id" id="class_id" onchange="loadStudents()">
                            <option value="">সব ক্লাস</option>
                            <?php foreach ($classes as $c): ?>
                                <option value="<?php echo $c['id']; ?>" 
                                        <?php echo $class_id == $c['id'] ? 'selected' : ''; ?>>
                                    <?php echo htmlspecialchars($c['name'] . ' - ' . $c['section']); ?>
                                </option>
                            <?php endforeach; ?>
                        </select>
                    </div>
                    <div class="col-md-2">
                        <label for="search_by" class="form-label">সার্চ টাইপ</label>
                        <select class="form-select" name="search_by" id="search_by">
                            <option value="name" <?php echo $search_by == 'name' ? 'selected' : ''; ?>>নাম</option>
                            <option value="roll" <?php echo $search_by == 'roll' ? 'selected' : ''; ?>>রোল নম্বর</option>
                            <option value="student_id" <?php echo $search_by == 'student_id' ? 'selected' : ''; ?>>আইডি নম্বর</option>
                            <option value="phone" <?php echo $search_by == 'phone' ? 'selected' : ''; ?>>ফোন নম্বর</option>
                        </select>
                    </div>
                    <div class="col-md-3">
                        <label for="search_text" class="form-label">সার্চ করুন</label>
                        <div class="input-group">
                            <input type="text" class="form-control" name="search_text" id="search_text" 
                                   placeholder="নাম, রোল, আইডি বা ফোন লিখুন..." 
                                   value="<?php echo htmlspecialchars($search_text); ?>"
                                   onkeyup="searchStudents()" 
                                   minlength="2"
                                   autocomplete="off">
                            <button class="btn btn-outline-light" type="button" onclick="clearSearchText()">
                                <i class="fas fa-times"></i>
                            </button>
                        </div>
                        <div id="student_search_results"></div>
                        <small class="text-light">কমপক্ষে ২ অক্ষর লিখুন</small>
                        <?php if (isset($_GET['debug'])): ?>
                        <div id="debug_info" class="mt-2 p-2 bg-dark text-light rounded" style="font-size: 11px; display: none;">
                            <strong>Debug Info:</strong>
                            <div id="debug_content"></div>
                        </div>
                        <?php endif; ?>
                    </div>
                    <div class="col-md-3">
                        <label class="form-label">&nbsp;</label>
                        <div>
                            <button type="button" class="btn btn-light me-2" onclick="searchStudents()">
                                <i class="fas fa-search"></i> খুঁজুন
                            </button>
                            <button type="button" class="btn btn-outline-light me-2" onclick="clearSearch()">
                                <i class="fas fa-times"></i> ক্লিয়ার
                            </button>
                            <small class="text-light d-block mt-1">
                                <span id="search-status">সার্চ করুন</span>
                            </small>
                        </div>
                    </div>
                </div>
                
                <!-- Second Row -->
                <div class="row g-3 mt-2">
                    <div class="col-md-4">
                        <label for="student_id" class="form-label">শিক্ষার্থী নির্বাচন করুন</label>
                        <input type="hidden" name="student_id" id="student_id" value="<?php echo htmlspecialchars($student_id); ?>">
                        <input type="text" class="form-control" id="selected_student_name" 
                               placeholder="শিক্ষার্থী নির্বাচন করুন" 
                               value="<?php if ($student_info) echo htmlspecialchars($student_info['first_name'] . ' ' . $student_info['last_name']); ?>" readonly>
                    </div>
                    <div class="col-md-2">
                        <label for="date_from" class="form-label">শুরুর তারিখ</label>
                        <input type="date" class="form-control" name="date_from" id="date_from" 
                               value="<?php echo htmlspecialchars($date_from); ?>">
                    </div>
                    <div class="col-md-2">
                        <label for="date_to" class="form-label">শেষ তারিখ</label>
                        <input type="date" class="form-control" name="date_to" id="date_to" 
                               value="<?php echo htmlspecialchars($date_to); ?>">
                    </div>
                    <div class="col-md-4">
                        <label class="form-label">&nbsp;</label>
                        <div>
                            <button type="submit" class="btn btn-light me-2">
                                <i class="fas fa-receipt"></i> ইনভয়েজ তৈরি করুন
                            </button>
                            <button type="button" class="btn btn-outline-light me-2" onclick="quickSearch()">
                                <i class="fas fa-bolt"></i> দ্রুত সার্চ
                            </button>
                            <button type="button" class="btn btn-outline-light" onclick="generateSampleURL()">
                                <i class="fas fa-link"></i> URL কপি
                            </button>
                        </div>
                    </div>
                </div>
                <?php if (!empty($student_id)): ?>
                <div class="row mt-3">
                    <div class="col-md-12">
                        <button type="button" class="btn btn-outline-light me-2" onclick="printInvoice()" id="printButton">
                            <i class="fas fa-print"></i> সাধারণ প্রিন্ট
                        </button>
                        <button type="button" class="btn btn-outline-success me-2" onclick="printCompactInvoice()" id="compactPrintButton">
                            <i class="fas fa-print"></i> কমপ্যাক্ট প্রিন্ট
                        </button>
                        <button type="button" class="btn btn-outline-info me-2" onclick="toggleCompactView()" id="toggleViewButton">
                            <i class="fas fa-eye"></i> কমপ্যাক্ট ভিউ
                        </button>
                        <button type="button" class="btn btn-outline-warning me-2" onclick="testPrintFunction()" id="testButton">
                            <i class="fas fa-bug"></i> টেস্ট
                        </button>
                        <a href="print_diagnostic.php" class="btn btn-outline-info me-2" target="_blank">
                            <i class="fas fa-stethoscope"></i> সমস্যা নির্ণয়
                        </a>
                        <a href="test_compact_invoice_new.php" class="btn btn-outline-success me-2" target="_blank">
                            <i class="fas fa-eye"></i> নতুন ডিজাইন দেখুন
                        </a>
                        <a href="?" class="btn btn-outline-light">
                            <i class="fas fa-refresh"></i> নতুন ইনভয়েজ
                        </a>
                    </div>
                </div>
                <?php endif; ?>
            </form>
        </div>

        <?php if (!empty($student_info) && !empty($invoice_data)): ?>
        
        <?php if (!$has_payments_table): ?>
        <!-- Warning Message -->
        <div class="alert alert-warning no-print">
            <h5><i class="fas fa-exclamation-triangle"></i> সীমিত ডাটা</h5>
            <p>fee_payments টেবিল খুঁজে পাওয়া যায়নি। শুধুমাত্র মূল ফি তথ্য দেখানো হচ্ছে।</p>
            <a href="create_table_direct.php" class="btn btn-sm btn-warning">
                <i class="fas fa-database"></i> ডাটাবেস সেটআপ করুন
            </a>
        </div>
        <?php endif; ?>
        
        <!-- Invoice -->
        <div id="regularInvoice" class="card regular-invoice">
            <div class="invoice-header">
                <h1><i class="fas fa-graduation-cap"></i> বিদ্যা নিকেতন</h1>
                <h3>স্কুল ম্যানেজমেন্ট সিস্টেম</h3>
                <h4 class="mt-3">ফি ইনভয়েজ</h4>
                <p class="mb-0">তারিখ: <?php echo date('d/m/Y'); ?></p>
            </div>
            
            <div class="invoice-body">
                <!-- Combined Invoice + Student Info -->
                <div class="row mb-4">
                    <div class="col-12">
                        <h5><i class="fas fa-info-circle"></i> ইনভয়েজ তথ্য ও <i class="fas fa-user"></i> শিক্ষার্থীর তথ্য</h5>
                        <div class="table-responsive">
                            <table class="table table-bordered combined-info-table">
                                <tbody>
                                    <tr>
                                        <td><strong>ইনভয়েজ নম্বর:</strong></td>
                                        <td>INV-<?php echo date('Ymd') . '-' . $student_info['id']; ?></td>
                                        <td><strong>নাম:</strong></td>
                                        <td><?php echo htmlspecialchars($student_info['first_name'] . ' ' . $student_info['last_name']); ?></td>
                                    </tr>
                                    <tr>
                                        <td><strong>তৈরির তারিখ:</strong></td>
                                        <td><?php echo date('d/m/Y H:i:s'); ?></td>
                                        <td><strong>রোল নম্বর:</strong></td>
                                        <td><?php echo htmlspecialchars($student_info['roll_number']); ?></td>
                                    </tr>
                                    <tr>
                                        <td><strong>সময়কাল:</strong></td>
                                        <td>
                                            <?php 
                                            if ($date_from && $date_to) {
                                                echo date('d/m/Y', strtotime($date_from)) . ' - ' . date('d/m/Y', strtotime($date_to));
                                            } elseif ($date_from) {
                                                echo date('d/m/Y', strtotime($date_from)) . ' থেকে';
                                            } elseif ($date_to) {
                                                echo date('d/m/Y', strtotime($date_to)) . ' পর্যন্ত';
                                            } else {
                                                echo '—';
                                            }
                                            ?>
                                        </td>
                                        <td><strong>ক্লাস:</strong></td>
                                        <td><?php echo htmlspecialchars($student_info['class_name'] . ' - ' . $student_info['class_section']); ?></td>
                                    </tr>
                                    <tr>
                                        <td><strong>সেশন:</strong></td>
                                        <td><?php echo htmlspecialchars($student_info['session']); ?></td>
                                        <td><strong>আইডি:</strong></td>
                                        <td><?php echo htmlspecialchars($student_info['student_id'] ?? ''); ?></td>
                                    </tr>
                                </tbody>
                            </table>
                        </div>
                    </div>
                </div>

                <!-- Fee Details (single table below) -->
                <h5><i class="fas fa-list"></i> ফি বিবরণ</h5>
                <div class="table-responsive">
                    <table class="table table-bordered">
                        <thead class="table-dark">
                            <tr>
                                <th style="width: 6%">ক্রমিক</th>
                                <th style="width: 20%">ফি এর ধরন</th>
                                <th style="width: 14%">মাস/বছর</th>
                                <th style="width: 15%" class="text-end">মোট পরিমাণ (৳)</th>
                                <th style="width: 15%" class="text-end">পরিশোধিত (৳)</th>
                                <th style="width: 15%" class="text-end">বকেয়া (৳)</th>
                                <th style="width: 15%">স্ট্যাটাস / নির্ধারিত তারিখ</th>
                            </tr>
                        </thead>
                        <tbody>
                            <?php 
                            $serial = 1;
                            foreach ($invoice_data as $fee_id => $data): 
                                $fee = $data['fee_info'];
                            ?>
                            <tr class="fee-row">
                                <td><?php echo $serial++; ?></td>
                                <td><?php echo htmlspecialchars($fee['fee_type']); ?></td>
                                <td>
                                    <?php 
                                    echo ($fee['month'] ? $fee['month'] . ' ' : '') . 
                                         ($fee['academic_year'] ? $fee['academic_year'] : ''); 
                                    ?>
                                </td>
                                <td class="text-end">৳<?php echo number_format($fee['amount'], 2); ?></td>
                                <td class="text-end">৳<?php echo number_format($fee['paid_amount'], 2); ?></td>
                                <td class="text-end">৳<?php echo number_format($fee['due_amount'], 2); ?></td>
                                <td>
                                    <div>
                                        <?php
                                        $status_labels = [
                                            'pending' => '<span class="badge bg-warning">অপেক্ষমান</span>',
                                            'partial' => '<span class="badge bg-info">আংশিক</span>',
                                            'paid' => '<span class="badge bg-success">পরিশোধিত</span>',
                                            'overdue' => '<span class="badge bg-danger">বকেয়া</span>'
                                        ];
                                        echo $status_labels[$fee['status']] ?? $fee['status'];
                                        ?>
                                    </div>
                                    <small class="text-muted">তারিখ: <?php echo date('d/m/Y', strtotime($fee['due_date'])); ?></small>
                                </td>
                            </tr>
                            <?php if (!empty($data['payments'])): ?>
                                <?php foreach ($data['payments'] as $payment): ?>
                                <tr class="payment-row">
                                    <td></td>
                                    <td colspan="2">
                                        <i class="fas fa-arrow-right text-success"></i>
                                        পেমেন্ট - <?php echo date('d/m/Y', strtotime($payment['payment_date'])); ?>
                                        <?php if ($payment['payment_method']): ?>
                                            (<?php echo htmlspecialchars($payment['payment_method']); ?>)
                                        <?php endif; ?>
                                    </td>
                                    <td></td>
                                    <td class="text-end text-success">
                                        <strong>৳<?php echo number_format($payment['amount'], 2); ?></strong>
                                    </td>
                                    <td></td>
                                    <td>
                                        <?php if ($payment['transaction_id']): ?>
                                            TXN: <?php echo htmlspecialchars($payment['transaction_id']); ?>
                                        <?php endif; ?>
                                    </td>
                                </tr>
                                <?php endforeach; ?>
                            <?php endif; ?>
                            <?php endforeach; ?>
                        </tbody>
                        <tfoot class="table-secondary">
                            <tr>
                                <th colspan="3">সর্বমোট</th>
                                <th class="text-end">৳<?php echo number_format($total_amount, 2); ?></th>
                                <th class="text-end">৳<?php echo number_format($total_paid, 2); ?></th>
                                <th class="text-end">৳<?php echo number_format($total_due, 2); ?></th>
                                <th>
                                    <?php if ($total_due > 0): ?>
                                        <span class="badge bg-danger">বকেয়া আছে</span>
                                    <?php else: ?>
                                        <span class="badge bg-success">সব পরিশোধিত</span>
                                    <?php endif; ?>
                                </th>
                            </tr>
                        </tfoot>
                    </table>
                </div>

                <!-- Footer -->
                <div class="row mt-4">
                    <div class="col-md-6">
                        <p><strong>নোট:</strong></p>
                        <ul>
                            <li>এই ইনভয়েজটি কম্পিউটার জেনারেটেড</li>
                            <li>যেকোনো প্রশ্নের জন্য অফিসে যোগাযোগ করুন</li>
                            <li>পেমেন্ট রসিদ সংরক্ষণ করুন</li>
                        </ul>
                    </div>
                    <div class="col-md-6 text-end">
                        <p><strong>যোগাযোগ:</strong></p>
                        <p>ফোন: ০১৭xxxxxxxx<br>
                        ইমেইল: info@school.edu.bd<br>
                        ঠিকানা: স্কুলের ঠিকানা</p>
                    </div>
                </div>
            </div>
        </div>
        
        <!-- Professional Compact Invoice Template -->
        <div class="compact-invoice" id="compactInvoice">
            <!-- Header Section -->
            <div class="invoice-header-compact">
                <div class="left-section">
                    <h4><i class="fas fa-graduation-cap"></i> ইনভয়েজের তথ্য</h4>
                    <p><i class="fas fa-user"></i> শিক্ষার্থীর তথ্য</p>
                </div>
                <div class="right-section">
                    <div>INV-<?php echo date('Ymd') . '-' . ($student_info['id'] ?? ''); ?></div>
                    <div><?php echo date('d/m/Y'); ?></div>
                    <div><?php echo date('H:i:s'); ?></div>
                </div>
            </div>
            
            <!-- Student Information Section -->
            <div class="student-info-compact">
                <div class="info-column">
                    <div class="info-row">
                        <span class="info-label">ইনভয়েজ নম্বর:</span>
                        <span class="info-value">INV-<?php echo date('Ymd') . '-' . ($student_info['id'] ?? ''); ?></span>
                    </div>
                    <div class="info-row">
                        <span class="info-label">তৈরির তারিখ:</span>
                        <span class="info-value"><?php echo date('d/m/Y'); ?></span>
                    </div>
                    <div class="info-row">
                        <span class="info-label">সময়:</span>
                        <span class="info-value"><?php echo date('H:i:s'); ?></span>
                    </div>
                    <div class="info-row">
                        <span class="info-label">সময়কাল:</span>
                        <span class="info-value">
                            <?php 
                            if ($date_from && $date_to) {
                                echo date('d/m/Y', strtotime($date_from)) . ' - ' . date('d/m/Y', strtotime($date_to));
                            } elseif ($date_from) {
                                echo date('d/m/Y', strtotime($date_from)) . ' থেকে';
                            } elseif ($date_to) {
                                echo date('d/m/Y', strtotime($date_to)) . ' পর্যন্ত';
                            } else {
                                echo 'সব সময়';
                            }
                            ?>
                        </span>
                    </div>
                </div>
                <div class="info-column">
                    <div class="info-row">
                        <span class="info-label">নাম:</span>
                        <span class="info-value"><?php echo htmlspecialchars(($student_info['first_name'] ?? '') . ' ' . ($student_info['last_name'] ?? '')); ?></span>
                    </div>
                    <div class="info-row">
                        <span class="info-label">রোল নম্বর:</span>
                        <span class="info-value"><?php echo htmlspecialchars($student_info['roll_number'] ?? ''); ?></span>
                    </div>
                    <div class="info-row">
                        <span class="info-label">ক্লাস:</span>
                        <span class="info-value"><?php echo htmlspecialchars(($student_info['class_name'] ?? '') . ' - ' . ($student_info['class_section'] ?? '')); ?></span>
                    </div>
                    <div class="info-row">
                        <span class="info-label">সেশন:</span>
                        <span class="info-value"><?php echo htmlspecialchars($student_info['session'] ?? ''); ?></span>
                    </div>
                    <div class="info-row">
                        <span class="info-label">আইডি:</span>
                        <span class="info-value"><?php echo htmlspecialchars($student_info['student_id'] ?? ''); ?></span>
                    </div>
                </div>
            </div>
            
            <!-- Fee Details Section -->
            <div class="fee-details-compact">
                <h5><i class="fas fa-list"></i> ফি বিবরণ</h5>
                <table class="table-compact">
                    <thead>
                        <tr>
                            <th style="width: 8%;">ক্রমিক</th>
                            <th style="width: 20%;">ফি এর ধরন</th>
                            <th style="width: 15%;">মাস/বছর</th>
                            <th style="width: 12%;">মোট পরিমাণ (৳)</th>
                            <th style="width: 12%;">পরিশোধিত (৳)</th>
                            <th style="width: 12%;">বকেয়া (৳)</th>
                            <th style="width: 10%;">স্ট্যাটাস</th>
                            <th style="width: 11%;">নির্ধারিত তারিখ</th>
                        </tr>
                    </thead>
                    <tbody>
                        <?php 
                        if (!empty($invoice_data)) {
                            $serial = 1;
                            foreach ($invoice_data as $fee_id => $data): 
                                $fee = $data['fee_info'];
                        ?>
                        <tr>
                            <td class="center-cell"><?php echo $serial++; ?></td>
                            <td><?php echo htmlspecialchars($fee['fee_type']); ?></td>
                            <td class="center-cell">
                                <?php 
                                echo ($fee['month'] ? $fee['month'] . ' ' : '') . 
                                     ($fee['academic_year'] ? $fee['academic_year'] : ''); 
                                ?>
                            </td>
                            <td class="amount-cell">৳<?php echo number_format($fee['amount'], 0); ?></td>
                            <td class="amount-cell">৳<?php echo number_format($fee['paid_amount'], 0); ?></td>
                            <td class="amount-cell">৳<?php echo number_format($fee['due_amount'], 0); ?></td>
                            <td class="center-cell">
                                <?php
                                if ($fee['status'] == 'paid' || $fee['due_amount'] == 0) {
                                    echo '<span class="status-paid">পরিশোধিত</span>';
                                } elseif ($fee['paid_amount'] > 0 && $fee['due_amount'] > 0) {
                                    echo '<span class="status-partial">আংশিক</span>';
                                } else {
                                    echo '<span class="status-due">বকেয়া</span>';
                                }
                                ?>
                            </td>
                            <td class="center-cell"><?php echo date('d/m/Y', strtotime($fee['due_date'])); ?></td>
                        </tr>
                        <?php 
                            endforeach;
                        }
                        ?>
                        <tr class="total-row">
                            <td colspan="3" style="text-align: center;"><strong>সর্বমোট</strong></td>
                            <td class="amount-cell"><strong>৳<?php echo number_format($total_amount, 0); ?></strong></td>
                            <td class="amount-cell"><strong>৳<?php echo number_format($total_paid, 0); ?></strong></td>
                            <td class="amount-cell"><strong>৳<?php echo number_format($total_due, 0); ?></strong></td>
                            <td colspan="2" class="center-cell">
                                <?php if ($total_due > 0): ?>
                                    <span class="status-due">বকেয়া আছে</span>
                                <?php else: ?>
                                    <span class="status-paid">সব পরিশোধিত</span>
                                <?php endif; ?>
                            </td>
                        </tr>
                    </tbody>
                </table>
            </div>
            
            <!-- Footer Section -->
            <div class="footer-compact">
                <div class="notes-section">
                    <p><strong>নোট:</strong></p>
                    <ul>
                        <li>এই ইনভয়েজটি কম্পিউটার জেনারেটেড</li>
                        <li>যেকোনো প্রশ্নের জন্য অফিসে যোগাযোগ করুন</li>
                        <li>পেমেন্ট রসিদ সংরক্ষণ করুন</li>
                    </ul>
                </div>
                <div class="contact-info">
                    <p><strong>যোগাযোগ:</strong></p>
                    <p>ফোন: ০১৭xxxxxxxx</p>
                    <p>ইমেইল: info@school.edu.bd</p>
                    <p>ঠিকানা: স্কুলের ঠিকানা</p>
                </div>
            </div>
        </div>
        
        <?php elseif (!empty($student_id)): ?>
        <!-- No Data Message -->
        <div class="card">
            <div class="card-body text-center py-5">
                <i class="fas fa-search fa-3x text-muted mb-3"></i>
                <h4>কোন ফি রেকর্ড পাওয়া যায়নি</h4>
                <p class="text-muted">নির্বাচিত শিক্ষার্থী ও সময়কালের জন্য কোন ফি রেকর্ড খুঁজে পাওয়া যায়নি।</p>
            </div>
        </div>
        <?php endif; ?>
    </div>

    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/js/bootstrap.bundle.min.js"></script>
    <script>
        function loadStudents() {
            const classId = document.getElementById('class_id').value;
            const session = document.getElementById('session').value;
            const searchText = document.getElementById('search_text').value.trim();
            const searchBy = document.getElementById('search_by').value;
            const searchResultsContainer = document.getElementById('student_search_results');
            
            // Build query parameters
            let params = new URLSearchParams();
            if (classId) params.append('class_id', classId);
            if (session) params.append('session', session);
            if (searchText) {
                params.append('search_text', searchText);
                params.append('search_by', searchBy);
            }
            
            // Clear results if no search criteria
            if (!classId && !searchText) {
                searchResultsContainer.innerHTML = '';
                document.getElementById('search-status').textContent = 'সার্চ করুন';
                return;
            }
            
            // Show loading state
            searchResultsContainer.innerHTML = '<div class="p-2"><i class="fas fa-spinner fa-spin"></i> খোঁজা হচ্ছে...</div>';
            document.getElementById('search-status').textContent = 'খোঁজা হচ্ছে...';
            document.getElementById('search-status').style.color = '#007bff';
            
            const apiUrl = `../api/get_students_simple.php?${params.toString()}`;
            
            // Debug mode
            const debugMode = window.location.search.includes('debug=1');
            if (debugMode) {
                const debugDiv = document.getElementById('debug_info');
                const debugContent = document.getElementById('debug_content');
                if (debugDiv && debugContent) {
                    debugDiv.style.display = 'block';
                    debugContent.innerHTML = `
                        <div>API URL: ${apiUrl}</div>
                        <div>Search Text: "${searchText}"</div>
                        <div>Search By: ${searchBy}</div>
                        <div>Class ID: ${classId}</div>
                        <div>Session: ${session}</div>
                    `;
                }
            }
            
            fetch(apiUrl)
                .then(response => {
                    if (debugMode) {
                        console.log('API Response Status:', response.status);
                        console.log('API Response Headers:', response.headers);
                    }
                    
                    if (!response.ok) {
                        throw new Error(`HTTP ${response.status}: ${response.statusText}`);
                    }
                    return response.json();
                })
                .then(data => {
                    if (debugMode) {
                        console.log('API Response Data:', data);
                        const debugContent = document.getElementById('debug_content');
                        if (debugContent) {
                            debugContent.innerHTML += `
                                <div>Response Type: ${Array.isArray(data) ? 'Array' : typeof data}</div>
                                <div>Results Count: ${Array.isArray(data) ? data.length : 'N/A'}</div>
                                <div>Raw Response: ${JSON.stringify(data).substring(0, 200)}...</div>
                            `;
                        }
                    }
                    
                    if (Array.isArray(data)) {
                        let resultsHtml = '';
                        data.forEach(student => {
                            const className = student.class_name || '';
                            const classSection = student.class_section || '';
                            const studentId = student.student_id || '';
                            const phone = student.phone || student.guardian_phone || '';
                            const session = student.session || '';
                            
                            // Escape quotes for onclick function
                            const fullName = `${student.first_name} ${student.last_name}`.replace(/'/g, "\\'");
                            
                            resultsHtml += `
                                <div class="student-result-item" onclick="selectStudent(${student.id}, '${fullName}', '${student.roll_number}', '${studentId}')">
                                    <div class="d-flex justify-content-between align-items-center">
                                        <div>
                                            <strong>${student.first_name} ${student.last_name}</strong>
                                            <small class="text-muted d-block">
                                                রোল: ${student.roll_number} | আইডি: ${studentId} | ক্লাস: ${className} ${classSection}
                                            </small>
                                            ${phone ? `<small class="text-muted d-block">ফোন: ${phone}</small>` : ''}
                                            ${session ? `<small class="text-muted d-block">সেশন: ${session}</small>` : ''}
                                        </div>
                                        <div class="text-end">
                                            <i class="fas fa-user-plus text-primary"></i>
                                        </div>
                                    </div>
                                </div>
                            `;
                        });
                        searchResultsContainer.innerHTML = resultsHtml;
                        
                        // Update status
                        const statusElement = document.getElementById('search-status');
                        if (data.length > 0) {
                            statusElement.textContent = `${data.length} জন পাওয়া গেছে`;
                            statusElement.style.color = '#28a745';
                        } else {
                            searchResultsContainer.innerHTML = `
                                <div class="p-3 text-center">
                                    <i class="fas fa-search fa-2x text-muted mb-2"></i>
                                    <div class="text-muted">কোন শিক্ষার্থী পাওয়া যায়নি</div>
                                    <small class="text-muted">অন্য কিওয়ার্ড দিয়ে চেষ্টা করুন</small>
                                </div>
                            `;
                            statusElement.textContent = 'কোন ফলাফল নেই';
                            statusElement.style.color = '#ffc107';
                        }
                    } else if (data.error) {
                        throw new Error(data.message || 'Unknown error');
                    } else {
                        throw new Error('Invalid response format');
                    }
                })
                .catch(error => {
                    console.error('API Error:', error);
                    const errorMsg = error.message.includes('HTTP') ? 
                        'সার্ভার সংযোগে সমস্যা' : 
                        `ত্রুটি: ${error.message}`;
                    
                    searchResultsContainer.innerHTML = `
                        <div class="p-3 text-center text-danger">
                            <i class="fas fa-exclamation-triangle fa-2x mb-2"></i>
                            <div>${errorMsg}</div>
                            <small>আবার চেষ্টা করুন</small>
                        </div>
                    `;
                    
                    const statusElement = document.getElementById('search-status');
                    statusElement.textContent = 'ত্রুটি হয়েছে';
                    statusElement.style.color = '#dc3545';
                });
        }

        function selectStudent(studentId, studentName, rollNumber, studentIdNumber) {
            document.getElementById('student_id').value = studentId;
            document.getElementById('selected_student_name').value = studentName;
            document.getElementById('student_search_results').innerHTML = '';
            
            // Save to recent students
            saveRecentStudent(studentId, studentName, rollNumber || 'N/A');
            
            // Update status
            const statusElement = document.getElementById('search-status');
            statusElement.textContent = 'শিক্ষার্থী নির্বাচিত';
            statusElement.style.color = '#28a745';
            
            // Show success message briefly
            setTimeout(() => {
                statusElement.textContent = 'ইনভয়েজ তৈরি করুন';
                statusElement.style.color = '#6c757d';
            }, 2000);
        }
        
        function searchStudents() {
            loadStudents();
        }
        
        function clearSearch() {
            document.getElementById('search_text').value = '';
            document.getElementById('search_by').value = 'name';
            document.getElementById('class_id').value = '';
            document.getElementById('session').value = '';
            document.getElementById('student_id').value = '';
            document.getElementById('selected_student_name').value = '';
            document.getElementById('student_search_results').innerHTML = '';
        }
        
        function quickSearch() {
            const searchText = document.getElementById('search_text').value;
            if (!searchText) {
                alert('প্রথমে কিছু লিখুন');
                document.getElementById('search_text').focus();
                return;
            }
            searchStudents();
        }
        
        function printInvoice() {
            console.log('Print function called'); // Debug log
            
            try {
                // Check if we have content to print
                const invoiceContent = document.querySelector('.invoice-body');
                if (!invoiceContent) {
                    alert('প্রিন্ট করার জন্য কোন ইনভয়েজ ডাটা নেই');
                    return;
                }
                
                // Hide no-print elements before printing
                const noPrintElements = document.querySelectorAll('.no-print');
                noPrintElements.forEach(element => {
                    element.style.display = 'none';
                });
                
                // Apply half-page print mode for regular invoice
                document.body.classList.add('half-page-print');
                
                // Add a small delay to ensure the page is ready
                setTimeout(function() {
                    console.log('Calling window.print()'); // Debug log
                    
                    // Try multiple methods for better browser compatibility
                    if (window.print) {
                        window.print();
                    } else {
                        // Fallback for older browsers
                        document.execCommand('print', false, null);
                    }
                    
                    // Restore after a delay
                    setTimeout(function() {
                        noPrintElements.forEach(element => {
                            element.style.display = '';
                        });
                        document.body.classList.remove('half-page-print');
                    }, 1000);
                    
                }, 100);
                
            } catch (error) {
                console.error('Print error:', error);
                alert('প্রিন্ট করতে সমস্যা হয়েছে। ব্রাউজারের প্রিন্ট অপশন ব্যবহার করুন (Ctrl+P)');
            }
        }
        
        function alternativePrint() {
            console.log('Alternative print function called');
            
            // Simple alert to test if function is called
            alert('বিকল্প প্রিন্ট ফাংশন কাজ করছে। এখন প্রিন্ট ডায়ালগ খোলা হবে।');
            
            try {
                // Direct call to window.print without any modifications
                window.print();
            } catch (error) {
                console.error('Alternative print error:', error);
                alert('প্রিন্ট করতে সমস্যা হয়েছে: ' + error.message);
            }
        }
        
        function testPrintFunction() {
            console.log('Test function called');
            alert('JavaScript কাজ করছে! Print function type: ' + typeof window.print);
        }
        
        function robustPrint() {
            console.log('Robust print function called');
            
            // Multiple fallback methods
            const printMethods = [
                // Method 1: Standard window.print
                () => {
                    console.log('Trying method 1: window.print()');
                    window.print();
                },
                
                // Method 2: With timeout
                () => {
                    console.log('Trying method 2: setTimeout + window.print()');
                    setTimeout(() => window.print(), 100);
                },
                
                // Method 3: Focus then print
                () => {
                    console.log('Trying method 3: focus + window.print()');
                    window.focus();
                    window.print();
                },
                
                // Method 4: Document execCommand (deprecated but might work)
                () => {
                    console.log('Trying method 4: document.execCommand()');
                    document.execCommand('print', false, null);
                }
            ];
            
            let methodIndex = 0;
            
            function tryNextMethod() {
                if (methodIndex < printMethods.length) {
                    try {
                        printMethods[methodIndex]();
                        console.log(`Print method ${methodIndex + 1} executed successfully`);
                        return true;
                    } catch (error) {
                        console.error(`Print method ${methodIndex + 1} failed:`, error);
                        methodIndex++;
                        return tryNextMethod();
                    }
                } else {
                    console.error('All print methods failed');
                    alert('সব প্রিন্ট পদ্ধতি ব্যর্থ হয়েছে। ব্রাউজারের মেনু থেকে প্রিন্ট করুন (Ctrl+P)');
                    return false;
                }
            }
            
            return tryNextMethod();
        }
        
        function generateSampleURL() {
            const studentId = document.getElementById('student_id').value;
            const classId = document.getElementById('class_id').value;
            const session = document.getElementById('session').value;
            const dateFrom = document.getElementById('date_from').value;
            const dateTo = document.getElementById('date_to').value;
            
            if (!studentId) {
                alert('প্রথমে একজন শিক্ষার্থী নির্বাচন করুন');
                return;
            }
            
            let url = window.location.origin + window.location.pathname + '?';
            let params = [];
            
            if (studentId) params.push(`student_id=${studentId}`);
            if (classId) params.push(`class_id=${classId}`);
            if (session) params.push(`session=${encodeURIComponent(session)}`);
            if (dateFrom) params.push(`date_from=${dateFrom}`);
            if (dateTo) params.push(`date_to=${dateTo}`);
            
            url += params.join('&');
            
            // Copy to clipboard
            navigator.clipboard.writeText(url).then(() => {
                alert('URL কপি করা হয়েছে!\n\n' + url);
            }).catch(() => {
                // Fallback for older browsers
                prompt('এই URL কপি করুন:', url);
            });
        }
        
        function showKeyboardShortcuts() {
            alert(`কিবোর্ড শর্টকাট:
            
• Ctrl + F: সার্চ বক্সে ফোকাস
• Enter: সার্চ করুন
• Ctrl + Enter: ইনভয়েজ তৈরি করুন
• Ctrl + P: সাধারণ প্রিন্ট করুন
• Ctrl + Shift + P: কমপ্যাক্ট প্রিন্ট করুন
• Ctrl + V: কমপ্যাক্ট ভিউ টগল করুন
• Escape: সার্চ ক্লিয়ার করুন`);
        }
        
        function showRecentStudents() {
            // Get recent students from localStorage
            const recent = JSON.parse(localStorage.getItem('recentStudents') || '[]');
            if (recent.length === 0) {
                alert('কোন সাম্প্রতিক শিক্ষার্থী নেই');
                return;
            }
            
            let message = 'সাম্প্রতিক শিক্ষার্থী:\n\n';
            recent.slice(0, 5).forEach((student, index) => {
                message += `${index + 1}. ${student.name} (রোল: ${student.roll})\n`;
            });
            
            alert(message);
        }
        
        function saveRecentStudent(studentId, name, roll) {
            let recent = JSON.parse(localStorage.getItem('recentStudents') || '[]');
            
            // Remove if already exists
            recent = recent.filter(s => s.id !== studentId);
            
            // Add to beginning
            recent.unshift({
                id: studentId,
                name: name,
                roll: roll,
                timestamp: new Date().toISOString()
            });
            
            // Keep only last 10
            recent = recent.slice(0, 10);
            
            localStorage.setItem('recentStudents', JSON.stringify(recent));
        }
        
        // Compact Invoice Functions
        function toggleCompactView() {
            const compactInvoice = document.getElementById('compactInvoice');
            const regularInvoice = document.getElementById('regularInvoice');
            const toggleButton = document.getElementById('toggleViewButton');
            
            if (compactInvoice.classList.contains('show')) {
                // Hide compact, show regular
                compactInvoice.classList.remove('show');
                if (regularInvoice) regularInvoice.style.display = 'block';
                toggleButton.innerHTML = '<i class="fas fa-eye"></i> কমপ্যাক্ট ভিউ';
                toggleButton.classList.remove('btn-outline-warning');
                toggleButton.classList.add('btn-outline-info');
            } else {
                // Show compact, hide regular
                compactInvoice.classList.add('show');
                if (regularInvoice) regularInvoice.style.display = 'none';
                toggleButton.innerHTML = '<i class="fas fa-eye-slash"></i> সাধারণ ভিউ';
                toggleButton.classList.remove('btn-outline-info');
                toggleButton.classList.add('btn-outline-warning');
            }
        }
        
        function printCompactInvoice() {
            const studentId = document.getElementById('student_id').value;
            if (!studentId) {
                alert('প্রথমে একজন শিক্ষার্থী নির্বাচন করুন');
                return;
            }
            
            // Show compact view first
            const compactInvoice = document.getElementById('compactInvoice');
            const regularInvoice = document.getElementById('regularInvoice');
            const wasCompactVisible = compactInvoice.classList.contains('show');
            
            // Temporarily show compact view
            compactInvoice.classList.add('show');
            if (regularInvoice) regularInvoice.style.display = 'none';
            
            // Hide all no-print elements
            const noPrintElements = document.querySelectorAll('.no-print');
            noPrintElements.forEach(el => el.style.display = 'none');
            
            try {
                // Print
                window.print();
            } catch (error) {
                console.error('Print failed:', error);
                alert('প্রিন্ট করতে সমস্যা হয়েছে। ব্রাউজারের মেনু থেকে প্রিন্ট করুন (Ctrl+P)');
            }
            
            // Restore original view after print dialog
            setTimeout(() => {
                noPrintElements.forEach(el => el.style.display = '');
                
                if (!wasCompactVisible) {
                    compactInvoice.classList.remove('show');
                    if (regularInvoice) regularInvoice.style.display = 'block';
                }
            }, 1000);
        }
        
        function printInvoiceWithStyle(useCompact = false) {
            const studentId = document.getElementById('student_id').value;
            if (!studentId) {
                alert('প্রথমে একজন শিক্ষার্থী নির্বাচন করুন');
                return;
            }
            
            if (useCompact) {
                printCompactInvoice();
            } else {
                printInvoice();
            }
        }
        
        // Auto search on typing (with delay and smart filtering)
        let searchTimeout;
        document.getElementById('search_text').addEventListener('input', function() {
            clearTimeout(searchTimeout);
            const searchValue = this.value.trim();
            
            // Clear results if search is too short
            if (searchValue.length < 2) {
                document.getElementById('student_search_results').innerHTML = '';
                document.getElementById('search-status').textContent = 'কমপক্ষে ২ অক্ষর লিখুন';
                document.getElementById('search-status').style.color = '#6c757d';
                return;
            }
            
            // Auto-detect search type based on input pattern
            const searchBy = document.getElementById('search_by');
            if (/^\d+$/.test(searchValue)) {
                // Pure numbers - likely roll number
                searchBy.value = 'roll';
            } else if (/^01\d{9}$/.test(searchValue)) {
                // Bangladeshi mobile number pattern
                searchBy.value = 'phone';
            } else if (/^[A-Z0-9]{4,}$/i.test(searchValue)) {
                // Alphanumeric 4+ chars - likely student ID
                searchBy.value = 'student_id';
            } else {
                // Default to name search
                searchBy.value = 'name';
            }
            
            // Update search type indicator
            const searchTypeText = {
                'name': 'নাম',
                'roll': 'রোল',
                'student_id': 'আইডি',
                'phone': 'ফোন'
            };
            
            document.getElementById('search-status').textContent = `${searchTypeText[searchBy.value]} দিয়ে খোঁজা হচ্ছে...`;
            document.getElementById('search-status').style.color = '#007bff';
            
            // Debounced search
            searchTimeout = setTimeout(() => {
                searchStudents();
            }, 300); // Slightly longer delay for better performance
        });
        
        function clearSearchText() {
            document.getElementById('search_text').value = '';
            document.getElementById('student_search_results').innerHTML = '';
            document.getElementById('search_text').focus();
        }
        
        // Keyboard shortcuts
        document.addEventListener('keydown', function(e) {
            if (e.ctrlKey) {
                switch(e.key) {
                    case 'f':
                        e.preventDefault();
                        document.getElementById('search_text').focus();
                        break;
                    case 'Enter':
                        e.preventDefault();
                        document.querySelector('form').submit();
                        break;
                    case 'p':
                        if (document.getElementById('student_id').value) {
                            e.preventDefault();
                            if (e.shiftKey) {
                                printCompactInvoice();
                            } else {
                                printInvoice();
                            }
                        }
                        break;
                    case 'v':
                        if (document.getElementById('student_id').value) {
                            e.preventDefault();
                            toggleCompactView();
                        }
                        break;
                }
            } else if (e.key === 'Escape') {
                clearSearch();
            } else if (e.key === 'Enter' && e.target.id === 'search_text') {
                e.preventDefault();
                quickSearch();
            }
        });
        
        // Load students on page load
        document.addEventListener('DOMContentLoaded', function() {
            const studentId = document.getElementById('student_id').value;
            <?php if ($student_info): ?>
            if (studentId) {
                const studentName = '<?php echo $student_info ? addslashes($student_info["first_name"] . " " . $student_info["last_name"]) : ""; ?>';
                document.getElementById('selected_student_name').value = studentName;
            }
            <?php endif; ?>
            
            // Add event listeners as backup for onclick handlers
            const printBtn = document.getElementById('printButton');
            const altPrintBtn = document.getElementById('altPrintButton');
            const testBtn = document.getElementById('testButton');
            
            if (printBtn) {
                printBtn.addEventListener('click', function(e) {
                    e.preventDefault();
                    console.log('Print button clicked via event listener');
                    printInvoice();
                });
            }
            
            if (altPrintBtn) {
                altPrintBtn.addEventListener('click', function(e) {
                    e.preventDefault();
                    console.log('Alt print button clicked via event listener');
                    alternativePrint();
                });
            }
            
            if (testBtn) {
                testBtn.addEventListener('click', function(e) {
                    e.preventDefault();
                    console.log('Test button clicked via event listener');
                    testPrintFunction();
                });
            }
        });
    </script>
</body>
</html>