<?php
declare(strict_types=1);

require_once __DIR__ . '/../includes/bootstrap.php';
require_once __DIR__ . '/../includes/admin_layout.php';

$me = require_admin();

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $action = (string) ($_POST['action'] ?? '');

    if ($action === 'add') {
        $name = trim((string) ($_POST['name'] ?? ''));
        $username = mb_strtolower(trim((string) ($_POST['username'] ?? '')));
        $password = (string) ($_POST['password'] ?? '');

        if ($name === '' || $username === '' || $password === '') {
            flash('error', 'Ad, kullanıcı adı ve şifre zorunlu.');
            redirect(url('admin/uyeler.php'));
        }
        if (!preg_match('/^[a-z0-9._-]{3,32}$/', $username)) {
            flash('error', 'Kullanıcı adı 3–32 karakter; harf, rakam, nokta, - veya _ olmalı.');
            redirect(url('admin/uyeler.php'));
        }
        if (mb_strlen($password) < 4) {
            flash('error', 'Şifre en az 4 karakter olmalı.');
            redirect(url('admin/uyeler.php'));
        }
        if (find_user_by_login($username)) {
            flash('error', 'Bu kullanıcı adı zaten var.');
            redirect(url('admin/uyeler.php'));
        }

        $user = [
            'id' => new_id('u_'),
            'name' => $name,
            'username' => $username,
            'email' => $username . '@local.admin',
            'password' => password_hash($password, PASSWORD_DEFAULT),
            'role' => 'admin',
            'bio' => 'Site yöneticisi',
            'iban' => '',
            'bank' => '',
            'account_name' => $name,
            'avatar' => '',
            'created_at' => date('c'),
        ];
        store_upsert('users', $user);
        flash('success', 'Yeni admin eklendi: ' . $username);
        redirect(url('admin/uyeler.php'));
    }

    if ($action === 'password') {
        $id = (string) ($_POST['id'] ?? '');
        $password = (string) ($_POST['password'] ?? '');
        $user = store_find('users', $id);
        if (!$user || ($user['role'] ?? '') !== 'admin') {
            flash('error', 'Admin bulunamadı.');
            redirect(url('admin/uyeler.php'));
        }
        if (mb_strlen($password) < 4) {
            flash('error', 'Şifre en az 4 karakter olmalı.');
            redirect(url('admin/uyeler.php'));
        }
        $user['password'] = password_hash($password, PASSWORD_DEFAULT);
        $user['updated_at'] = date('c');
        store_upsert('users', $user);
        flash('success', 'Şifre güncellendi.');
        redirect(url('admin/uyeler.php'));
    }

    if ($action === 'delete') {
        $id = (string) ($_POST['id'] ?? '');
        if ($id === ($me['id'] ?? '')) {
            flash('error', 'Kendi hesabını silemezsin.');
            redirect(url('admin/uyeler.php'));
        }
        $user = store_find('users', $id);
        if ($user && ($user['role'] ?? '') === 'admin') {
            store_delete('users', $id);
            flash('success', 'Admin silindi.');
        }
        redirect(url('admin/uyeler.php'));
    }
}

$admins = array_values(array_filter(
    store_read('users'),
    static fn(array $u): bool => ($u['role'] ?? '') === 'admin'
));
usort($admins, static fn(array $a, array $b): int => strcmp($a['username'] ?? $a['name'] ?? '', $b['username'] ?? $b['name'] ?? ''));

admin_layout_start('Üyeler / Adminler', 'users');
?>

<section class="admin-panel">
    <h2>Yeni admin ekle</h2>
    <p class="hint">Bu kişiler <code>/temo</code> üzerinden panele giriş yapabilir. Müşteri üyeliği yok.</p>
    <form method="post" class="admin-form">
        <input type="hidden" name="action" value="add">
        <label>Ad soyad
            <input type="text" name="name" required placeholder="Örn: Ayşe Yönetici">
        </label>
        <div class="admin-form-row">
            <label>Kullanıcı adı
                <input type="text" name="username" required placeholder="ornekadmin" autocomplete="off">
            </label>
            <label>Şifre
                <input type="text" name="password" required placeholder="geçici şifre" autocomplete="off">
            </label>
        </div>
        <button class="admin-btn" type="submit">Admin Ekle</button>
    </form>
</section>

<section class="admin-panel">
    <h2>Admin listesi (<?= count($admins) ?>)</h2>
    <?php foreach ($admins as $u):
        $isMe = (($u['id'] ?? '') === ($me['id'] ?? ''));
        $login = (string) ($u['username'] ?? $u['email'] ?? '');
    ?>
        <div class="admin-order">
            <div class="admin-order-head">
                <strong><?= e($u['name'] ?? 'Admin') ?></strong>
                <?php if ($isMe): ?><span class="admin-badge paid">Sen</span><?php endif; ?>
            </div>
            <p>Giriş: <code><?= e($login) ?></code></p>
            <form method="post" class="admin-form" style="margin-top:0.65rem;max-width:420px">
                <input type="hidden" name="action" value="password">
                <input type="hidden" name="id" value="<?= e((string) ($u['id'] ?? '')) ?>">
                <label>Yeni şifre
                    <input type="text" name="password" required minlength="4" placeholder="yeni şifre">
                </label>
                <div style="display:flex;gap:0.4rem;flex-wrap:wrap">
                    <button class="admin-btn sm" type="submit">Şifreyi Güncelle</button>
                    <?php if (!$isMe): ?>
                        <button class="admin-btn danger sm" type="submit" form="del-<?= e((string) ($u['id'] ?? '')) ?>"
                            onclick="return confirm('Bu admin silinsin mi?')">Sil</button>
                    <?php endif; ?>
                </div>
            </form>
            <?php if (!$isMe): ?>
                <form method="post" id="del-<?= e((string) ($u['id'] ?? '')) ?>" hidden>
                    <input type="hidden" name="action" value="delete">
                    <input type="hidden" name="id" value="<?= e((string) ($u['id'] ?? '')) ?>">
                </form>
            <?php endif; ?>
        </div>
    <?php endforeach; ?>
</section>

<?php admin_layout_end(); ?>
