<?php
declare(strict_types=1);

$pid = (int)($p['id'] ?? 0);
$authorId = (int)($p['user_id'] ?? ($p['author_user_id'] ?? 0));

$isPromoted = ((int)($p['is_promoted'] ?? 0) === 1);
$promotedCampaignId = (int)($p['promoted_campaign_id'] ?? 0);
$promotedClickUrl = trim((string)($p['promoted_click_url'] ?? ''));

$isRepost = $hasRepost && ((int)($p['repost_post_id'] ?? 0) > 0);
$contentId = $pid;
if ($isRepost) $contentId = (int)$p['repost_post_id'];

$atts = $attachmentsByPost[$contentId] ?? [];
$poll = $pollByPost[$contentId] ?? null;

$likes = (int)($p['likes'] ?? 0);
$dislikes = (int)($p['dislikes'] ?? 0);
$myReaction = (string)($p['my_reaction'] ?? '');

$posterFullName = vm_row_full_name($p);
$posterUsername = (string)($p['username'] ?? ($p['author_username'] ?? ''));
$posterAva = user_avatar_path($p);
$posterIni = user_initials($posterFullName, $posterUsername !== '' ? $posterUsername : 'U');

$posterProfileUrl = ($posterUsername !== '')
    ? ('/profile/index.php?u=' . rawurlencode($posterUsername))
    : (($authorId > 0) ? ('/profile/index.php?id=' . $authorId) : '#');

$gid = $hasGroupId ? (int)($p['group_id'] ?? 0) : 0;
$groupName = $hasGroupId ? (string)($p['group_name'] ?? '') : '';
$groupSlug = $hasGroupId ? (string)($p['group_slug'] ?? '') : '';
$groupAva  = $hasGroupId ? (string)($p['group_avatar_path'] ?? '') : '';

$isGroupPost = $hasGroupId && ($gid > 0) && ($groupName !== '');

$groupUrl = '';
if ($isGroupPost) {
    $groupUrl = ($groupSlug !== '')
        ? ('/functional/group/view.php?g=' . rawurlencode($groupSlug))
        : ('/functional/group/view.php?id=' . $gid);
}

$fullName = $isGroupPost ? $groupName : $posterFullName;
$username = $isGroupPost ? $groupSlug : $posterUsername;
$ava      = $isGroupPost ? $groupAva : $posterAva;
$ini      = $isGroupPost ? user_initials($groupName, $groupSlug !== '' ? $groupSlug : 'G') : $posterIni;

$groupOwnerId  = $isGroupPost ? (int)($p['group_owner_user_id'] ?? 0) : 0;
$myGroupRole   = $isGroupPost ? (string)($p['my_group_role'] ?? '') : '';
$myGroupStatus = $isGroupPost ? (string)($p['my_group_status'] ?? '') : '';

$canManagePost = ($meId > 0) && (
    $isAdmin
    || $meId === $authorId
    || (
        $isGroupPost
        && (
            ($groupOwnerId > 0 && $meId === $groupOwnerId)
            || ($myGroupStatus === 'active' && in_array($myGroupRole, ['owner','admin'], true))
        )
    )
);

$canPromoteGroupPost = (
    $isGroupPost
    && (
        ($groupOwnerId > 0 && $meId === $groupOwnerId)
        || ($myGroupStatus === 'active' && in_array($myGroupRole, ['owner','admin'], true))
    )
);

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

$origUserId   = $isRepost ? (int)($p['orig_user_id'] ?? 0) : 0;
$origFullName = $isRepost ? vm_row_full_name($p, 'orig_') : '';
$origUsername = $isRepost ? (string)($p['orig_username'] ?? '') : '';
$origAva = $isRepost ? user_avatar_path($p, 'orig_') : '';
$origIni = $isRepost ? user_initials($origFullName, $origUsername !== '' ? $origUsername : 'U') : '';
$origBody = $isRepost ? (string)($p['orig_body'] ?? '') : '';
$origCreated = $isRepost ? (string)($p['orig_created_at'] ?? '') : '';

$origProfileUrl = ($origUsername !== '')
    ? ('/profile/index.php?u=' . rawurlencode($origUsername))
    : (($origUserId > 0) ? ('/profile/index.php?id=' . $origUserId) : '#');

$origGid = ($hasGroupId && $isRepost) ? (int)($p['orig_group_id'] ?? 0) : 0;
$origGroupName = ($hasGroupId && $isRepost) ? (string)($p['orig_group_name'] ?? '') : '';
$origGroupSlug = ($hasGroupId && $isRepost) ? (string)($p['orig_group_slug'] ?? '') : '';
$origGroupAva  = ($hasGroupId && $isRepost) ? (string)($p['orig_group_avatar_path'] ?? '') : '';
$origIsGroupPost = ($hasGroupId && $isRepost && $origGid > 0 && $origGroupName !== '');

$origGroupUrl = '';
if ($origIsGroupPost) {
    $origGroupUrl = ($origGroupSlug !== '')
        ? ('/functional/group/view.php?g=' . rawurlencode($origGroupSlug))
        : ('/functional/group/view.php?id=' . $origGid);
}

$byLabel = $T('Від', 'От', 'By');

$firstUrl = normalize_url(extract_first_url((string)($p['body'] ?? '')));
$firstHash = $firstUrl !== '' ? url_hash($firstUrl) : '';
$lp = ($firstHash !== '' && isset($previewByHash[$firstHash])) ? $previewByHash[$firstHash] : null;

$backToPost = current_uri() . '#post-' . $pid;

$canPromotePost = (
    $meId > 0
    && !$isPromoted
    && function_exists('reclama_is_enabled')
    && function_exists('reclama_allow_post_campaigns')
    && reclama_is_enabled($pdo)
    && reclama_allow_post_campaigns($pdo)
    && (
        $authorId === $meId
        || $canPromoteGroupPost
    )
);

$likeBtnClass = ($myReaction === 'like') ? 'btn-success' : 'btn-outline-success';
$disBtnClass  = ($myReaction === 'dislike') ? 'btn-danger' : 'btn-outline-danger';

$likeTitle = $T('Лайків: ', 'Лайков: ', 'Likes: ') . $likes;
$disTitle  = $T('Дизлайків: ', 'Дизлайков: ', 'Dislikes: ') . $dislikes;
$sponsoredLabel = $T('РЕКЛАМА', 'РЕКЛАМА', 'SPONSORED');

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);
}
</style>
HTML;
}
?>
<div class="card card-app p-3 mb-3" id="post-<?= $pid ?>">
    <div class="d-flex justify-content-between align-items-start gap-2">
        <div class="d-flex align-items-center gap-2">
            <div class="vm-ava">
                <?php if ($ava !== ''): ?>
                    <img loading="lazy" decoding="async" src="<?= h($ava) ?>" alt="">
                <?php else: ?>
                    <div class="vm-ava-ph"><?= h($ini) ?></div>
                <?php endif; ?>
            </div>

            <div>
                <div class="post-author">
                    <?php if ($isGroupPost && $groupUrl !== ''): ?>
                        <a href="<?= h($groupUrl) ?>" class="text-decoration-none"><?= h($fullName) ?></a>
                    <?php else: ?>
                        <a href="<?= h($posterProfileUrl) ?>" class="text-decoration-none"><?= h($fullName) ?></a>
                    <?php endif; ?>

                    <?php if ($username !== ''): ?>
                        <span class="text-muted small"> @<?= h($username) ?></span>
                    <?php endif; ?>
                </div>

                <div class="post-meta d-flex flex-wrap align-items-center gap-2">
                    <span><?= h((string)$p['created_at']) ?></span>
                    <?php if ($isPromoted): ?>
                        <span class="vm-sponsored-badge"><?= h($sponsoredLabel) ?></span>
                    <?php endif; ?>
                </div>

                <?php if ($isGroupPost): ?>
                    <div class="text-muted small">
                        <?= h($byLabel) ?>
                        <a href="<?= h($posterProfileUrl) ?>" class="text-decoration-none"><?= h($posterFullName) ?></a>
                        <?php if ($posterUsername !== ''): ?>
                            <span class="text-muted small"> @<?= h($posterUsername) ?></span>
                        <?php endif; ?>
                    </div>
                <?php endif; ?>

                <?php if ($isRepost): ?>
                    <div class="vm-repost-label"><?= h($T('Репост','Репост','Repost')) ?></div>
                <?php endif; ?>
            </div>
        </div>

        <div class="d-flex align-items-center gap-2">
            <?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(current_uri()) ?>">
                            <?= h($T('Редагувати','Редактировать','Edit')) ?>
                        </a>

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

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

        <?php if ($firstUrl !== '' && $firstHash !== ''): ?>
            <?php render_link_preview_card($lp, $firstUrl, $firstHash); ?>
        <?php endif; ?>

        <div class="vm-repost-box mt-3">
            <div class="d-flex align-items-center gap-2">
                <div class="vm-ava-sm">
                    <?php if ($origIsGroupPost): ?>
                        <?php if ($origGroupAva !== ''): ?>
                            <img loading="lazy" decoding="async" src="<?= h($origGroupAva) ?>" alt="">
                        <?php else: ?>
                            <div class="vm-ava-ph"><?= h(user_initials($origGroupName, $origGroupSlug !== '' ? $origGroupSlug : 'G')) ?></div>
                        <?php endif; ?>
                    <?php else: ?>
                        <?php if ($origAva !== ''): ?>
                            <img loading="lazy" decoding="async" src="<?= h($origAva) ?>" alt="">
                        <?php else: ?>
                            <div class="vm-ava-ph"><?= h($origIni) ?></div>
                        <?php endif; ?>
                    <?php endif; ?>
                </div>
                <div>
                    <div class="fw-semibold">
                        <?php if ($origIsGroupPost && $origGroupUrl !== ''): ?>
                            <a href="<?= h($origGroupUrl) ?>" class="text-decoration-none"><?= h($origGroupName) ?></a>
                            <?php if ($origGroupSlug !== ''): ?>
                                <span class="text-muted small"> @<?= h($origGroupSlug) ?></span>
                            <?php endif; ?>
                        <?php else: ?>
                            <a href="<?= h($origProfileUrl) ?>" class="text-decoration-none"><?= h($origFullName) ?></a>
                            <?php if ($origUsername !== ''): ?>
                                <span class="text-muted small"> @<?= h($origUsername) ?></span>
                            <?php endif; ?>
                        <?php endif; ?>
                    </div>
                    <div class="text-muted small"><?= h($origCreated) ?></div>

                    <?php if ($origIsGroupPost): ?>
                        <div class="text-muted small">
                            <?= h($byLabel) ?>
                            <a href="<?= h($origProfileUrl) ?>" class="text-decoration-none"><?= h($origFullName) ?></a>
                            <?php if ($origUsername !== ''): ?>
                                <span class="text-muted small"> @<?= h($origUsername) ?></span>
                            <?php endif; ?>
                        </div>
                    <?php endif; ?>
                </div>
            </div>

            <?php if (trim($origBody) !== ''): ?>
                <div class="mt-2"><?= linkify_text((string)$origBody) ?></div>
            <?php endif; ?>

            <?php if ($atts): ?>
                <?php render_attachments($atts, 'p' . $pid); ?>
            <?php endif; ?>

            <?php render_poll_box($poll, $pollOptionsByPoll, $pollVotesByOption, $myPollVoteByPoll, (bool)$me); ?>
        </div>

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

        <?php if ($firstUrl !== '' && $firstHash !== ''): ?>
            <?php render_link_preview_card($lp, $firstUrl, $firstHash); ?>
        <?php endif; ?>

        <?php if ($atts): ?>
            <?php render_attachments($atts, 'p' . $pid); ?>
        <?php endif; ?>

        <?php render_poll_box($poll, $pollOptionsByPoll, $pollVotesByOption, $myPollVoteByPoll, (bool)$me); ?>
    <?php endif; ?>

    <div class="post-actions mt-3 d-flex align-items-center gap-2 flex-wrap">
        <form method="post" action="/post_react.php" class="d-inline js-post-react-form" data-no-pjax="1">
            <?= csrf_field() ?>
            <input type="hidden" name="post_id" value="<?= $pid ?>">
            <input type="hidden" name="reaction" value="like">
            <input type="hidden" name="back" value="<?= h($backToPost) ?>">
            <button type="submit"
                    class="btn btn-sm <?= h($likeBtnClass) ?>"
                    data-post="<?= $pid ?>" data-react="like"
                    title="<?= h($likeTitle) ?>"
                    aria-label="<?= h(t('like')) ?>">
                👍 <span class="count" id="likes-<?= $pid ?>"><?= $likes ?></span>
            </button>
        </form>

        <form method="post" action="/post_react.php" class="d-inline js-post-react-form" data-no-pjax="1">
            <?= csrf_field() ?>
            <input type="hidden" name="post_id" value="<?= $pid ?>">
            <input type="hidden" name="reaction" value="dislike">
            <input type="hidden" name="back" value="<?= h($backToPost) ?>">
            <button type="submit"
                    class="btn btn-sm <?= h($disBtnClass) ?>"
                    data-post="<?= $pid ?>" data-react="dislike"
                    title="<?= h($disTitle) ?>"
                    aria-label="<?= h(t('dislike')) ?>">
                👎 <span class="count" id="dislikes-<?= $pid ?>"><?= $dislikes ?></span>
            </button>
        </form>

        <?php if ($meId > 0 && $hasRepost): ?>
            <?php
            $targetRepostId = $pid;
            if ($isRepost) $targetRepostId = (int)$p['repost_post_id'];
            ?>
            <form method="post" action="/post_repost.php" class="d-inline">
                <?= csrf_field() ?>
                <input type="hidden" name="post_id" value="<?= $targetRepostId ?>">
                <input type="hidden" name="back" value="<?= h($backToPost) ?>">
                <button type="submit" class="btn btn-sm btn-outline-secondary">
                    🔁 <?= h($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 ?>">
                📣 <?= h($T('Рекламувати', 'Рекламировать', 'Promote')) ?>
            </a>
        <?php endif; ?>

        <?php if ($isPromoted && $promotedClickUrl !== ''): ?>
            <?php
              $promotedCampaignId = (int)($p['promoted_campaign_id'] ?? 0);
              $promotedOpenHref = $promotedClickUrl;
              if ($promotedCampaignId > 0) {
                  $promotedOpenHref = '/functional/reclama/click.php?c=' . $promotedCampaignId
                      . '&p=' . rawurlencode($isGroupPost ? 'group_feed' : 'feed')
                      . '&to=' . rawurlencode($promotedClickUrl);
              }
            ?>
            <a class="btn btn-sm btn-outline-primary"
               href="<?= h($promotedOpenHref) ?>"
               target="_blank"
               rel="noopener nofollow sponsored">
                ↗ <?= h($T('Перейти', 'Перейти', 'Open')) ?>
            </a>
        <?php endif; ?>
    </div>

    <div class="comments-box mt-3">
        <div class="comments-title"><?= h(t('comments')) ?></div>

        <?php if ($me): ?>
            <form method="post" action="/functional/comment/create.php" enctype="multipart/form-data" class="vstack gap-2 mt-2">
                <?= csrf_field() ?>
                <input type="hidden" name="post_id" value="<?= $pid ?>">

                <input type="hidden" name="parent_id" value="">
                <input type="hidden" name="back" value="<?= h($backToPost) ?>">

                <div class="vm-emoji-wrap">
                    <textarea class="form-control js-emoji-target" name="body" rows="2" placeholder="<?= h(t('write_comment')) ?>"></textarea>
                </div>

                <div class="d-flex flex-wrap gap-2 align-items-center justify-content-between">
                    <label class="btn btn-sm btn-outline-secondary mb-0">
                        <?= h(t('attach_files')) ?>
                        <input type="file" name="files[]" multiple hidden
                               accept="image/*,audio/*,video/*,.pdf,.zip,.rar,.7z,.txt,.doc,.docx,.xls,.xlsx">
                    </label>

                    <button class="btn btn-sm btn-primary" type="submit"><?= h(t('send')) ?></button>
                </div>
            </form>
        <?php else: ?>
            <div class="text-muted small mt-2"><?= h(t('only_for_logged')) ?></div>
        <?php endif; ?>

        <div class="comments-list mt-3">
            <?php
            $top = $commentsByPost[$pid] ?? [];
            foreach ($top as $c) {
                render_comment($c, $repliesByParent, $commentAttById, $previewByHash, $pid, $meId, $isAdmin, $T, false);
            }
            ?>
        </div>
    </div>
</div>