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

$message = '';
$error = '';
$students = [];

// Get filter parameters from URL
$session = $_GET['session'] ?? '';
$class_id = $_GET['class_id'] ?? '';
$group = $_GET['group'] ?? '';
$exam_type_filter = $_GET['exam_type'] ?? 'all';

// Fetch data for dropdowns
$sessions = $pdo->query("SELECT DISTINCT session FROM students ORDER BY session DESC")->fetchAll(PDO::FETCH_COLUMN);
$classes = $pdo->query("SELECT id, name, section FROM classes ORDER BY name")->fetchAll(PDO::FETCH_ASSOC);
$groups = $pdo->query("SELECT DISTINCT group_name FROM students WHERE group_name IS NOT NULL AND group_name != '' ORDER BY group_name")->fetchAll(PDO::FETCH_COLUMN);
$exam_types = $pdo->query("SELECT DISTINCT exam_type FROM results WHERE exam_type IS NOT NULL AND exam_type != '' ORDER BY exam_type")->fetchAll(PDO::FETCH_COLUMN);


// Handle data reset action
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['reset_action'])) {
    $student_ids = $_POST['student_ids'] ?? [];
    $reset_action = $_POST['reset_action'];
    $exam_type = $_POST['exam_type'] ?? 'all';

    if (!empty($student_ids)) {
        try {
            $student_id_placeholders = implode(',', array_fill(0, count($student_ids), '?'));

            if ($reset_action === 'reset_marks') {
                $params = $student_ids;
                $sql = "DELETE FROM results WHERE student_id IN ($student_id_placeholders)";
                if ($exam_type !== 'all') {
                    $sql .= " AND exam_type = ?";
                    $params[] = $exam_type;
                }
                $delete_stmt = $pdo->prepare($sql);
                $delete_stmt->execute($params);
                $message = count($student_ids) . " জন শিক্ষার্থীর " . ($exam_type === 'all' ? 'সকল' : htmlspecialchars($exam_type)) . " পরীক্ষার মার্কস সফলভাবে মুছে ফেলা হয়েছে।";
            } elseif ($reset_action === 'reset_subjects') {
                $delete_stmt = $pdo->prepare("DELETE FROM student_subjects WHERE student_id IN ($student_id_placeholders)");
                $delete_stmt->execute($student_ids);
                $message = count($student_ids) . " জন শিক্ষার্থীর বিষয় সফলভাবে মুছে ফেলা হয়েছে।";
            } elseif ($reset_action === 'reset_fees') {
                $session = $_POST['session'] ?? '';
                if (empty($session)) {
                    throw new Exception("সেশন পাওয়া যায়নি।");
                }
                $stmt = $pdo->prepare("SELECT id FROM fees WHERE student_id IN ($student_id_placeholders) AND academic_year = ?");
                $stmt->execute(array_merge($student_ids, [$session]));
                $fee_ids = $stmt->fetchAll(PDO::FETCH_COLUMN);

                if (!empty($fee_ids)) {
                    $fee_ph = implode(',', array_fill(0, count($fee_ids), '?'));
                    $stmt = $pdo->prepare("DELETE FROM fee_payments WHERE fee_id IN ($fee_ph)");
                    $stmt->execute($fee_ids);
                    $stmt = $pdo->prepare("DELETE FROM fees WHERE id IN ($fee_ph)");
                    $stmt->execute($fee_ids);
                }
                $message = count($student_ids) . " জন শিক্ষার্থীর " . htmlspecialchars($session) . " সেশনের ফি সফলভাবে মুছে ফেলা হয়েছে।";
            }
        } catch (Exception $e) {
            $error = "একটি ত্রুটি হয়েছে: " . $e->getMessage();
        }
    } else {
        $error = "রিসেট করার জন্য কোনো শিক্ষার্থী নির্বাচন করা হয়নি।";
    }
}

// Fetch students if filters are set
if ($session && $class_id) {
    try {
        $sql = "SELECT s.id, s.first_name, s.last_name, s.roll_number FROM students s WHERE s.session = :session AND s.class_id = :class_id";
        $params = ['session' => $session, 'class_id' => $class_id];
        if ($group && $group !== 'all') {
            $sql .= " AND group_name = :group";
            $params['group'] = $group;
        }
        $sql .= " ORDER BY roll_number";
        $stmt = $pdo->prepare($sql);
        $stmt->execute($params);
        $students = $stmt->fetchAll(PDO::FETCH_ASSOC);
    } catch (Exception $e) {
        $error = "শিক্ষার্থী আনতে গিয়ে একটি ত্রুটি হয়েছে: " . $e->getMessage();
    }
}

?>

<!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; }
        .page-header { background: linear-gradient(135deg, #667eea 0%, #764ba2 100%); color: white; padding: 2rem 0; margin-bottom: 2rem; }
        .card { border: none; border-radius: 15px; box-shadow: 0 5px 15px rgba(0,0,0,0.08); margin-bottom: 2rem; }
        .card-header { background-color: #fff; border-bottom: 1px solid #eee; font-weight: 600; font-size: 1.2rem; padding: 1rem 1.5rem; }
        .form-label { font-weight: 500; }
        .student-list-table th { background-color: #f8f9fa; }
    </style>
</head>
<body>

<div class="page-header text-center">
    <div class="container">
        <h1><i class="fas fa-undo"></i> শিক্ষার্থী ডেটা রিসেট</h1>
        <p class="lead">সেশন, শ্রেণি, পরীক্ষা এবং গ্রুপ অনুসারে শিক্ষার্থীর ডেটা রিসেট করুন</p>
    </div>
</div>

<div class="container">
    <div class="row justify-content-center">
        <div class="col-lg-12">

            <?php if ($message): ?>
                <div class="alert alert-success alert-dismissible fade show" role="alert"><i class="fas fa-check-circle"></i> <?php echo $message; ?><button type="button" class="btn-close" data-bs-dismiss="alert" aria-label="Close"></button></div>
            <?php endif; ?>
            <?php if ($error): ?>
                <div class="alert alert-danger alert-dismissible fade show" role="alert"><i class="fas fa-exclamation-triangle"></i> <?php echo $error; ?><button type="button" class="btn-close" data-bs-dismiss="alert" aria-label="Close"></button></div>
            <?php endif; ?>

            <!-- Filter Card -->
            <div class="card">
                <div class="card-header"><i class="fas fa-filter"></i> ফিল্টার শিক্ষার্থী</div>
                <div class="card-body p-4">
                    <form method="GET" action="">
                        <div class="row">
                            <div class="col-md-3 mb-3">
                                <label for="session" class="form-label">সেশন</label>
                                <select name="session" id="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-3 mb-3">
                                <label for="class_id" class="form-label">শ্রেণি</label>
                                <select name="class_id" id="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-3 mb-3">
                                <label for="exam_type" class="form-label">পরীক্ষা (মার্কস রিসেটের জন্য)</label>
                                <select name="exam_type" id="exam_type" class="form-select">
                                    <option value="all">সকল পরীক্ষা</option>
                                    <?php foreach ($exam_types as $exam): ?>
                                        <option value="<?php echo htmlspecialchars($exam); ?>" <?php echo ($exam_type_filter === $exam) ? 'selected' : ''; ?>><?php echo htmlspecialchars(ucfirst(str_replace('_', ' ', $exam))); ?></option>
                                    <?php endforeach; ?>
                                </select>
                            </div>
                            <div class="col-md-3 mb-3">
                                <label for="group" class="form-label">গ্রুপ</label>
                                <select name="group" id="group" class="form-select">
                                    <option value="all">সকল গ্রুপ</option>
                                    <?php foreach ($groups as $grp): ?>
                                        <option value="<?php echo htmlspecialchars($grp); ?>" <?php echo ($group === $grp) ? 'selected' : ''; ?>><?php echo htmlspecialchars($grp); ?></option>
                                    <?php endforeach; ?>
                                </select>
                            </div>
                        </div>
                        <div class="text-center mt-3">
                            <button type="submit" class="btn btn-primary btn-lg"><i class="fas fa-search"></i> শিক্ষার্থী খুঁজুন</button>
                        </div>
                    </form>
                </div>
            </div>

            <!-- Student List and Reset Actions -->
            <?php if (!empty($students)): ?>
            <div class="card">
                <div class="card-header d-flex justify-content-between align-items-center">
                    <span><i class="fas fa-users"></i> শিক্ষার্থী তালিকা (মোট: <?php echo count($students); ?>)</span>
                    <div>
                        <button type="button" class="btn btn-warning" onclick="showConfirmationModal('reset_marks')"><i class="fas fa-eraser"></i> নির্বাচিতদের মার্কস রিসেট</button>
                        <button type="button" class="btn btn-info" onclick="showConfirmationModal('reset_fees')"><i class="fas fa-money-bill-wave"></i> নির্বাচিতদের ফি রিসেট</button>
                        <button type="button" class="btn btn-danger" onclick="showConfirmationModal('reset_subjects')"><i class="fas fa-book"></i> নির্বাচিতদের বিষয় রিসেট</button>
                    </div>
                </div>
                <div class="card-body p-0">
                    <form method="POST" action="" id="resetForm">
                        <input type="hidden" name="reset_action" id="reset_action">
                        <input type="hidden" name="session" value="<?php echo htmlspecialchars($session); ?>">
                        <input type="hidden" name="exam_type" id="form_exam_type" value="<?php echo htmlspecialchars($exam_type_filter); ?>">
                        <div class="table-responsive">
                            <table class="table table-striped table-hover student-list-table mb-0">
                                <thead>
                                    <tr>
                                        <th class="text-center" style="width: 5%;"><input type="checkbox" id="selectAll"></th>
                                        <th>রোল</th>
                                        <th>নাম</th>
                                    </tr>
                                </thead>
                                <tbody>
                                    <?php foreach ($students as $student): ?>
                                    <tr>
                                        <td class="text-center"><input type="checkbox" name="student_ids[]" value="<?php echo $student['id']; ?>" class="student-checkbox"></td>
                                        <td><?php echo htmlspecialchars($student['roll_number']); ?></td>
                                        <td><?php echo htmlspecialchars($student['first_name'] . ' ' . $student['last_name']); ?></td>
                                    </tr>
                                    <?php endforeach; ?>
                                </tbody>
                            </table>
                        </div>
                    </form>
                </div>
            </div>
            <?php elseif(isset($_GET['session'])): ?>
            <div class="alert alert-info text-center"><i class="fas fa-info-circle"></i> আপনার নির্বাচিত ফিল্টারে কোনো শিক্ষার্থী পাওয়া যায়নি।</div>
            <?php endif; ?>

        </div>
    </div>
</div>

<!-- Confirmation Modal -->
<div class="modal fade" id="confirmationModal" tabindex="-1">
    <div class="modal-dialog">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title">নিশ্চিতকরণ</h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
            </div>
            <div class="modal-body">
                <p id="modal-message"></p>
                <p class="text-danger"><strong>সতর্কতা:</strong> এই কাজটি ফিরিয়ে আনা যাবে না। আপনি কি নিশ্চিত?</p>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">বাতিল</button>
                <button type="button" class="btn btn-primary" id="confirmResetBtn">নিশ্চিত করুন</button>
            </div>
        </div>
    </div>
</div>

<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/js/bootstrap.bundle.min.js"></script>
<script>
document.getElementById('selectAll')?.addEventListener('change', function(e) {
    document.querySelectorAll('.student-checkbox').forEach(checkbox => {
        checkbox.checked = e.target.checked;
    });
});

let currentAction = '';
const confirmationModal = new bootstrap.Modal(document.getElementById('confirmationModal'));

function showConfirmationModal(action) {
    const selectedStudents = document.querySelectorAll('.student-checkbox:checked').length;
    if (selectedStudents === 0) {
        alert('অনুগ্রহ করে অন্তত একজন শিক্ষার্থী নির্বাচন করুন।');
        return;
    }

    currentAction = action;
    let actionText = '';
    let examSelect = document.getElementById('exam_type');
    let selectedExamText = examSelect.options[examSelect.selectedIndex].text;

    if (action === 'reset_marks') {
        actionText = `<strong>${selectedExamText}</strong> পরীক্ষার মার্কস`;
    } else if (action === 'reset_subjects') {
        actionText = 'বিষয়';
    } else if (action === 'reset_fees') {
        actionText = 'ফি';
    }
    const message = `আপনি কি নিশ্চিত যে আপনি নির্বাচিত <strong>${selectedStudents}</strong> জন শিক্ষার্থীর ${actionText} মুছে ফেলতে চান?`;
    
    document.getElementById('modal-message').innerHTML = message;
    confirmationModal.show();
}

document.getElementById('confirmResetBtn').addEventListener('click', function() {
    document.getElementById('reset_action').value = currentAction;
    document.getElementById('resetForm').submit();
});
</script>

</body>
</html>