<?php
/**
 * ===================================================================================
 * Student Actions Handler (for Teachers)
 * ===================================================================================
 *
 * File: student_actions.php
 * Location: /homework_portal/teacher/student_actions.php
 *
 * Purpose:
 * 1. Handles actions like deleting a student account, initiated by a teacher.
 * 2. Contains security checks to ensure a teacher can only modify students
 * in their own assigned classes.
 */

require_once '../config.php';

// --- Security Check: Ensure teacher is logged in ---
if (!isset($_SESSION['teacher_id'])) {
    header('Location: login.php');
    exit();
}

$teacher_id = $_SESSION['teacher_id'];
$action = $_GET['action'] ?? '';
$student_id = isset($_GET['id']) ? (int)$_GET['id'] : 0;
$message_type = 'error';
$message = 'An unknown error occurred.';

if ($student_id > 0 && $action === 'delete') {
    try {
        // --- Ownership Verification ---
        // First, get the class_id of the student being deleted.
        $student_stmt = $pdo->prepare("SELECT class_id FROM students WHERE id = ?");
        $student_stmt->execute([$student_id]);
        $student = $student_stmt->fetch();

        if ($student) {
            $student_class_id = $student['class_id'];
            
            // Now, check if the logged-in teacher is assigned to that student's class.
            $permission_stmt = $pdo->prepare("SELECT COUNT(*) FROM teacher_subject_class WHERE teacher_id = ? AND class_id = ?");
            $permission_stmt->execute([$teacher_id, $student_class_id]);
            $has_permission = $permission_stmt->fetchColumn() > 0;

            if ($has_permission) {
                // If permission is confirmed, proceed with deletion.
                $delete_stmt = $pdo->prepare("DELETE FROM students WHERE id = ?");
                $delete_stmt->execute([$student_id]);
                
                $message = 'Student account has been deleted successfully.';
                $message_type = 'success';
            } else {
                $message = "You do not have permission to delete this student.";
            }
        } else {
            $message = "Student not found.";
        }
    } catch (PDOException $e) {
        $message = "Database error: Could not delete student.";
        // error_log($e->getMessage());
    }
} else {
    $message = "Invalid action or student ID.";
}

// Redirect back to the student management page with feedback.
header('Location: manage_students.php?' . $message_type . '=' . urlencode($message));
exit();
?>
