<?php
session_start();
if (!isset($_SESSION['logged_in']) || $_SESSION['logged_in'] !== true) {
    header("Location: login.php");
    exit;
}

require_once '../config.php';

$db_host = 'localhost';
$db_name = 'vfvsdvco_bot';
$db_user = 'vfvsdvco_bot';
$db_pass = '1dU8wbvzxe!4-+,I';

try {
    $db = new PDO("mysql:host=$db_host;dbname=$db_name;charset=utf8mb4", $db_user, $db_pass);
    $db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
} catch (PDOException $e) {
    die("Connection failed: " . $e->getMessage());
}

$search = $_GET['search'] ?? '';

if ($search !== '') {
    // حالت جستجو (فقط بر اساس آیدی)
    $stmt = $db->prepare("SELECT * FROM Users 
                          WHERE UserId LIKE :search
                          ORDER BY LastVisit DESC");
    $stmt->execute([':search' => "%$search%"]);
    $users = $stmt->fetchAll(PDO::FETCH_ASSOC);
    $total_users = count($users);
    $total_pages = 1;
    $page = 1;
} else {
    // حالت صفحه‌بندی عادی
    $users_per_page = 25;
    $page = isset($_GET['page']) ? max(1, intval($_GET['page'])) : 1;
    $offset = ($page - 1) * $users_per_page;

    $total_stmt = $db->query("SELECT COUNT(*) FROM Users");
    $total_users = $total_stmt->fetchColumn();
    $total_pages = ceil($total_users / $users_per_page);

    $stmt = $db->prepare("SELECT * FROM Users 
                          ORDER BY LastVisit DESC 
                          LIMIT :limit OFFSET :offset");
    $stmt->bindValue(':limit', $users_per_page, PDO::PARAM_INT);
    $stmt->bindValue(':offset', $offset, PDO::PARAM_INT);
    $stmt->execute();
    $users = $stmt->fetchAll(PDO::FETCH_ASSOC);
}
?>

<!DOCTYPE html>
<html lang="fa" dir="rtl">
<head>
    <meta charset="UTF-8">
    <title>لیست کاربران</title>
    <style>
        body { font-family: 'Vazirmatn', sans-serif; background-color: #f9f9f9; padding: 20px; }
        table { border-collapse: collapse; width: 100%; background-color: #fff; box-shadow: 0 0 10px rgba(0,0,0,0.05); }
        th, td { border: 1px solid #eee; padding: 10px 12px; text-align: center; }
        th { background-color: #f1f1f1; }
        input[type=text] { padding: 8px; width: 250px; }
        button { padding: 8px 12px; }
    </style>
</head>
<body>

<h2>📋 لیست کاربران (صفحه <?= $page ?> از <?= $total_pages ?>)</h2>

<!-- فرم جستجو -->
<form method="get" style="margin-bottom: 20px; text-align: center;">
    <input type="text" name="search" placeholder="جستجو آیدی یا یوزرنیم"
           value="<?= htmlspecialchars($search) ?>">
    <button type="submit">🔍 جستجو</button>
    <?php if ($search !== ''): ?>
        <a href="?" style="margin-right: 10px;">🧹 حذف فیلتر</a>
    <?php endif; ?>
</form>

<!-- جدول کاربران -->
<table>
    <thead>
        <tr>
            <th>ردیف</th>
            <th>آیدی / یوزرنیم</th>
            <th>محدودیت</th>
            <th>بن</th>
            <th>عضویت</th>
            <th>تیکت باز</th>
            <th>آخرین ورود</th>
        </tr>
    </thead>
    <tbody>
        <?php $i = ($search !== '') ? 1 : ($offset + 1); ?>
        <?php foreach ($users as $user): ?>
            <tr>
                <td><?= $i++ ?></td>
                <td>
                    <?= htmlspecialchars($user['UserId']) ?>
                    <?php if (!empty($user['UserName'])): ?>
                        <br><span style="color:gray">@<?= htmlspecialchars($user['UserName']) ?></span>
                    <?php endif; ?>
                </td>
                <td><?= htmlspecialchars($user['Limit']) ?></td>
                <td><?= $user['Ban'] ? '✅' : '❌' ?></td>
                <td><?= $user['HasJoin'] !== 'left' ? '✅' : '❌' ?></td>
                <td><?= $user['Sup'] ? '✅' : '❌' ?></td>
                <td><?= !empty($user['LastVisit']) ? date("Y-m-d H:i", strtotime($user['LastVisit'])) : '-' ?></td>
            </tr>
        <?php endforeach; ?>
    </tbody>
</table>

<!-- صفحه‌بندی (فقط در حالت بدون جستجو) -->
<?php if ($search === ''): ?>
<div style="margin-top: 20px; text-align: center;">
    <?php if ($page > 1): ?>
        <a href="?page=<?= $page - 1 ?>">⬅️ صفحه قبل</a>
    <?php endif; ?>
    <?php if ($page < $total_pages): ?>
        <a href="?page=<?= $page + 1 ?>" style="margin-right: 15px;">صفحه بعد ➡️</a>
    <?php endif; ?>
</div>
<?php endif; ?>

<div style="margin: 20px 0; text-align: center;">
    <a href="dashboard.php" style="color: blue; text-decoration: none; font-weight: bold;">
        ⬅️ بازگشت به داشبورد
    </a>
</div>

</body>
</html>
