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

// AJAX handler for getting students
if (isset($_GET['ajax']) && $_GET['ajax'] == 'get_students') {
    header('Content-Type: application/json');
    
    try {
        $class_id = $_GET['class_id'] ?? '';
        $session = $_GET['session'] ?? '';
        $group_name = $_GET['group_name'] ?? null;
        
        $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;
        }
        
        // Handle group filtering properly
        if ($group_name !== null) {
            if ($group_name === '') {
                // Special case: "no group" selected (empty string)
                $where_conditions[] = "s.group_name IS NULL OR s.group_name = ''";
            } else {
                // Specific group selected
                $where_conditions[] = "s.group_name = ?";
                $params[] = $group_name;
            }
        }
        
        $where_clause = implode(' AND ', $where_conditions);
        
        $sql = "
            SELECT s.id, s.student_id, s.first_name, s.last_name, s.roll_number, s.session, s.group_name, s.scholarship, c.name as class_name, c.section as class_section,
                   COALESCE(SUM(f.amount - f.paid_amount), 0) as total_due
            FROM students s
            JOIN classes c ON s.class_id = c.id
            LEFT JOIN fees f ON s.id = f.student_id
            WHERE $where_clause
            GROUP BY s.id, s.student_id, s.first_name, s.last_name, s.roll_number, s.session, s.group_name, s.scholarship, c.name, c.section
            ORDER BY s.roll_number
        ";
        
        $stmt = $pdo->prepare($sql);
        $stmt->execute($params);
        $students = $stmt->fetchAll();
        
        echo json_encode($students);
    } catch (Exception $e) {
        http_response_code(500);
        echo json_encode(['error' => 'Database error: ' . $e->getMessage()]);
    }
    exit();
}

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

// Clear session variable if requested (for testing)
if (isset($_GET['clear_session'])) {
    unset($_SESSION['fee_password_verified']);
}

// Function to get setting from admin settings table
function get_admin_setting($pdo, $key, $default = null) {
    try {
        $stmt = $pdo->prepare("SELECT setting_value FROM settings WHERE setting_key = ? LIMIT 1");
        $stmt->execute([$key]);
        $row = $stmt->fetch();
        if ($row && !empty($row['setting_value'])) return $row['setting_value'];
    } catch (Exception $e) {
        // ignore
    }
    return $default;
}

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

// Check if fee password is set and verify it
$fee_password_verified = false;
$fee_password_hash = get_admin_setting($pdo, 'fee_password');

// If no fee password is set, allow access
if (empty($fee_password_hash)) {
    $fee_password_verified = true;
} else {
    // Check if password is already verified in session
    if (!empty($_SESSION['fee_password_verified']) && $_SESSION['fee_password_verified'] === true) {
        $fee_password_verified = true;
    } else if (!empty($_POST['fee_access_password'])) {
        if (password_verify($_POST['fee_access_password'], $fee_password_hash)) {
            $_SESSION['fee_password_verified'] = true;
            $fee_password_verified = true;
        }
    } else {
        // If fee password is set but not verified, show password form
        $fee_password_verified = false;
    }
}

// If fee password is required but not verified, show password form
if (!$fee_password_verified):
    ?>
    <!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; 
                display: flex;
                justify-content: center;
                align-items: center;
                min-height: 100vh;
                margin: 0;
                padding: 20px;
            }
            .password-container { 
                max-width: 400px; 
                width: 100%;
            }
            .card {
                border-radius: 15px;
                box-shadow: 0 0 30px rgba(0,0,0,0.1);
            }
        </style>
    </head>
    <body>
        <div class="password-container">
            <div class="card">
                <div class="card-header text-center bg-primary text-white">
                    <h4><i class="fas fa-lock"></i> ফি সংগ্রহ পাসওয়ার্ড</h4>
                </div>
                <div class="card-body">
                    <p class="text-center text-muted mb-4">এই মডিউলটি সুরক্ষিত। অ্যাক্সেসের জন্য পাসওয়ার্ড প্রয়োজন।</p>
                    
                    <?php if (isset($_GET['clear_session'])): ?>
                        <div class="alert alert-info">
                            সেশন মুছে ফেলা হয়েছে। ফি সংগ্রহ মডিউলে প্রবেশের জন্য পাসওয়ার্ড দিন।
                        </div>
                    <?php endif; ?>
                    
                    <?php if (isset($_POST['fee_access_password']) && !$fee_password_verified): ?>
                        <div class="alert alert-danger">
                            <i class="fas fa-exclamation-triangle"></i> পাসওয়ার্ড সঠিক নয়!
                        </div>
                    <?php endif; ?>
                    
                    <form method="POST" action="">
                        <div class="mb-3">
                            <label for="fee_access_password" class="form-label">পাসওয়ার্ড দিন</label>
                            <input type="password" class="form-control" id="fee_access_password" name="fee_access_password" required autofocus>
                            <div class="form-text">ফি সংগ্রহ মডিউলে প্রবেশের জন্য পাসওয়ার্ড প্রয়োজন</div>
                        </div>
                        <button type="submit" class="btn btn-primary w-100">
                            <i class="fas fa-unlock"></i> প্রবেশ করুন
                        </button>
                        
                        <div class="text-center mt-3">
                            <a href="../index.php" class="btn btn-secondary">
                                <i class="fas fa-arrow-left"></i> ড্যাশবোর্ডে ফিরে যান
                            </a>
                            <?php if (isset($_GET['clear_session'])): ?>
                                <a href="." class="btn btn-success ms-2">
                                    <i class="fas fa-redo"></i> রিফ্রেশ
                                </a>
                            <?php else: ?>
                                <a href="?clear_session=1" class="btn btn-warning ms-2">
                                    <i class="fas fa-trash"></i> সেশন মুছুন
                                </a>
                            <?php endif; ?>
                        </div>
                    </form>
                </div>
            </div>
            
            <div class="text-center mt-4 text-muted">
                <small>© <?php echo date('Y'); ?> স্কুল ম্যানেজমেন্ট সিস্টেম</small>
            </div>
        </div>
    </body>
    </html>
    <?php
    exit();
endif;

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

// 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 pre-selection from URL
$preselected_student_id = $_GET['student_id'] ?? null;
$preselection_data = null;
if ($preselected_student_id) {
    $stmt = $pdo->prepare("SELECT id, class_id, session FROM students WHERE id = ?");
    $stmt->execute([$preselected_student_id]);
    $student_data = $stmt->fetch();
    if ($student_data) {
        $preselection_data = $student_data;
    }
}

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

                    // Store info for success message
                    $processed_payments[] = [
                        'payment_id' => $payment_id,
                        'transaction_id' => $transaction_id,
                        'fee_type' => $fee['fee_type'],
                        'amount' => $actual_payment
                    ];
                }
                
                $total_collected += $actual_payment;
            }
            
            $pdo->commit();
            
            // Process SMS notification after successful payment
            if ($total_collected > 0) {
                // Prepare notification status information
                $notification_status_msg = "";
                
                // Determine notification status based on settings
                $stmt = $pdo->prepare("SELECT setting_value FROM settings WHERE setting_key = 'non_musking_enabled'");
                $stmt->execute();
                $result = $stmt->fetch();
                $nonMuskingEnabled = $result && $result['setting_value'] === '1';
                
                $stmt = $pdo->prepare("SELECT setting_value FROM settings WHERE setting_key = 'sms_send_fee_notifications'");
                $stmt->execute();
                $result = $stmt->fetch();
                $feeNotificationsEnabled = $result && $result['setting_value'] === '1';
                
                // Check if student has phone numbers
                $stmt = $pdo->prepare('SELECT phone, guardian_phone FROM students WHERE id=?');
                $stmt->execute([$student_id]);
                $student_info = $stmt->fetch();
                $has_phone_numbers = (!empty($student_info['phone']) || !empty($student_info['guardian_phone']));
                
                // Determine if SMS was attempted to be sent
                if ($nonMuskingEnabled && $feeNotificationsEnabled) {
                    if ($has_phone_numbers) {
                        $notification_status_msg = " | নোটিফিকেশন: প্রচেষ্টা করা হয়েছে";
                    } else {
                        $notification_status_msg = " | নোটিফিকেশন: ফোন নম্বর পাওয়া যায়নি";
                    }
                } else {
                    $reasons = [];
                    if (!$nonMuskingEnabled) {
                        $reasons[] = 'নন-মাস্কিং এসএমএস সার্ভিস নিষ্ক্রিয়';
                    }
                    if (!$feeNotificationsEnabled) {
                        $reasons[] = 'ফি নোটিফিকেশন নিষ্ক্রিয়';
                    }
                    $notification_status_msg = " | নোটিফিকেশন: " . implode(', ', $reasons);
                }
                
                $success_message = "সফলভাবে ৳" . number_format($total_collected, 2) . " টাকা সংগ্রহ করা হয়েছে" . $notification_status_msg . "।";
                if (!empty($processed_payments)) {
                    $success_message .= "<hr class='my-2'><strong>প্রসেসকৃত পেমেন্ট:</strong><ul class='list-unstyled mt-2'>";
                    foreach ($processed_payments as $p) {
                        $success_message .= "<li class='d-flex justify-content-between align-items-center mb-1'>" . htmlspecialchars($p['fee_type']) . ": ৳" . number_format($p['amount'], 2);
                        $success_message .= " <span>(ID: {$p['payment_id']}) ";
                        $success_message .= "<a href='receipt.php?id={$p['payment_id']}' target='_blank' class='btn btn-sm btn-outline-success ms-2'><i class='fas fa-print'></i> রসিদ</a></span></li>";
                    }
                    $success_message .= "</ul>";
                }
            } else {
                $error_message = "কোন পেমেন্ট প্রক্রিয়া করা হয়নি";
            }
            
            if ($total_collected > 0) {
                try {
                    $smsHelperPath = __DIR__ . '/../includes/sms_helper.php';
                    if (file_exists($smsHelperPath)) {
                        require_once $smsHelperPath;
                        
                        // Check if non-musking SMS service is enabled
                        $stmt = $pdo->prepare("SELECT setting_value FROM settings WHERE setting_key = 'non_musking_enabled'");
                        $stmt->execute();
                        $result = $stmt->fetch();
                        $nonMuskingEnabled = $result && $result['setting_value'] === '1';
                        
                        // Check if fee payment notifications are enabled
                        $stmt = $pdo->prepare("SELECT setting_value FROM settings WHERE setting_key = 'sms_send_fee_notifications'");
                        $stmt->execute();
                        $result = $stmt->fetch();
                        $feeNotificationsEnabled = $result && $result['setting_value'] === '1';
                        
                        if ($nonMuskingEnabled && $feeNotificationsEnabled) {
                            $cfg = sms_config();
                            $numbers = [];
                            // Fetch phones
                            $pStmt = $pdo->prepare('SELECT phone, guardian_phone, first_name, last_name FROM students WHERE id=?');
                            $pStmt->execute([$student_id]);
                            $p = $pStmt->fetch();
                            if (!empty($p['phone'])) $numbers[] = $p['phone'];
                            if (($cfg['send_to_guardian'] ?? true) && !empty($p['guardian_phone'])) $numbers[] = $p['guardian_phone'];

                            if (!empty($numbers)) {
                                // Compute due after all payments
                                $dueStmt = $pdo->prepare('SELECT COALESCE(SUM(amount-COALESCE(paid_amount,0)),0) AS due FROM fees WHERE student_id=?');
                                $dueStmt->execute([$student_id]);
                                $due = (float)($dueStmt->fetch()['due'] ?? 0);
                                $vars = [
                                    'name' => trim(($p['first_name'] ?? '').' '.($p['last_name'] ?? '')),
                                    'paid_amount' => number_format($total_collected, 2),
                                    'due_amount' => number_format($due, 2),
                                ];
                                
                                // Try to use non-musking template, fallback to hardcoded message
                                $result = non_musking_send_template($pdo, 'fee_payment', $vars, $numbers);
                                
                                // If template doesn't exist, use hardcoded message
                                if (!$result['success'] && strpos($result['message'], 'Template not found') !== false) {
                                    $feeMessage = "\xE0\xA6\xAA\xE0\xA7\x8D\xE0\xA6\xB0\xE0\xA6\xBF\xE0\xA6\xAF\xE0\xA6\xBC \xE0\xA6\x86\xE0\xA6\xAA\xE0\xA6\xA8\xE0\xA6\xBE\xE0\xA6\xB0 \xE0\xA6\xAB\xE0\xA6\xBF \xE0\xA7\xBB\xE0\xA6\x93" . number_format($total_collected, 2) . " \xE0\xA6\x9F\xE0\xA6\xBE\xE0\xA6\x95\xE0\xA6\xBE \xE0\xA6\x97\xE0\xA7\x83\xE0\xA6\xB9\xE0\xA7\x80\xE0\xA6\xA4 \xE0\xA6\xB9\xE0\xA6\xAF\xE0\xA6\xBC\xE0\xA7\x87\xE0\xA6\x9B\xE0\xA7\x87\xE0\xA5\xA4 \xE0\xA6\xAC\xE0\xA6\xB0\xE0\xA7\x8D\xE0\xA6\xA4\xE0\xA6\xAE\xE0\xA6\xBE\xE0\xA6\xA8 \xE0\xA6\xAC\xE0\xA6\x95\xE0\xA7\x87\xE0\xA6\xAF\xE0\xA6\xBC\xE0\xA6\xBE: " . number_format($due, 2) . " \xE0\xA6\x9F\xE0\xA6\xBE\xE0\xA6\x95\xE0\xA6\xBE\xE0\xA5\xA4 \xE0\xA6\xA7\xE0\xA6\xA8\xE0\xA7\x8D\xE0\xA6\xAF\xE0\xA6\xAC\xE0\xA6\xBE\xE0\xA6\xA6\xE0\xA5\xA4";
                                    non_musking_send($pdo, $numbers, $feeMessage, ['template'=>'fee_payment']);
                                }
                            } else {
                                // Log that no phone numbers were found for the student
                                if (function_exists('sms_log')) sms_log('No phone numbers found for student ID: ' . $student_id);
                            }
                        } else {
                            // Show why notifications were not sent
                            $reasons = [];
                            if (!$nonMuskingEnabled) {
                                $reasons[] = '\xE0\xA6\xA8\xE0\xA6\xA8-\xE0\xA6\xAE\xE0\xA6\xBE\xE0\xA6\xB8\xE0\xA7\x8D\xE0\xA6\x95\xE0\xA6\xBF\xE0\xA6\x82 \xE0\xA6\x8F\xE0\xA6\xB8\xE0\xA6\x8F\xE0\xA6\xAE\xE0\xA6\x8F\xE0\xA6\xB8 \xE0\xA6\xB8\xE0\xA6\xBE\xE0\xA6\xB0\xE0\xA7\x8D\xE0\xA6\xAD\xE0\xA6\xBF\xE0\xA6\xB8 \xE0\xA6\xA8\xE0\xA6\xBF\xE0\xA6\xB7\xE0\xA7\x8D\xE0\xA6\x95\xE0\xA7\x8D\xE0\xA6\xB0\xE0\xA6\xBF\xE0\xA6\xAF\xE0\xA6\xBC';
                            }
                            if (!$feeNotificationsEnabled) {
                                $reasons[] = '\xE0\xA6\xAB\xE0\xA6\xBF \xE0\xA6\xA8\xE0\xA7\x8B\xE0\xA6\x9F\xE0\xA6\xBF\xE0\xA6\xAB\xE0\xA6\xBF\xE0\xA6\x95\xE0\xA7\x87\xE0\xA6\xB6\xE0\xA6\xA8 \xE0\xA6\xA8\xE0\xA6\xBF\xE0\xA6\xB7\xE0\xA7\x8D\xE0\xA6\x95\xE0\xA7\x8D\xE0\xA6\xB0\xE0\xA6\xBF\xE0\xA6\xAF\xE0\xA6\xBC';
                            }
                            if (function_exists('sms_log')) sms_log('SMS not sent to student ID: ' . $student_id . '. Reasons: ' . implode(', ', $reasons));
                        }
                    }
                } catch (Throwable $e) {
                    if (function_exists('sms_log')) sms_log('FEE SMS error: '.$e->getMessage());
                }
            }

            
        } catch (Exception $e) {
            // Rollback only if there's an active transaction
            if ($pdo->inTransaction()) {
                $pdo->rollBack();
            }
            $error_message = 'পেমেন্ট প্রক্রিয়ায় সমস্যা হয়েছে: ' . $e->getMessage();
        }
    } else {
        $error_message = 'সকল প্রয়োজনীয় তথ্য পূরণ করুন';
    }
}


?>

<!DOCTYPE html>
<html lang="bn">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>শিক্ষার্থী ফি ব্যবস্থাপনা</title>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/css/bootstrap.min.css" rel="stylesheet">
    <link href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.0.0/css/all.min.css" rel="stylesheet">
    <link href="https://fonts.googleapis.com/css2?family=Hind+Siliguri:wght@300;400;500;600;700&display=swap" rel="stylesheet">
    <style>
        :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;font-size:.85rem;color:#e0e0e0}
        .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 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);overflow:hidden}
        .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:.82rem}
        .card .card-header .badge{font-size:.7rem;font-weight:600;padding:3px 10px}
        .card .card-body{padding:10px 12px;background:rgba(255,255,255,.02)}
        .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)}
        .fee-item{border:1px solid rgba(255,255,255,.08);border-radius:8px;padding:8px 10px;margin-bottom:5px;background:rgba(255,255,255,.04)}
        .fee-item.overdue{border-left:3px solid #ef5350;background:rgba(239,83,80,.08)}
        .amount-display{font-size:.95rem;font-weight:700;color:#fff}
        .total-due{color:#ef5350}
        .btn-collect{background:linear-gradient(135deg,#1565c0,#1e88e5);border:none;border-radius:6px;padding:6px 16px;font-weight:700;font-size:.82rem;color:#fff;width:100%}
        .btn-collect:hover{background:linear-gradient(135deg,#1976d2,#42a5f5);color:#fff}
        .pagination{margin:6px 0 0}
        .pagination .page-link{background:rgba(255,255,255,.06);border:1px solid rgba(255,255,255,.1);color:#90caf9;padding:3px 10px;font-size:.75rem}
        .pagination .page-link:hover{background:rgba(255,255,255,.12);color:#fff}
        .pagination .page-item.active .page-link{background:#4fc3f7;border-color:#4fc3f7;color:#0a1929}
        .table-light{--bs-table-bg:rgba(255,255,255,.06);--bs-table-color:#e0e0e0;--bs-table-striped-bg:rgba(255,255,255,.04)}
        .table{--bs-table-border-color:rgba(255,255,255,.08);color:#e0e0e0}
        .table-hover tbody tr:hover{--bs-table-hover-bg:rgba(79,195,247,.08);--bs-table-hover-color:#fff}
        .table-primary{--bs-table-bg:rgba(79,195,247,.15)!important;--bs-table-color:#fff!important}
        .input-group-text{background:rgba(0,0,0,.3);border:1px solid rgba(255,255,255,.12);color:#90caf9;font-size:.7rem;padding:2px 6px}
        .form-control::placeholder{color:rgba(255,255,255,.3)}
        .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;border-color:rgba(255,255,255,.3)}
        .btn-light{background:rgba(255,255,255,.1);border-color:rgba(255,255,255,.15);color:#e0e0e0}
        .btn-light:hover{background:rgba(255,255,255,.18);color:#fff}
        .btn-light.active{background:#4fc3f7!important;border-color:#4fc3f7!important;color:#0a1929!important}
        .bg-light{background:rgba(255,255,255,.1)!important}
        .text-dark{color:#e0e0e0!important}
        .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}
    </style>
</head>
<body>
    <div class="top-bar no-print">
        <a href="../index.php" class="brand"><i class="fas fa-graduation-cap"></i> স্কুল ম্যানেজমেন্ট</a>
        <div class="nav-links">
            <a href="management_dashboard.php"><i class="fas fa-cog"></i> ফি ড্যাশবোর্ড</a>
            <a href="manage.php"><i class="fas fa-wrench"></i> ফি ম্যানেজ</a>
            <a href="../index.php"><i class="fas fa-home"></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 no-print py-2 small"><?php echo $success_message; ?></div><?php endif; ?>
        <?php if ($error_message): ?><div class="alert alert-danger no-print py-2 small"><?php echo $error_message; ?></div><?php endif; ?>

        <div class="filter-card no-print">
            <div class="row g-1">
                <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="__NO_GROUP__">কোন গ্রুপ নেই</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,#667eea,#764ba2);color:#fff;border:none;border-radius:6px;padding:5px;font-weight:700;font-size:.82rem" onclick="loadStudents()"><i class="fas fa-search me-1"></i>খুঁজুন</button></div>
            </div>
        </div>

        <div class="row g-2">
            <div class="col-md-5">
                <div class="card">
                    <div class="card-header d-flex justify-content-between align-items-center">
                        <span><i class="fas fa-users me-1"></i>শিক্ষার্থী তালিকা</span>
                        <div class="d-flex align-items-center gap-2">
                            <span class="badge bg-light text-dark" id="student-count">0 জন</span>
                            <div class="btn-group" role="group">
                                <button type="button" class="btn btn-sm btn-light active" id="btn-card-view" onclick="switchView('card')" style="padding:2px 6px;font-size:.72rem"><i class="fas fa-th-large"></i></button>
                                <button type="button" class="btn btn-sm btn-light" id="btn-table-view" onclick="switchView('table')" style="padding:2px 6px;font-size:.72rem"><i class="fas fa-table"></i></button>
                            </div>
                        </div>
                    </div>
                    <div class="card-body">
                        <div class="mb-2">
                            <div class="input-group input-group-sm">
                                <input type="text" class="form-control" id="student-search" placeholder="নাম, আইডি বা রোল দিয়ে খুঁজুন..." style="font-size:.78rem">
                                <button class="btn btn-outline-secondary" type="button" id="search-button" style="font-size:.75rem"><i class="fas fa-search"></i></button>
                            </div>
                        </div>
                        <div style="max-height:480px;overflow-y:auto">
                            <div id="students-list">
                                <div class="text-center text-muted py-4"><i class="fas fa-search fa-2x mb-2"></i><p class="small">শিক্ষার্থী খুঁজতে ফিল্টার ব্যবহার করুন</p></div>
                            </div>
                        </div>
                        <nav><ul class="pagination justify-content-center" id="pagination-controls"></ul></nav>
                    </div>
                </div>
            </div>
            <div class="col-md-7">
                <div class="card">
                    <div class="card-header"><i class="fas fa-money-bill-wave me-1"></i>ফি কালেকশন</div>
                    <div class="card-body">
                        <div id="fee-collection-area">
                            <div class="text-center text-muted py-4"><i class="fas fa-hand-point-left fa-2x mb-2"></i><p class="small">একজন শিক্ষার্থী নির্বাচন করুন</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>
        const preselectionData = <?php echo $preselection_data ? json_encode($preselection_data) : 'null'; ?>;
        let selectedStudentId = null;
        
        let allStudents = [];
        let filteredStudents = [];
        const studentsPerPage = 15;
        let currentPage = 1;
        let currentView = 'card'; // 'card' or 'table'

        function switchView(view) {
            currentView = view;
            document.getElementById('btn-card-view').classList.toggle('active', view === 'card');
            document.getElementById('btn-table-view').classList.toggle('active', view === 'table');
            renderPage(currentPage);
        }

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

            // Build parameters object
            const paramsObj = { ajax: 'get_students' };
            
            if (session) paramsObj.session = session;
            if (classId) paramsObj.class_id = classId;
            
            // Handle group filtering
            if (groupName !== '') {
                if (groupName === '__NO_GROUP__') {
                    // Special case: "no group" selected
                    paramsObj.group_name = '';
                } else {
                    // Specific group selected
                    paramsObj.group_name = groupName;
                }
            }

            const params = new URLSearchParams(paramsObj);

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

            return fetch(`?${params}`)
                .then(response => {
                    if (!response.ok) {
                        throw new Error(`HTTP error! status: ${response.status}`);
                    }
                    return response.json();
                })
                .then(data => {
                    // Check if the response contains an error
                    if (data.error) {
                        throw new Error(data.error);
                    }
                    
                    allStudents = data;
                    // Don't clear the search term here, let filterStudents handle it
                    filterStudents();
                })
                .catch(error => {
                    console.error('Error:', error);
                    showAlert('শিক্ষার্থী লোড করতে সমস্যা হয়েছে: ' + error.message, 'danger');
                });
        }

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

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

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

            const startIndex = (page - 1) * studentsPerPage;
            const endIndex = startIndex + studentsPerPage;
            container.innerHTML = currentView === 'table'
                ? generateStudentTable(filteredStudents.slice(startIndex, endIndex))
                : generateStudentCards(filteredStudents.slice(startIndex, endIndex));
        }

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

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

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

        function generateStudentTable(students) {
            let rows = students.map(student => {
                const totalDue = parseFloat(student.total_due) || 0;
                const hasScholarship = student.scholarship === 'yes';
                const isSelected = selectedStudentId == student.id;
                return `
                    <tr class="${isSelected ? 'table-primary' : ''}" style="cursor:pointer"
                        onclick="selectStudent(event, ${student.id}, '${student.first_name} ${student.last_name}')">
                        <td class="fw-bold">${student.roll_number}</td>
                        <td>${student.first_name} ${student.last_name}${hasScholarship ? ' <span class="badge bg-success" style="font-size:.65rem">উপবৃত্তি</span>' : ''}</td>
                        <td><small class="text-muted">${student.student_id || 'N/A'}</small></td>
                        <td>${student.class_name || ''}</td>
                        <td class="text-end fw-bold ${totalDue > 0 ? 'text-danger' : 'text-success'}">${hasScholarship ? '<span class="text-success" style="font-size:.72rem">মওকুত</span>' : '৳' + totalDue.toFixed(2)}</td>
                    </tr>`;
            }).join('');
            return `<div class="table-responsive"><table class="table table-hover table-sm align-middle mb-0" style="font-size:.78rem"><thead class="table-light"><tr><th style="padding:4px 6px">রোল</th><th style="padding:4px 6px">নাম</th><th style="padding:4px 6px">আইডি</th><th style="padding:4px 6px">ক্লাস</th><th class="text-end" style="padding:4px 6px">বকেয়া</th></tr></thead><tbody>${rows}</tbody></table></div>`;
        }

        function generateStudentCards(students) {
            let html = '';
            students.forEach(student => {
                const totalDue = parseFloat(student.total_due) || 0;
                const hasScholarship = student.scholarship === 'yes';
                html += `<div class="student-card ${selectedStudentId == student.id ? 'selected' : ''}" onclick="selectStudent(event, ${student.id}, '${student.first_name} ${student.last_name}')">
                    <div class="d-flex justify-content-between align-items-center">
                        <div><strong style="font-size:.82rem">${student.first_name} ${student.last_name}</strong>${hasScholarship ? ' <span class="badge bg-success" style="font-size:.62rem">উপবৃত্তি</span>' : ''}<br><small class="text-muted" style="font-size:.7rem">রোল: ${student.roll_number} | ${student.student_id || 'N/A'}</small></div>
                        <div class="text-end">${hasScholarship ? '<span class="text-success" style="font-size:.72rem;font-weight:600">মওকুত</span>' : '<div class="amount-display total-due">৳' + totalDue.toFixed(2) + '</div><span style="font-size:.68rem;color:#999">বকেয়া</span>'}</div>
                    </div>
                </div>`;
            });
            return html;
        }

        function selectStudent(event, studentId, studentName) {
            selectedStudentId = studentId;
            // Remove selection from cards
            document.querySelectorAll('.student-card').forEach(card => card.classList.remove('selected'));
            // Remove selection from table rows
            document.querySelectorAll('#students-list tr').forEach(row => row.classList.remove('table-primary'));
            // Highlight current
            const el = event.currentTarget;
            if (el.tagName === 'TR') {
                el.classList.add('table-primary');
            } else {
                el.classList.add('selected');
            }
            loadStudentFees(studentId, studentName);
        }

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

        function displayFeeCollection(studentId, studentName, response) {
            const container = document.getElementById('fee-collection-area');
            
            // Check if response is the new format with has_scholarship property
            const hasScholarship = response.has_scholarship || false;
            const fees = response.fees || (Array.isArray(response) ? response : []);
            
            // Check if student has scholarship exemption (old format)
            if (response.scholarship === true) {
            container.innerHTML = `<div class="text-center text-success py-3"><i class="fas fa-graduation-cap fa-2x mb-2"></i><h6 class="fw-bold">${studentName}</h6><div class="alert alert-success py-2 small">উপবৃত্তি পেয়েছেন। বেতন মওকুত।</div></div>`;
            return;
        }
        
        if (fees.length === 0) {
            container.innerHTML = `<div class="text-center text-success py-3"><i class="fas fa-check-circle fa-2x mb-2"></i><h6 class="fw-bold">${studentName}</h6><p class="small">সব ফি পরিশোধিত</p></div>`;
                return;
            }

            let totalDue = 0;
            let feesHtml = fees.map(fee => {
                const dueAmount = parseFloat(fee.due_amount);
                totalDue += dueAmount;
                // Check if this is a salary fee AND student has scholarship
                const isSalaryFee = (fee.fee_type === 'বেতন' || fee.fee_type === 'মাসিক বেতন') && hasScholarship;
                return `<div class="fee-item ${new Date(fee.due_date) < new Date() ? 'overdue' : ''}">
                    <div class="d-flex justify-content-between align-items-center">
                        <div><strong style="font-size:.78rem">${fee.fee_type}</strong>${fee.month ? ' <span class="text-muted" style="font-size:.68rem">'+fee.month+'</span>' : ''}<br><span style="font-size:.65rem;color:#999">${fee.due_date}${isSalaryFee ? ' <span class="badge bg-success" style="font-size:.6rem">মওকুত</span>' : ''}</span></div>
                        <div class="text-end"><span class="amount-display" style="${dueAmount>0?'color:#dc3545':''}">৳${dueAmount.toFixed(2)}</span></div>
                    </div>
                    ${!isSalaryFee ? `<div class="input-group input-group-sm mt-1"><span class="input-group-text" style="font-size:.7rem;padding:2px 6px">৳</span><input type="number" class="form-control payment-input" name="fee_payments[${fee.id}]" max="${dueAmount}" min="0" step="0.01" placeholder="পেমেন্ট" onchange="updateTotalPayment()" style="font-size:.75rem;padding:2px 6px"></div>` : ''}
                </div>`;
            }).join('');

            container.innerHTML = `
                <div class="d-flex justify-content-between align-items-center mb-2">
                    <h6 class="fw-bold mb-0">${studentName}</h6>
                    <span class="badge bg-danger" style="font-size:.75rem">বকেয়া: ৳${totalDue.toFixed(2)}</span>
                </div>
                <form method="POST" action="">
                    <input type="hidden" name="student_id" value="${studentId}">
                    <div class="mb-2">${feesHtml}</div>
                    <div class="row g-1 mb-2">
                        <div class="col-5"><select class="form-select form-select-sm" name="payment_method" style="font-size:.78rem"><option value="cash">নগদ</option><option value="bank">ব্যাংক</option></select></div>
                        <div class="col-3"><div class="form-control form-control-sm text-center fw-bold" id="total-payment-display" style="font-size:.78rem">৳0.00</div></div>
                        <div class="col-4"><button type="submit" name="collect_fee" class="btn btn-collect" style="font-size:.78rem;padding:4px 10px"><i class="fas fa-money-bill-wave me-1"></i>ফি সংগ্রহ</button></div>
                    </div>
                    <textarea class="form-control form-control-sm" name="payment_note" rows="1" placeholder="নোট..." style="font-size:.75rem"></textarea>
                </form>
            `;
        }

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

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

        document.addEventListener('DOMContentLoaded', function() {
            if (preselectionData) {
                document.getElementById('filter_class').value = preselectionData.class_id;
                document.getElementById('filter_session').value = preselectionData.session;

                loadStudents().then(() => {
                    const studentCard = document.querySelector(`[onclick*="selectStudent(event, ${preselectionData.id},"]`);
                    if (studentCard) {
                        studentCard.click();
                        studentCard.scrollIntoView({ behavior: 'smooth', block: 'center' });
                    }
                });
            } else {
                // Automatically load students if filters are set from previous visits or manually
                if (document.getElementById('filter_session').value && document.getElementById('filter_class').value) {
                    loadStudents();
                }
            }

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