<?php
/**
 * POST /api/admin/users_update_role.php
 * Body (JSON): { id, action } — action is 'promote' or 'demote'.
 *
 * promote: personal/business -> admin.
 * demote: admin -> back to whatever they originally were. This is
 * determined automatically from which profile table actually has a row
 * for them (see profile/me.php's docblock) rather than trusting an
 * arbitrary account_type value from the request - that would risk
 * mismatching account_type against the wrong profile shape.
 *
 * Safety: an admin can't change their own role (avoids accidental
 * self-lockout), and the last remaining admin can't be demoted (avoids
 * a zero-admin platform with no one able to fix it).
 */

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();
$actingAdminId = require_login();
require_role(['admin']);

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

if ($id <= 0 || !in_array($action, ['promote', 'demote'], true)) {
    send_error('A valid user id and action (promote|demote) are required.', 422);
}
if ($id === $actingAdminId) {
    send_error('You cannot change your own admin role.', 403);
}

$pdo = Database::connect();
$stmt = $pdo->prepare('SELECT id, account_type FROM users WHERE id = ?');
$stmt->execute([$id]);
$user = $stmt->fetch();

if (!$user) {
    send_error('User not found.', 404);
}

if ($action === 'promote') {
    if ($user['account_type'] === 'admin') {
        send_error('This user is already an admin.', 409);
    }
    $stmt = $pdo->prepare('UPDATE users SET account_type = "admin" WHERE id = ?');
    $stmt->execute([$id]);
    create_notification($pdo, $id, 'admin_promoted', 'You have been made an admin on Ragreen.');
    send_json(true, 'User promoted to admin.');
}

// --- demote ---
if ($user['account_type'] !== 'admin') {
    send_error('This user is not currently an admin.', 409);
}

$adminCount = (int) $pdo->query("SELECT COUNT(*) FROM users WHERE account_type = 'admin'")->fetchColumn();
if ($adminCount <= 1) {
    send_error('You cannot demote the last remaining admin.', 409);
}

$stmt = $pdo->prepare('SELECT 1 FROM personal_profiles WHERE user_id = ?');
$stmt->execute([$id]);
$restoredType = $stmt->fetchColumn() ? 'personal' : 'business';

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

send_json(true, "Admin access removed - account restored to $restoredType.");
