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

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

$usersStmt = $pdo->query("
    SELECT u.*, COUNT(r.id) AS requests_count
    FROM users u
    LEFT JOIN requests r ON r.user_id = u.id
    GROUP BY u.id
    ORDER BY u.created_at DESC
");
$users = $usersStmt->fetchAll(PDO::FETCH_ASSOC);
?>

<!DOCTYPE html>
<html lang="fa">
<head>
    <meta charset="UTF-8">
    <title>لیست کاربران | Video Bot</title>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.3/dist/css/bootstrap.rtl.min.css" rel="stylesheet">
    <style>
        body { direction: rtl; text-align: right; }
        table th, table td { text-align: center; vertical-align: middle; }
    </style>
</head>
<body class="bg-light">
<div class="container mt-4">
    <h3 class="text-center mb-3">لیست کاربران</h3>
    <div class="text-center mb-3">
        <a href="dashboard.php" class="btn btn-secondary">بازگشت به داشبورد</a>
    </div>

    <table class="table table-bordered table-striped text-center">
        <thead class="table-light">
            <tr>
                <th>#</th>
                <th>تاریخ ثبت</th>
                <th>Telegram ID</th>
                <th>نام</th>
                <th>نام خانوادگی</th>
                <th>یوزرنیم</th>
                <th>شماره موبایل</th>
                <th>تعداد درخواست‌ها</th>
            </tr>
        </thead>
        <tbody>
        <?php foreach($users as $i => $u): ?>
            <tr>
                <td><?= $i+1 ?></td>
                <td><?= jdate($u['created_at']) ?></td>
                <td><?= htmlspecialchars($u['telegram_id']) ?></td>
                <td><?= htmlspecialchars($u['first_name'] ?: '-') ?></td>
                <td><?= htmlspecialchars($u['last_name'] ?: '-') ?></td>
                <td><?= htmlspecialchars($u['username'] ?: '-') ?></td>
                <td><?= htmlspecialchars($u['phone']) ?></td>
                <td><?= $u['requests_count'] ?></td>
            </tr>
        <?php endforeach; ?>
        </tbody>
    </table>
</div>
</body>
</html>
