<?php
// 1. INITIAL SETUP
session_start();
// The path is ../../ because this file is inside the 'actions' sub-folder
require_once '../../includes/db.php'; 

// 2. SECURITY CHECK
// Ensure an admin is logged in before proceeding.
if (!isset($_SESSION['admin_logged_in'])) {
    // If not logged in, redirect to the login page.
    header("Location: ../login.php");
    exit;
}

// 3. VALIDATE INPUTS
// Get the comment ID and the new status from the URL and validate them.
$comment_id = filter_input(INPUT_GET, 'id', FILTER_VALIDATE_INT);
$new_status = $_GET['status'] ?? '';

// Create a list of allowed statuses to prevent malicious input.
$allowed_statuses = ['approved', 'pending', 'spam'];

// If the inputs are not valid, set an error message and redirect.
if (!$comment_id || !in_array($new_status, $allowed_statuses)) {
    $_SESSION['error_message'] = "Invalid action or comment ID provided.";
    header("Location: ../manage-comments.php");
    exit();
}

// 4. UPDATE THE DATABASE
// If validation passes, prepare and execute the database update.
$stmt = $conn->prepare("UPDATE comments SET status = ? WHERE id = ?");
$stmt->bind_param("si", $new_status, $comment_id);

if ($stmt->execute()) {
    // On success, set a success message.
    $_SESSION['success_message'] = "Comment status has been updated to '" . ucfirst($new_status) . "'.";
} else {
    // On failure, set an error message.
    $_SESSION['error_message'] = "Database error: Could not update the comment status.";
}
$stmt->close();

// 5. REDIRECT BACK
// Redirect the admin back to the comment management page.
header("Location: ../manage-comments.php");
exit();
?>
