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

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

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

// Get sessions for dropdown
$stmt = $pdo->query("SELECT DISTINCT session FROM students WHERE session IS NOT NULL ORDER BY session DESC");
$sessions = $stmt->fetchAll();

// Get classes for dropdown
$stmt = $pdo->query("SELECT id, name, section FROM classes WHERE status = 'active' ORDER BY name, section");
$classes = $stmt->fetchAll();

// Get groups for dropdown
$stmt = $pdo->query("SELECT DISTINCT group_name FROM students WHERE group_name IS NOT NULL AND group_name != '' ORDER BY group_name");
$groups = $stmt->fetchAll();

// Process bulk operations
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
    if (isset($_POST['bulk_action']) && isset($_POST['selected_students']) && !empty($_POST['selected_students'])) {
        $action = $_POST['bulk_action'];
        $selected_ids = $_POST['selected_students'];
        $new_roll_prefix = isset($_POST['new_roll_prefix']) ? trim($_POST['new_roll_prefix']) : '';
        
        try {
            $pdo->beginTransaction();
            
            $placeholders = str_repeat('?,', count($selected_ids) - 1) . '?';
            $stmt = $pdo->prepare("SELECT id, roll_number FROM students WHERE id IN ($placeholders)");
            $stmt->execute($selected_ids);
            $current_students = $stmt->fetchAll(PDO::FETCH_ASSOC);
            
            $affected_count = 0;
            
            switch ($action) {
                case 'modify':
                    // Modify roll numbers individually based on user input
                    if (isset($_POST['roll_numbers']) && is_array($_POST['roll_numbers'])) {
                        foreach ($selected_ids as $student_id) {
                            $new_roll = isset($_POST['roll_numbers'][$student_id]) ? trim($_POST['roll_numbers'][$student_id]) : null;
                            // If the input is empty, set to NULL, otherwise use the provided value
                            if ($new_roll === '') {
                                $new_roll = null;
                            }
                            $stmt = $pdo->prepare("UPDATE students SET roll_number = ? WHERE id = ?");
                            $stmt->execute([$new_roll, $student_id]);
                            $affected_count++;
                        }
                    } else {
                        $error_message = 'রোল নম্বর ডেটা পাওয়া যায়নি';
                    }
                    break;
                    
                case 'remove':
                    // Remove roll numbers
                    $stmt = $pdo->prepare("UPDATE students SET roll_number = NULL WHERE id IN ($placeholders)");
                    $stmt->execute($selected_ids);
                    $affected_count = count($selected_ids);
                    break;
                    
                case 'add':
                    // Add roll numbers sequentially starting from a number
                    $start_roll = isset($_POST['start_roll']) ? intval($_POST['start_roll']) : 1;
                    foreach ($selected_ids as $idx => $student_id) {
                        $new_roll = $start_roll + $idx;
                        $stmt = $pdo->prepare("UPDATE students SET roll_number = ? WHERE id = ?");
                        $stmt->execute([$new_roll, $student_id]);
                        $affected_count++;
                    }
                    break;
            }
            
            if ($affected_count > 0) {
                $pdo->commit();
                $success_message = "$affected_count জন শিক্ষার্থীর রোল নম্বর সফলভাবে হালনাগাদ করা হয়েছে!";
            } else {
                $pdo->rollback();
            }
        } catch (Exception $e) {
            $pdo->rollback();
            $error_message = 'ত্রুটি: ' . $e->getMessage();
        }
    } elseif (isset($_POST['filter_submit'])) {
        // Just re-render the page with filtered results
    } else {
        $error_message = 'কোন শিক্ষার্থী নির্বাচন করা হয়নি বা ক্রিয়াকলাপ নির্বাচন করা হয়নি।';
    }
}

// Get students based on filters
$students = [];
$session_filter = isset($_POST['session_filter']) ? $_POST['session_filter'] : '';
$class_filter = isset($_POST['class_filter']) ? $_POST['class_filter'] : '';
$group_filter = isset($_POST['group_filter']) ? $_POST['group_filter'] : '';

$where_conditions = [];
$params = [];

if (!empty($session_filter)) {
    $where_conditions[] = "s.session = ?";
    $params[] = $session_filter;
}

if (!empty($class_filter)) {
    $where_conditions[] = "s.class_id = ?";
    $params[] = $class_filter;
}

if (!empty($group_filter)) {
    $where_conditions[] = "s.group_name = ?";
    $params[] = $group_filter;
}

$where_clause = '';
if (!empty($where_conditions)) {
    $where_clause = 'WHERE ' . implode(' AND ', $where_conditions);
}

$sql = "SELECT s.id, s.student_id, s.first_name, s.last_name, s.roll_number, s.session, c.name as class_name, c.section, s.group_name 
        FROM students s 
        LEFT JOIN classes c ON s.class_id = c.id 
        $where_clause 
        ORDER BY s.class_id, s.roll_number, s.first_name";

$stmt = $pdo->prepare($sql);
$stmt->execute($params);
$students = $stmt->fetchAll();
?>

<!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="../assets/css/style.css" rel="stylesheet">
    <style>
        body {
            font-family: 'Hind Siliguri', 'Noto Sans Bengali', Arial, sans-serif;
        }
        .form-check-input:checked {
            background-color: #0d6efd;
            border-color: #0d6efd;
        }
        .table th, .table td {
            vertical-align: middle;
        }
        .roll-input {
            width: 100px;
            padding: 0.375rem 0.5rem;
            font-size: 0.9rem;
        }
        .sticky-top {
            background-color: white;
        }
    </style>
</head>
<body>
    <!-- Navigation -->
    <nav class="navbar navbar-expand-lg navbar-dark bg-primary">
        <div class="container-fluid">
            <a class="navbar-brand" href="../index.php">
                <i class="fas fa-graduation-cap"></i> স্কুল ম্যানেজমেন্ট সিস্টেম
            </a>
            
            <div class="navbar-nav ms-auto">
                <a class="nav-link" href="../index.php">
                    <i class="fas fa-home"></i> হোম
                </a>
            </div>
        </div>
    </nav>

    <div class="container mt-4">
        <div class="row">
            <!-- Sidebar -->
            <div class="col-md-3">
                <div class="card">
                    <div class="card-header">
                        <h5><i class="fas fa-filter"></i> ফিল্টার অপশন</h5>
                    </div>
                    <div class="card-body">
                        <form method="POST" id="filterForm">
                            <!-- Session Filter -->
                            <div class="mb-3">
                                <label for="session_filter" class="form-label">সেশন</label>
                                <select class="form-select" id="session_filter" name="session_filter">
                                    <option value="">সব</option>
                                    <?php foreach ($sessions as $session): ?>
                                        <option value="<?php echo htmlspecialchars($session['session']); ?>" 
                                            <?php echo $session_filter == $session['session'] ? 'selected' : ''; ?>>
                                            <?php echo htmlspecialchars($session['session']); ?>
                                        </option>
                                    <?php endforeach; ?>
                                </select>
                            </div>
                            
                            <!-- Class Filter -->
                            <div class="mb-3">
                                <label for="class_filter" class="form-label">ক্লাস</label>
                                <select class="form-select" id="class_filter" name="class_filter">
                                    <option value="">সব</option>
                                    <?php foreach ($classes as $class): ?>
                                        <option value="<?php echo $class['id']; ?>" 
                                            <?php echo $class_filter == $class['id'] ? 'selected' : ''; ?>>
                                            <?php echo htmlspecialchars($class['name'] . ' - ' . $class['section']); ?>
                                        </option>
                                    <?php endforeach; ?>
                                </select>
                            </div>
                            
                            <!-- Group Filter -->
                            <div class="mb-3">
                                <label for="group_filter" class="form-label">গ্রুপ</label>
                                <select class="form-select" id="group_filter" name="group_filter">
                                    <option value="">সব</option>
                                    <?php foreach ($groups as $group): ?>
                                        <option value="<?php echo htmlspecialchars($group['group_name']); ?>" 
                                            <?php echo $group_filter == $group['group_name'] ? 'selected' : ''; ?>>
                                            <?php echo htmlspecialchars($group['group_name']); ?>
                                        </option>
                                    <?php endforeach; ?>
                                </select>
                            </div>
                            
                            <div class="d-grid gap-2">
                                <button type="submit" name="filter_submit" class="btn btn-primary">
                                    <i class="fas fa-filter"></i> ফিল্টার
                                </button>
                                <button type="button" class="btn btn-outline-secondary" onclick="clearFilters()">
                                    <i class="fas fa-undo"></i> রিসেট
                                </button>
                            </div>
                        </form>
                        
                        <hr>
                        
                        <div class="alert alert-info">
                            <h6><i class="fas fa-info-circle"></i> নির্দেশনা:</h6>
                            <ol class="small mb-0">
                                <li>ফিল্টার ব্যবহার করুন শিক্ষার্থীদের নির্বাচন করুন</li>
                                <li>তালিকা থেকে শিক্ষার্থীদের নির্বাচন করুন</li>
                                <li>"রোল নম্বর পরিবর্তন" সিলেক্ট করলে টেবিলের রোল নম্বর ঘরে কাস্টমাইজ করে সেভ দিন</li>
                                <li>ক্রিয়াকলাপ নির্বাচন করুন এবং সম্পন্ন করুন</li>
                            </ol>
                        </div>
                    </div>
                </div>
            </div>
            
            <!-- Main Content -->
            <div class="col-md-9">
                <div class="card">
                    <div class="card-header">
                        <h4><i class="fas fa-users"></i> শিক্ষার্থীদের রোল নম্বর বাল্ক সম্পাদনা</h4>
                    </div>
                    <div class="card-body">
                        <?php if ($success_message): ?>
                            <div class="alert alert-success alert-dismissible fade show">
                                <i class="fas fa-check-circle"></i> <?php echo $success_message; ?>
                                <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
                            </div>
                        <?php endif; ?>

                        <?php if ($error_message): ?>
                            <div class="alert alert-danger alert-dismissible fade show">
                                <i class="fas fa-exclamation-triangle"></i> <?php echo $error_message; ?>
                                <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
                            </div>
                        <?php endif; ?>

                        <form method="POST" id="bulkEditForm">
                            <!-- Bulk Action Controls -->
                            <div class="row mb-3 sticky-top py-2" style="top: 70px; z-index: 100;">
                                <div class="col-md-3">
                                    <label for="bulk_action" class="form-label">ক্রিয়াকলাপ</label>
                                    <select class="form-select" id="bulk_action" name="bulk_action" required>
                                        <option value="">ক্রিয়াকলাপ নির্বাচন করুন</option>
                                        <option value="add">রোল নম্বর যোগ করুন</option>
                                        <option value="modify">রোল নম্বর পরিবর্তন করুন</option>
                                        <option value="remove">রোল নম্বর মুছুন</option>
                                    </select>
                                </div>
                                
                                <div class="col-md-3" id="prefixField" style="display: none;">
                                    <label for="new_roll_prefix" class="form-label">নতুন রোল প্রিফিক্স</label>
                                    <input type="text" class="form-control" id="new_roll_prefix" name="new_roll_prefix" placeholder="রোল প্রিফিক্স">
                                    <small class="form-text text-muted">উদাহরণ: A01, B01 (অপশনাল)</small>
                                </div>
                                
                                <div class="col-md-3" id="startRollField" style="display: none;">
                                    <label for="start_roll" class="form-label">শুরুর রোল</label>
                                    <input type="number" class="form-control" id="start_roll" name="start_roll" min="1" value="1">
                                </div>
                                
                                <div class="col-md-3">
                                    <label>&nbsp;</label>
                                    <div class="d-grid">
                                        <button type="submit" class="btn btn-success" id="applyActionBtn" disabled>
                                            <i class="fas fa-check-circle"></i> প্রয়োগ করুন
                                        </button>
                                    </div>
                                </div>
                            </div>

                            <!-- Student Selection Table -->
                            <div class="table-responsive">
                                <table class="table table-striped table-hover">
                                    <thead class="table-dark">
                                        <tr>
                                            <th width="5%">
                                                <div class="form-check">
                                                    <input class="form-check-input" type="checkbox" id="selectAll">
                                                    <label class="form-check-label" for="selectAll">সব</label>
                                                </div>
                                            </th>
                                            <th>ছাত্র/ছাত্রীর নাম</th>
                                            <th>ছাত্র/ছাত্রী আইডি</th>
                                            <th>রোল নম্বর</th>
                                            <th>সেশন</th>
                                            <th>ক্লাস</th>
                                            <th>গ্রুপ</th>
                                        </tr>
                                    </thead>
                                    <tbody>
                                        <?php if (empty($students)): ?>
                                            <tr>
                                                <td colspan="7" class="text-center text-muted">কোন শিক্ষার্থী পাওয়া যায়নি</td>
                                            </tr>
                                        <?php else: ?>
                                            <?php foreach ($students as $student): ?>
                                                <tr>
                                                    <td>
                                                        <div class="form-check">
                                                            <input class="form-check-input student-checkbox" type="checkbox" 
                                                                name="selected_students[]" 
                                                                value="<?php echo $student['id']; ?>"
                                                                id="chk_<?php echo $student['id']; ?>">
                                                            <label class="form-check-label" for="chk_<?php echo $student['id']; ?>"></label>
                                                        </div>
                                                    </td>
                                                    <td>
                                                        <strong><?php echo htmlspecialchars($student['first_name'] . ' ' . $student['last_name']); ?></strong>
                                                    </td>
                                                    <td><?php echo htmlspecialchars($student['student_id']); ?></td>
                                                    <td>
                                                        <?php if ($student['roll_number']): ?>
                                                            <input type="text" class="form-control roll-input" name="roll_numbers[<?php echo $student['id']; ?>]" value="<?php echo $student['roll_number']; ?>" <?php echo (isset($_POST['bulk_action']) && $_POST['bulk_action'] == 'modify') ? '' : 'readonly'; ?>>
                                                        <?php else: ?>
                                                            <input type="text" class="form-control roll-input" name="roll_numbers[<?php echo $student['id']; ?>]" value="" <?php echo (isset($_POST['bulk_action']) && $_POST['bulk_action'] == 'modify') ? '' : 'readonly'; ?>>
                                                        <?php endif; ?>
                                                    </td>
                                                    <td><?php echo htmlspecialchars($student['session']); ?></td>
                                                    <td><?php echo htmlspecialchars($student['class_name'] . ' - ' . $student['section']); ?></td>
                                                    <td><?php echo htmlspecialchars($student['group_name'] ?: 'কোনটি না'); ?></td>
                                                </tr>
                                            <?php endforeach; ?>
                                        <?php endif; ?>
                                    </tbody>
                                </table>
                            </div>
                            
                            <?php if (!empty($students)): ?>
                                <div class="mt-3">
                                    <small class="text-muted">মোট শিক্ষার্থী: <?php echo count($students); ?> | 
                                        <span id="selectedCount">0</span> জন নির্বাচিত</small>
                                </div>
                            <?php endif; ?>
                        </form>
                    </div>
                </div>
            </div>
        </div>
    </div>

    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/js/bootstrap.bundle.min.js"></script>
    <script>
        // Toggle bulk action fields based on selection
        document.getElementById('bulk_action').addEventListener('change', function() {
            const action = this.value;
            const prefixField = document.getElementById('prefixField');
            const startRollField = document.getElementById('startRollField');
            const applyBtn = document.getElementById('applyActionBtn');
            
            // Hide all conditional fields first
            prefixField.style.display = 'none';
            startRollField.style.display = 'none';
            
            // Enable/disable roll number inputs based on action
            const rollInputs = document.querySelectorAll('.roll-input');
            if (action === 'modify') {
                // Enable all roll number inputs
                rollInputs.forEach(input => {
                    input.removeAttribute('readonly');
                });
            } else {
                // Disable all roll number inputs
                rollInputs.forEach(input => {
                    input.setAttribute('readonly', 'readonly');
                });
            }
            
            // Show appropriate field based on action
            if (action === 'add') {
                startRollField.style.display = 'block';
            }
            // Note: For 'modify' action, we enable the individual roll inputs in the table instead of showing a prefix field
            
            // Enable/disable apply button based on selections
            const selectedCheckboxes = document.querySelectorAll('.student-checkbox:checked');
            applyBtn.disabled = selectedCheckboxes.length === 0 || action === '';
        });

        // Select/deselect all checkboxes
        document.getElementById('selectAll').addEventListener('change', function() {
            const checkboxes = document.querySelectorAll('.student-checkbox');
            checkboxes.forEach(checkbox => {
                checkbox.checked = this.checked;
            });
            updateSelectedCount();
            updateApplyButtonState();
        });

        // Initialize on page load
        document.addEventListener('DOMContentLoaded', function() {
            const selectedCheckboxes = document.querySelectorAll('.student-checkbox:checked');
            updateSelectedCount();
            updateApplyButtonState();
            
            // Initialize roll number inputs based on current action
            const currentAction = document.getElementById('bulk_action').value;
            const rollInputs = document.querySelectorAll('.roll-input');
            const prefixField = document.getElementById('prefixField');
            const startRollField = document.getElementById('startRollField');
            
            // Hide all conditional fields first
            prefixField.style.display = 'none';
            startRollField.style.display = 'none';
            
            if (currentAction === 'modify') {
                // Enable all roll number inputs
                rollInputs.forEach(input => {
                    input.removeAttribute('readonly');
                });
            } else {
                // Disable all roll number inputs
                rollInputs.forEach(input => {
                    input.setAttribute('readonly', 'readonly');
                });
            }
            
            // Show appropriate field based on action
            if (currentAction === 'add') {
                startRollField.style.display = 'block';
            }
            // Note: For 'modify' action, we enable the individual roll inputs in the table instead of showing a prefix field
        });

        // Update selected count when individual checkboxes change
        document.querySelectorAll('.student-checkbox').forEach(checkbox => {
            checkbox.addEventListener('change', function() {
                updateSelectedCount();
                updateApplyButtonState();
            });
        });

        // Function to update selected count
        function updateSelectedCount() {
            const selectedCount = document.querySelectorAll('.student-checkbox:checked').length;
            document.getElementById('selectedCount').textContent = selectedCount;
        }

        // Function to update apply button state
        function updateApplyButtonState() {
            const selectedCheckboxes = document.querySelectorAll('.student-checkbox:checked');
            const action = document.getElementById('bulk_action').value;
            const applyBtn = document.getElementById('applyActionBtn');
            
            applyBtn.disabled = selectedCheckboxes.length === 0 || action === '';
        }

        // Confirm before applying bulk action
        document.getElementById('bulkEditForm').addEventListener('submit', function(e) {
            const selectedCount = document.querySelectorAll('.student-checkbox:checked').length;
            const action = document.getElementById('bulk_action').value;
            
            if (selectedCount === 0) {
                e.preventDefault();
                alert('অনুগ্রহ করে কমপক্ষে একজন শিক্ষার্থী নির্বাচন করুন।');
                return;
            }
            
            if (action === '') {
                e.preventDefault();
                alert('অনুগ্রহ করে একটি ক্রিয়াকলাপ নির্বাচন করুন।');
                return;
            }
            
            let actionText = '';
            let actionDesc = '';
            switch(action) {
                case 'add': 
                    actionText = 'রোল নম্বর যোগ'; 
                    actionDesc = 'নতুন রোল নম্বর যোগ করা হবে';
                    break;
                case 'modify': 
                    actionText = 'রোল নম্বর পরিবর্তন'; 
                    actionDesc = 'বিদ্যমান রোল নম্বর পরিবর্তন করা হবে';
                    break;
                case 'remove': 
                    actionText = 'রোল নম্বর মুছুন'; 
                    actionDesc = 'রোল নম্বর মুছে ফেলা হবে';
                    break;
            }
            
            if (!confirm(selectedCount + ' জন শিক্ষার্থীর জন্য ' + actionDesc + ' হবে। নিশ্চিত করুন?')) {
                e.preventDefault();
            }
        });

        // Clear filters function
        function clearFilters() {
            document.getElementById('session_filter').value = '';
            document.getElementById('class_filter').value = '';
            document.getElementById('group_filter').value = '';
            document.getElementById('filterForm').submit();
        }
    </script>
</body>
</html>