<?php
require_once __DIR__ . '/../includes/bootstrap.php';
require_once __DIR__ . '/_helpers.php';
require_admin();

$current_admin = User::current();

// İşlem
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    if (!csrf_check($_POST['csrf_token'] ?? null)) {
        flash_set('error', __('err_csrf'));
        redirect(APP_URL . '/admin/users.php');
    }

    $action  = $_POST['action'] ?? '';
    $userId  = (int)($_POST['user_id'] ?? 0);
    $target  = User::findById($userId);

    if (!$target) {
        flash_set('error', __('error'));
        redirect(APP_URL . '/admin/users.php');
    }

    // Kendine işlem yapma kontrolü
    if ($userId === (int)$current_admin['id'] && in_array($action, ['ban', 'remove_admin', 'delete'], true)) {
        flash_set('error', __('error') . ': cannot do this on yourself');
        redirect(APP_URL . '/admin/users.php?id=' . $userId);
    }

    switch ($action) {
        case 'ban':
            $reason = trim((string)($_POST['ban_reason'] ?? 'No reason'));
            DB::execute("UPDATE users SET is_banned = 1, ban_reason = :r WHERE id = :u",
                [':r' => $reason, ':u' => $userId]);
            admin_log('user_ban', $userId, "Banned: {$target['name']} – {$reason}");
            flash_set('success', __('admin_action_done'));
            break;

        case 'unban':
            DB::execute("UPDATE users SET is_banned = 0, ban_reason = NULL WHERE id = :u", [':u' => $userId]);
            admin_log('user_unban', $userId, "Unbanned: {$target['name']}");
            flash_set('success', __('admin_action_done'));
            break;

        case 'give_gold':
            $amount = (int)($_POST['amount'] ?? 0);
            DB::execute("UPDATE users SET gold = gold + :a WHERE id = :u",
                [':a' => $amount, ':u' => $userId]);
            admin_log('give_gold', $userId, "Gave {$amount} gold to {$target['name']}");
            flash_set('success', __('admin_action_done'));
            break;

        case 'give_stones':
            $amount = (int)($_POST['amount'] ?? 0);
            DB::execute("UPDATE users SET hellstones = hellstones + :a WHERE id = :u",
                [':a' => $amount, ':u' => $userId]);
            admin_log('give_stones', $userId, "Gave {$amount} hellstones to {$target['name']}");
            flash_set('success', __('admin_action_done'));
            break;

        case 'set_level':
            $level = max(1, (int)($_POST['level'] ?? 1));
            $exp = User::expForLevel($level);
            DB::execute("UPDATE users SET exp = :e WHERE id = :u",
                [':e' => $exp, ':u' => $userId]);
            admin_log('set_level', $userId, "Set level {$level} for {$target['name']}");
            flash_set('success', __('admin_action_done'));
            break;

        case 'make_admin':
            DB::execute("UPDATE users SET is_admin = 1 WHERE id = :u", [':u' => $userId]);
            admin_log('make_admin', $userId, "Made {$target['name']} an admin");
            flash_set('success', __('admin_action_done'));
            break;

        case 'remove_admin':
            DB::execute("UPDATE users SET is_admin = 0 WHERE id = :u", [':u' => $userId]);
            admin_log('remove_admin', $userId, "Removed admin from {$target['name']}");
            flash_set('success', __('admin_action_done'));
            break;

        case 'delete':
            DB::execute("DELETE FROM users WHERE id = :u", [':u' => $userId]);
            admin_log('delete_user', $userId, "Deleted user {$target['name']}");
            flash_set('success', __('admin_action_done'));
            redirect(APP_URL . '/admin/users.php');
    }
    redirect(APP_URL . '/admin/users.php?id=' . $userId);
}

// Tek kullanıcı detayı
$detailUser = null;
if (isset($_GET['id'])) {
    $detailUser = User::findById((int)$_GET['id']);
}

// Liste
$search = trim((string)($_GET['q'] ?? ''));
if ($search !== '') {
    $users = DB::fetchAll(
        "SELECT * FROM users
         WHERE name LIKE :q OR email LIKE :q
         ORDER BY id DESC LIMIT 50",
        [':q' => "%{$search}%"]
    );
} else {
    $users = DB::fetchAll(
        "SELECT * FROM users ORDER BY id DESC LIMIT 50"
    );
}

$page_title = __('admin_users');
require __DIR__ . '/_header.php';
?>

<h1>👥 <?= e(__('admin_users')) ?></h1>

<?php if ($detailUser): ?>
    <div class="card">
        <h3>
            <?= e($detailUser['name']) ?>
            <?php if ((int)$detailUser['is_admin']): ?><span class="badge badge-admin">ADMIN</span><?php endif; ?>
            <?php if ((int)$detailUser['is_banned']): ?><span class="badge badge-banned">BANNED</span><?php endif; ?>
        </h3>
        <p>📧 <?= e($detailUser['email']) ?></p>
        <p>💰 <?= format_number((int)$detailUser['gold']) ?> · 🔥 <?= format_number((int)$detailUser['hellstones']) ?></p>
        <p><?= __('level') ?>: <?= User::calculateLevel((int)$detailUser['exp']) ?> · EXP: <?= format_number((int)$detailUser['exp']) ?></p>
        <p>🕐 <?= format_datetime((int)$detailUser['created_at']) ?> | <?= __('last_active') ?? 'last' ?>: <?= format_datetime((int)$detailUser['last_active']) ?></p>

        <?php if ((int)$detailUser['is_banned']): ?>
            <p class="text-danger">⛔ <?= e($detailUser['ban_reason'] ?? '') ?></p>
        <?php endif; ?>
    </div>

    <div style="display:grid; grid-template-columns: 1fr 1fr; gap:1rem;">
        <!-- Ban / Unban -->
        <form method="post" class="card">
            <?= csrf_field() ?>
            <input type="hidden" name="user_id" value="<?= (int)$detailUser['id'] ?>">
            <h4><?= __('admin_user_ban') ?> / <?= __('admin_user_unban') ?></h4>
            <?php if ((int)$detailUser['is_banned']): ?>
                <button type="submit" name="action" value="unban" class="btn btn-success">
                    ✓ <?= __('admin_user_unban') ?>
                </button>
            <?php else: ?>
                <input type="text" name="ban_reason" placeholder="<?= __('warning') ?>..." class="mb-1" style="margin-bottom:0.5rem;">
                <button type="submit" name="action" value="ban" class="btn btn-danger">
                    ⛔ <?= __('admin_user_ban') ?>
                </button>
            <?php endif; ?>
        </form>

        <!-- Altın -->
        <form method="post" class="card">
            <?= csrf_field() ?>
            <input type="hidden" name="user_id" value="<?= (int)$detailUser['id'] ?>">
            <h4><?= __('admin_give_gold') ?></h4>
            <input type="number" name="amount" value="1000" required style="margin-bottom:0.5rem;">
            <button type="submit" name="action" value="give_gold"><?= __('admin_give_gold') ?></button>
        </form>

        <!-- Cehennem taşı -->
        <form method="post" class="card">
            <?= csrf_field() ?>
            <input type="hidden" name="user_id" value="<?= (int)$detailUser['id'] ?>">
            <h4><?= __('admin_give_stones') ?></h4>
            <input type="number" name="amount" value="100" required style="margin-bottom:0.5rem;">
            <button type="submit" name="action" value="give_stones"><?= __('admin_give_stones') ?></button>
        </form>

        <!-- Seviye -->
        <form method="post" class="card">
            <?= csrf_field() ?>
            <input type="hidden" name="user_id" value="<?= (int)$detailUser['id'] ?>">
            <h4><?= __('admin_set_level') ?></h4>
            <input type="number" name="level" value="<?= User::calculateLevel((int)$detailUser['exp']) ?>" min="1" required style="margin-bottom:0.5rem;">
            <button type="submit" name="action" value="set_level"><?= __('admin_set_level') ?></button>
        </form>

        <!-- Admin yetkisi -->
        <form method="post" class="card">
            <?= csrf_field() ?>
            <input type="hidden" name="user_id" value="<?= (int)$detailUser['id'] ?>">
            <h4>👑 Admin</h4>
            <?php if ((int)$detailUser['is_admin']): ?>
                <button type="submit" name="action" value="remove_admin" class="btn btn-secondary"
                        <?= (int)$detailUser['id'] === (int)$current_admin['id'] ? 'disabled' : '' ?>>
                    <?= __('admin_remove_admin') ?>
                </button>
            <?php else: ?>
                <button type="submit" name="action" value="make_admin" class="btn btn-success">
                    <?= __('admin_make_admin') ?>
                </button>
            <?php endif; ?>
        </form>

        <!-- Sil -->
        <form method="post" class="card" onsubmit="return confirm('<?= e(__('admin_confirm_delete')) ?>')">
            <?= csrf_field() ?>
            <input type="hidden" name="user_id" value="<?= (int)$detailUser['id'] ?>">
            <h4 class="text-danger">⚠ <?= __('admin_delete_user') ?></h4>
            <button type="submit" name="action" value="delete" class="btn btn-danger"
                    <?= (int)$detailUser['id'] === (int)$current_admin['id'] ? 'disabled' : '' ?>>
                🗑 <?= __('admin_delete_user') ?>
            </button>
        </form>
    </div>
    <p class="mt-1"><a href="<?= APP_URL ?>/admin/users.php">← <?= __('back') ?></a></p>
<?php else: ?>
    <form method="get" style="margin-bottom:1rem;">
        <input type="text" name="q" value="<?= e($search) ?>" placeholder="<?= __('search') ?>..." style="max-width:400px; display:inline-block;">
        <button type="submit" class="btn btn-sm"><?= __('search') ?></button>
    </form>

    <table class="tbl">
        <thead>
            <tr>
                <th>ID</th>
                <th><?= __('username') ?></th>
                <th><?= __('email') ?></th>
                <th><?= __('level') ?></th>
                <th><?= __('gold') ?></th>
                <th>Status</th>
                <th></th>
            </tr>
        </thead>
        <tbody>
            <?php foreach ($users as $u):
                $lvl = User::calculateLevel((int)$u['exp']);
            ?>
            <tr>
                <td><?= (int)$u['id'] ?></td>
                <td>
                    <img src="<?= APP_URL ?>/assets/img/race<?= (int)$u['race'] ?>small.gif"
                         alt="" style="vertical-align:middle; margin-right:0.4rem;">
                    <strong><?= e($u['name']) ?></strong>
                    <?php if ((int)$u['is_admin']): ?><span class="badge badge-admin">ADMIN</span><?php endif; ?>
                </td>
                <td class="text-muted"><?= e($u['email']) ?></td>
                <td><?= $lvl ?></td>
                <td><?= format_number((int)$u['gold']) ?></td>
                <td>
                    <?php if ((int)$u['is_banned']): ?>
                        <span class="badge badge-banned">BANNED</span>
                    <?php else: ?>
                        <span class="text-success">●</span>
                    <?php endif; ?>
                </td>
                <td>
                    <a href="?id=<?= (int)$u['id'] ?>" class="btn btn-sm btn-secondary"><?= __('edit') ?></a>
                </td>
            </tr>
            <?php endforeach; ?>
        </tbody>
    </table>
<?php endif; ?>

<?php require __DIR__ . '/_footer.php'; ?>
