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

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

// Get system name for branding
$system_name = get_system_name($pdo);

$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();

// Ensure fee_types table exists and fetch active fee types
try {
    $pdo->exec("
        CREATE TABLE IF NOT EXISTS fee_types (
            id INT AUTO_INCREMENT PRIMARY KEY,
            name VARCHAR(100) NOT NULL UNIQUE,
            default_amount DECIMAL(10,2) NULL,
            status ENUM('active','inactive') DEFAULT 'active',
            sort_order INT DEFAULT 0,
            created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
            updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP
        )
    ");
    $stmt = $pdo->query("SELECT id, name, default_amount FROM fee_types WHERE status = 'active' ORDER BY sort_order, name");
    $fee_types = $stmt->fetchAll();
} catch (Exception $e) {
    $fee_types = [];
}

// Handle fee assignment
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
    // Handle fee update
    if (isset($_POST['action']) && $_POST['action'] == 'update_fee') {
        $fee_id = (int)$_POST['fee_id'];
        $fee_type = trim($_POST['fee_type']);
        $amount = (float)$_POST['amount'];
        $due_date = $_POST['due_date'];
        $academic_year = trim($_POST['academic_year']);
        $month = trim($_POST['month']);
        $remarks = isset($_POST['remarks']) ? trim($_POST['remarks']) : '';
        
        if ($fee_id > 0 && !empty($fee_type) && $amount > 0) {
            try {
                $stmt = $pdo->prepare("UPDATE fees SET fee_type = ?, amount = ?, due_date = ?, academic_year = ?, month = ?, remarks = ?, updated_at = NOW() WHERE id = ?");
                $result = $stmt->execute([$fee_type, $amount, $due_date, $academic_year, $month, $remarks, $fee_id]);
                
                if ($result) {
                    $success_message = 'ফি আপডেট করা হয়েছে';
                } else {
                    $error_message = 'ফি আপডেট করতে সমস্যা হয়েছে';
                }
            } catch (Exception $e) {
                $error_message = 'ফি আপডেট করতে সমস্যা হয়েছে: ' . $e->getMessage();
            }
        } else {
            $error_message = 'সকল প্রয়োজনীয় তথ্য পূরণ করুন';
        }
    }
    
    // Handle fee deletion
    if (isset($_POST['action']) && $_POST['action'] == 'delete_fee') {
        $fee_id = (int)$_POST['fee_id'];
        
        if ($fee_id > 0) {
            try {
                $stmt = $pdo->prepare("DELETE FROM fees WHERE id = ?");
                $result = $stmt->execute([$fee_id]);
                
                if ($result) {
                    $success_message = 'ফি ডিলিট করা হয়েছে';
                } else {
                    $error_message = 'ফি ডিলিট করতে সমস্যা হয়েছে';
                }
            } catch (Exception $e) {
                $error_message = 'ফি ডিলিট করতে সমস্যা হয়েছে: ' . $e->getMessage();
            }
        }
    }
    
    if (isset($_POST['action']) && $_POST['action'] == 'bulk_upload_fees') {
        if (isset($_FILES['fee_csv_file']) && $_FILES['fee_csv_file']['error'] == UPLOAD_ERR_OK) {
            $file = $_FILES['fee_csv_file']['tmp_name'];
            $overwrite = isset($_POST['overwrite_existing']);
            
            $handle = fopen($file, "r");
            if ($handle !== FALSE) {
                try {
                    $pdo->beginTransaction();
                    
                    // Skip header row
                    fgetcsv($handle, 1000, ",");
                    
                    $success_count = 0;
                    $error_count = 0;
                    $skipped_count = 0;

                    $insert_stmt = $pdo->prepare(
                        "INSERT INTO fees (student_id, fee_type, amount, due_date, academic_year, month, remarks) 
                         VALUES (?, ?, ?, ?, ?, ?, ?)"
                    );

                    $update_stmt = $pdo->prepare(
                        "UPDATE fees SET amount = ?, due_date = ?, remarks = ?, updated_at = NOW()
                         WHERE student_id = ? AND fee_type = ? AND academic_year = ? AND month = ?"
                    );

                    $check_stmt = $pdo->prepare(
                        "SELECT id FROM fees WHERE student_id = ? AND fee_type = ? AND academic_year = ? AND month = ?"
                    );

                    while (($data = fgetcsv($handle, 1000, ",")) !== FALSE) {
                        if (count($data) < 7) {
                            $error_count++;
                            continue;
                        }
                        
                        $student_id = trim($data[0]);
                        $fee_type = trim($data[1]);
                        $amount = (float)trim($data[2]);
                        $due_date = trim($data[3]);
                        $academic_year = trim($data[4]);
                        $month = trim($data[5]);
                        $remarks = trim($data[6]);

                        if (empty($student_id) || empty($fee_type) || $amount <= 0) {
                            $error_count++;
                            continue;
                        }

                        $check_stmt->execute([$student_id, $fee_type, $academic_year, $month]);
                        $existing_fee_id = $check_stmt->fetchColumn();

                        if ($existing_fee_id) {
                            if ($overwrite) {
                                $update_stmt->execute([$amount, $due_date, $remarks, $student_id, $fee_type, $academic_year, $month]);
                                $success_count++;
                            } else {
                                $skipped_count++;
                            }
                        } else {
                            $insert_stmt->execute([$student_id, $fee_type, $amount, $due_date, $academic_year, $month, $remarks]);
                            $success_count++;
                        }
                    }
                    
                    $pdo->commit();
                    $success_message = "বাল্ক আপলোড সম্পন্ন হয়েছে। সফল: $success_count, ত্রুটি: $error_count, এড়িয়ে যাওয়া হয়েছে: $skipped_count।";

                } catch (Exception $e) {
                    if ($pdo->inTransaction()) {
                        $pdo->rollBack();
                    }
                    $error_message = "আপলোড প্রক্রিয়ায় সমস্যা হয়েছে: " . $e->getMessage();
                } finally {
                    fclose($handle);
                }
            } else {
                $error_message = "CSV ফাইলটি খোলা যায়নি।";
            }
        } else {
            $error_message = "ফাইল আপলোডে ত্রুটি হয়েছে।";
        }
    }

    if (isset($_POST['assign_fees'])) {
    $class_id = (int)$_POST['class_id'];
    $fee_type = trim($_POST['fee_type']);
    $amount = (float)$_POST['amount'];
    $due_date = $_POST['due_date'];
    $academic_year = trim($_POST['academic_year']);
    $month = trim($_POST['month']);
    $remarks = isset($_POST['remarks']) ? trim($_POST['remarks']) : '';
    
    if ($class_id > 0 && !empty($fee_type) && $amount > 0) {
        try {
            // If this is a salary fee, exclude scholarship students
            if ($fee_type === 'বেতন' || $fee_type === 'মাসিক বেতন') {
                $stmt = $pdo->prepare("SELECT id FROM students WHERE class_id = ? AND status = 'active' AND scholarship = 'no'");
                $stmt->execute([$class_id]);
                $students = $stmt->fetchAll();
                $exclusion_note = " (উপবৃত্তি প্রাপকদের বাদে)";
            } else {
                // For other fees, include all students
                $stmt = $pdo->prepare("SELECT id FROM students WHERE class_id = ? AND status = 'active'");
                $stmt->execute([$class_id]);
                $students = $stmt->fetchAll();
                $exclusion_note = "";
            }
            
            if (empty($students)) {
                $error_message = 'নির্বাচিত ক্লাসে কোন সক্রিয় ছাত্র-ছাত্রী নেই' . ($exclusion_note ? " (উপবৃত্তি প্রাপকদের বাদে)" : "");
            } else {
                $pdo->beginTransaction();
                
                $stmt = $pdo->prepare("
                    INSERT INTO fees (student_id, fee_type, amount, due_date, academic_year, month, remarks) 
                    VALUES (?, ?, ?, ?, ?, ?, ?)
                ");
                
                $assigned_count = 0;
                foreach ($students as $student) {
                    // Check if fee already exists for this student, type, and month
                    $check_stmt = $pdo->prepare("
                        SELECT COUNT(*) FROM fees 
                        WHERE student_id = ? AND fee_type = ? AND academic_year = ? AND month = ?
                    ");
                    $check_stmt->execute([$student['id'], $fee_type, $academic_year, $month]);
                    
                    if ($check_stmt->fetchColumn() == 0) {
                        $stmt->execute([$student['id'], $fee_type, $amount, $due_date, $academic_year, $month, $remarks]);
                        $assigned_count++;
                    }
                }
                
                $pdo->commit();
                $success_message = "$assigned_count জন ছাত্র-ছাত্রীর জন্য ফি নির্ধারণ করা হয়েছে" . $exclusion_note;
            }
            
        } catch (Exception $e) {
            $pdo->rollBack();
            $error_message = 'ফি নির্ধারণে সমস্যা হয়েছে: ' . $e->getMessage();
        }
    } else {
        $error_message = 'সকল প্রয়োজনীয় তথ্য পূরণ করুন';
    }
}
} // This closes the outer if statement

// Get recent fees
$stmt = $pdo->prepare("
    SELECT f.*, s.first_name, s.last_name, s.student_id, s.roll_number, s.scholarship,
           c.name as class_name, c.section as class_section
    FROM fees f
    JOIN students s ON f.student_id = s.id
    JOIN classes c ON s.class_id = c.id
    ORDER BY f.created_at DESC
    LIMIT 20
");
$stmt->execute();
$recent_fees = $stmt->fetchAll();

// Get fee statistics
$stmt = $pdo->query("
    SELECT 
        COUNT(*) as total_fees,
        SUM(CASE WHEN status = 'paid' THEN 1 ELSE 0 END) as paid_fees,
        SUM(CASE WHEN status = 'pending' THEN 1 ELSE 0 END) as pending_fees,
        SUM(CASE WHEN status = 'overdue' THEN 1 ELSE 0 END) as overdue_fees,
        SUM(amount) as total_amount,
        SUM(paid_amount) as total_paid
    FROM fees
");
$fee_stats = $stmt->fetch();
?>

<!DOCTYPE html>
<html lang="bn">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>ফি ব্যবস্থাপনা - <?php echo htmlspecialchars($system_name); ?></title>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/css/bootstrap.min.css" rel="stylesheet">
    <link href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.0.0/css/all.min.css" rel="stylesheet">
    <link href="https://fonts.googleapis.com/css2?family=Hind+Siliguri:wght@300;400;500;600;700&display=swap" rel="stylesheet">
    <style>
        :root{--indigo:#4fc3f7;--pink:#e83e8c;--teal:#4dd0e1;--orange:#ffb74d}
        body{font-family:'Hind Siliguri',sans-serif;background:linear-gradient(135deg,#0a1929,#11294a);min-height:100vh;color:#e0e0e0}
        .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;align-items:center}
        .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)}
        .top-bar .nav-links .dropdown-menu{background:#11294a;border:1px solid rgba(255,255,255,.1);border-radius:8px;padding:4px;min-width:200px}
        .top-bar .nav-links .dropdown-menu a{color:rgba(255,255,255,.7);font-size:.75rem;padding:5px 10px;border-radius:6px}
        .top-bar .nav-links .dropdown-menu a:hover{background:rgba(255,255,255,.08);color:#fff}
        .card{border:none;border-radius:10px;background:rgba(255,255,255,.04);border:1px solid rgba(255,255,255,.06);margin-bottom:1rem}
        .card .card-header{background:linear-gradient(135deg,#0d2137,#1a3a5c);color:#4fc3f7;border-bottom:1px solid rgba(255,255,255,.06);padding:8px 12px;font-weight:600;font-size:.9rem}
        .card .card-body{padding:12px 14px;background:rgba(255,255,255,.02)}
        .form-control,.form-select{font-size:.82rem;padding:5px 10px;border-radius:6px;border:1px solid rgba(255,255,255,.15);background:rgba(0,0,0,.35);color:#e0e0e0}
        .form-control:focus,.form-select:focus{border-color:#4fc3f7;box-shadow:0 0 0 3px rgba(79,195,247,.15)}
        .form-select option{background:#11294a;color:#e0e0e0}
        .form-control::placeholder{color:rgba(255,255,255,.3)}
        .stat-card{border-radius:10px;padding:14px 16px;display:flex;align-items:center;justify-content:space-between}
        .stat-card h4{font-size:1.5rem;font-weight:800;margin:0}
        .stat-card p{margin:0;font-size:.78rem;opacity:.8}
        .stat-card .fa-2x{font-size:1.8rem;opacity:.5}
        .table{--bs-table-border-color:rgba(255,255,255,.08);color:#e0e0e0;font-size:.78rem;margin:0}
        .table-striped>tbody>tr:nth-of-type(odd){--bs-table-accent-bg:rgba(255,255,255,.03);color:#e0e0e0}
        .table-striped>tbody>tr:nth-of-type(even){--bs-table-accent-bg:rgba(255,255,255,.01);color:#e0e0e0}
        .table thead th{border-bottom:1px solid rgba(255,255,255,.1);color:#90caf9;font-size:.75rem;font-weight:700;padding:6px 8px}
        .table td{padding:5px 8px;vertical-align:middle}
        .table-hover tbody tr:hover{--bs-table-hover-bg:rgba(79,195,247,.08);--bs-table-hover-color:#e0e0e0}
        .badge{font-size:.68rem;font-weight:600;padding:3px 8px;border-radius:6px}
        .alert{font-size:.8rem;border-radius:8px;padding:8px 12px}
        .alert-dismissible .btn-close{filter:invert(1)}
        .bg-light{background:rgba(255,255,255,.06)!important}
        .text-muted{color:rgba(255,255,255,.5)!important}
        label.form-label{font-size:.78rem;font-weight:600;color:#90caf9;margin-bottom:2px}
        .btn{font-size:.78rem;border-radius:6px;padding:5px 14px;font-weight:600}
        .btn-success{background:#2e7d32;border:none}
        .btn-success:hover{background:#388e3c}
        .btn-primary{background:#1565c0;border:none}
        .btn-primary:hover{background:#1976d2}
        .btn-dark{background:rgba(0,0,0,.5);border:1px solid rgba(255,255,255,.1)}
        .btn-dark:hover{background:rgba(0,0,0,.7);border-color:rgba(255,255,255,.2)}
        .btn-info{background:#0277bd;border:none;color:#fff}
        .btn-info:hover{background:#0288d1;color:#fff}
        .btn-warning{background:#e65100;border:none;color:#fff}
        .btn-warning:hover{background:#ef6c00;color:#fff}
        .btn-secondary{background:rgba(255,255,255,.15);border:1px solid rgba(255,255,255,.15);color:#e0e0e0}
        .btn-secondary:hover{background:rgba(255,255,255,.25);color:#fff}
        .btn-outline-success{color:#66bb6a;border-color:#66bb6a}
        .btn-outline-success:hover{background:#2e7d32;color:#fff;border-color:#2e7d32}
        .btn .fa-2x{font-size:1.5rem}
        .modal-content{background:#0d2137;border:1px solid rgba(255,255,255,.1);border-radius:10px}
        .modal-header{border-bottom:1px solid rgba(255,255,255,.08);color:#4fc3f7;padding:10px 14px}
        .modal-header .modal-title{font-size:.9rem;font-weight:700}
        .modal-header .btn-close{filter:invert(1)}
        .modal-body{padding:12px 14px}
        .modal-footer{border-top:1px solid rgba(255,255,255,.08);padding:10px 14px}
        hr{border-color:rgba(255,255,255,.08)}
        .form-check-label{font-size:.78rem;color:rgba(255,255,255,.7)}
        .form-check-input{background:rgba(0,0,0,.35);border:1px solid rgba(255,255,255,.15)}
        .form-check-input:checked{background:#4fc3f7;border-color:#4fc3f7}
        .nav-link.dropdown-toggle{color:rgba(255,255,255,.7)!important;font-size:.75rem;padding:4px 10px;border-radius:6px;cursor:pointer;text-decoration:none;display:flex;align-items:center;gap:4px}
        .nav-link.dropdown-toggle:hover{color:#fff!important;background:rgba(255,255,255,.08)}
        .text-danger{color:#ef5350!important}
        .text-success{color:#66bb6a!important}
    </style>
</head>
<body>
    <div class="top-bar">
        <a href="../index.php" class="brand"><i class="fas fa-graduation-cap"></i> স্কুল ম্যানেজমেন্ট</a>
        <div class="nav-links">
            <a href="../index.php"><i class="fas fa-home"></i> হোম</a>
            <a href="student_fees.php"><i class="fas fa-money-bill-wave"></i> ফি কালেক্ট</a>
            <a href="management_dashboard.php"><i class="fas fa-cog"></i> ফি ড্যাশবোর্ড</a>
            <div class="dropdown">
                <a class="nav-link dropdown-toggle" href="#" id="navbarDropdown" role="button" data-bs-toggle="dropdown" aria-expanded="false"><i class="fas fa-tools"></i> টুলস</a>
                <ul class="dropdown-menu dropdown-menu-end" aria-labelledby="navbarDropdown">
                    <li><a class="dropdown-item" href="#bulk-upload-card"><i class="fas fa-upload"></i> বাল্ক ফি আপলোড</a></li>
                    <li><a class="dropdown-item" href="custom_assign.php"><i class="fas fa-users"></i> নির্বাচিতদের জন্য ফি</a></li>
                    <li><a class="dropdown-item" href="bulk_edit.php"><i class="fas fa-edit"></i> বাল্ক ফি এডিট</a></li>
                    <li><a class="dropdown-item" href="bulk_remove.php"><i class="fas fa-trash-alt"></i> বাল্ক ফি রিমুভ</a></li>
                    <li><a class="dropdown-item" href="reports.php"><i class="fas fa-chart-bar"></i> বিস্তারিত রিপোর্ট</a></li>
                    <li><hr class="dropdown-divider"></li>
                    <li><a class="dropdown-item" href="verify_bkash_payments.php"><i class="fas fa-mobile-alt"></i> bKash ভেরিফাই</a></li>
                </ul>
            </div>
            <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 (empty($fee_types)): ?>
            <div class="alert alert-info d-flex justify-content-between align-items-center" role="alert" style="background:rgba(21,101,192,.2);border:1px solid rgba(21,101,192,.3);color:#90caf9">
                <div><i class="fas fa-info-circle me-1"></i> আগে ফি টাইপ কনফিগার করলে ব্যবহার সহজ হয়।</div>
                <a class="btn btn-sm" style="background:rgba(255,255,255,.1);color:#90caf9;border:1px solid rgba(255,255,255,.15);border-radius:6px" href="types.php"><i class="fas fa-plus-circle"></i> নতুন ফি টাইপ</a>
            </div>
        <?php endif; ?>
        <div class="row g-2 mb-3">
            <div class="col-md-3">
                <div class="stat-card" style="background:linear-gradient(135deg,#1565c0,#1976d2)">
                    <div><h4><?php echo $fee_stats['total_fees'] ?: 0; ?></h4><p>মোট ফি</p></div>
                    <i class="fas fa-money-bill fa-2x"></i>
                </div>
            </div>
            <div class="col-md-3">
                <div class="stat-card" style="background:linear-gradient(135deg,#2e7d32,#388e3c)">
                    <div><h4><?php echo $fee_stats['paid_fees'] ?: 0; ?></h4><p>পরিশোধিত</p></div>
                    <i class="fas fa-check-circle fa-2x"></i>
                </div>
            </div>
            <div class="col-md-3">
                <div class="stat-card" style="background:linear-gradient(135deg,#e65100,#ef6c00)">
                    <div><h4><?php echo $fee_stats['pending_fees'] ?: 0; ?></h4><p>অপেক্ষমান</p></div>
                    <i class="fas fa-clock fa-2x"></i>
                </div>
            </div>
            <div class="col-md-3">
                <div class="stat-card" style="background:linear-gradient(135deg,#c62828,#d32f2f)">
                    <div><h4><?php echo $fee_stats['overdue_fees'] ?: 0; ?></h4><p>বকেয়া</p></div>
                    <i class="fas fa-exclamation-triangle fa-2x"></i>
                </div>
            </div>
        </div>

        <div class="row">
            <!-- Fee Assignment Form -->
            <div class="col-md-12">
                <div class="card">
                    <div class="card-header">
                        <span><i class="fas fa-plus-circle me-1"></i> নতুন ফি নির্ধারণ (ক্লাস ভিত্তিক)</span>
                    </div>
                    <div class="card-body">
                        <?php if ($success_message && !isset($_POST['action'])): ?>
                            <div class="alert alert-success alert-dismissible fade show" role="alert" style="background:rgba(46,125,50,.2);border:1px solid rgba(46,125,50,.3);color:#a5d6a7">
                                <i class="fas fa-check-circle"></i> <?php echo $success_message; ?>
                                <button type="button" class="btn-close" data-bs-dismiss="alert" style="filter:invert(1)"></button>
                            </div>
                        <?php endif; ?>
                        
                        <?php if ($error_message && !isset($_POST['action'])): ?>
                            <div class="alert alert-danger alert-dismissible fade show" role="alert" style="background:rgba(198,40,40,.2);border:1px solid rgba(198,40,40,.3);color:#ef9a9a">
                                <i class="fas fa-exclamation-triangle"></i> <?php echo $error_message; ?>
                                <button type="button" class="btn-close" data-bs-dismiss="alert" style="filter:invert(1)"></button>
                            </div>
                        <?php endif; ?>

                        <form method="POST" action="">
                            <input type="hidden" name="assign_fees" value="1">
                            <div class="row">
                                <div class="col-md-4 mb-3">
                                    <label for="class_id" class="form-label">ক্লাস <span class="text-danger">*</span></label>
                                    <select class="form-select" id="class_id" name="class_id" required>
                                        <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-4 mb-3">
                                    <label for="fee_type" class="form-label">ফি এর ধরন <span class="text-danger">*</span></label>
                                    <select class="form-select" id="fee_type" name="fee_type" required>
                                        <option value="">নির্বাচন করুন</option>
                                        <?php if (!empty($fee_types)) : ?>
                                            <?php foreach ($fee_types as $t): ?>
                                                <option value="<?php echo htmlspecialchars($t['name']); ?>" data-default="<?php echo htmlspecialchars($t['default_amount']); ?>">
                                                    <?php echo htmlspecialchars($t['name']); ?>
                                                </option>
                                            <?php endforeach; ?>
                                        <?php else: ?>
                                            <option value="মাসিক বেতন">মাসিক বেতন</option>
                                        <?php endif; ?>
                                    </select>
                                </div>
                                <div class="col-md-4 mb-3">
                                    <label for="amount" class="form-label">পরিমাণ (টাকা) <span class="text-danger">*</span></label>
                                    <input type="number" class="form-control" id="amount" name="amount" min="0" step="0.01" required>
                                </div>
                                <div class="col-md-4 mb-3">
                                    <label for="academic_year" class="form-label">সেশন</label>
                                    <select class="form-select" id="academic_year" name="academic_year">
                                        <option value="">সেশন নির্বাচন করুন</option>
                                        <?php foreach ($sessions as $s): ?>
                                            <option value="<?php echo htmlspecialchars($s['session_name']); ?>">
                                                <?php echo htmlspecialchars($s['session_name']); ?>
                                            </option>
                                        <?php endforeach; ?>
                                    </select>
                                </div>
                                <div class="col-md-4 mb-3">
                                    <label for="month" class="form-label">মাস</label>
                                    <select class="form-select" id="month" name="month">
                                        <option value="">নির্বাচন করুন</option>
                                        <option value="জানুয়ারি">জানুয়ারি</option>
                                        <option value="ফেব্রুয়ারি">ফেব্রুয়ারি</option>
                                        <option value="মার্চ">মার্চ</option>
                                        <option value="এপ্রিল">এপ্রিল</option>
                                        <option value="মে">মে</option>
                                        <option value="জুন">জুন</option>
                                        <option value="জুলাই">জুলাই</option>
                                        <option value="আগস্ট">আগস্ট</option>
                                        <option value="সেপ্টেম্বর">সেপ্টেম্বর</option>
                                        <option value="অক্টোবর">অক্টোবর</option>
                                        <option value="নভেম্বর">নভেম্বর</option>
                                        <option value="ডিসেম্বর">ডিসেম্বর</option>
                                    </select>
                                </div>
                                <div class="col-md-4 mb-3">
                                    <label for="due_date" class="form-label">শেষ তারিখ <span class="text-danger">*</span></label>
                                    <input type="date" class="form-control" id="due_date" name="due_date" required>
                                </div>
                                <div class="col-md-12 mb-3">
                                    <label for="remarks" class="form-label">বিবরণ</label>
                                    <input type="text" class="form-control" id="remarks" name="remarks" placeholder="যেমন: ২০২১ জানুয়ারি মাসিক বেতন">
                                </div>
                            </div>
                            <button type="submit" class="btn btn-success" style="background:#2e7d32"><i class="fas fa-save"></i> ফি নির্ধারণ করুন</button>
                        </form>
                    </div>
                </div>
            </div>
        </div>

        <!-- Bulk Upload Card -->
        <div class="card" id="bulk-upload-card" style="margin-top:8px">
            <div class="card-header">
                <span><i class="fas fa-upload me-1"></i> বাল্ক ফি আপলোড (CSV)</span>
            </div>
            <div class="card-body">
                <?php if ($success_message && isset($_POST['action'])): ?>
                    <div class="alert alert-success alert-dismissible fade show" role="alert" style="background:rgba(46,125,50,.2);border:1px solid rgba(46,125,50,.3);color:#a5d6a7">
                        <i class="fas fa-check-circle"></i> <?php echo $success_message; ?>
                        <button type="button" class="btn-close" data-bs-dismiss="alert" style="filter:invert(1)"></button>
                    </div>
                <?php endif; ?>
                <?php if ($error_message && isset($_POST['action'])): ?>
                    <div class="alert alert-danger alert-dismissible fade show" role="alert" style="background:rgba(198,40,40,.2);border:1px solid rgba(198,40,40,.3);color:#ef9a9a">
                        <i class="fas fa-exclamation-triangle"></i> <?php echo $error_message; ?>
                        <button type="button" class="btn-close" data-bs-dismiss="alert" style="filter:invert(1)"></button>
                    </div>
                <?php endif; ?>
                <p>একাধিক ছাত্র-ছাত্রীর জন্য একসাথে ফি নির্ধারণ করতে একটি CSV ফাইল আপলোড করুন।</p>
                <div class="mb-3 p-3 bg-light rounded">
                    <strong>CSV ফাইলের ফরম্যাট:</strong>
                    <p class="mb-1">আপনার CSV ফাইলে নিম্নলিখিত কলামগুলো থাকতে হবে: <code>student_id</code>, <code>fee_type</code>, <code>amount</code>, <code>due_date</code>, <code>academic_year</code>, <code>month</code>, <code>remarks</code>।</p>
                    <a href="sample_fees.csv" class="btn btn-sm btn-outline-success"><i class="fas fa-file-csv"></i> নমুনা CSV ডাউনলোড করুন</a>
                </div>
                <hr>
                <form method="POST" action="" enctype="multipart/form-data">
                    <input type="hidden" name="action" value="bulk_upload_fees">
                    <div class="mb-3">
                        <label for="fee_csv_file" class="form-label">CSV ফাইল নির্বাচন করুন</label>
                        <input type="file" class="form-control" name="fee_csv_file" id="fee_csv_file" accept=".csv" required>
                    </div>
                    <div class="form-check mb-3">
                        <input class="form-check-input" type="checkbox" name="overwrite_existing" id="overwrite_existing">
                        <label class="form-check-label" for="overwrite_existing">
                            যদি একই ছাত্র, ফি টাইপ, বছর এবং মাসের জন্য ফি আগে থেকেই থাকে, তাহলে সেটিকে আপডেট করুন। (টিক না দিলে এড়িয়ে যাওয়া হবে)
                        </label>
                    </div>
                    <button type="submit" class="btn btn-primary" style="background:#1565c0"><i class="fas fa-upload"></i> আপলোড ও প্রসেস করুন</button>
                </form>
            </div>
        </div>

        <div class="row g-2 mb-3">
            <div class="col-12">
                <div class="card">
                    <div class="card-header d-flex justify-content-between align-items-center">
                        <span><i class="fas fa-history me-1"></i> সাম্প্রতিক ফি</span>
                    </div>
                    <div class="card-body">
                        <?php if (empty($recent_fees)): ?>
                            <div class="text-center py-4" style="color:rgba(255,255,255,.4)"><i class="fas fa-file-invoice fa-3x mb-3"></i><p class="small">কোন ফি নির্ধারণ করা হয়নি</p></div>
                        <?php else: ?>
                            <div class="table-responsive">
                                <table class="table table-hover">
                                    <thead>
                                        <tr>
                                            <th>ছাত্র</th>
                                            <th>আইডি</th>
                                            <th>ক্লাস</th>
                                            <th>ফি ধরন</th>
                                            <th>পরিমাণ</th>
                                            <th>পরিশোধিত</th>
                                            <th>বকেয়া</th>
                                            <th>শেষ তারিখ</th>
                                            <th>অবস্থা</th>
                                            <th>কার্যক্রম</th>
                                        </tr>
                                    </thead>
                                    <tbody>
                                        <?php foreach ($recent_fees as $fee): 
                                            $due_amount = $fee['amount'] - $fee['paid_amount'];
                                            $status_class = '';
                                            switch ($fee['status']) {
                                                case 'paid': $status_class = 'bg-success'; break;
                                                case 'partial': $status_class = 'bg-warning'; break;
                                                case 'overdue': $status_class = 'bg-danger'; break;
                                                default: $status_class = 'bg-info';
                                            }
                                        ?>
                                        <tr>
                                            <td class="fw-bold"><?php echo htmlspecialchars($fee['first_name'] . ' ' . $fee['last_name']); ?></td>
                                            <td><span style="color:rgba(255,255,255,.5)"><?php echo htmlspecialchars($fee['student_id']); ?></span></td>
                                            <td><?php echo htmlspecialchars($fee['class_name'] . ' - ' . $fee['class_section']); ?></td>
                                            <td><?php echo htmlspecialchars($fee['fee_type']); ?><?php echo $fee['month'] ? ' (' . $fee['month'] . ')' : ''; ?>
                                                <?php if (($fee['fee_type'] === 'বেতন' || $fee['fee_type'] === 'মাসিক বেতন') && $fee['scholarship'] === 'yes'): ?>
                                                    <br><span class="badge bg-success">উপবৃত্তি মওকুফ</span>
                                                <?php endif; ?>
                                            </td>
                                            <td>৳<?php echo number_format($fee['amount'], 2); ?></td>
                                            <td>৳<?php echo number_format($fee['paid_amount'], 2); ?></td>
                                            <td class="fw-bold <?php echo $due_amount > 0 ? 'text-danger' : 'text-success'; ?>">
                                                ৳<?php echo number_format($due_amount, 2); ?>
                                                <?php if ($fee['scholarship'] === 'yes' && ($fee['fee_type'] === 'বেতন' || $fee['fee_type'] === 'মাসিক বেতন')): ?>
                                                    <br><span class="badge bg-success" style="font-size:.6rem">মওকুফ</span>
                                                <?php endif; ?>
                                            </td>
                                            <td><?php echo $fee['due_date'] ? date('d/m/Y', strtotime($fee['due_date'])) : 'N/A'; ?></td>
                                            <td><span class="badge <?php echo $status_class; ?>"><?php echo ucfirst($fee['status']); ?></span></td>
                                            <td>
                                                <button type="button" class="btn btn-sm" style="background:rgba(21,101,192,.3);color:#90caf9;border:none;padding:2px 8px;font-size:.7rem" data-bs-toggle="modal" data-bs-target="#editFeeModal" 
                                                    onclick="fillEditForm(<?php echo $fee['id']; ?>, '<?php echo addslashes(htmlspecialchars($fee['fee_type'])); ?>', <?php echo $fee['amount']; ?>, '<?php echo $fee['due_date']; ?>', '<?php echo addslashes(htmlspecialchars($fee['academic_year'])); ?>', '<?php echo addslashes(htmlspecialchars($fee['month'])); ?>', '<?php echo addslashes(htmlspecialchars($fee['remarks'])); ?>')">
                                                    <i class="fas fa-edit"></i>
                                                </button>
                                                <form method="POST" action="" style="display:inline;" onsubmit="return confirm('আপনি কি নিশ্চিত?');">
                                                <input type="hidden" name="action" value="delete_fee">
                                                <input type="hidden" name="fee_id" value="<?php echo $fee['id']; ?>">
                                                <button type="submit" class="btn btn-sm" style="background:rgba(198,40,40,.3);color:#ef9a9a;border:none;padding:2px 8px;font-size:.7rem"><i class="fas fa-trash"></i></button>
                                                </form>
                                            </td>
                                        </tr>
                                        <?php endforeach; ?>
                                    </tbody>
                                </table>
                            </div>
                        <?php endif; ?>
                    </div>
                </div>
            </div>
        </div>

        <div class="row g-2">
            <div class="col-12">
                <div class="card">
                    <div class="card-header"><span><i class="fas fa-bolt me-1"></i> দ্রুত কার্যক্রম</span></div>
                    <div class="card-body">
                        <div class="row g-2">
                            <div class="col-md-3 col-6"><a href="types.php" class="btn w-100" style="background:rgba(255,255,255,.06);border:1px solid rgba(255,255,255,.08);color:#e0e0e0;padding:10px 8px;border-radius:8px"><i class="fas fa-tags" style="font-size:1.2rem;display:block;margin-bottom:4px;color:#4fc3f7"></i><span style="font-size:.72rem;font-weight:600">ফি টাইপ</span></a></div>
                            <div class="col-md-3 col-6"><a href="custom_assign.php" class="btn w-100" style="background:rgba(255,255,255,.06);border:1px solid rgba(255,255,255,.08);color:#e0e0e0;padding:10px 8px;border-radius:8px"><i class="fas fa-users" style="font-size:1.2rem;display:block;margin-bottom:4px;color:#4dd0e1"></i><span style="font-size:.72rem;font-weight:600">নির্বাচিতদের ফি</span></a></div>
                            <div class="col-md-3 col-6"><a href="collect.php" class="btn w-100" style="background:rgba(255,255,255,.06);border:1px solid rgba(255,255,255,.08);color:#e0e0e0;padding:10px 8px;border-radius:8px"><i class="fas fa-hand-holding-usd" style="font-size:1.2rem;display:block;margin-bottom:4px;color:#66bb6a"></i><span style="font-size:.72rem;font-weight:600">ফি সংগ্রহ</span></a></div>
                            <div class="col-md-3 col-6"><a href="student_summary_report.php" class="btn w-100" style="background:rgba(255,255,255,.06);border:1px solid rgba(255,255,255,.08);color:#e0e0e0;padding:10px 8px;border-radius:8px"><i class="fas fa-user-tag" style="font-size:1.2rem;display:block;margin-bottom:4px;color:#ffb74d"></i><span style="font-size:.72rem;font-weight:600">ফি সারসংক্ষেপ</span></a></div>
                            <div class="col-md-3 col-6"><a href="reports.php" class="btn w-100" style="background:rgba(255,255,255,.06);border:1px solid rgba(255,255,255,.08);color:#e0e0e0;padding:10px 8px;border-radius:8px"><i class="fas fa-chart-pie" style="font-size:1.2rem;display:block;margin-bottom:4px;color:#90caf9"></i><span style="font-size:.72rem;font-weight:600">ফি রিপোর্ট</span></a></div>
                            <div class="col-md-3 col-6"><a href="overdue.php" class="btn w-100" style="background:rgba(255,255,255,.06);border:1px solid rgba(255,255,255,.08);color:#e0e0e0;padding:10px 8px;border-radius:8px"><i class="fas fa-exclamation-circle" style="font-size:1.2rem;display:block;margin-bottom:4px;color:#ef5350"></i><span style="font-size:.72rem;font-weight:600">বকেয়া ফি</span></a></div>
                            <div class="col-md-3 col-6"><a href="receipt.php" class="btn w-100" style="background:rgba(255,255,255,.06);border:1px solid rgba(255,255,255,.08);color:#e0e0e0;padding:10px 8px;border-radius:8px"><i class="fas fa-receipt" style="font-size:1.2rem;display:block;margin-bottom:4px;color:#ce93d8"></i><span style="font-size:.72rem;font-weight:600">রসিদ প্রিন্ট</span></a></div>
                            <div class="col-md-3 col-6"><a href="bulk_remove.php" class="btn w-100" style="background:rgba(255,255,255,.06);border:1px solid rgba(255,255,255,.08);color:#e0e0e0;padding:10px 8px;border-radius:8px"><i class="fas fa-trash-alt" style="font-size:1.2rem;display:block;margin-bottom:4px;color:#ef5350"></i><span style="font-size:.72rem;font-weight:600">বাল্ক রিমুভ</span></a></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>
        // Set current month as default and auto-fill amount from fee type defaults
        document.addEventListener('DOMContentLoaded', function() {
            const monthSelect = document.getElementById('month');
            if (monthSelect) {
                const currentMonth = new Date().getMonth();
                const months = ['জানুয়ারি', 'ফেব্রুয়ারি', 'মার্চ', 'এপ্রিল', 'মে', 'জুন', 
                               'জুলাই', 'আগস্ট', 'সেপ্টেম্বর', 'অক্টোবর', 'নভেম্বর', 'ডিসেম্বর'];
                if (months[currentMonth]) {
                    monthSelect.value = months[currentMonth];
                }
            }
            
            const dueDateInput = document.getElementById('due_date');
            if (dueDateInput) {
                const today = new Date();
                const lastDay = new Date(today.getFullYear(), today.getMonth() + 1, 0);
                dueDateInput.value = lastDay.toISOString().split('T')[0];
            }

            const feeTypeSelect = document.getElementById('fee_type');
            const amountInput = document.getElementById('amount');
            if (feeTypeSelect && amountInput) {
                feeTypeSelect.addEventListener('change', function() {
                    const opt = feeTypeSelect.selectedOptions[0];
                    if (!opt) return;
                    const def = opt.getAttribute('data-default');
                    if (def !== null && def !== '' && !isNaN(def)) {
                        amountInput.value = parseFloat(def).toFixed(2);
                    }
                });
            }
        });
        
        // Function to fill edit form with fee data
        function fillEditForm(id, fee_type, amount, due_date, academic_year, month, remarks) {
            document.getElementById('edit_fee_id').value = id;
            document.getElementById('edit_fee_type').value = fee_type;
            document.getElementById('edit_amount').value = amount;
            document.getElementById('edit_due_date').value = due_date;
            document.getElementById('edit_academic_year').value = academic_year;
            document.getElementById('edit_month').value = month;
            document.getElementById('edit_remarks').value = remarks;
        }
    </script>
    
    <!-- Edit Fee Modal -->
    <div class="modal fade" id="editFeeModal" tabindex="-1" aria-labelledby="editFeeModalLabel" aria-hidden="true">
        <div class="modal-dialog">
            <div class="modal-content">
                <div class="modal-header">
                    <h5 class="modal-title" id="editFeeModalLabel">ফি আপডেট করুন</h5>
                    <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
                </div>
                <form method="POST" action="">
                    <div class="modal-body">
                        <input type="hidden" name="action" value="update_fee">
                        <input type="hidden" name="fee_id" id="edit_fee_id" value="">
                        
                        <div class="mb-3">
                            <label for="edit_fee_type" class="form-label">ফি ধরন</label>
                            <input type="text" class="form-control" id="edit_fee_type" name="fee_type" required>
                        </div>
                        
                        <div class="mb-3">
                            <label for="edit_amount" class="form-label">পরিমাণ (টাকা)</label>
                            <input type="number" class="form-control" id="edit_amount" name="amount" min="0" step="0.01" required>
                        </div>
                        
                        <div class="mb-3">
                            <label for="edit_due_date" class="form-label">শেষ তারিখ</label>
                            <input type="date" class="form-control" id="edit_due_date" name="due_date" required>
                        </div>
                        
                        <div class="mb-3">
                            <label for="edit_academic_year" class="form-label">সেশন</label>
                            <input type="text" class="form-control" id="edit_academic_year" name="academic_year">
                        </div>
                        
                        <div class="mb-3">
                            <label for="edit_month" class="form-label">মাস</label>
                            <select class="form-select" id="edit_month" name="month">
                                <option value="">নির্বাচন করুন</option>
                                <option value="জানুয়ারি">জানুয়ারি</option>
                                <option value="ফেব্রুয়ারি">ফেব্রুয়ারি</option>
                                <option value="মার্চ">মার্চ</option>
                                <option value="এপ্রিল">এপ্রিল</option>
                                <option value="মে">মে</option>
                                <option value="জুন">জুন</option>
                                <option value="জুলাই">জুলাই</option>
                                <option value="আগস্ট">আগস্ট</option>
                                <option value="সেপ্টেম্বর">সেপ্টেম্বর</option>
                                <option value="অক্টোবর">অক্টোবর</option>
                                <option value="নভেম্বর">নভেম্বর</option>
                                <option value="ডিসেম্বর">ডিসেম্বর</option>
                            </select>
                        </div>
                        
                        <div class="mb-3">
                            <label for="edit_remarks" class="form-label">বিবরণ</label>
                            <input type="text" class="form-control" id="edit_remarks" name="remarks">
                        </div>
                    </div>
                    <div class="modal-footer">
                        <button type="button" class="btn btn-secondary" style="background:rgba(255,255,255,.12);border:1px solid rgba(255,255,255,.15);color:#e0e0e0" data-bs-dismiss="modal">বাতিল</button>
                        <button type="submit" class="btn btn-primary" style="background:#1565c0;border:none">আপডেট করুন</button>
                    </div>
                </form>
            </div>
        </div>
    </div>
</body>
</html>
