<?php
session_start();
require '../db.php';

header('Content-Type: application/json');

// Безопасность: Только администраторы могут редактировать пользователей
if (!isset($_SESSION['user_id']) || ($_SESSION['role'] !== 'admin' && $_SESSION['user_id'] != 1)) {
    echo json_encode(['status' => 'error', 'message' => 'Unauthorized']);
    exit;
}

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $target_user_id = intval($_POST['user_id']);
    $new_username = trim($_POST['username']);
    $new_email = trim($_POST['email']);
    $new_role = $_POST['role'] === 'admin' ? 'admin' : 'user';

    if (!$target_user_id) {
        echo json_encode(['status' => 'error', 'message' => 'Missing User ID']);
        exit;
    }

    // Защита: Нельзя понизить главного администратора (ID 1)
    if ($target_user_id == 1 && $new_role !== 'admin') {
        echo json_encode(['status' => 'error', 'message' => 'Cannot demote the main administrator']);
        exit;
    }

    try {
        $stmt = $pdo->prepare("UPDATE users SET username = ?, email = ?, role = ? WHERE id = ?");
        $stmt->execute([$new_username, $new_email, $new_role, $target_user_id]);

        echo json_encode(['status' => 'success', 'message' => 'User updated successfully']);
    } catch (PDOException $e) {
        echo json_encode(['status' => 'error', 'message' => 'Database error: ' . $e->getMessage()]);
    }
} else {
    echo json_encode(['status' => 'error', 'message' => 'Invalid request method']);
}
