Path : /home/vishqocm/pcib.in/admin/
File Upload :
Current File : /home/vishqocm/pcib.in/admin/delete_student.php

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

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

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $student_id = (int)$_POST['student_id'];
    
    // Start transaction
    $conn->begin_transaction();
    
    try {
        // Check if student exists and is actually a student
        $stmt = $conn->prepare("SELECT id FROM users WHERE id = ? AND role = 'student'");
        $stmt->bind_param("i", $student_id);
        $stmt->execute();
        if ($stmt->get_result()->num_rows === 0) {
            throw new Exception("Student not found");
        }
        
        // Delete student's enrollments
        $stmt = $conn->prepare("DELETE FROM enrollments WHERE user_id = ?");
        $stmt->bind_param("i", $student_id);
        $stmt->execute();
        
        // Delete student's submissions
        $stmt = $conn->prepare("DELETE FROM submissions WHERE user_id = ?");
        $stmt->bind_param("i", $student_id);
        $stmt->execute();
        
        // Delete student's payments
        $stmt = $conn->prepare("DELETE FROM payments WHERE user_id = ?");
        $stmt->bind_param("i", $student_id);
        $stmt->execute();
        
        // Finally, delete the student
        $stmt = $conn->prepare("DELETE FROM users WHERE id = ? AND role = 'student'");
        $stmt->bind_param("i", $student_id);
        $stmt->execute();
        
        if ($stmt->affected_rows > 0) {
            $conn->commit();
            $_SESSION['success_message'] = "Student deleted successfully";
        } else {
            throw new Exception("Failed to delete student");
        }
    } catch (Exception $e) {
        $conn->rollback();
        $_SESSION['error_message'] = "Error deleting student: " . $e->getMessage();
    }
}

header('Location: students.php');
exit();