<?php
/**
 * POST /api/admin/users_update_status.php
 * Body (JSON): { id, status } — status must be 'active' or 'suspended'.
 * Admins cannot change their own status here, to avoid accidentally locking
 * themselves out of the admin panel.
 */

require_once __DIR__ . '/../config/database.php';
require_once __DIR__ . '/../includes/response.php';
require_once __DIR__ . '/../includes/auth.php';
require_once __DIR__ . '/../includes/notifications.php';

only_post_allowed();
$adminId = require_login();
require_role(['admin']);

$input = get_json_input();
$id = (int) ($input['id'] ?? 0);
$status = $input['status'] ?? '';

if ($id <= 0 || !in_array($status, ['active', 'suspended'], true)) {
    send_error('A valid user id and status (active|suspended) are required.', 422);
}
if ($id === $adminId) {
    send_error('You cannot change your own account status.', 403);
}

$pdo = Database::connect();
$stmt = $pdo->prepare('SELECT id FROM users WHERE id = ?');
$stmt->execute([$id]);
if (!$stmt->fetch()) {
    send_error('User not found.', 404);
}

$stmt = $pdo->prepare('UPDATE users SET status = ? WHERE id = ?');
$stmt->execute([$status, $id]);

if ($status === 'active') {
    create_notification($pdo, $id, 'account_reactivated', 'Your account has been reactivated. Welcome back!');
}

send_json(true, 'User status updated.');
