<?php
session_start();
require_once 'inc/functions.php';
check404();
securityCheck();
if (!isLoggedIn()) {
    header('Location: index.php');
    exit;
}

$user = getUserById($_SESSION['user_id']);
if (!$user) {
    session_destroy();
    header('Location: index.php');
    exit;
}

$mode = isset($_GET['mode']) ? $_GET['mode'] : 'all'; // all, new, inbox, outbox, marked
$page = isset($_GET['page']) ? (int)$_GET['page'] : 1;
$perPage = 10;

// Handle bulk actions
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    if (isset($_POST['mark_all_read'])) {
        markAllIncomingAsRead($user['id']);
        $_SESSION['mail_message'] = 'Все входящие отмечены как прочитанные.';
        header("Location: mail.php?mode=$mode");
        exit;
    }
    if (isset($_POST['delete_all_read'])) {
        deleteAllReadIncoming($user['id']);
        $_SESSION['mail_message'] = 'Все прочитанные входящие удалены.';
        header("Location: mail.php?mode=$mode");
        exit;
    }
    // "Забрать все из почты" – можно реализовать позже
}

// Fetch messages based on mode
switch ($mode) {
    case 'new':
        $messages = getUnreadMail($user['id'], $page, $perPage);
        $total = getUnreadMailCount($user['id']);
        $title = 'Новые';
        break;
    case 'inbox':
        $messages = getInbox($user['id'], $page, $perPage);
        $total = $GLOBALS['pdo']->prepare("SELECT COUNT(*) FROM mail_messages WHERE to_user_id = ? AND is_deleted_by_recipient = 0");
        $total->execute([$user['id']]);
        $total = $total->fetchColumn();
        $title = 'Входящие';
        break;
    case 'outbox':
        $messages = getOutbox($user['id'], $page, $perPage);
        $total = $GLOBALS['pdo']->prepare("SELECT COUNT(*) FROM mail_messages WHERE from_user_id = ? AND is_deleted_by_sender = 0");
        $total->execute([$user['id']]);
        $total = $total->fetchColumn();
        $title = 'Отправленные';
        break;
    case 'marked':
        // For "Пом" (marked) we need is_flagged column; we'll just show inbox for now.
        // If you want to implement flagged, add a filter.
        $messages = getInbox($user['id'], $page, $perPage);
        $total = $GLOBALS['pdo']->prepare("SELECT COUNT(*) FROM mail_messages WHERE to_user_id = ? AND is_deleted_by_recipient = 0");
        $total->execute([$user['id']]);
        $total = $total->fetchColumn();
        $title = 'Помеченные';
        break;
    case 'all':
    default:
        $messages = getAllMail($user['id'], $page, $perPage);
        $total = countAllMail($user['id']);
        $title = 'Все';
        break;
}

$totalPages = ceil($total / $perPage);

require_once 'inc/header.php';
?>

<span class="ttl"><b><span>Почта для <?= htmlspecialchars($user['username']) ?></span></b></span>
<div class="clb"></div>
<div class="hr"></div>

<!-- Tabs -->
<div>
    [<span><em>Все</em></span>]
    [<a href="?mode=new">Нов</a>]
    [<a href="?mode=inbox">Вхд</a>]
    [<a href="?mode=outbox">Отп</a>]
    [<a href="?mode=marked">Пом</a>]
</div>
<div class="hr"></div>

<?php if (empty($messages)): ?>
    <div class="minor">Почта пустая, писем нет</div>
<?php else: ?>
    <?php foreach ($messages as $msg): ?>
        <?php
        $direction = $msg['direction'] ?? (($msg['to_user_id'] == $user['id']) ? 'incoming' : 'outgoing');
        $otherName = $direction == 'incoming' ? ($msg['from_username'] ?? 'Система') : ($msg['to_username'] ?? '');
        $otherSide = $direction == 'incoming' ? ($msg['from_side'] ?? '') : ($msg['to_side'] ?? '');
        $isUnread = ($direction == 'incoming' && !$msg['is_read']);
        $hasAttachment = $msg['attachment_type'] && !$msg['is_claimed'] && $direction == 'incoming';
        ?>
        <div>
            <img width="12" height="12" src="/images/icons/letter.png" alt="" border="0"/>
            <?php if ($direction == 'incoming'): ?>
                <strong><?= htmlspecialchars($otherName) ?></strong>
                <?php if ($otherSide): ?><span class="minor">(<?= htmlspecialchars($otherSide) ?>)</span><?php endif; ?>
            <?php else: ?>
                <strong><?= htmlspecialchars($otherName) ?></strong>
                <?php if ($otherSide): ?><span class="minor">(<?= htmlspecialchars($otherSide) ?>)</span><?php endif; ?>
            <?php endif; ?>
            – <a href="mail_view.php?id=<?= $msg['id'] ?>"><?= htmlspecialchars($msg['subject']) ?></a>
            <span class="minor"><?= date('d.m.Y H:i', strtotime($msg['sent_at'])) ?></span>
            <?php if ($isUnread): ?>
                <span class="info">(новое)</span>
            <?php endif; ?>
            <?php if ($hasAttachment): ?>
                <span class="rc">[вложение]</span>
            <?php endif; ?>
        </div>
    <?php endforeach; ?>

    <div class="hr"></div>
    <!-- Pagination -->
    <div>
        <?php for ($i = 1; $i <= $totalPages; $i++): ?>
            <?php if ($i == $page): ?>
                <span><?= $i ?></span>
            <?php else: ?>
                <a href="?mode=<?= $mode ?>&page=<?= $i ?>"><?= $i ?></a>
            <?php endif; ?>
            <?php if ($i < $totalPages): ?> | <?php endif; ?>
        <?php endfor; ?>
    </div>
<?php endif; ?>

<div class="hr"></div>

<!-- Bulk actions -->
<div>
    <img class="internalIcon" alt="" border="0" src="/images/icons/dot.png"/>
    <a class="info" href="#" onclick="document.getElementById('claimAllForm').submit(); return false;">ЗАБРАТЬ ВСЕ ИЗ ПОЧТЫ</a>
    <form id="claimAllForm" method="post" style="display:none;">
        <input type="hidden" name="claim_all" value="1">
    </form>
</div>
<div class="hr"></div>

<div>
    <img width="12" height="12" src="/images/icons/forum_new.png" alt="" border="0"/>
    <a href="friends.php">Контакты</a> | <a href="blacklist.php">Черный список</a>
</div>
<div class="hr"></div>

<div>
    <img class="internalIcon" alt="" border="0" src="/images/icons/dot.png"/>
    <a href="#" onclick="document.getElementById('markReadForm').submit(); return false;">Отметить все как прочитанные</a>
    <form id="markReadForm" method="post" style="display:none;">
        <input type="hidden" name="mark_all_read" value="1">
    </form>
</div>
<div class="hr"></div>

<div class="info small">
    Почта хранится 30 дней!<br/>
    Подсказка: регулярное удаление сообщений ускоряет загрузку страниц :)
</div>
<div class="hr"></div>

<div>
    <img class="internalIcon" alt="" border="0" src="/images/icons/dot.png"/>
    <a href="#" onclick="if(confirm('Удалить все прочитанные?')) document.getElementById('deleteReadForm').submit(); return false;">Удалить все прочитанные!</a>
    <form id="deleteReadForm" method="post" style="display:none;">
        <input type="hidden" name="delete_all_read" value="1">
    </form>
</div>
<div class="hr"></div>

<?php
if (isset($_SESSION['mail_message'])) {
    echo '<div class="ok">' . htmlspecialchars($_SESSION['mail_message']) . '</div>';
    unset($_SESSION['mail_message']);
}
require_once 'inc/foot.php';
?>