<?php
session_start();

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

// Database connection
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "school_db";

try {
    $conn = new PDO("mysql:host=$servername;dbname=$dbname", $username, $password);
    $conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
} catch(PDOException $e) {
    error_log("Connection failed: " . $e->getMessage());
    header("Location: admin_page.php?error=Connection failed");
    exit();
}

// Function to log a message
function log_message($conn, $message, $created_by = 'System', $name = null, $email = null, $subject = null) {
    try {
        $stmt = $conn->prepare("INSERT INTO contact_messages (name, email, subject, message, timestamp, created_by) VALUES (?, ?, ?, ?, NOW(), ?)");
        $stmt->execute([$name, $email, $subject, $message, $created_by]);
    } catch(PDOException $e) {
        error_log("Message log error: " . $e->getMessage());
    }
}

// Handle deletion
if (isset($_POST['student_id'])) {
    $student_id = $_POST['student_id'];
    try {
        $stmt = $conn->prepare("SELECT name, grade FROM students WHERE id = ?");
        $stmt->execute([$student_id]);
        $student = $stmt->fetch(PDO::FETCH_ASSOC);

        if ($student) {
            $stmt = $conn->prepare("DELETE FROM students WHERE id = ?");
            $stmt->execute([$student_id]);
            log_message($conn, "Student deleted: {$student['name']} (Grade {$student['grade']})");
            header("Location: admin_page.php?success=Student deleted successfully");
        } else {
            header("Location: admin_page.php?error=Student not found");
        }
    } catch(PDOException $e) {
        error_log("Delete error: " . $e->getMessage());
        header("Location: admin_page.php?error=Failed to delete student");
    }
} else {
    header("Location: admin_page.php?error=Invalid request");
}
exit();
?>