<?php
session_start();
require_once 'config.php';
require_once 'functions.php';

requireLogin();
$user = getConnectedUser($pdo);
requireAdmin($user);

$msg = ''; $error = '';

// --- ACTIONS ---
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $targetId = (int)($_POST['target_id'] ?? 0);

    if (isset($_POST['update_user']) && $targetId) {
        $username = trim(htmlspecialchars($_POST['username']));
        $email    = trim(htmlspecialchars($_POST['email']));
        $tier     = in_array($_POST['tier'],['free','premium','premium_plus','admin']) ? $_POST['tier'] : 'free';
        $nickname = trim(htmlspecialchars($_POST['nickname'] ?? ''));
        $adminFlg = isset($_POST['is_admin']) ? 1 : 0;
        $storeFlg = isset($_POST['is_admin_store']) ? 1 : 0;
        $pts      = max(0, (int)($_POST['points']        ?? 0));
        $wallet   = max(0, (int)($_POST['wallet_points'] ?? 0));

        try {
            $pdo->prepare("UPDATE users SET username=?,email=?,tier=?,nickname=?,admin=?,is_admin_store=?,points=?,wallet_points=? WHERE id=?")
                ->execute([$username,$email,$tier,$nickname,$adminFlg,$storeFlg,$pts,$wallet,$targetId]);
        } catch (Exception $e) {
            $pdo->prepare("UPDATE users SET username=?,email=?,tier=?,nickname=?,admin=?,is_admin_store=? WHERE id=?")
                ->execute([$username,$email,$tier,$nickname,$adminFlg,$storeFlg,$targetId]);
        }
        $msg = "Membre #{$targetId} mis a jour.";
    }

    if (isset($_POST['send_pw_reset']) && $targetId) {
        $em = $pdo->prepare("SELECT email, username FROM users WHERE id=?");
        $em->execute([$targetId]);
        $row = $em->fetch();
        if ($row) {
            $code = bin2hex(random_bytes(20));
            $pdo->prepare("UPDATE users SET recovery_code=? WHERE id=?")->execute([password_hash($code, PASSWORD_DEFAULT), $targetId]);
            $link = "https://jetegageque.com/reset_password.php?code={$code}&id={$targetId}";
            notifyUser($row['email'], "Réinitialisation mot de passe", "Lien : <a href='{$link}'>{$link}</a>");
            $msg = "Courriel de réinitialisation envoyé à {$row['email']}.";
        }
    }

    if (isset($_POST['delete_user']) && $targetId) {
        $pdo->prepare("DELETE FROM circle_members WHERE user_id=?")->execute([$targetId]);
        $pdo->prepare("DELETE FROM friends WHERE user_id=? OR friend_id=?")->execute([$targetId,$targetId]);
        $pdo->prepare("DELETE FROM users WHERE id=?")->execute([$targetId]);
        $msg = "Membre #{$targetId} supprimé.";
    }
}

// Recherche / filtre
$search = trim($_GET['q'] ?? '');
$filterTier = $_GET['tier'] ?? '';
$where  = "WHERE 1=1";
$params = [];
if ($search) { $where .= " AND (u.username LIKE ? OR u.email LIKE ? OR u.nickname LIKE ?)"; $params = array_merge($params,["%$search%","%$search%","%$search%"]); }
if ($filterTier) { $where .= " AND u.tier = ?"; $params[] = $filterTier; }

$stmt = $pdo->prepare("SELECT u.*, us.total_bets, us.won_bets FROM users u LEFT JOIN user_stats us ON us.user_id = u.id $where ORDER BY u.id DESC");
$stmt->execute($params);
$users = $stmt->fetchAll();

include 'header.php';
?>

<div class="container-fluid mt-4 px-4">
    <a href="admin.php" class="btn btn-outline-secondary btn-sm mb-3">&larr; Admin</a>
    <h5 class="oracle-text text-primary mb-3"> GESTION DES MEMBRES</h5>

    <?php if ($msg):   ?><div class="alert alert-success small py-2"><?= $msg ?></div><?php endif; ?>
    <?php if ($error): ?><div class="alert alert-danger  small py-2"><?= $error ?></div><?php endif; ?>

    <!-- Filtres -->
    <form method="GET" class="row g-2 mb-3">
        <div class="col-md-4">
            <input type="text" name="q" class="form-control form-control-sm" placeholder="Rechercher nom/courriel/surnom…" value="<?= htmlspecialchars($search) ?>">
        </div>
        <div class="col-md-3">
            <select name="tier" class="form-select form-select-sm">
                <option value="">Tous les forfaits</option>
                <option value="free"         <?= $filterTier==='free'?'selected':'' ?>>Free</option>
                <option value="premium"      <?= $filterTier==='premium'?'selected':'' ?>>Premium</option>
                <option value="premium_plus" <?= $filterTier==='premium_plus'?'selected':'' ?>>Premium+</option>
                <option value="admin"        <?= $filterTier==='admin'?'selected':'' ?>>Admin</option>
            </select>
        </div>
        <div class="col-md-2">
            <button type="submit" class="btn btn-primary btn-sm w-100">Filtrer</button>
        </div>
        <div class="col-md-2">
            <a href="admin_users.php" class="btn btn-outline-secondary btn-sm w-100">Réinitialiser</a>
        </div>
    </form>

    <div class="table-responsive">
        <table class="table table-dark table-hover table-sm small border-secondary">
            <thead>
                <tr class="border-secondary">
                    <th>#</th><th>Utilisateur</th><th>Courriel</th>
                    <th class="text-center">Forfait</th><th class="text-center">Pts</th>
                    <th class="text-center">Admin</th><th class="text-center">Dernière connexion</th>
                    <th class="text-center">Actions</th>
                </tr>
            </thead>
            <tbody>
            <?php foreach ($users as $u): ?>
            <tr>
                <td class="text-muted"><?= $u['id'] ?></td>
                <td><strong><?= htmlspecialchars($u['username']) ?></strong>
                    <?php if (!empty($u['nickname'])): ?>
                    <small class="text-muted d-block" style="font-size:0.6rem;"><?= htmlspecialchars($u['nickname']) ?></small>
                    <?php endif; ?>
                </td>
                <td style="font-size:0.7rem;"><?= htmlspecialchars($u['email']) ?></td>
                <td class="text-center">
                    <span class="badge bg-<?= match($u['tier']??'free'){'premium'=>'warning text-dark','premium_plus'=>'info text-dark','admin'=>'danger',default=>'secondary'} ?>" style="font-size:0.55rem;">
                        <?= strtoupper($u['tier']??'FREE') ?>
                    </span>
                </td>
                <td class="text-center text-success"><?= (int)$u['points'] ?></td>
                <td class="text-center"><?= $u['admin'] ? '<span class="text-danger">✓</span>' : '—' ?></td>
                <td class="text-center text-muted" style="font-size:0.62rem;">
                    <?php
                    $lastAct = $u['last_activity'] ?? null;
                    if ($lastAct && $lastAct !== '0000-00-00 00:00:00') {
                        $ago = time() - strtotime($lastAct);
                        if ($ago < 300)       echo '<span class="text-success">En ligne</span>';
                        elseif ($ago < 3600)  echo round($ago/60) . ' min';
                        elseif ($ago < 86400) echo round($ago/3600) . ' h';
                        elseif ($ago < 604800) echo round($ago/86400) . ' j';
                        else echo date('d M Y', strtotime($lastAct));
                    } else { echo '—'; }
                    ?>
                </td>
                <td class="text-center">
                    <button class="btn btn-xs btn-outline-warning py-0" data-bs-toggle="modal" data-bs-target="#editUser<?= $u['id'] ?>">
                        <i class="fa-solid fa-gear" style="font-size:0.6rem;"></i>
                    </button>
                    <a href="admin_as_user.php?action=login&user_id=<?= $u['id'] ?>"
                       class="btn btn-xs btn-outline-info py-0 ms-1"
                       title="Naviguer en tant que cet utilisateur"
                       onclick="return confirm('Naviguer en tant que <?= htmlspecialchars(addslashes($u['username'])) ?> ?')">Vue</a>
                </td>
            </tr>

            <!-- Modal édition -->
            <div class="modal fade" id="editUser<?= $u['id'] ?>" tabindex="-1" aria-hidden="true">
                <div class="modal-dialog modal-dialog-centered">
                    <div class="modal-content bg-dark border-warning text-white">
                        <div class="modal-header border-secondary py-2">
                            <h6 class="modal-title text-warning small">Modifier — <?= htmlspecialchars($u['username']) ?></h6>
                            <button type="button" class="btn-close btn-close-white" data-bs-dismiss="modal"></button>
                        </div>
                        <form method="POST">
                            <input type="hidden" name="target_id" value="<?= $u['id'] ?>">
                            <div class="modal-body p-3">
                                <div class="row g-2">
                                    <div class="col-6">
                                        <label class="small text-white d-block mb-1">Nom d'utilisateur</label>
                                        <input type="text" name="username" class="form-control form-control-sm" value="<?= htmlspecialchars($u['username']) ?>" required>
                                    </div>
                                    <div class="col-6">
                                        <label class="small text-white d-block mb-1">Surnom</label>
                                        <input type="text" name="nickname" class="form-control form-control-sm" value="<?= htmlspecialchars($u['nickname']??'') ?>">
                                    </div>
                                    <div class="col-8">
                                        <label class="small text-white d-block mb-1">Courriel</label>
                                        <input type="email" name="email" class="form-control form-control-sm" value="<?= htmlspecialchars($u['email']) ?>" required>
                                    </div>
                                    <div class="col-4">
                                        <label class="small text-white d-block mb-1">Forfait</label>
                                        <select name="tier" class="form-select form-select-sm">
                                            <option value="free"         <?= ($u['tier']??'')==='free'?'selected':'' ?>>Free</option>
                                            <option value="premium"      <?= ($u['tier']??'')==='premium'?'selected':'' ?>>Premium</option>
                                            <option value="premium_plus" <?= ($u['tier']??'')==='premium_plus'?'selected':'' ?>>Premium+</option>
                                            <option value="admin"        <?= ($u['tier']??'')==='admin'?'selected':'' ?>>Admin</option>
                                        </select>
                                    </div>
                                    <div class="col-6">
                                        <label class="small text-white d-block mb-1">Points honneur</label>
                                        <input type="number" name="points" class="form-control form-control-sm" value="<?= (int)$u['points'] ?>" min="0">
                                    </div>
                                    <div class="col-6">
                                        <label class="small text-white d-block mb-1">Jetons wallet</label>
                                        <input type="number" name="wallet_points" class="form-control form-control-sm" value="<?= (int)($u['wallet_points']??0) ?>" min="0">
                                    </div>
                                    <div class="col-6">
                                        <div class="form-check mt-2">
                                            <input class="form-check-input" type="checkbox" name="is_admin" id="adm<?= $u['id'] ?>" <?= $u['admin']?'checked':'' ?>>
                                            <label class="form-check-label small text-danger" for="adm<?= $u['id'] ?>">Admin site</label>
                                        </div>
                                    </div>
                                    <div class="col-6">
                                        <div class="form-check mt-2">
                                            <input class="form-check-input" type="checkbox" name="is_admin_store" id="adms<?= $u['id'] ?>" <?= ($u['is_admin_store']??0)?'checked':'' ?>>
                                            <label class="form-check-label small text-warning" for="adms<?= $u['id'] ?>">Admin boutique</label>
                                        </div>
                                    </div>
                                </div>
                            </div>
                            <div class="modal-footer border-secondary py-2 d-flex justify-content-between">
                                <div class="d-flex gap-2">
                                    <button type="submit" name="send_pw_reset" class="btn btn-outline-info btn-sm">Reset MDP</button>
                                    <button type="submit" name="delete_user" class="btn btn-outline-danger btn-sm"
                                            onclick="return confirm('Supprimer definitivement ?')">Supprimer</button>
                                </div>
                                <button type="submit" name="update_user" class="btn btn-warning btn-sm fw-bold">ENREGISTRER</button>
                            </div>
                        </form>
                    </div>
                </div>
            </div>
            <?php endforeach; ?>
            </tbody>
        </table>
    </div>
</div>

<?php include 'footer.php'; ?>
