<?php
declare(strict_types=1);

$pid = (int)($p['id'] ?? 0);
$atts = $attByPost[$pid] ?? [];

$posterName = g_user_display($p);
$posterUser = (string)($p['username'] ?? '');
$posterUid  = (int)($p['user_id'] ?? 0);

$profileUrl = '#';
if ($posterUser !== '') {
    $profileUrl = '/profile/index.php?u=' . rawurlencode($posterUser);
} elseif ($posterUid > 0) {
    $profileUrl = '/profile/index.php?id=' . $posterUid;
}

$canManagePost = $me && (
    ((int)($me['id'] ?? 0) === (int)($p['user_id'] ?? 0)) ||
    $viewerIsAdmin ||
    $isManager
);

$confirmDel = g_t('Видалити пост?', 'Удалить пост?', 'Delete post?');

$firstUrl = g_extract_first_url((string)($p['body'] ?? ''));
$createdLabel = $postsHasCreated ? (string)($p['created_at'] ?? '') : '';

$my = (string)($myReact[$pid] ?? '');
$likeActive = ($my === 'like');
$disActive  = ($my === 'dislike');

$likesCount = (int)($reactCounts[$pid]['likes'] ?? 0);
$dislikesCount = (int)($reactCounts[$pid]['dislikes'] ?? 0);

$backToPost = $backUri . '#post-' . $pid;

$isPromoted = ((int)($p['is_promoted'] ?? 0) === 1);
$promotedClickUrl = trim((string)($p['promoted_click_url'] ?? ''));
$sponsoredLabel = 'РЕКЛАМА';

$canPromotePost = false;
if (
    $me
    && ((int)($me['id'] ?? 0) > 0)
    && ((int)($me['id'] ?? 0) === (int)($p['user_id'] ?? 0))
    && !$isPromoted
) {
    $reclamaEnabled = true;

    if (function_exists('reclama_is_enabled')) {
        try {
            $reclamaEnabled = (bool)reclama_is_enabled($pdo);
        } catch (Throwable $e) {
            $reclamaEnabled = true;
        }
    }

    if ($reclamaEnabled && function_exists('reclama_allow_post_campaigns')) {
        try {
            $reclamaEnabled = (bool)reclama_allow_post_campaigns($pdo);
        } catch (Throwable $e) {
            $reclamaEnabled = true;
        }
    }

    $canPromotePost = $reclamaEnabled;
}

if (!defined('VM_PROMOTED_BADGE_STYLE_PRINTED')) {
    define('VM_PROMOTED_BADGE_STYLE_PRINTED', true);
    echo <<<'HTML'
<style>
.vm-sponsored-badge{
  display:inline-flex;
  align-items:center;
  justify-content:center;
  padding:4px 11px;
  border-radius:999px;
  font-size:11px;
  font-weight:800;
  line-height:1;
  letter-spacing:.08em;
  text-transform:uppercase;
  white-space:nowrap;
  color:#f3fff8;
  background:linear-gradient(180deg,#1fc56f 0%,#0f9f56 100%);
  border:1px solid rgba(106,255,174,.95);
  box-shadow:
    0 0 0 1px rgba(11,90,48,.22) inset,
    0 0 10px rgba(44,255,157,.38),
    0 0 22px rgba(44,255,157,.20);
  text-shadow:0 0 10px rgba(255,255,255,.18);
  vertical-align:middle;
}
.g-post-video-list,
.g-post-audio-list,
.g-post-file-list{
  display:grid;
  gap:10px;
  margin-top:10px;
}
.g-post-video-wrap{
  width:100%;
  border-radius:16px;
  overflow:hidden;
  background:#000;
  box-shadow:0 2px 10px rgba(0,0,0,.08);
}
.g-post-video-wrap .g-att-video{
  display:block;
  width:100%;
  aspect-ratio:16 / 9;
  background:#000;
}
.g-post-att{
  display:grid;
  grid-template-columns:repeat(3,minmax(0,1fr));
  gap:8px;
  margin-top:10px;
}
@media (max-width: 768px){
  .g-post-att{
    grid-template-columns:repeat(2,minmax(0,1fr));
  }
}
</style>
HTML;
}
?>
<?php
$imageAtts = [];
$videoAtts = [];
$audioAtts = [];
$fileAtts  = [];

foreach ($atts as $attRow) {
    $ft = (string)($attRow['file_type'] ?? '');
    if ($ft === 'image') {
        $imageAtts[] = $attRow;
    } elseif ($ft === 'video') {
        $videoAtts[] = $attRow;
    } elseif ($ft === 'audio') {
        $audioAtts[] = $attRow;
    } else {
        $fileAtts[] = $attRow;
    }
}
?>
<div class="card mb-3" id="post-<?= $pid ?>">
    <div class="card-body">
        <div class="d-flex align-items-center gap-2 mb-2">
            <?php if ($groupAvatar !== ''): ?>
                <img class="g-post-userava" src="<?= g_h($groupAvatar) ?>" alt="">
            <?php else: ?>
                <div class="g-post-userava g-avatar-ph"><?= g_h($groupIni) ?></div>
            <?php endif; ?>

            <div class="flex-grow-1 g-post-authorline">
                <div class="fw-semibold"><?= g_h((string)($g['name'] ?? '')) ?></div>
                <div class="g-post-subline">
                    <?= g_h(g_t('Опублікував', 'Опубликовал', 'Posted by')) ?>:
                    <a href="<?= g_h($profileUrl) ?>"><?= $posterUser !== '' ? ('@' . g_h($posterUser)) : g_h($posterName) ?></a>

                    <?php if ($createdLabel !== ''): ?>
                        <span class="mx-1">•</span>
                        <span><?= g_h($createdLabel) ?></span>
                    <?php endif; ?>

                    <?php if ($isPromoted): ?>
                        <span class="mx-1">•</span>
                        <span class="vm-sponsored-badge"><?= g_h($sponsoredLabel) ?></span>
                    <?php endif; ?>
                </div>
            </div>

            <?php if ($canManagePost): ?>
                <details class="vm-menu">
                    <summary class="vm-menu-btn" aria-label="menu">⋯</summary>
                    <div class="vm-menu-box">
                        <a class="vm-menu-item" href="/post_edit.php?id=<?= $pid ?>&back=<?= urlencode($backUri) ?>">
                            <?= g_h(g_t('Редагувати', 'Редактировать', 'Edit')) ?>
                        </a>

                        <form method="post" action="/functional/post/manage.php"
                              onsubmit="return confirm(<?= json_encode($confirmDel, JSON_UNESCAPED_UNICODE) ?>);">
                            <?php g_csrf_field_fallback(); ?>
                            <input type="hidden" name="action" value="delete">
                            <input type="hidden" name="id" value="<?= $pid ?>">
                            <input type="hidden" name="back" value="<?= g_h($backToPost) ?>">
                            <button type="submit" class="vm-menu-item vm-menu-danger">
                                <?= g_h(g_t('Видалити', 'Удалить', 'Delete')) ?>
                            </button>
                        </form>
                    </div>
                </details>
            <?php endif; ?>
        </div>

        <?php if (trim((string)($p['body'] ?? '')) !== ''): ?>
            <div class="mb-2"><?= g_linkify_text((string)($p['body'] ?? '')) ?></div>
        <?php endif; ?>

        <?php if ($firstUrl !== '' && preg_match('~^https?://~i', $firstUrl)): ?>
            <?php g_render_link_preview_card($firstUrl); ?>
        <?php endif; ?>

        <?php if ($hasAttachments && $atts): ?>
            <?php $galleryId = 'gpost-' . $pid; ?>

            <?php if ($imageAtts): ?>
                <div class="g-post-att" data-gallery-images="<?= g_h($galleryId) ?>">
                    <?php foreach ($imageAtts as $a): ?>
                        <?php $path = (string)($a['path'] ?? ''); ?>
                        <?php if ($path === '') continue; ?>
                        <a class="g-att-img js-lightbox" href="<?= g_h($path) ?>" data-gallery="<?= g_h($galleryId) ?>" target="_blank" rel="noopener">
                            <img src="<?= g_h($path) ?>" alt="">
                        </a>
                    <?php endforeach; ?>
                </div>
            <?php endif; ?>

            <?php if ($videoAtts): ?>
                <div class="g-post-video-list">
                    <?php foreach ($videoAtts as $a): ?>
                        <?php $path = (string)($a['path'] ?? ''); ?>
                        <?php if ($path === '') continue; ?>
                        <div class="g-post-video-wrap">
                            <video class="g-att-video" controls preload="metadata">
                                <source src="<?= g_h($path) ?>" type="<?= g_h((string)($a['mime'] ?? 'video/mp4')) ?>">
                            </video>
                        </div>
                    <?php endforeach; ?>
                </div>
            <?php endif; ?>

            <?php if ($audioAtts): ?>
                <div class="g-post-audio-list">
                    <?php foreach ($audioAtts as $a): ?>
                        <?php $path = (string)($a['path'] ?? ''); ?>
                        <?php if ($path === '') continue; ?>
                        <audio class="w-100" controls preload="none">
                            <source src="<?= g_h($path) ?>" type="<?= g_h((string)($a['mime'] ?? 'audio/mpeg')) ?>">
                        </audio>
                    <?php endforeach; ?>
                </div>
            <?php endif; ?>

            <?php if ($fileAtts): ?>
                <div class="g-post-file-list">
                    <?php foreach ($fileAtts as $a): ?>
                        <?php $path = (string)($a['path'] ?? ''); ?>
                        <?php if ($path === '') continue; ?>
                        <a class="btn btn-sm btn-outline-secondary" href="<?= g_h($path) ?>" target="_blank" rel="noopener">
                            <?= g_h((string)($a['original_name'] ?? 'file')) ?>
                        </a>
                    <?php endforeach; ?>
                </div>
            <?php endif; ?>
        <?php endif; ?>

        <div class="d-flex gap-2 mt-3 flex-wrap align-items-center">
            <form method="post" action="/post_react.php" class="d-inline js-post-react-form" data-no-pjax="1">
                <input type="hidden" name="csrf" value="<?= g_h(vm_csrf_token()) ?>">
                <input type="hidden" name="post_id" value="<?= $pid ?>">
                <input type="hidden" name="reaction" value="like">
                <input type="hidden" name="back" value="<?= g_h($backToPost) ?>">

                <button class="btn btn-sm g-react-btn <?= $likeActive ? 'btn-success' : 'btn-outline-success' ?>"
                        type="submit"
                        data-post="<?= $pid ?>"
                        data-react="like"
                        title="<?= g_h(g_t('Лайків: ', 'Лайков: ', 'Likes: ') . $likesCount) ?>"
                        aria-label="<?= g_h(g_t('Лайк', 'Лайк', 'Like')) ?>">
                    <span>👍</span>
                    <span class="count" id="likes-<?= $pid ?>"><?= $likesCount ?></span>
                </button>
            </form>

            <form method="post" action="/post_react.php" class="d-inline js-post-react-form" data-no-pjax="1">
                <input type="hidden" name="csrf" value="<?= g_h(vm_csrf_token()) ?>">
                <input type="hidden" name="post_id" value="<?= $pid ?>">
                <input type="hidden" name="reaction" value="dislike">
                <input type="hidden" name="back" value="<?= g_h($backToPost) ?>">
                <button class="btn btn-sm g-react-btn <?= $disActive ? 'btn-danger' : 'btn-outline-danger' ?>"
                        type="submit"
                        data-post="<?= $pid ?>"
                        data-react="dislike"
                        title="<?= g_h(g_t('Дизлайків: ', 'Дизлайков: ', 'Dislikes: ') . $dislikesCount) ?>"
                        aria-label="<?= g_h(g_t('Дизлайк', 'Дизлайк', 'Dislike')) ?>">
                    <span>👎</span>
                    <span class="count" id="dislikes-<?= $pid ?>"><?= $dislikesCount ?></span>
                </button>
            </form>

            <?php if ($me): ?>
                <form method="post" action="/post_repost.php" class="d-inline">
                    <input type="hidden" name="csrf" value="<?= g_h(vm_csrf_token()) ?>">
                    <input type="hidden" name="post_id" value="<?= $pid ?>">
                    <input type="hidden" name="back" value="<?= g_h($backToPost) ?>">
                    <button class="btn btn-sm btn-outline-primary" type="submit">
                        ↻ <?= g_h(g_t('Репост', 'Репост', 'Repost')) ?>
                    </button>
                </form>
            <?php endif; ?>

            <?php if ($canPromotePost): ?>
                <a class="btn btn-sm btn-outline-warning" href="/functional/reclama/create.php?post_id=<?= $pid ?>">
                    📣 <?= g_h(g_t('Рекламувати', 'Рекламировать', 'Promote')) ?>
                </a>
            <?php endif; ?>

            <?php if ($isPromoted && $promotedClickUrl !== ''): ?>
                <a class="btn btn-sm btn-outline-info"
                   href="<?= g_h($promotedClickUrl) ?>"
                   target="_blank"
                   rel="noopener nofollow sponsored">
                    ↗ <?= g_h(g_t('Перейти', 'Перейти', 'Open')) ?>
                </a>
            <?php endif; ?>

            <a class="btn btn-sm btn-outline-secondary" href="<?= g_h($profileUrl) ?>">
                <?= g_h(g_t('Профіль автора', 'Профиль автора', 'Author profile')) ?>
            </a>
        </div>

        <div class="g-comments-wrap">
            <div class="comments-title"><?= g_h(g_t('Коментарі', 'Комментарии', 'Comments')) ?></div>

            <?php if ($canComment): ?>
                <form method="post" action="/functional/comment/create.php" enctype="multipart/form-data" class="mt-2">
                    <input type="hidden" name="csrf" value="<?= g_h(vm_csrf_token()) ?>">
                    <input type="hidden" name="post_id" value="<?= $pid ?>">
                    <input type="hidden" name="parent_id" value="">
                    <input type="hidden" name="back" value="<?= g_h($backToPost) ?>">

                    <div class="vm-emoji-wrap">
                        <textarea class="form-control form-control-sm js-emoji-target" name="body" rows="2" placeholder="<?= g_h(g_t('Коментар...', 'Комментарий...', 'Comment...')) ?>"></textarea>
                    </div>

                    <div class="d-flex flex-wrap gap-2 align-items-center justify-content-between mt-2">
                        <input class="form-control form-control-sm" type="file" name="files[]" multiple
                               accept="image/*,audio/*,video/*,.pdf,.zip,.rar,.7z,.txt,.doc,.docx,.xls,.xlsx">
                        <button class="btn btn-sm btn-primary" type="submit"><?= g_h(g_t('Надіслати', 'Отправить', 'Send')) ?></button>
                    </div>
                </form>
            <?php elseif (!$me): ?>
                <div class="text-muted small mt-2"><?= g_h(g_t('Увійдіть, щоб коментувати.', 'Войдите, чтобы комментировать.', 'Log in to comment.')) ?></div>
            <?php elseif ($isPendingInvite): ?>
                <div class="text-muted small mt-2"><?= g_h(g_t('Спочатку прийміть запрошення в групу.', 'Сначала примите приглашение в группу.', 'Accept the group invite first.')) ?></div>
            <?php elseif ($isBannedMember): ?>
                <div class="text-muted small mt-2"><?= g_h(g_t('Ви не можете коментувати в цій групі.', 'Вы не можете комментировать в этой группе.', 'You cannot comment in this group.')) ?></div>
            <?php else: ?>
                <div class="text-muted small mt-2"><?= g_h(g_t('Щоб коментувати, вступіть до групи.', 'Чтобы комментировать, вступите в группу.', 'Join the group to comment.')) ?></div>
            <?php endif; ?>

            <div class="comments-list mt-3">
                <?php
                $topComments = $commentsByPost[$pid] ?? [];
                foreach ($topComments as $c) {
                    g_render_comment($c, $repliesByParent, $commentAttById, $pid, $canComment, $me, $viewerIsAdmin, $isManager, $backUri, false);
                }
                ?>
            </div>
        </div>
    </div>
</div>