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

// Check if user is logged in
if ((!isset($_SESSION['student_logged_in']) || $_SESSION['student_logged_in'] !== true) && (!isset($_SESSION['user_id']) || $_SESSION['user_role'] != 'student')) {
    // Redirect to login with a message
    $_SESSION['error_message'] = 'আপনাকে প্রথমে লগইন করতে হবে। শিক্ষার্থী হিসেবে লগইন করুন।';
    header('Location: student_login.php');
    exit();
}

// Check if user logged in with student credentials (after approval)
if (isset($_SESSION['student_id']) && isset($_SESSION['user_id'])) {
    // User logged in with student credentials
    $student_id = $_SESSION['student_id'];
    
    // Get student details
    $stmt = $pdo->prepare("SELECT s.*, aa.application_no, aa.status as application_status FROM students s LEFT JOIN admission_applications aa ON s.application_no = aa.application_no WHERE s.id = ?");
    $stmt->execute([$student_id]);
    $student = $stmt->fetch();
    
    if (!$student) {
        // If student not found, check if they're trying to access with application credentials
        if (isset($_SESSION['student_application_no'])) {
            // User has application credentials, redirect back to login to refresh session
            $_SESSION['error_message'] = 'তথ্য পুনরায় লোড করা হচ্ছে। দয়া করে আবার লগইন করুন।';
            header('Location: student_login.php');
            exit();
        } else {
            // No valid credentials, redirect to login
            $_SESSION['error_message'] = 'আপনাকে প্রথমে লগইন করতে হবে। শিক্ষার্থী হিসেবে লগইন করুন।';
            header('Location: student_login.php');
            exit();
        }
    }
    
    // Use student information to populate application-like data
    $application = [
        'application_no' => $student['application_no'],
        'id' => null,
        'first_name' => $student['first_name'],
        'last_name' => $student['last_name'],
        'father_name' => $student['father_name'],
        'mother_name' => $student['mother_name'],
        'date_of_birth' => $student['date_of_birth'],
        'gender' => $student['gender'],
        'religion' => $student['religion'] ?? 'other',
        'phone' => $student['phone'],
        'email' => $student['email'],
        'present_address' => $student['address'],
        'permanent_address' => $student['address'],
        'applying_for_class_id' => $student['class_id'],
        'status' => $student['application_status'] ?? $student['status'], // Use application status if available, otherwise student status
        'created_at' => $student['created_at'],
        'photo_path' => $student['photo']
    ];
    
    // Get application ID
    if ($student['application_no']) {
        $stmt = $pdo->prepare("SELECT id, status FROM admission_applications WHERE application_no = ?");
        $stmt->execute([$student['application_no']]);
        $app_result = $stmt->fetch();
        if ($app_result) {
            $application_id = $app_result['id'];
            // Update the application status to match the application record
            $application['status'] = $app_result['status'];
        } else {
            $application_id = null;
        }
    } else {
        $application_id = null;
    }
    
    // Update application array with proper ID
    $application['id'] = $application_id;
} elseif (isset($_SESSION['user_id']) && $_SESSION['user_role'] == 'student' && isset($_SESSION['student_customer_number'])) {
    // User logged in with customer number
    $customer_number = $_SESSION['student_customer_number'];
    
    // Get student details by customer number
    $stmt = $pdo->prepare("SELECT s.*, aa.application_no, aa.status as application_status FROM students s LEFT JOIN admission_applications aa ON s.application_no = aa.application_no WHERE s.customer_number = ?");
    $stmt->execute([$customer_number]);
    $student = $stmt->fetch();
    
    if (!$student) {
        // If student not found by customer number
        $_SESSION['error_message'] = 'গ্রাহক নম্বর দিয়ে শিক্ষার্থী তথ্য খুঁজে পাওয়া যাচ্ছে না।';
        header('Location: student_login.php');
        exit();
    }
    
    // Use student information to populate application-like data
    $application = [
        'application_no' => $student['application_no'],
        'id' => null,
        'first_name' => $student['first_name'],
        'last_name' => $student['last_name'],
        'father_name' => $student['father_name'],
        'mother_name' => $student['mother_name'],
        'date_of_birth' => $student['date_of_birth'],
        'gender' => $student['gender'],
        'religion' => $student['religion'] ?? 'other',
        'phone' => $student['phone'],
        'email' => $student['email'],
        'present_address' => $student['address'],
        'permanent_address' => $student['address'],
        'applying_for_class_id' => $student['class_id'],
        'status' => $student['application_status'] ?? $student['status'], // Use application status if available, otherwise student status
        'created_at' => $student['created_at'],
        'photo_path' => $student['photo']
    ];
    
    // Get application ID
    if ($student['application_no']) {
        $stmt = $pdo->prepare("SELECT id, status FROM admission_applications WHERE application_no = ?");
        $stmt->execute([$student['application_no']]);
        $app_result = $stmt->fetch();
        if ($app_result) {
            $application_id = $app_result['id'];
            // Update the application status to match the application record
            $application['status'] = $app_result['status'];
        } else {
            $application_id = null;
        }
    } else {
        $application_id = null;
    }
    
    // Update application array with proper ID
    $application['id'] = $application_id;
} else {
    // User logged in with application credentials
    $application_no = $_SESSION['student_application_no'];
    $application_id = $_SESSION['student_application_id'];
    
    // Get application details
    $stmt = $pdo->prepare("SELECT * FROM admission_applications WHERE application_no = ?");
    $stmt->execute([$application_no]);
    $application = $stmt->fetch();
    
    if (!$application) {
        $_SESSION['error_message'] = 'আপনার আবেদন খুঁজে পাওয়া যাচ্ছে না। দয়া করে আবার লগইন করুন।';
        header('Location: student_login.php');
        exit();
    }
}

// Get outstanding fees for this application
$outstanding_fees = [];

// First, try to find if this application has been converted to a student record
$stmt = $pdo->prepare("SELECT id, class_id FROM students WHERE phone = ? AND first_name = ? AND last_name = ? LIMIT 1");
$stmt->execute([$application['phone'], $application['first_name'], $application['last_name']]);
$student = $stmt->fetch();

if ($student) {
    $student_id = $student['id'];
    $student_class_id = $student['class_id'];
    
    // Fetch all fees for this student's class that are not fully paid
    $stmt = $pdo->prepare("SELECT * FROM fees WHERE student_id = ? AND status != 'paid' ORDER BY due_date ASC");
    $stmt->execute([$student_id]);
    $outstanding_fees = $stmt->fetchAll();
    
    // If no unpaid fees found for the student directly, get all class fees
    if (empty($outstanding_fees)) {
        $stmt = $pdo->prepare(
            "SELECT f.* 
            FROM fees f 
            JOIN students s ON f.student_id = s.id 
            WHERE s.class_id = ? 
            AND f.status != 'paid' 
            ORDER BY f.due_date ASC 
            LIMIT 50"
        );
        $stmt->execute([$student_class_id]);
        $outstanding_fees = $stmt->fetchAll();
    }
} else {
    // If student not found in students table, try to match by application number or other identifiers
    // For admission applications, fees might be associated directly with the application
    // or we can try to match based on the application number if it's stored in fees table
    // This is a fallback for when the student is not yet converted to a full student record
    
    // For now, we'll check if there are any fees associated with this phone number
    // by checking the students table for records with this phone
    $stmt = $pdo->prepare("SELECT id, class_id FROM students WHERE phone = ? LIMIT 1");
    $stmt->execute([$application['phone']]);
    $possible_students = $stmt->fetchAll();
    
    foreach ($possible_students as $possible_student) {
        $stmt = $pdo->prepare("SELECT * FROM fees WHERE student_id = ? AND status != 'paid' ORDER BY due_date ASC");
        $stmt->execute([$possible_student['id']]);
        $fees = $stmt->fetchAll();
        
        if (!empty($fees)) {
            $outstanding_fees = $fees;
            break;
        }
    }
    
    // If still no fees found, get class-specific fees for pending student
    if (empty($outstanding_fees) && !empty($application['applying_for_class_id'])) {
        // Check if a student record exists with this phone number
        $student_lookup = $pdo->prepare("SELECT id, class_id FROM students WHERE phone = ? LIMIT 1");
        $student_lookup->execute([$application['phone']]);
        $student_result = $student_lookup->fetch();
        
        if ($student_result) {
            // If student exists in students table, fetch their fees
            $stmt = $pdo->prepare("SELECT * FROM fees WHERE student_id = ? AND status != 'paid' ORDER BY due_date ASC");
            $stmt->execute([$student_result['id']]);
            $outstanding_fees = $stmt->fetchAll();
            
            // If no unpaid fees found for the student directly, get all class fees
            if (empty($outstanding_fees)) {
                $stmt = $pdo->prepare(
                    "SELECT f.* 
                    FROM fees f 
                    JOIN students s ON f.student_id = s.id 
                    WHERE s.class_id = ? 
                    AND f.status != 'paid' 
                    ORDER BY f.due_date ASC 
                    LIMIT 50"
                );
                $stmt->execute([$student_result['class_id']]);
                $outstanding_fees = $stmt->fetchAll();
            }
        } else {
            // For pending admission applications, check if fees have been assigned to students in this class
            // Look for fees assigned to the class but not yet linked to a specific student record
            try {
                // First, check if there's an existing student record for this application based on application_no
                $stmt = $pdo->prepare("SELECT id, class_id FROM students WHERE application_no = ?");
                $stmt->execute([$application['application_no']]);
                $app_student = $stmt->fetch();
                
                if ($app_student) {
                    // If student record exists based on application, get their fees
                    $stmt = $pdo->prepare("SELECT * FROM fees WHERE student_id = ? AND status != 'paid' ORDER BY due_date ASC");
                    $stmt->execute([$app_student['id']]);
                    $outstanding_fees = $stmt->fetchAll();
                    
                    // If no unpaid fees found for the student directly, get all class fees
                    if (empty($outstanding_fees)) {
                        $stmt = $pdo->prepare(
                            "SELECT f.* 
                            FROM fees f 
                            JOIN students s ON f.student_id = s.id 
                            WHERE s.class_id = ? 
                            AND f.status != 'paid' 
                            ORDER BY f.due_date ASC 
                            LIMIT 50"
                        );
                        $stmt->execute([$app_student['class_id']]);
                        $outstanding_fees = $stmt->fetchAll();
                    }
                } else {
                    // Check if student record exists by matching name and phone
                    $stmt = $pdo->prepare("SELECT id, class_id FROM students WHERE phone = ? AND first_name = ? AND last_name = ?");
                    $stmt->execute([$application['phone'], $application['first_name'], $application['last_name']]);
                    $matched_student = $stmt->fetch();
                    
                    if ($matched_student) {
                        // Get fees for the matched student
                        $stmt = $pdo->prepare("SELECT * FROM fees WHERE student_id = ? AND status != 'paid' ORDER BY due_date ASC");
                        $stmt->execute([$matched_student['id']]);
                        $outstanding_fees = $stmt->fetchAll();
                        
                        // If no unpaid fees found for the student directly, get all class fees
                        if (empty($outstanding_fees)) {
                            $stmt = $pdo->prepare(
                                "SELECT f.* 
                                FROM fees f 
                                JOIN students s ON f.student_id = s.id 
                                WHERE s.class_id = ? 
                                AND f.status != 'paid' 
                                ORDER BY f.due_date ASC 
                                LIMIT 50"
                            );
                            $stmt->execute([$matched_student['class_id']]);
                            $outstanding_fees = $stmt->fetchAll();
                        }
                    } else {
                        // For pending students, get all fees that are assigned to their specific class
                        // Get all fees for the class that are not yet paid
                        $stmt = $pdo->prepare(
                            "SELECT f.fee_type, f.amount, f.due_date, f.academic_year, f.month, f.remarks, f.status, f.paid_amount 
                            FROM fees f 
                            JOIN students s ON f.student_id = s.id 
                            WHERE s.class_id = ? 
                            ORDER BY f.due_date ASC 
                            LIMIT 50"
                        );
                        $stmt->execute([$application['applying_for_class_id']]);
                        $all_class_fees = $stmt->fetchAll();
                        
                        if (!empty($all_class_fees)) {
                            // Create placeholder fees for the pending student based on what's assigned to the class
                            foreach ($all_class_fees as $class_fee) {
                                // Calculate the actual status based on amount and paid_amount
                                $calculated_status = 'pending';
                                if ($class_fee['paid_amount'] > 0 && $class_fee['paid_amount'] < $class_fee['amount']) {
                                    $calculated_status = 'partial';
                                } elseif ($class_fee['paid_amount'] >= $class_fee['amount']) {
                                    $calculated_status = 'paid';
                                }
                                
                                // Only add to outstanding fees if not fully paid
                                if ($calculated_status != 'paid') {
                                    $outstanding_fees[] = [
                                        'id' => 0, // Placeholder since not yet assigned to this student
                                        'fee_type' => $class_fee['fee_type'],
                                        'amount' => $class_fee['amount'],
                                        'due_date' => $class_fee['due_date'],
                                        'paid_amount' => $class_fee['paid_amount'] ?? 0,
                                        'status' => $calculated_status,
                                        'academic_year' => $class_fee['academic_year'] ?? '',
                                        'month' => $class_fee['month'] ?? '',
                                        'remarks' => $class_fee['remarks'] ?? ''
                                    ];
                                }
                            }
                        } else {
                            // If no specific fees found for this class, create default fees
                            // For pending students, ensure session charge is shown as required
                            $default_fees = [];
                            
                            // Check if there are any fees assigned to students in this class
                            // This will show all types of fees that are assigned to students in the same class
                            $class_fees_stmt = $pdo->prepare(
                                "SELECT DISTINCT f.fee_type, f.amount, f.due_date, f.academic_year, f.month, f.remarks 
                                FROM fees f 
                                JOIN students s ON f.student_id = s.id 
                                WHERE s.class_id = ?
                                ORDER BY f.due_date ASC 
                                LIMIT 20"
                            );
                            $class_fees_stmt->execute([$application['applying_for_class_id']]);
                            $class_fees = $class_fees_stmt->fetchAll();
                            
                            if (!empty($class_fees)) {
                                // Use class-specific fees if available
                                foreach ($class_fees as $class_fee) {
                                    $default_fees[] = [
                                        'id' => 0, // Placeholder since not yet assigned to this student
                                        'fee_type' => $class_fee['fee_type'],
                                        'amount' => $class_fee['amount'],
                                        'due_date' => $class_fee['due_date'] ?? date('Y-m-d', strtotime('+30 days')),
                                        'paid_amount' => 0,
                                        'status' => 'pending',
                                        'academic_year' => $class_fee['academic_year'] ?? '',
                                        'month' => $class_fee['month'] ?? '',
                                        'remarks' => $class_fee['remarks'] ?? ''
                                    ];
                                }
                            } else {
                                // If no class-specific fees found in database, add default session charge
                                $default_fees[] = [
                                    'id' => 0,
                                    'fee_type' => 'সেশন চার্জ',
                                    'amount' => 300, // Default amount
                                    'due_date' => date('Y-m-d', strtotime('+30 days')),
                                    'paid_amount' => 0,
                                    'status' => 'pending',
                                    'academic_year' => date('Y'),
                                    'month' => '',
                                    'remarks' => 'আবেদনকৃত ক্লাসের সেশন চার্জ - এডমিশন সম্পন্ন করতে দরকার'
                                ];
                            }
                            
                            $outstanding_fees = $default_fees;
                        }
                    }
                }
            } catch (Exception $e) {
                // On error, keep outstanding_fees as empty array
                $outstanding_fees = []; // This will show the "no fees" message
            }
        }
    }
}

// Get class name for the application
$application_class_name = '';
if (!empty($application['applying_for_class_id'])) {
    $class_stmt = $pdo->prepare("SELECT name, section FROM classes WHERE id = ?");
    $class_stmt->execute([$application['applying_for_class_id']]);
    $class = $class_stmt->fetch();
    if ($class) {
        $application_class_name = $class['name'] . ($class['section'] ? ' - ' . $class['section'] : '');
    }
}

// Calculate total due amount
$total_payable = 0;
$total_paid = 0;
$total_due = 0;

foreach ($outstanding_fees as $fee) {
    $total_payable += (float)$fee['amount'];
    $total_paid += (float)$fee['paid_amount'];
    $total_due += (float)($fee['amount'] - $fee['paid_amount']);
}

// Handle payment submission
$payment_success = false;
$payment_error = '';

if ($_SERVER['REQUEST_METHOD'] == 'POST' && isset($_POST['pay_fee'])) {
    $fee_id = (int)$_POST['fee_id'];
    $fee_type = trim($_POST['fee_type'] ?? '');
    
    // For pending students, we need to check if the fee is valid based on the fee type
    // since the fees are displayed as placeholders with id=0
    $fee_valid = false;
    $selected_fee = null;
    
    foreach ($outstanding_fees as $fee) {
        if ($fee['id'] == $fee_id || ($fee_id == 0 && $fee['fee_type'] == $fee_type)) {
            $fee_valid = true;
            $selected_fee = $fee;
            break;
        }
    }
    
    if ($fee_valid && $selected_fee) {
        // Check if there's an existing student record for this application
        $student_check_stmt = $pdo->prepare("SELECT id, class_id FROM students WHERE application_no = ?");
        $student_check_stmt->execute([$application['application_no']]);
        $existing_student = $student_check_stmt->fetch();
        
        if ($existing_student) {
            // If student exists, update the existing fee or create a new one if it doesn't exist
            $stmt = $pdo->prepare("SELECT id FROM fees WHERE student_id = ? AND fee_type = ?");
            $stmt->execute([$existing_student['id'], $selected_fee['fee_type']]);
            $existing_fee = $stmt->fetch();
            
            if ($existing_fee) {
                // Update existing fee
                $stmt = $pdo->prepare("UPDATE fees SET status = 'paid', paid_date = NOW(), paid_amount = amount WHERE id = ?");
                $result = $stmt->execute([$existing_fee['id']]);
            } else {
                // Check if fee already exists for this student and fee type
                $check_stmt = $pdo->prepare(
                    "SELECT id FROM fees WHERE student_id = ? AND fee_type = ? AND status != 'cancelled' LIMIT 1"
                );
                $check_stmt->execute([$existing_student['id'], $selected_fee['fee_type']]);
                $existing_fee = $check_stmt->fetch();
                
                if (!$existing_fee) {
                    // Create a new fee record for this student
                    $stmt = $pdo->prepare(
                        "INSERT INTO fees (student_id, fee_type, amount, due_date, academic_year, month, remarks, paid_amount, status, created_at) 
                        VALUES (?, ?, ?, ?, ?, ?, ?, ?, 'paid', NOW())"
                    );
                    $result = $stmt->execute([
                        $existing_student['id'],
                        $selected_fee['fee_type'],
                        $selected_fee['amount'],
                        $selected_fee['due_date'],
                        $selected_fee['academic_year'],
                        $selected_fee['month'],
                        $selected_fee['remarks'],
                        $selected_fee['amount'] // paid_amount = amount since it's paid
                    ]);
                } else {
                    // Update existing fee if needed
                    $stmt = $pdo->prepare(
                        "UPDATE fees SET paid_amount = ?, status = 'paid', paid_date = NOW() WHERE id = ?"
                    );
                    $result = $stmt->execute([
                        $selected_fee['amount'],
                        $existing_fee['id']
                    ]);
                }
            }
        } else {
            // For pending students without a student record, create a student record first
            $stmt = $pdo->prepare(
                "INSERT INTO students (first_name, last_name, father_name, mother_name, date_of_birth, gender, religion, phone, email, present_address, permanent_address, class_id, admission_date, application_no, photo_path, status) 
                VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, NOW(), ?, ?, 'pending')"
            );
            $result = $stmt->execute([
                $application['first_name'],
                $application['last_name'],
                $application['father_name'],
                $application['mother_name'],
                $application['date_of_birth'],
                $application['gender'],
                $application['religion'],
                $application['phone'],
                $application['email'] ?? '',
                $application['present_address'],
                $application['permanent_address'],
                $application['applying_for_class_id'],
                $application['application_no'],
                $application['photo_path'] ?? ''
            ]);
            
            if ($result) {
                $new_student_id = $pdo->lastInsertId();
                
                // Check if fee already exists for this student and fee type
                $check_stmt = $pdo->prepare(
                    "SELECT id FROM fees WHERE student_id = ? AND fee_type = ? AND status != 'cancelled' LIMIT 1"
                );
                $check_stmt->execute([$new_student_id, $selected_fee['fee_type']]);
                $existing_fee = $check_stmt->fetch();
                
                if (!$existing_fee) {
                    // Create the fee record for the new student
                    $stmt = $pdo->prepare(
                        "INSERT INTO fees (student_id, fee_type, amount, due_date, academic_year, month, remarks, paid_amount, status, created_at) 
                        VALUES (?, ?, ?, ?, ?, ?, ?, ?, 'paid', NOW())"
                    );
                    $result = $stmt->execute([
                        $new_student_id,
                        $selected_fee['fee_type'],
                        $selected_fee['amount'],
                        $selected_fee['due_date'],
                        $selected_fee['academic_year'],
                        $selected_fee['month'],
                        $selected_fee['remarks'],
                        $selected_fee['amount'] // paid_amount = amount since it's paid
                    ]);
                } else {
                    // Update existing fee if needed
                    $stmt = $pdo->prepare(
                        "UPDATE fees SET paid_amount = ?, status = 'paid', paid_date = NOW() WHERE id = ?"
                    );
                    $result = $stmt->execute([
                        $selected_fee['amount'],
                        $existing_fee['id']
                    ]);
                }
            }
        }
        
        if ($result) {
            // Check if this fee is a session charge or admission-related fee
            $is_session_charge = (stripos($selected_fee['fee_type'], 'সেশন') !== false || stripos($selected_fee['fee_type'], 'session') !== false || stripos($selected_fee['fee_type'], 'ভর্তি') !== false || stripos($selected_fee['fee_type'], 'admission') !== false);
            
            if ($is_session_charge) {
                // If the paid fee is a session charge or admission fee, approve the application
                $stmt = $pdo->prepare("UPDATE admission_applications SET status = 'approved', approved_at = NOW() WHERE id = ?");
                $stmt->execute([$application_id]);
                
                $payment_success = true;
            } else {
                // For other fees, check if all fees for this student are now paid
                // First get the student ID that was just created or existed
                $student_check_stmt = $pdo->prepare("SELECT id FROM students WHERE application_no = ?");
                $student_check_stmt->execute([$application['application_no']]);
                $student_record = $student_check_stmt->fetch();
                
                if ($student_record) {
                    $stmt = $pdo->prepare("SELECT COUNT(*) FROM fees WHERE student_id = ? AND (status = 'pending' OR status = 'partial')");
                    $stmt->execute([$student_record['id']]);
                    $remaining_fees = $stmt->fetchColumn();
                    
                    if ($remaining_fees == 0) {
                        // Update application status to approved
                        $stmt = $pdo->prepare("UPDATE admission_applications SET status = 'approved', approved_at = NOW() WHERE id = ?");
                        $stmt->execute([$application_id]);
                        
                        $payment_success = true;
                    }
                }
            }
        } else {
            $payment_error = 'পেমেন্ট প্রক্রিয়াকরণে সমস্যা হয়েছে।';
        }
    } else {
        $payment_error = 'অবৈধ ফি নির্বাচন।';
    }
}
?>

<!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;800&display=swap" rel="stylesheet">
    <style>
        body {
            font-family: 'Hind Siliguri', sans-serif;
            background: #f5f7fa;
        }
        
        .dashboard-header {
            background: linear-gradient(135deg, #006747 0%, #004d35 100%);
            color: white;
            padding: 1.5rem 0;
            margin-bottom: 2rem;
        }
        
        .dashboard-card {
            background: white;
            border-radius: 15px;
            box-shadow: 0 10px 30px rgba(0,103,71,0.15);
            border: 1px solid #e0e0e0;
            margin-bottom: 2rem;
        }
        
        .status-badge {
            font-size: 1rem;
            padding: 0.5em 1em;
        }
        
        .fee-card {
            border-left: 4px solid #006747;
            margin-bottom: 1rem;
        }
        
        .fee-card.overdue {
            border-left-color: #dc3545;
        }
        
        .fee-card.partial {
            border-left-color: #ffc107;
        }
        
        .account-number-label {
            font-size: 1.2em;
            font-weight: bold;
        }
        
        .account-number-value {
            font-size: 1.2em;
            font-weight: bold;
        }
    </style>
</head>
<body>
    <!-- Header -->
    <div class="dashboard-header">
        <div class="container">
            <div class="row align-items-center">
                <div class="col-md-8">
                    <h1><i class="fas fa-user-graduate"></i> শিক্ষার্থী ড্যাশবোর্ড</h1>
                    <p class="mb-0">স্বাগতম, <?php echo isset($_SESSION['student_name']) ? htmlspecialchars($_SESSION['student_name']) : (isset($_SESSION['user_name']) ? htmlspecialchars($_SESSION['user_name']) : 'শিক্ষার্থী'); ?></p>
                </div>
                <div class="col-md-6 text-md-end">
                    <a href="index.php" class="btn btn-outline-primary me-2">
                        <i class="fas fa-home"></i> হোম
                    </a>
                    <a href="student_portal.php" class="btn btn-outline-success me-2">
                        <i class="fas fa-graduation-cap"></i> স্টুডেন্ট পোর্টাল
                    </a>
                    <a href="logout.php" class="btn btn-light">
                        <i class="fas fa-sign-out-alt"></i> লগআউট
                    </a>
                </div>
            </div>
        </div>
    </div>

    <div class="container">
        <?php 
        // Show unique credentials on first login
        if (isset($_SESSION['first_time_login']) && $_SESSION['first_time_login'] === true && isset($_SESSION['temp_password'])):
        ?>
            <div class="alert alert-success alert-dismissible fade show" role="alert">
                <h4><i class="fas fa-user-lock"></i> আপনার নিরাপত্তা তথ্য:</h4>
                <p><strong>ইউজারনেম:</strong> <?php 
                if (isset($_SESSION['user_id'])) {
                    $stmt = $pdo->prepare("SELECT username FROM users WHERE id = ?");
                    $stmt->execute([$_SESSION['user_id']]);
                    $user = $stmt->fetch();
                    echo $user ? htmlspecialchars($user['username']) : 'N/A';
                } else {
                    echo 'N/A';
                }
                ?></p>
                <p><strong>পাসওয়ার্ড:</strong> <?php echo htmlspecialchars($_SESSION['temp_password']); ?></p>
                <p class="mb-0 text-warning"><i class="fas fa-exclamation-triangle"></i> এই পাসওয়ার্ডটি শুধুমাত্র প্রথমবারের জন্য। দয়া করে পাসওয়ার্ড পরিবর্তন করুন।</p>
                <button type="button" class="btn-close" data-bs-dismiss="alert" aria-label="Close"></button>
            </div>
            <?php 
            // Mark first time login as done
            unset($_SESSION['first_time_login']);
            unset($_SESSION['temp_password']);
            ?>
        <?php endif; ?>
        
        <?php if ($payment_success): ?>
            <div class="alert alert-success">
                <i class="fas fa-check-circle"></i> পেমেন্ট সফল! আপনার আবেদন এখন অনুমোদিত।
            </div>
        <?php endif; ?>
        
        <?php if ($payment_error): ?>
            <div class="alert alert-danger">
                <i class="fas fa-exclamation-triangle"></i> <?php echo $payment_error; ?>
            </div>
        <?php endif; ?>

        <!-- Application Information -->
        <div class="dashboard-card">
            <div class="card-body p-4">
                <div class="row mb-4">
                    <div class="col-md-8">
                        <h3><i class="fas fa-file-alt"></i> আবেদন তথ্য</h3>
                        <p>আবেদন নং: <strong><?php echo htmlspecialchars($application['application_no']); ?></strong></p>
                        <p>আবেদনের তারিখ: <?php echo date('d/m/Y H:i', strtotime($application['created_at'])); ?></p>
                    </div>
                    <div class="col-md-4 text-md-end">
                        <span class="badge bg-<?php 
                            if ($application['status'] == 'pending') echo 'warning'; 
                            elseif ($application['status'] == 'approved') echo 'success'; 
                            elseif ($application['status'] == 'rejected') echo 'danger'; 
                            else echo 'secondary'; 
                        ?> status-badge">
                            <?php 
                                if ($application['status'] == 'pending') echo 'মুলতুবি'; 
                                elseif ($application['status'] == 'approved') echo 'অনুমোদিত'; 
                                elseif ($application['status'] == 'rejected') echo 'প্রত্যাখ্যাত'; 
                                else echo 'বাতিল'; 
                            ?>
                        </span>
                    </div>
                </div>
                
                <div class="row">
                    <div class="col-md-6">
                        <div class="mb-2">
                            <strong>নাম:</strong> <?php echo htmlspecialchars($application['first_name'] . ' ' . $application['last_name']); ?>
                        </div>
                        <div class="mb-2">
                            <strong>পিতার নাম:</strong> <?php echo htmlspecialchars($application['father_name']); ?>
                        </div>
                        <div class="mb-2">
                            <strong>মাতার নাম:</strong> <?php echo htmlspecialchars($application['mother_name']); ?>
                        </div>
                        <div class="mb-2">
                            <strong>ফোন:</strong> <?php echo htmlspecialchars($application['phone']); ?>
                        </div>
                    </div>
                    <div class="col-md-6">
                        <div class="mb-2">
                            <strong>আবেদনকৃত ক্লাস:</strong> 
                            <?php 
                                // Get class name based on applying_for_class_id
                                if (!empty($application['applying_for_class_id'])) {
                                    $class_stmt = $pdo->prepare("SELECT name, section FROM classes WHERE id = ?");
                                    $class_stmt->execute([$application['applying_for_class_id']]);
                                    $class = $class_stmt->fetch();
                                    
                                    if ($class) {
                                        echo htmlspecialchars($class['name'] . ($class['section'] ? ' - ' . $class['section'] : ''));
                                    } else {
                                        echo 'N/A';
                                    }
                                } else {
                                    echo 'N/A';
                                }
                            ?>
                        </div>
                        <div class="mb-2">
                            <strong>ধর্ম:</strong> 
                            <?php 
                                switch($application['religion']) {
                                    case 'islam': echo 'ইসলাম'; break;
                                    case 'hinduism': echo 'হিন্দু'; break;
                                    case 'buddhism': echo 'বৌদ্ধ'; break;
                                    case 'christianity': echo 'খ্রিস্টান'; break;
                                    case 'other': echo 'অন্যান্য'; break;
                                    default: echo 'N/A';
                                }
                            ?>
                        </div>
                        <div class="mb-2">
                            <strong>ইমেইল:</strong> <?php echo htmlspecialchars($application['email'] ?? 'N/A'); ?>
                        </div>
                    </div>
                </div>
            </div>
        </div>

        <!-- Outstanding Fees Section -->
        <div class="dashboard-card">
            <div class="card-body p-4">
                <h3><i class="fas fa-money-bill-wave"></i> বকেয়া ফি তথ্য</h3>
                
                <?php if (!empty($outstanding_fees) && is_array($outstanding_fees)): ?>
                    <div class="table-responsive">
                        <table class="table table-bordered">
                            <thead class="table-success">
                                <tr>
                                    <th>ক্রমিক</th>
                                    <th>ফি ধরন</th>
                                    <th>মোট পরিমান</th>
                                    <th>জমা দেওয়া হয়েছে</th>
                                    <th>বকেয়া রয়েছে</th>
                                    <th>অবস্থা</th>
                                    <th>পরিশোধের তারিখ</th>
                                    <th>কার্যক্রম</th>
                                </tr>
                            </thead>
                            <tbody>
                                <?php $counter = 1; ?>
                                <?php foreach ($outstanding_fees as $fee): ?>
                                <?php 
                                    $due_amount = $fee['amount'] - $fee['paid_amount'];
                                ?>
                                <tr class="
                                    <?php 
                                        if (strtotime($fee['due_date']) < time() && $fee['status'] !== 'paid') echo 'table-danger'; 
                                        elseif ($fee['status'] == 'partial') echo 'table-warning';
                                    ?>
                                ">
                                    <td><?php echo $counter++; ?></td>
                                    <td><?php echo htmlspecialchars($fee['fee_type']); ?></td>
                                    <td><?php echo number_format($fee['amount'], 2); ?> টাকা</td>
                                    <td><?php echo number_format($fee['paid_amount'], 2); ?> টাকা</td>
                                    <td class="text-danger fw-bold"><?php echo number_format($due_amount, 2); ?> টাকা</td>
                                    <td>
                                        <span class="badge bg-
                                            <?php 
                                                if ($fee['status'] == 'paid') echo 'success'; 
                                                elseif ($fee['status'] == 'partial') echo 'warning'; 
                                                else echo 'danger'; 
                                            ?>
                                        ">
                                            <?php 
                                                if ($fee['status'] == 'paid') echo 'পরিশোধিত'; 
                                                elseif ($fee['status'] == 'partial') echo 'আংশিক পরিশোধ'; 
                                                else echo 'বকেয়া'; 
                                            ?>
                                        </span>
                                    </td>
                                    <td><?php echo date('d/m/Y', strtotime($fee['due_date'])); ?></td>
                                    <td>
                                        <form method="POST" action="" style="display: inline;">
                                            <input type="hidden" name="fee_id" value="<?php echo $fee['id']; ?>">
                                            <input type="hidden" name="fee_type" value="<?php echo htmlspecialchars($fee['fee_type']); ?>">
                                            <input type="hidden" name="pay_fee" value="1">
                                            <button type="submit" class="btn btn-sm btn-secondary" disabled>
                                                <i class="fas fa-credit-card"></i> পরিশোধ করুন (অক্ষম)
                                            </button>
                                        </form>
                                    </td>
                                </tr>
                                <?php endforeach; ?>
                            </tbody>
                        </table>
                    </div>
                    
                    <?php if ($total_due > 0): ?>
                    <div class="card border-0 shadow-sm mt-3">
                        <div class="card-header bg-success text-white py-2">
                            <h5 class="mb-0 fs-6"><i class="fas fa-money-bill-wave"></i> অনলাইন পেমেন্ট</h5>
                        </div>
                        <div class="card-body py-2">
                            <p class="mb-3">অনলাইনে পেমেন্ট করতে নিচের বাটনগুলোর যেকোন একটিতে ক্লিক করুন</p>
                            
                            <div class="d-grid gap-2 d-md-block mb-2">
                                <a href="fees/student_payment.php?amount=<?= $total_due ?>" class="btn payment-btn btn-success me-md-2 py-1 px-2">
                                    <i class="fas fa-credit-card"></i> ক্রেডিট/ডেবিট কার্ড
                                    <div class="small">৳<?= number_format($total_due, 2) ?></div>
                                </a>
                                <a href="fees/bKash_payment.php?amount=<?= $total_due ?>" class="btn payment-btn btn-info py-1 px-2">
                                    <i class="fas fa-mobile-alt"></i> bKash Personal
                                    <div class="small">৳<?= number_format($total_due, 2) ?></div>
                                </a>
                            </div>
                            
                            <div class="row g-1">
                                <div class="col-md-6 mb-1">
                                    <a href="fees/submit_bkash_transaction.php" class="btn btn-outline-primary w-100 payment-btn py-1 px-2">
                                        <i class="fas fa-paper-plane"></i> bKash ট্রানজেকশন আইডি জমা দিন
                                    </a>
                                </div>
                                <div class="col-md-6 mb-1">
                                    <a href="fees/submit_bank_transaction.php" class="btn btn-outline-warning w-100 payment-btn py-1 px-2">
                                        <i class="fas fa-file-invoice-dollar"></i> ব্যাংক ট্রানজেকশন আইডি জমা দিন
                                    </a>
                                </div>
                                <div class="col-md-6 mb-1">
                                    <button class="btn btn-warning w-100 payment-btn py-1 px-2" data-bs-toggle="modal" data-bs-target="#bankReceiptModal">
                                        <i class="fas fa-file-invoice"></i> ব্যাংক রসিদ প্রিন্ট করুন
                                    </button>
                                </div>
                                <div class="col-md-6 mb-1">
                                    <a href="fees/select_fees.php" class="btn btn-secondary w-100 payment-btn py-1 px-2">
                                        <i class="fas fa-list-check"></i> ফি নির্বাচন করুন
                                    </a>
                                </div>
                                <div class="col-md-6 mb-1">
                                    <a href="fees/my_fees.php" class="btn btn-primary w-100 payment-btn py-1 px-2">
                                        <i class="fas fa-file-invoice"></i> আমার ফি তালিকা
                                    </a>
                                </div>
                            </div>
                            
                            <div class="mt-3 text-center">
                                <small class="text-muted"><i class="fas fa-info-circle"></i> পেমেন্ট সম্পূর্ণ হলে অ্যাডমিন ভেরিফিকেশন করবেন</small>
                            </div>
                        </div>
                    </div>
                    
                    <div class="alert alert-info mt-3">
                        <h5><i class="fas fa-info-circle"></i> ব্যাংকে জমা দেয়ার নির্দেশনা:</h5>
                        <ol>
                            <li>উপরের বকেয়া ফি টাকা ব্যাংকে জমা দিন</li>
                            <li>ব্যাংক রসিদে আপনার নাম, শ্রেণি ও ফোন নম্বর উল্লেখ করুন</li>
                            <li>ব্যাংক জমার পর রসিক সংরক্ষণ করুন</li>
                            <li>ট্রানজেকশন আইডি জমা দিন বাটনে ক্লিক করুন</li>
                        </ol>
                    </div>
                    <?php endif; ?>
                <?php else: ?>
                    <div class="alert alert-success">
                        <i class="fas fa-check-circle"></i> আপনার কোনো বকেয়া ফি নেই। সমস্ত ফি পরিশোধিত!
                    </div>
                    
                    <?php if ($application['status'] == 'pending'): ?>
                        <div class="alert alert-warning">
                            <i class="fas fa-exclamation-triangle"></i> আপনার আবেদন এখনো মুলতুবি রয়েছে। সেশন চার্জ পরিশোধের পর এটি অনুমোদিত হবে।
                        </div>
                    <?php elseif ($application['status'] == 'approved'): ?>
                        <div class="alert alert-success">
                            <i class="fas fa-check-circle"></i> আপনার আবেদন অনুমোদিত হয়েছে! ধন্যবাদ।
                        </div>
                    <?php endif; ?>
                <?php endif; ?>
            </div>
        </div>
    </div>

    <!-- Bank Receipt Modal -->
    <div class="modal fade" id="bankReceiptModal" tabindex="-1" aria-labelledby="bankReceiptModalLabel" aria-hidden="true">
      <div class="modal-dialog modal-lg">
        <div class="modal-content">
          <div class="modal-header">
            <h5 class="modal-title" id="bankReceiptModalLabel">ব্যাংক রসিদ প্রিন্ট</h5>
            <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
          </div>
          <div class="modal-body">
            <form id="bankReceiptForm">
              <div class="mb-3">
                <label for="bankAccount" class="form-label">ব্যাংক নির্বাচন করুন</label>
                <select class="form-select" id="bankAccount" required>
                  <option value="">ব্যাংক নির্বাচন করুন</option>
                  <?php 
                  $bank_accounts = [];
                  try {
                      $stmt = $pdo->query("SELECT id, bank_name, branch_name, account_number, account_name FROM bank_accounts ORDER BY bank_name, branch_name");
                      $bank_accounts = $stmt->fetchAll();
                  } catch (Exception $e) {
                      $bank_accounts = [];
                  }
                  foreach ($bank_accounts as $account): 
                  ?>
                    <option value="<?= $account['id'] ?>" 
                            data-bank="<?= htmlspecialchars($account['bank_name']) ?>"
                            data-branch="<?= htmlspecialchars($account['branch_name']) ?>"
                            data-account="<?= htmlspecialchars($account['account_number']) ?>"
                            data-name="<?= htmlspecialchars($account['account_name']) ?>">
                      <?= htmlspecialchars($account['bank_name']) ?> - <?= htmlspecialchars($account['branch_name']) ?> (<?= htmlspecialchars($account['account_number']) ?>)
                    </option>
                  <?php endforeach; ?>
                </select>
              </div>
              
              <div class="mb-3">
                <label class="form-label">ফি নির্বাচন করুন</label>
                <div id="feeSelection">
                  <?php foreach ($outstanding_fees as $f): $due = (float)($f['amount'] - $f['paid_amount']); ?>
                    <?php if ($due > 0): ?>
                      <div class="form-check mb-2">
                        <input class="form-check-input fee-checkbox" type="checkbox" 
                               id="fee_<?= $f['id'] ?>" 
                               value="<?= $f['id'] ?>" 
                               data-description="<?= htmlspecialchars($f['fee_type'] . ($f['month'] ? ' - ' . $f['month'] : '')) ?>"
                               data-amount="<?= $due ?>">
                        <label class="form-check-label" for="fee_<?= $f['id'] ?>">
                          <?= htmlspecialchars($f['fee_type']) ?><?= $f['month'] ? ' - ' . htmlspecialchars($f['month']) : '' ?> 
                          (৳<?= number_format($due, 2) ?>)
                        </label>
                      </div>
                    <?php endif; ?>
                  <?php endforeach; ?>
                </div>
                <div class="mt-2">
                  <button type="button" class="btn btn-sm btn-outline-primary" id="selectAllFees">সব নির্বাচন করুন</button>
                  <button type="button" class="btn btn-sm btn-outline-secondary" id="clearAllFees">সব মুছুন</button>
                </div>
              </div>
              
              <div class="mb-3">
                <label for="totalAmount" class="form-label">মোট পরিমাণ (৳)</label>
                <input type="number" class="form-control" id="totalAmount" value="0.00" step="0.01" min="0" readonly>
              </div>
              
              <div class="mb-3" id="bankDetails" style="display: none;">
                <h6>ব্যাংক তথ্য:</h6>
                <div class="card">
                  <div class="card-body">
                    <p><strong>ব্যাংকের নাম:</strong> <span id="selectedBankName"></span></p>
                    <p><strong>ব্রাঞ্চ:</strong> <span id="selectedBranch"></span></p>
                    <p><strong class="account-number-label">একাউন্ট নম্বর:</strong> <span id="selectedAccountNo" class="account-number-value"></span></p>
                    <p><strong>একাউন্ট নাম:</strong> <span id="selectedAccountName"></span></p>
                  </div>
                </div>
              </div>
            </form>
          </div>
          <div class="modal-footer">
            <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">বাতিল</button>
            <button type="button" class="btn btn-primary" id="previewReceiptBtn">প্রিভিউ</button>
          </div>
        </div>
      </div>
    </div>

    <script>
        // Auto-refresh functionality removed to prevent unwanted page refresh
        
        // Handle bank account selection
        document.getElementById('bankAccount')?.addEventListener('change', function() {
          const selectedOption = this.options[this.selectedIndex];
          if (selectedOption.value) {
            document.getElementById('selectedBankName').textContent = selectedOption.getAttribute('data-bank');
            document.getElementById('selectedBranch').textContent = selectedOption.getAttribute('data-branch');
            document.getElementById('selectedAccountNo').textContent = selectedOption.getAttribute('data-account');
            document.getElementById('selectedAccountName').textContent = selectedOption.getAttribute('data-name');
            document.getElementById('bankDetails').style.display = 'block';
          } else {
            document.getElementById('bankDetails').style.display = 'none';
          }
        });

        // Handle fee selection
        document.querySelectorAll('.fee-checkbox').forEach(checkbox => {
          checkbox.addEventListener('change', updateTotalAmount);
        });
        
        // Select all fees
        document.getElementById('selectAllFees')?.addEventListener('click', function() {
          document.querySelectorAll('.fee-checkbox').forEach(checkbox => {
            checkbox.checked = true;
          });
          updateTotalAmount();
        });
        
        // Clear all fees
        document.getElementById('clearAllFees')?.addEventListener('click', function() {
          document.querySelectorAll('.fee-checkbox').forEach(checkbox => {
            checkbox.checked = false;
          });
          updateTotalAmount();
        });
        
        // Update total amount based on selected fees
        function updateTotalAmount() {
          let total = 0;
          document.querySelectorAll('.fee-checkbox:checked').forEach(checkbox => {
            total += parseFloat(checkbox.getAttribute('data-amount')) || 0;
          });
          document.getElementById('totalAmount').value = total.toFixed(2);
        }
        
        // Preview receipt
        document.getElementById('previewReceiptBtn')?.addEventListener('click', function() {
          const bankAccountSelect = document.getElementById('bankAccount');
          
          if (!bankAccountSelect.value) {
            alert('দয়া করে ব্যাংক নির্বাচন করুন');
            return;
          }
          
          // Get selected fees
          const selectedFees = [];
          const selectedFeeIds = [];
          document.querySelectorAll('.fee-checkbox:checked').forEach(checkbox => {
            selectedFees.push({
              description: checkbox.getAttribute('data-description'),
              amount: parseFloat(checkbox.getAttribute('data-amount'))
            });
            selectedFeeIds.push(checkbox.value);
          });
          
          if (selectedFees.length === 0) {
            alert('দয়া করে অন্তত একটি ফি নির্বাচন করুন');
            return;
          }
          
          // Store selected fee IDs in a hidden field for form submission
          let hiddenInput = document.getElementById('selectedFeeIds');
          if (!hiddenInput) {
            hiddenInput = document.createElement('input');
            hiddenInput.type = 'hidden';
            hiddenInput.id = 'selectedFeeIds';
            hiddenInput.name = 'selected_fee_ids';
            document.getElementById('bankReceiptForm').appendChild(hiddenInput);
          }
          hiddenInput.value = JSON.stringify(selectedFeeIds);
          
          const totalAmount = selectedFees.reduce((sum, fee) => sum + fee.amount, 0);
          
          const selectedOption = bankAccountSelect.options[bankAccountSelect.selectedIndex];
          const bankInfo = {
            bankName: selectedOption.getAttribute('data-bank'),
            branch: selectedOption.getAttribute('data-branch'),
            accountNo: selectedOption.getAttribute('data-account'),
            accountName: selectedOption.getAttribute('data-name')
          };
          
          const studentInfo = {
            name: '<?= htmlspecialchars($application['first_name'] . ' ' . $application['last_name']) ?>',
            studentId: '<?= htmlspecialchars($application['application_no']) ?>',
            className: '<?= htmlspecialchars($application_class_name) ?>'
          };
          
          // Generate receipt HTML (simplified)
          const receiptHtml = `
            <div class="text-center">
              <h4>ব্যাংক রসিদ প্রিন্ট প্রিভিউ</h4>
              <p><strong>নাম:</strong> ${studentInfo.name}</p>
              <p><strong>আইডি:</strong> ${studentInfo.studentId}</p>
              <p><strong>ক্লাস:</strong> ${studentInfo.className}</p>
              <p><strong>মোট পরিমাণ:</strong> ৳${totalAmount.toFixed(2)}</p>
              <p><strong>ব্যাংক:</strong> ${bankInfo.bankName}</p>
              <p><strong>ব্রাঞ্চ:</strong> ${bankInfo.branch}</p>
              <p><strong style=\"font-size: 1.2em; font-weight: bold;\">একাউন্ট নম্বর:</strong> <span style=\"font-size: 1.2em; font-weight: bold;\">" + bankInfo.accountNo + "</span></p>
            </div>
          `;
          
          // Open in new window for printing
          const printWindow = window.open('', '_blank');
          printWindow.document.write(`
            <html>
              <head>
                <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;800&display=swap" rel="stylesheet">
                <style>
                  body { font-family: 'Hind Siliguri', sans-serif; }
                </style>
              </head>
              <body>
                <div class="container">
                  ${receiptHtml}
                  <div class="text-center mt-4">
                    <button class="btn btn-success" onclick="window.print()">প্রিন্ট করুন</button>
                  </div>
                </div>
              </body>
            </html>
          `);
          printWindow.document.close();
        });
    </script>
</body>
</html>