<?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 = '';
$classes = [];

// Get all classes for display
try {
    $stmt = $pdo->query("
        SELECT c.*, 
               t.first_name as teacher_first_name, 
               t.last_name as teacher_last_name,
               (SELECT COUNT(*) FROM students WHERE class_id = c.id AND status = 'active') as student_count
        FROM classes c
        LEFT JOIN teachers t ON c.class_teacher_id = t.id
        ORDER BY c.name, c.section
    ");
    $classes = $stmt->fetchAll(PDO::FETCH_ASSOC);
} catch (Exception $e) {
    $error = "ক্লাস আনতে গিয়ে একটি ত্রুটি হয়েছে: " . $e->getMessage();
}

// Handle class deletion
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['delete_class'])) {
    $class_ids = $_POST['class_ids'] ?? [];
    
    if (!empty($class_ids)) {
        try {
            $deleted_count = 0;
            
            foreach ($class_ids as $class_id) {
                $class_id = (int)$class_id;
                
                if ($class_id > 0) {
                    // Check if class has any ACTIVE students
                    $stmt = $pdo->prepare("SELECT COUNT(*) FROM students WHERE class_id = ? AND status = 'active'");
                    $stmt->execute([$class_id]);
                    $student_count = $stmt->fetchColumn();
                    
                    if ($student_count > 0) {
                        // Skip this class but continue with others
                        $error .= "ক্লাস ID $class_id এ ছাত্র-ছাত্রী আছে, তাই মুছে ফেলা যাবে না। ";
                        continue;
                    }
                    
                    $pdo->beginTransaction();
                    
                    // Set class_id to NULL for all students in this class (to satisfy foreign key constraint)
                    $stmt = $pdo->prepare("UPDATE students SET class_id = NULL WHERE class_id = ?");
                    $stmt->execute([$class_id]);
                    
                    // Delete class teachers
                    $stmt = $pdo->prepare("DELETE FROM class_teachers WHERE class_id = ?");
                    $stmt->execute([$class_id]);
                    
                    // Delete class subjects
                    $stmt = $pdo->prepare("DELETE FROM class_subjects WHERE class_id = ?");
                    $stmt->execute([$class_id]);
                    
                    // Delete class
                    $stmt = $pdo->prepare("DELETE FROM classes WHERE id = ?");
                    $stmt->execute([$class_id]);
                    
                    $pdo->commit();
                    $deleted_count++;
                }
            }
            
            if ($deleted_count > 0) {
                $message = "$deleted_count টি ক্লাস সফলভাবে মুছে ফেলা হয়েছে।";
            }
            
            // Refresh the class list
            $stmt = $pdo->query("
                SELECT c.*, 
                       t.first_name as teacher_first_name, 
                       t.last_name as teacher_last_name,
                       (SELECT COUNT(*) FROM students WHERE class_id = c.id AND status = 'active') as student_count
                FROM classes c
                LEFT JOIN teachers t ON c.class_teacher_id = t.id
                ORDER BY c.name, c.section
            ");
            $classes = $stmt->fetchAll(PDO::FETCH_ASSOC);
            
        } catch (Exception $e) {
            $pdo->rollBack();
            $error .= "ক্লাস মুছে ফেলতে সমস্যা হয়েছে: " . $e->getMessage();
        }
    } else {
        $error = "মুছে ফেলার জন্য কোনো ক্লাস নির্বাচন করা হয়নি।";
    }
}
?>

<!DOCTYPE html>
<html lang="bn">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>ক্লাস ডেটা রিসেট</title>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/css/bootstrap.min.css" rel="stylesheet">
    <link href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.0.0/css/all.min.css" rel="stylesheet">
    <link href="https://fonts.googleapis.com/css2?family=Hind+Siliguri:wght@300;400;500;600;700&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; }
        .class-list-table th { background-color: #f8f9fa; }
    </style>
</head>
<body>

<div class="page-header text-center">
    <div class="container">
        <h1><i class="fas fa-trash-alt"></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; ?>

            <!-- Class List -->
            <?php if (!empty($classes)): ?>
            <div class="card">
                <div class="card-header d-flex justify-content-between align-items-center">
                    <span><i class="fas fa-school"></i> ক্লাস তালিকা (মোট: <?php echo count($classes); ?>)</span>
                    <button type="button" class="btn btn-danger" onclick="showConfirmationModal()"><i class="fas fa-trash"></i> নির্বাচিত ক্লাস মুছে ফেলুন</button>
                </div>
                <div class="card-body p-0">
                    <form method="POST" action="" id="deleteForm">
                        <input type="hidden" name="delete_class" value="1">
                        <div class="table-responsive">
                            <table class="table table-striped table-hover class-list-table mb-0">
                                <thead>
                                    <tr>
                                        <th class="text-center" style="width: 5%;"><input type="checkbox" id="selectAll"></th>
                                        <th>ক্লাস</th>
                                        <th>শাখা</th>
                                        <th>ক্লাস শিক্ষক</th>
                                        <th>ছাত্র-ছাত্রী</th>
                                        <th>ধারণক্ষমতা</th>
                                        <th>স্ট্যাটাস</th>
                                    </tr>
                                </thead>
                                <tbody>
                                    <?php foreach ($classes as $class): ?>
                                    <tr>
                                        <td class="text-center">
                                            <?php if ($class['student_count'] == 0): ?>
                                                <input type="checkbox" name="class_ids[]" value="<?php echo $class['id']; ?>" class="class-checkbox">
                                            <?php else: ?>
                                                <i class="fas fa-lock text-danger" title="এই ক্লাসে ছাত্র-ছাত্রী আছে, তাই মুছে ফেলা যাবে না"></i>
                                            <?php endif; ?>
                                        </td>
                                        <td><?php echo htmlspecialchars($class['name']); ?></td>
                                        <td><?php echo !empty($class['section']) ? htmlspecialchars($class['section']) : '-'; ?></td>
                                        <td>
                                            <?php if ($class['teacher_first_name']): ?>
                                                <?php echo htmlspecialchars($class['teacher_first_name'] . ' ' . $class['teacher_last_name']); ?>
                                            <?php else: ?>
                                                <span class="text-muted">নির্ধারিত নয়</span>
                                            <?php endif; ?>
                                        </td>
                                        <td>
                                            <span class="badge bg-<?php echo ($class['student_count'] > 0) ? 'primary' : 'secondary'; ?>">
                                                <?php echo $class['student_count']; ?>
                                            </span>
                                        </td>
                                        <td><?php echo $class['capacity']; ?></td>
                                        <td>
                                            <span class="badge bg-<?php echo ($class['status'] == 'active') ? 'success' : 'secondary'; ?>">
                                                <?php echo ($class['status'] == 'active') ? 'সক্রিয়' : 'নিষ্ক্রিয়'; ?>
                                            </span>
                                        </td>
                                    </tr>
                                    <?php endforeach; ?>
                                </tbody>
                            </table>
                        </div>
                    </form>
                </div>
            </div>
            <?php else: ?>
            <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-danger" id="confirmDeleteBtn">নিশ্চিত করুন</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('.class-checkbox').forEach(checkbox => {
        checkbox.checked = e.target.checked;
    });
});

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

function showConfirmationModal() {
    const selectedClasses = document.querySelectorAll('.class-checkbox:checked').length;
    if (selectedClasses === 0) {
        alert('অনুগ্রহ করে অন্তত একটি ক্লাস নির্বাচন করুন।');
        return;
    }

    const message = `আপনি কি নিশ্চিত যে আপনি নির্বাচিত <strong>${selectedClasses}</strong> টি ক্লাস মুছে ফেলতে চান?`;
    
    document.getElementById('modal-message').innerHTML = message;
    confirmationModal.show();
}

document.getElementById('confirmDeleteBtn').addEventListener('click', function() {
    document.getElementById('deleteForm').submit();
});
</script>

</body>
</html>