<?php
require_once '../includes/header.php';
require_once '../includes/require_admin.php';

// Only allow POST requests
if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
    redirect(SITE_URL . '/admin/manage_users.php');
}

// Get data from POST
$user_id = isset($_POST['user_id']) ? intval($_POST['user_id']) : 0;
$action = isset($_POST['action']) ? sanitizeInput($_POST['action']) : '';

// Validate input
if ($user_id <= 0 || !in_array($action, ['promote', 'demote'])) {
    $_SESSION['error_message'] = "Invalid request.";
    redirect(SITE_URL . '/admin/manage_users.php');
}

// Prevent users from modifying themselves
if ($user_id == $_SESSION['user_id']) {
    $_SESSION['error_message'] = "You cannot modify your own account.";
    redirect(SITE_URL . '/admin/manage_users.php');
}

try {
    if ($action === 'promote') {
        $stmt = $pdo->prepare("UPDATE users SET role = 'admin' WHERE id = ?");
        $stmt->execute([$user_id]);
        $_SESSION['success_message'] = "User promoted to admin successfully.";
    } elseif ($action === 'demote') {
        $stmt = $pdo->prepare("UPDATE users SET role = 'user' WHERE id = ?");
        $stmt->execute([$user_id]);
        $_SESSION['success_message'] = "Admin demoted to user successfully.";
    }
} catch (PDOException $e) {
    $_SESSION['error_message'] = "Error processing request: " . $e->getMessage();
}

redirect(SITE_URL . '/admin/manage_users.php');
?>