<?php
session_start();
require_once '../inc/admin_auth.php';
requireAdmin();
require_once '../inc/functions.php';

$filterUser = isset($_GET['user_id']) ? (int)$_GET['user_id'] : 0;
$page = (int)($_GET['page'] ?? 1);
if ($page < 1) $page = 1;
$perPage = 30;
$offset = ($page - 1) * $perPage;

$sql = "SELECT SQL_CALC_FOUND_ROWS m.*, u_from.username as from_name, u_to.username as to_name 
        FROM mail_messages m
        LEFT JOIN users u_from ON m.from_user_id = u_from.id
        LEFT JOIN users u_to ON m.to_user_id = u_to.id";
$params = [];
if ($filterUser) {
    $sql .= " WHERE m.from_user_id = ? OR m.to_user_id = ?";
    $params[] = $filterUser;
    $params[] = $filterUser;
}
$sql .= " ORDER BY m.sent_at DESC LIMIT ? OFFSET ?";

$stmt = $pdo->prepare($sql);
$i = 1;
foreach ($params as $param) {
    $stmt->bindValue($i++, $param, is_int($param) ? PDO::PARAM_INT : PDO::PARAM_STR);
}
$stmt->bindValue($i++, (int)$perPage, PDO::PARAM_INT);
$stmt->bindValue($i++, (int)$offset, PDO::PARAM_INT);
$stmt->execute();

$mails = $stmt->fetchAll();
$total = $pdo->query("SELECT FOUND_ROWS()")->fetchColumn();

require_once '../inc/header.php';
?>
<span class="ttl"><b>📬 Почта пользователей</b></span>
<div class="clb"></div>
<div class="hr"></div>

<div class="menu">
    <a class="btn full" href="index.php">← В админ-панель</a>
</div>
<div class="hr"></div>

<form method="get" style="margin-bottom:10px;">
    <label>Фильтр по ID пользователя:</label>
    <input type="number" name="user_id" value="<?= $filterUser ?: '' ?>" placeholder="0 = все">
    <button type="submit">Применить</button>
</form>

<table class="tables" border="1" cellpadding="5" style="width:100%;">
    <tr>
        <th>ID</th>
        <th>От</th>
        <th>Кому</th>
        <th>Тема</th>
        <th>Дата</th>
        <th>Прочитано</th>
        <th>Вложение</th>
        <th>Действия</th>
    </tr>
    <?php foreach ($mails as $mail): ?>
    <tr>
        <td><?= $mail['id'] ?></td>
        <td><?= htmlspecialchars($mail['from_name'] ?? 'Система') ?></td>
        <td><?= htmlspecialchars($mail['to_name'] ?? '?') ?></td>
        <td><?= htmlspecialchars($mail['subject']) ?></td>
        <td><?= date('d.m.Y H:i', strtotime($mail['sent_at'])) ?></td>
        <td><?= $mail['is_read'] ? 'Да' : 'Нет' ?></td>
        <td>
            <?php if ($mail['attachment_type'] && !$mail['is_claimed']): ?>
                <?= $mail['attachment_type'] ?>: <?= $mail['attachment_value'] ?>
            <?php elseif ($mail['is_claimed']): ?>
                Забрано
            <?php else: ?>
                —
            <?php endif; ?>
        </td>
        <td>
            <a href="admin_mail_view.php?id=<?= $mail['id'] ?>">Просмотр</a> |
            <a href="admin_mail_delete.php?id=<?= $mail['id'] ?>" onclick="return confirm('Удалить письмо?');">Удалить</a>
        </td>
    </tr>
    <?php endforeach; ?>
</table>

<?php if ($total > $perPage): ?>
<div style="margin-top:15px;">
    Страницы: 
    <?php for ($i = 1; $i <= ceil($total / $perPage); $i++): ?>
        <a href="?user_id=<?= $filterUser ?>&page=<?= $i ?>" <?= ($i == $page) ? 'style="font-weight:bold;"' : '' ?>>
            [<?= $i ?>]
        </a>
    <?php endfor; ?>
</div>
<?php endif; ?>

<?php require_once '../inc/foot.php'; ?>