<?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();
}
?>
<!DOCTYPE html>
<html lang="bn">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Direct Class Deletion</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; }
    </style>
</head>
<body>

<div class="page-header text-center">
    <div class="container">
        <h1><i class="fas fa-trash-alt"></i> Direct Class Deletion Tool</h1>
        <p class="lead">সরাসরি ডাটাবেস থেকে ক্লাস মুছে ফেলুন</p>
    </div>
</div>

<?php

function getAllClasses() {
    global $pdo;
    
    try {
        $stmt = $pdo->prepare("
            SELECT c.id, c.name, c.section, COUNT(s.id) as student_count 
            FROM classes c 
            LEFT JOIN students s ON c.id = s.class_id AND s.status = 'active' 
            GROUP BY c.id, c.name, c.section 
            ORDER BY c.name
        ");
        $stmt->execute();
        return $stmt->fetchAll(PDO::FETCH_ASSOC);
    } catch (Exception $e) {
        return [];
    }
}

function deleteClassDirectly($class_id) {
    global $pdo;
    
    try {
        // Validate class ID
        $class_id = (int)$class_id;
        if ($class_id <= 0) {
            return ['success' => false, 'message' => 'Invalid class ID'];
        }
        
        // Start transaction
        $pdo->beginTransaction();
        
        // First, check if class exists
        $stmt = $pdo->prepare("SELECT name, section FROM classes WHERE id = ?");
        $stmt->execute([$class_id]);
        $class = $stmt->fetch(PDO::FETCH_ASSOC);
        
        if (!$class) {
            $pdo->rollBack();
            return ['success' => false, 'message' => 'Class not found'];
        }
        
        // 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) {
            $pdo->rollBack();
            return ['success' => false, 'message' => "Cannot delete class '{$class['name']}' - it has $student_count active students"];
        }
        
        // Delete related records in proper order to respect foreign key constraints
        // 1. Delete class_subjects records
        $stmt = $pdo->prepare("DELETE FROM class_subjects WHERE class_id = ?");
        $stmt->execute([$class_id]);
        
        // 2. Delete class_teachers records
        $stmt = $pdo->prepare("DELETE FROM class_teachers WHERE class_id = ?");
        $stmt->execute([$class_id]);
        
        // 3. Delete the class itself
        $stmt = $pdo->prepare("DELETE FROM classes WHERE id = ?");
        $stmt->execute([$class_id]);
        
        // Commit transaction
        $pdo->commit();
        
        $class_name = $class['name'] . (!empty($class['section']) ? ' - ' . $class['section'] : '');
        return ['success' => true, 'message' => "Class '$class_name' deleted successfully"];
        
    } catch (Exception $e) {
        // Rollback transaction on error
        if ($pdo->inTransaction()) {
            $pdo->rollBack();
        }
        return ['success' => false, 'message' => 'Database error: ' . $e->getMessage()];
    }
}

$message = '';
$message_type = '';

// Handle POST request
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['class_id'])) {
    $result = deleteClassDirectly($_POST['class_id']);
    
    if ($result['success']) {
        $message = $result['message'];
        $message_type = 'success';
    } else {
        $message = $result['message'];
        $message_type = 'danger';
    }
}

$classes = getAllClasses();
?>

<div class="main-content">
    <div class="container-fluid">
        <div class="row">
            <div class="col-md-12">
                <div class="card">
                    <div class="card-header bg-danger text-white">
                        <h4><i class="fas fa-trash-alt"></i> Direct Class Deletion Tool</h4>
                        <p class="mb-0">সরাসরি ডাটাবেস থেকে ক্লাস মুছে ফেলুন</p>
                    </div>
                    <div class="card-body">
                        <?php if ($message): ?>
                            <div class="alert alert-<?php echo $message_type; ?> alert-dismissible fade show" role="alert">
                                <?php if ($message_type === 'success'): ?>
                                    <i class="fas fa-check-circle"></i>
                                <?php else: ?>
                                    <i class="fas fa-exclamation-triangle"></i>
                                <?php endif; ?>
                                <?php echo $message; ?>
                                <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
                            </div>
                        <?php endif; ?>
                        
                        <div class="alert alert-warning">
                            <i class="fas fa-exclamation-triangle"></i> 
                            <strong>সতর্কতা:</strong> এই টুলটি সরাসরি ডাটাবেস থেকে ক্লাস মুছে ফেলবে। ক্লাসে কোনো ছাত্র-ছাত্রী থাকলে তা মুছে ফেলা হবে না।
                        </div>
                        
                        <form method="POST" action="">
                            <div class="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 htmlspecialchars($class['name']); ?>
                                            <?php if (!empty($class['section'])): ?>
                                                - <?php echo htmlspecialchars($class['section']); ?>
                                            <?php endif; ?>
                                            (<?php echo $class['student_count']; ?> students)
                                            <?php if ($class['student_count'] == 0): ?>
                                                - [মুছে ফেলা যাবে]
                                            <?php else: ?>
                                                - [মুছে ফেলা যাবে না]
                                            <?php endif; ?>
                                        </option>
                                    <?php endforeach; ?>
                                </select>
                                <div class="form-text">শুধুমাত্র ছাত্র-ছাত্রী নেই এমন ক্লাস মুছে ফেলা যাবে</div>
                            </div>
                            
                            <button type="submit" class="btn btn-danger" onclick="return confirm('আপনি কি নিশ্চিতভাবে এই ক্লাসটি মুছে ফেলতে চান?')">
                                <i class="fas fa-trash"></i> ক্লাস মুছে ফেলুন
                            </button>
                            
                            <a href="../classes/manage.php" class="btn btn-secondary">
                                <i class="fas fa-arrow-left"></i> ক্লাস ম্যানেজমেন্ট পেজে ফিরে যান
                            </a>
                        </form>
                        
                        <div class="mt-4">
                            <h5>ক্লাস তালিকা:</h5>
                            <table class="table table-striped">
                                <thead>
                                    <tr>
                                        <th>ক্লাস আইডি</th>
                                        <th>ক্লাসের নাম</th>
                                        <th>শাখা</th>
                                        <th>ছাত্র-ছাত্রী সংখ্যা</th>
                                        <th>মুছে ফেলা যাবে?</th>
                                    </tr>
                                </thead>
                                <tbody>
                                    <?php foreach ($classes as $class): ?>
                                        <tr>
                                            <td><?php echo $class['id']; ?></td>
                                            <td><?php echo htmlspecialchars($class['name']); ?></td>
                                            <td><?php echo htmlspecialchars($class['section'] ?? ''); ?></td>
                                            <td><?php echo $class['student_count']; ?></td>
                                            <td>
                                                <?php if ($class['student_count'] == 0): ?>
                                                    <span class="badge bg-success">হ্যাঁ</span>
                                                <?php else: ?>
                                                    <span class="badge bg-danger">না</span>
                                                <?php endif; ?>
                                            </td>
                                        </tr>
                                    <?php endforeach; ?>
                                </tbody>
                            </table>
                        </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>
    // Add any additional JavaScript here if needed
</script>

</body>
</html>