<?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;
}

$otherId = isset($_GET['user']) ? (int)$_GET['user'] : 0;
$otherUser = getUserById($otherId);
if (!$otherUser) {
    header('Location: mail.php');
    exit;
}

$messages = getConversation($user['id'], $otherId, 100);

require_once 'inc/header.php';
?>

<span class="ttl"><b><span>История переписки с <?= htmlspecialchars($otherUser['username']) ?></span></b></span>
<div class="clb"></div>
<div class="hr"></div>

<div style="margin-bottom:10px;">
    <a href="mail.php" class="btn small">← Назад</a>
    <a href="mail_compose.php?to=<?= $otherId ?>" class="btn small">Написать</a>
</div>

<?php if (empty($messages)): ?>
    <div class="minor">Нет сообщений в истории.</div>
<?php else: ?>
    <?php foreach ($messages as $msg): 
        $isFromMe = ($msg['from_user_id'] == $user['id']);
        $sender = $isFromMe ? $user : $otherUser;
        $side = $sender['side'] ?? '';
        $icon = ($side == 'Коза Ностра') ? 'blue_warrior.png' : (($side == 'Якудза') ? 'red_warrior.png' : 'gray_warrior.png');
        $isOnline = (time() - strtotime($sender['last_activity'])) < 300;
        if ($isOnline) {
            $icon = str_replace('.png', '_online.png', $icon);
        }
        $date = date('d M H:i', strtotime($msg['sent_at']));
    ?>
        <div style="margin-bottom:15px; padding:5px; border-bottom:1px dashed #ccc;">
            <span>
                <img width="12" height="12" src="/images/icons/<?= $icon ?>" alt="" border="0"/>
                <a href="profile.php?id=<?= $sender['id'] ?>"><strong><?= htmlspecialchars($sender['username']) ?></strong></a>
                (<?= $sender['level'] ?> ур.)
            </span>
            <span class="minor"><?= $date ?></span>
            <br/>
            <div style="margin-top:5px;"><?= nl2br(htmlspecialchars($msg['body'])) ?></div>
            <?php if ($msg['attachment_type'] && $msg['to_user_id'] == $user['id'] && !$msg['is_claimed'] && $msg['is_claimed'] == 0): ?>
                <div class="info small">[вложение: <?= $msg['attachment_value'] ?> <?= $msg['attachment_type'] ?>]</div>
            <?php endif; ?>
        </div>
    <?php endforeach; ?>
<?php endif; ?>

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