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

// Admin only
if (!isset($_SESSION['user_id']) || $_SESSION['user_role'] !== 'admin') {
    header('Location: ../login.php');
    exit();
}

$success_message = '';
$error_message = '';
$fees_to_edit = [];

// Get filter parameters
$session = $_GET['session'] ?? '';
$class_id = $_GET['class_id'] ?? '';
$fee_type = $_GET['fee_type'] ?? '';

// Fetch data for dropdowns
$sessions = $pdo->query("SELECT DISTINCT academic_year FROM fees ORDER BY academic_year DESC")->fetchAll(PDO::FETCH_COLUMN);
$classes = $pdo->query("SELECT id, name, section FROM classes WHERE status = 'active' ORDER BY name, section")->fetchAll(PDO::FETCH_ASSOC);
$fee_types = $pdo->query("SELECT DISTINCT fee_type FROM fees ORDER BY fee_type")->fetchAll(PDO::FETCH_COLUMN);

// Handle form submission for saving changes
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['save_bulk_edit'])) {
    $fee_data = $_POST['fees'] ?? [];
    if (!empty($fee_data)) {
        try {
            $pdo->beginTransaction();
            $update_stmt = $pdo->prepare(
                "UPDATE fees SET amount = ?, due_date = ?, status = ?, remarks = ?, updated_at = NOW() WHERE id = ?"
            );
            $updated_count = 0;
            foreach ($fee_data as $fee_id => $data) {
                $update_stmt->execute([
                    (float)$data['amount'],
                    $data['due_date'],
                    $data['status'],
                    $data['remarks'],
                    $fee_id
                ]);
                $updated_count++;
            }
            $pdo->commit();
            $success_message = "সফলভাবে $updated_count টি ফি আপডেট করা হয়েছে।";
        } catch (Exception $e) {
            if ($pdo->inTransaction()) {
                $pdo->rollBack();
            }
            $error_message = "ফি আপডেট করার সময় একটি ত্রুটি হয়েছে: " . $e->getMessage();
        }
    }
}

// Fetch fees to edit based on filters
if ($session && $class_id) {
    $sql = "SELECT f.*, s.first_name, s.last_name, s.roll_number 
            FROM fees f 
            JOIN students s ON f.student_id = s.id
            WHERE s.class_id = :class_id AND f.academic_year = :session";
    $params = ['class_id' => $class_id, 'session' => $session];

    if ($fee_type) {
        $sql .= " AND f.fee_type = :fee_type";
        $params['fee_type'] = $fee_type;
    }
    $sql .= " ORDER BY s.roll_number, f.due_date";

    $stmt = $pdo->prepare($sql);
    $stmt->execute($params);
    $fees_to_edit = $stmt->fetchAll(PDO::FETCH_ASSOC);
}

?>

<!DOCTYPE html>
<html lang="bn">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>বাল্ক ফি এডিট</title>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/css/bootstrap.min.css" rel="stylesheet">
    <link href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.0.0/css/all.min.css" rel="stylesheet">
    <link href="https://fonts.googleapis.com/css2?family=Hind+Siliguri:wght@300;400;500;600;700&display=swap" rel="stylesheet">
    <style>
        body {
            font-family: 'Hind Siliguri', sans-serif;
            background-color: #f4f7f6;
        }
        .navbar {
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
        }
        .card {
            border: none;
            border-radius: 15px;
            box-shadow: 0 5px 15px rgba(0,0,0,0.08);
            margin-bottom: 1.5rem;
        }
        .card-header {
            background-color: #fff;
            border-bottom: 1px solid #eee;
            font-weight: 600;
            font-size: 1.2rem;
            padding: 1rem 1.5rem;
            border-radius: 15px 15px 0 0 !important;
        }
        .table-bordered {
            border-radius: 0 0 15px 15px;
            overflow: hidden;
        }
        .table thead th {
            background-color: #667eea;
            color: white;
            border-color: #667eea;
        }
        .btn-primary {
            background-color: #667eea;
            border-color: #667eea;
        }
        .btn-primary:hover {
            background-color: #5a67d8;
            border-color: #5a67d8;
        }
        .pagination .page-item.active .page-link {
            background-color: #667eea;
            border-color: #667eea;
        }
        .form-control, .form-select {
            border-radius: 8px;
        }
        .form-control:focus, .form-select:focus {
            border-color: #667eea;
            box-shadow: 0 0 0 0.25rem rgba(102, 126, 234, 0.25);
        }
    </style>
</head>
<body>

<nav class="navbar navbar-expand-lg navbar-dark mb-4">
    <div class="container-fluid">
        <a class="navbar-brand" href="../index.php"><i class="fas fa-graduation-cap"></i> ফি ম্যানেজমেন্ট</a>
        <a class="nav-link text-white" href="manage.php"><i class="fas fa-arrow-left"></i> ফি ব্যবস্থাপনায় ফিরে যান</a>
    </div>
</nav>

<div class="container-fluid">
    <div class="card filter-card">
        <div class="card-header">
            <h5><i class="fas fa-filter"></i> ফি ফিল্টার করুন</h5>
        </div>
        <div class="card-body">
            <form method="GET" action="">
                <div class="row g-3">
                    <div class="col-md-4">
                        <label class="form-label">সেশন</label>
                        <select name="session" class="form-select" required>
                            <option value="">সেশন নির্বাচন করুন</option>
                            <?php foreach ($sessions as $sess): ?>
                                <option value="<?php echo htmlspecialchars($sess); ?>" <?php echo ($session === $sess) ? 'selected' : ''; ?>><?php echo htmlspecialchars($sess); ?></option>
                            <?php endforeach; ?>
                        </select>
                    </div>
                    <div class="col-md-4">
                        <label class="form-label">ক্লাস</label>
                        <select name="class_id" class="form-select" required>
                            <option value="">ক্লাস নির্বাচন করুন</option>
                            <?php foreach ($classes as $class): ?>
                                <option value="<?php echo $class['id']; ?>" <?php echo ($class_id == $class['id']) ? 'selected' : ''; ?>><?php echo htmlspecialchars($class['name'] . ' - ' . $class['section']); ?></option>
                            <?php endforeach; ?>
                        </select>
                    </div>
                    <div class="col-md-4">
                        <label class="form-label">ফি-এর ধরন (ঐচ্ছিক)</label>
                        <select name="fee_type" class="form-select">
                            <option value="">সকল ধরন</option>
                            <?php foreach ($fee_types as $ft): ?>
                                <option value="<?php echo htmlspecialchars($ft); ?>" <?php echo ($fee_type === $ft) ? 'selected' : ''; ?>><?php echo htmlspecialchars($ft); ?></option>
                            <?php endforeach; ?>
                        </select>
                    </div>
                    <div class="col-12 text-center mt-4">
                        <button type="submit" class="btn btn-primary btn-lg"><i class="fas fa-search"></i> ফি খুঁজুন</button>
                    </div>
                </div>
            </form>
        </div>
    </div>

    <?php if ($success_message): ?><div class="alert alert-success mt-3"><?php echo $success_message; ?></div><?php endif; ?>
    <?php if ($error_message): ?><div class="alert alert-danger mt-3"><?php echo $error_message; ?></div><?php endif; ?>

    <?php if (!empty($fees_to_edit)): ?>
    <form method="POST" action="">
        <input type="hidden" name="session" value="<?php echo htmlspecialchars($session); ?>">
        <input type="hidden" name="class_id" value="<?php echo htmlspecialchars($class_id); ?>">
        <input type="hidden" name="fee_type" value="<?php echo htmlspecialchars($fee_type); ?>">
        <div class="card">
            <div class="card-header d-flex justify-content-between align-items-center">
                <h5><i class="fas fa-edit"></i> ফি সম্পাদনা করুন</h5>
                <div class="w-50">
                    <input type="text" id="feeSearchInput" class="form-control" placeholder="রোল বা নাম দিয়ে খুঁজুন...">
                </div>
            </div>
            <div class="card-body p-0">
                <div class="table-responsive">
                    <table class="table table-striped table-bordered mb-0">
                        <thead>
                            <tr>
                                <th>রোল</th>
                                <th>নাম</th>
                                <th>ফি-এর ধরন</th>
                                <th>পরিমাণ</th>
                                <th>শেষ তারিখ</th>
                                <th>স্ট্যাটাস</th>
                                <th>মন্তব্য</th>
                            </tr>
                        </thead>
                        <tbody>
                            <?php foreach ($fees_to_edit as $fee): ?>
                            <tr>
                                <td><?php echo htmlspecialchars($fee['roll_number']); ?></td>
                                <td><?php echo htmlspecialchars($fee['first_name'] . ' ' . $fee['last_name']); ?></td>
                                <td><?php echo htmlspecialchars($fee['fee_type']); ?></td>
                                <td><input type="number" name="fees[<?php echo $fee['id']; ?>][amount]" class="form-control" value="<?php echo htmlspecialchars($fee['amount']); ?>"></td>
                                <td><input type="date" name="fees[<?php echo $fee['id']; ?>][due_date]" class="form-control" value="<?php echo htmlspecialchars($fee['due_date']); ?>"></td>
                                <td>
                                    <select name="fees[<?php echo $fee['id']; ?>][status]" class="form-select">
                                        <option value="pending" <?php echo ($fee['status'] === 'pending') ? 'selected' : ''; ?>>Pending</option>
                                        <option value="paid" <?php echo ($fee['status'] === 'paid') ? 'selected' : ''; ?>>Paid</option>
                                        <option value="partial" <?php echo ($fee['status'] === 'partial') ? 'selected' : ''; ?>>Partial</option>
                                        <option value="overdue" <?php echo ($fee['status'] === 'overdue') ? 'selected' : ''; ?>>Overdue</option>
                                    </select>
                                </td>
                                <td><input type="text" name="fees[<?php echo $fee['id']; ?>][remarks]" class="form-control" value="<?php echo htmlspecialchars($fee['remarks']); ?>"></td>
                            </tr>
                            <?php endforeach; ?>
                        </tbody>
                    </table>
                </div>
            </div>
            <div class="card-footer d-flex justify-content-between align-items-center">
                <div id="pagination-summary" class="text-muted"></div>
                <nav id="pagination-nav"></nav>
                <button type="submit" name="save_bulk_edit" class="btn btn-success"><i class="fas fa-save"></i> পরিবর্তন সেভ করুন</button>
            </div>
        </div>
    </form>
    <?php elseif(isset($_GET['session'])): ?>
        <div class="alert alert-info mt-3">আপনার নির্বাচিত ফিল্টারে কোনো ফি পাওয়া যায়নি।</div>
    <?php endif; ?>

</div>

<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/js/bootstrap.bundle.min.js"></script>
<script>
document.addEventListener('DOMContentLoaded', function() {
    const searchInput = document.getElementById('feeSearchInput');
    const table = document.querySelector('.table-bordered');
    const tbody = table?.querySelector('tbody');
    const rows = tbody ? Array.from(tbody.querySelectorAll('tr')) : [];
    
    const paginationSummary = document.getElementById('pagination-summary');
    const paginationNav = document.getElementById('pagination-nav');
    const rowsPerPage = 10;
    let currentPage = 1;
    let filteredRows = rows;

    function setupPagination() {
        if (!tbody) return;

        function displayPage(page) {
            currentPage = page;
            rows.forEach(row => row.style.display = 'none');
            
            const startIndex = (page - 1) * rowsPerPage;
            const endIndex = startIndex + rowsPerPage;
            const pageRows = filteredRows.slice(startIndex, endIndex);
            pageRows.forEach(row => row.style.display = '');

            if (paginationSummary) {
                const start = Math.min(startIndex + 1, filteredRows.length);
                const end = Math.min(endIndex, filteredRows.length);
                paginationSummary.textContent = `${filteredRows.length} টির মধ্যে ${start}-${end} টি দেখানো হচ্ছে`;
            }

            renderPaginationLinks();
        }

        function renderPaginationLinks() {
            if (!paginationNav) return;
            paginationNav.innerHTML = '';
            const pageCount = Math.ceil(filteredRows.length / rowsPerPage);

            if (pageCount <= 1) return;

            const ul = document.createElement('ul');
            ul.className = 'pagination pagination-sm mb-0';

            const prevLi = document.createElement('li');
            prevLi.className = `page-item ${currentPage === 1 ? 'disabled' : ''}`;
            const prevA = document.createElement('a');
            prevA.className = 'page-link';
            prevA.href = '#';
            prevA.innerHTML = '&laquo;';
            prevA.addEventListener('click', (e) => {
                e.preventDefault();
                if (currentPage > 1) displayPage(currentPage - 1);
            });
            prevLi.appendChild(prevA);
            ul.appendChild(prevLi);

            // Page numbers logic
            const maxPagesToShow = 5;
            let startPage = Math.max(1, currentPage - Math.floor(maxPagesToShow / 2));
            let endPage = Math.min(pageCount, startPage + maxPagesToShow - 1);
            if (endPage - startPage + 1 < maxPagesToShow) {
                startPage = Math.max(1, endPage - maxPagesToShow + 1);
            }

            if (startPage > 1) {
                const firstLi = document.createElement('li');
                firstLi.className = 'page-item';
                const firstA = document.createElement('a');
                firstA.className = 'page-link';
                firstA.href = '#';
                firstA.textContent = '1';
                firstA.addEventListener('click', (e) => { e.preventDefault(); displayPage(1); });
                firstLi.appendChild(firstA);
                ul.appendChild(firstLi);
                if (startPage > 2) {
                    const dotsLi = document.createElement('li');
                    dotsLi.className = 'page-item disabled';
                    dotsLi.innerHTML = '<span class="page-link">...</span>';
                    ul.appendChild(dotsLi);
                }
            }

            for (let i = startPage; i <= endPage; i++) {
                const li = document.createElement('li');
                li.className = `page-item ${i === currentPage ? 'active' : ''}`;
                const a = document.createElement('a');
                a.className = 'page-link';
                a.href = '#';
                a.textContent = i;
                a.addEventListener('click', (e) => {
                    e.preventDefault();
                    displayPage(i);
                });
                li.appendChild(a);
                ul.appendChild(li);
            }

            if (endPage < pageCount) {
                if (endPage < pageCount - 1) {
                    const dotsLi = document.createElement('li');
                    dotsLi.className = 'page-item disabled';
                    dotsLi.innerHTML = '<span class="page-link">...</span>';
                    ul.appendChild(dotsLi);
                }
                const lastLi = document.createElement('li');
                lastLi.className = 'page-item';
                const lastA = document.createElement('a');
                lastA.className = 'page-link';
                lastA.href = '#';
                lastA.textContent = pageCount;
                lastA.addEventListener('click', (e) => { e.preventDefault(); displayPage(pageCount); });
                lastLi.appendChild(lastA);
                ul.appendChild(lastLi);
            }

            const nextLi = document.createElement('li');
            nextLi.className = `page-item ${currentPage === pageCount ? 'disabled' : ''}`;
            const nextA = document.createElement('a');
            nextA.className = 'page-link';
            nextA.href = '#';
            nextA.innerHTML = '&raquo;';
            nextA.addEventListener('click', (e) => {
                e.preventDefault();
                if (currentPage < pageCount) displayPage(currentPage + 1);
            });
            nextLi.appendChild(nextA);
            ul.appendChild(nextLi);

            paginationNav.appendChild(ul);
        }

        displayPage(1);
    }

    function handleSearch() {
        if (!searchInput) return;
        const searchTerm = searchInput.value.toLowerCase().trim();
        
        filteredRows = rows.filter(row => {
            const roll = row.cells[0].textContent.toLowerCase();
            const name = row.cells[1].textContent.toLowerCase();
            const match = roll.includes(searchTerm) || name.includes(searchTerm);
            return match;
        });
        
        setupPagination();
    }

    if (searchInput) {
        searchInput.addEventListener('keyup', handleSearch);
    }

    setupPagination();
});
</script>
</body>
</html>