<?php
require_once 'config/database.php';

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

// Handle POST request
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['class_id'])) {
    $result = deleteClassDirectly($_POST['class_id']);
    
    if ($result['success']) {
        echo json_encode(['status' => 'success', 'message' => $result['message']]);
    } else {
        echo json_encode(['status' => 'error', 'message' => $result['message']]);
    }
    exit;
}

// Display form for manual deletion
?>
<!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">
</head>
<body>
    <div class="container mt-5">
        <div class="row justify-content-center">
            <div class="col-md-8">
                <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">
                        <div class="alert alert-warning">
                            <i class="fas fa-exclamation-triangle"></i> 
                            <strong>সতর্কতা:</strong> এই টুলটি সরাসরি ডাটাবেস থেকে ক্লাস মুছে ফেলবে। ক্লাসে কোনো ছাত্র-ছাত্রী থাকলে তা মুছে ফেলা হবে না।
                        </div>
                        
                        <form id="deleteForm">
                            <div class="mb-3">
                                <label for="class_id" class="form-label">ক্লাস আইডি <span class="text-danger">*</span></label>
                                <input type="number" class="form-control" id="class_id" name="class_id" required min="1">
                                <div class="form-text">মুছে ফেলতে চাওয়া ক্লাসের আইডি লিখুন</div>
                            </div>
                            
                            <button type="submit" class="btn btn-danger">
                                <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 id="result" class="mt-4"></div>
                    </div>
                </div>
            </div>
        </div>
    </div>

    <script>
        document.getElementById('deleteForm').addEventListener('submit', function(e) {
            e.preventDefault();
            
            const classId = document.getElementById('class_id').value;
            if (!classId || classId <= 0) {
                alert('দয়া করে একটি বৈধ ক্লাস আইডি লিখুন');
                return;
            }
            
            // Confirm deletion
            if (!confirm('আপনি কি নিশ্চিতভাবে এই ক্লাসটি মুছে ফেলতে চান?')) {
                return;
            }
            
            // Show loading
            document.getElementById('result').innerHTML = '<div class="alert alert-info"><i class="fas fa-spinner fa-spin"></i> মুছে ফেলা হচ্ছে...</div>';
            
            // Submit form via AJAX
            const formData = new FormData(this);
            
            fetch('direct_class_delete.php', {
                method: 'POST',
                body: formData
            })
            .then(response => response.json())
            .then(data => {
                if (data.status === 'success') {
                    document.getElementById('result').innerHTML = '<div class="alert alert-success"><i class="fas fa-check-circle"></i> ' + data.message + '</div>';
                    document.getElementById('class_id').value = '';
                } else {
                    document.getElementById('result').innerHTML = '<div class="alert alert-danger"><i class="fas fa-exclamation-triangle"></i> ' + data.message + '</div>';
                }
            })
            .catch(error => {
                document.getElementById('result').innerHTML = '<div class="alert alert-danger"><i class="fas fa-exclamation-triangle"></i> ত্রুটি: ' + error.message + '</div>';
            });
        });
    </script>
</body>
</html>