<?php
header("Content-Type: application/json");

// Include database connection
require_once "../database.php";

// Check if it's a POST request
if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
    http_response_code(405);
    echo json_encode(["error" => "Only POST method allowed"]);
    exit;
}

// Get JSON input
$data = json_decode(file_get_contents("php://input"));

// Validate user ID and status
if (!isset($data->id) || !is_numeric($data->id) || !isset($data->status) || !in_array($data->status, ['active', 'blocked'])) {
    http_response_code(400);
    echo json_encode(["error" => "Invalid or missing user ID or status"]);
    exit;
}

$userId = intval($data->id);
$status = $data->status;

try {
    $stmt = $conn->prepare("UPDATE users SET status = :status WHERE id = :id");
    $stmt->bindParam(':status', $status, PDO::PARAM_STR);
    $stmt->bindParam(':id', $userId, PDO::PARAM_INT);
    $stmt->execute();

    if ($stmt->rowCount() > 0) {
        echo json_encode(["message" => "User " . ($status === 'blocked' ? "blocked" : "unblocked") . " successfully"]);
    } else {
        http_response_code(404);
        echo json_encode(["error" => "User not found"]);
    }
} catch (PDOException $e) {
    http_response_code(500);
    echo json_encode(["error" => "Failed to update user status", "details" => $e->getMessage()]);
}
?>