<?php
session_start();

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['news_id'])) {
    $news_id = $_POST['news_id'];
    try {
        $stmt = $conn->prepare("SELECT title FROM news WHERE id = ?");
        $stmt->execute([$news_id]);
        $news = $stmt->fetch(PDO::FETCH_ASSOC);

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