<?php
declare(strict_types=1);

if (!function_exists('vm_has_col')) {
    function vm_has_col(PDO $pdo, string $table, string $col): bool
    {
        static $cache = [];
        $k = $table . '.' . $col;
        if (array_key_exists($k, $cache)) return (bool)$cache[$k];
        $cache[$k] = function_exists('db_has_column') ? (bool)db_has_column($pdo, $table, $col) : false;
        return (bool)$cache[$k];
    }
}

if (!function_exists('vm_has_tbl')) {
    function vm_has_tbl(PDO $pdo, string $table): bool
    {
        static $cache = [];
        $k = 't:' . $table;
        if (array_key_exists($k, $cache)) return (bool)$cache[$k];
        $cache[$k] = function_exists('db_has_table') ? (bool)db_has_table($pdo, $table) : false;
        return (bool)$cache[$k];
    }
}

if (!function_exists('vm_row_full_name')) {
    function vm_row_full_name(array $row, string $prefix = ''): string
    {
        $fn = trim((string)($row[$prefix . 'full_name'] ?? ''));
        if ($fn !== '') return $fn;

        $first = trim((string)($row[$prefix . 'first_name'] ?? ''));
        $last  = trim((string)($row[$prefix . 'last_name'] ?? ''));
        $name  = trim($first . ' ' . $last);
        if ($name !== '') return $name;

        $u = trim((string)($row[$prefix . 'username'] ?? ''));
        if ($u !== '') return $u;

        return 'User';
    }
}

if (!function_exists('group_view_url_by_row')) {
    function group_view_url_by_row(array $row): string
    {
        $gid = (int)($row['group_pk'] ?? 0);
        $slug = (string)($row['group_slug'] ?? '');
        if ($slug !== '') return '/functional/group/view.php?g=' . rawurlencode($slug);
        if ($gid > 0) return '/functional/group/view.php?id=' . $gid;
        return '/functional/group/index.php';
    }
}

if (!function_exists('render_link_preview_card')) {
    function render_link_preview_card(?array $p, string $url, string $hash): void
    {
        $title = trim((string)($p['title'] ?? ''));
        $desc  = trim((string)($p['description'] ?? ''));
        $img   = trim((string)($p['image'] ?? ''));
        $site  = trim((string)($p['site_name'] ?? ''));

        ?>
        <div class="lp-card-feed mt-3" data-lp-hash="<?= h($hash) ?>" data-lp-url="<?= h($url) ?>">
            <a class="lp-card-inner" href="<?= h($url) ?>" target="_blank" rel="noopener nofollow ugc">
                <div class="lp-img">
                    <img loading="lazy" decoding="async" src="<?= h($img) ?>" alt="" <?= $img !== '' ? '' : 'style="display:none;"' ?>>
                </div>
                <div class="lp-meta">
                    <div class="lp-title"><?= h($title !== '' ? $title : $url) ?></div>
                    <?php if ($desc !== ''): ?>
                        <div class="lp-desc"><?= h($desc) ?></div>
                    <?php endif; ?>
                    <?php if ($site !== ''): ?>
                        <div class="lp-site"><?= h($site) ?></div>
                    <?php endif; ?>
                </div>
            </a>
        </div>
        <?php
    }
}

if (!function_exists('render_attachments')) {
    function render_attachments(array $atts, string $galleryId): void
    {
        $imgs = array_values(array_filter($atts, fn($a) => ($a['file_type'] ?? '') === 'image'));
        $aud  = array_values(array_filter($atts, fn($a) => ($a['file_type'] ?? '') === 'audio'));
        $vid  = array_values(array_filter($atts, fn($a) => ($a['file_type'] ?? '') === 'video'));
        $fil  = array_values(array_filter($atts, fn($a) => ($a['file_type'] ?? '') === 'file'));
        ?>
        <div class="post-attachments mt-3" data-gallery-images="<?= h($galleryId) ?>">
            <?php if ($imgs): ?>
                <?php if (count($imgs) === 1): ?>
                    <?php $a = $imgs[0]; ?>
                    <div class="attachments-single">
                        <a class="att-img att-img-single js-lightbox"
                           href="<?= h((string)$a['path']) ?>"
                           data-gallery="<?= h($galleryId) ?>"
                           target="_blank" rel="noopener">
                            <img loading="lazy" decoding="async" src="<?= h((string)$a['path']) ?>" alt="">
                        </a>
                    </div>
                <?php else: ?>
                    <div class="attachments-grid">
                        <?php foreach ($imgs as $a): ?>
                            <a class="att-img js-lightbox"
                               href="<?= h((string)$a['path']) ?>"
                               data-gallery="<?= h($galleryId) ?>"
                               target="_blank" rel="noopener">
                                <img loading="lazy" decoding="async" src="<?= h((string)$a['path']) ?>" alt="">
                            </a>
                        <?php endforeach; ?>
                    </div>
                <?php endif; ?>
            <?php endif; ?>

            <?php foreach ($aud as $a): ?>
                <div class="mt-2">
                    <audio controls preload="none" class="w-100">
                        <source src="<?= h((string)$a['path']) ?>" type="<?= h((string)$a['mime']) ?>">
                    </audio>
                </div>
            <?php endforeach; ?>

            <?php foreach ($vid as $a): ?>
                <div class="mt-2">
                    <video controls preload="metadata" class="w-100 rounded-3"
                           playsinline webkit-playsinline
                           disablepictureinpicture
                           controlslist="nodownload noplaybackrate">
                        <source src="<?= h((string)$a['path']) ?>" type="<?= h((string)$a['mime']) ?>">
                    </video>
                </div>
            <?php endforeach; ?>

            <?php if ($fil): ?>
                <div class="mt-2 d-flex flex-column gap-1">
                    <?php foreach ($fil as $a): ?>
                        <a class="att-file" href="<?= h((string)$a['path']) ?>" target="_blank" rel="noopener">
                            <?= h(t('download')) ?>: <?= h((string)$a['original_name']) ?>
                        </a>
                    <?php endforeach; ?>
                </div>
            <?php endif; ?>
        </div>
        <?php
    }
}

if (!function_exists('render_poll_box')) {
    function render_poll_box(
        ?array $poll,
        array $pollOptionsByPoll,
        array $pollVotesByOption,
        array $myPollVoteByPoll,
        bool $isLogged
    ): void {
        if (!$poll) return;

        $pollId = (int)($poll['id'] ?? 0);
        if ($pollId <= 0) return;

        $opts = $pollOptionsByPoll[$pollId] ?? [];
        if (!$opts) return;

        $myVoteOpt = (int)($myPollVoteByPoll[$pollId] ?? 0);

        $totalVotes = 0;
        foreach ($opts as $o) {
            $totalVotes += (int)($pollVotesByOption[(int)$o['id']] ?? 0);
        }
        ?>
        <div class="poll-box mt-3">
            <div class="fw-semibold mb-2"><?= h((string)$poll['question']) ?></div>

            <?php if ($isLogged): ?>
                <?php if ($myVoteOpt <= 0): ?>
                    <form method="post" action="/poll_vote.php" class="vstack gap-2">
                        <?= csrf_field() ?>
                        <input type="hidden" name="poll_id" value="<?= $pollId ?>">

                        <?php foreach ($opts as $o): ?>
                            <?php $oid = (int)$o['id']; ?>
                            <label class="poll-opt">
                                <input type="radio" name="option_id" value="<?= $oid ?>" required>
                                <span><?= h((string)$o['option_text']) ?></span>
                            </label>
                        <?php endforeach; ?>

                        <div class="d-flex align-items-center justify-content-between">
                            <button class="btn btn-sm btn-primary" type="submit"><?= h(t('poll_vote')) ?></button>
                            <div class="text-muted small"><?= h(t('poll_total_votes')) ?>: <?= $totalVotes ?></div>
                        </div>
                    </form>
                <?php else: ?>
                    <div class="vstack gap-2">
                        <?php foreach ($opts as $o): ?>
                            <?php
                            $oid = (int)$o['id'];
                            $cnt = (int)($pollVotesByOption[$oid] ?? 0);
                            $pct = $totalVotes > 0 ? (int)round(($cnt / $totalVotes) * 100) : 0;
                            $isMine = ($oid === (int)$myVoteOpt);
                            ?>
                            <div class="poll-res <?= $isMine ? 'mine' : '' ?>">
                                <div class="d-flex justify-content-between small mb-1">
                                    <div><?= h((string)$o['option_text']) ?><?= $isMine ? ' ✓' : '' ?></div>
                                    <div class="text-muted"><?= $cnt ?> (<?= $pct ?>%)</div>
                                </div>
                                <div class="poll-bar">
                                    <div class="poll-bar-fill" style="width: <?= $pct ?>%"></div>
                                </div>
                            </div>
                        <?php endforeach; ?>
                        <div class="text-muted small"><?= h(t('poll_total_votes')) ?>: <?= $totalVotes ?></div>
                    </div>
                <?php endif; ?>
            <?php else: ?>
                <div class="text-muted small"><?= h(t('only_for_logged')) ?></div>
            <?php endif; ?>
        </div>
        <?php
    }
}

if (!function_exists('render_comment')) {
    function render_comment(
        array $c,
        array $repliesByParent,
        array $commentAttById,
        array $previewByHash,
        int $postId,
        int $meId,
        bool $isAdmin,
        callable $T,
        bool $isReply = false
    ): void {
        $cid = (int)$c['id'];
        $galleryId = 'c' . $cid;

        $likes = (int)($c['likes'] ?? 0);
        $dislikes = (int)($c['dislikes'] ?? 0);
        $myReaction = (string)($c['my_reaction'] ?? '');
        $atts = $commentAttById[$cid] ?? [];

        $authorId = (int)($c['user_id'] ?? 0);
        $canManage = ($meId > 0) && ($isAdmin || $meId === $authorId);

        $fullName = vm_row_full_name($c);
        $username = (string)($c['username'] ?? '');
        $ava = user_avatar_path($c);
        $ini = user_initials($fullName, $username !== '' ? $username : 'U');

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

        $confirmDel = $T('Видалити коментар?', 'Удалить комментарий?', 'Delete comment?');
        $backToComment = current_uri() . '#comment-' . $cid;

        $likeBtnClass = ($myReaction === 'like') ? 'btn-success' : 'btn-outline-success';
        $disBtnClass  = ($myReaction === 'dislike') ? 'btn-danger' : 'btn-outline-danger';
        $likeTitle = $T('Лайків: ', 'Лайков: ', 'Likes: ') . $likes;
        $disTitle  = $T('Дизлайків: ', 'Дизлайков: ', 'Dislikes: ') . $dislikes;

        $imgs = array_values(array_filter($atts, fn($a) => ($a['file_type'] ?? '') === 'image'));
        $aud  = array_values(array_filter($atts, fn($a) => ($a['file_type'] ?? '') === 'audio'));
        $vid  = array_values(array_filter($atts, fn($a) => ($a['file_type'] ?? '') === 'video'));
        $fil  = array_values(array_filter($atts, fn($a) => ($a['file_type'] ?? '') === 'file'));

        $bodyText = (string)($c['body'] ?? '');
        $firstUrl = normalize_url(extract_first_url($bodyText));
        $firstHash = $firstUrl !== '' ? url_hash($firstUrl) : '';
        $lp = ($firstHash !== '' && isset($previewByHash[$firstHash])) ? $previewByHash[$firstHash] : null;
        ?>
        <div class="comment <?= $isReply ? 'is-reply' : '' ?>" id="comment-<?= $cid ?>">
            <div class="comment-head d-flex justify-content-between align-items-start gap-2">
                <div class="d-flex align-items-center gap-2">
                    <?php if ($authorProfileUrl !== ''): ?>
                        <a href="<?= h($authorProfileUrl) ?>" class="vm-ava-sm text-decoration-none">
                            <?php if ($ava !== ''): ?>
                                <img loading="lazy" decoding="async" src="<?= h($ava) ?>" alt="">
                            <?php else: ?>
                                <div class="vm-ava-ph"><?= h($ini) ?></div>
                            <?php endif; ?>
                        </a>
                    <?php else: ?>
                        <div class="vm-ava-sm">
                            <?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>
                    <?php endif; ?>

                    <div>
                        <div class="comment-author">
                            <?php if ($authorProfileUrl !== ''): ?>
                                <a href="<?= h($authorProfileUrl) ?>" class="text-decoration-none"><?= h($fullName) ?></a>
                            <?php else: ?>
                                <?= h($fullName) ?>
                            <?php endif; ?>
                            <?php if ($username !== ''): ?>
                                <span class="text-muted small"> @<?= h($username) ?></span>
                            <?php endif; ?>
                        </div>
                        <div class="comment-meta"><?= h((string)$c['created_at']) ?></div>
                    </div>
                </div>

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

                            <form method="post" action="/functional/comment/manage.php"
                                  onsubmit="return confirm(<?= json_encode($confirmDel, JSON_UNESCAPED_UNICODE) ?>);">
                                <?= csrf_field() ?>
                                <input type="hidden" name="action" value="delete">
                                <input type="hidden" name="id" value="<?= $cid ?>">
                                <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>

            <?php if (trim($bodyText) !== ''): ?>
                <div class="comment-body"><?= linkify_text($bodyText) ?></div>
            <?php endif; ?>

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

            <?php if ($atts): ?>
                <div class="comment-attachments mt-2" data-gallery-images="<?= h($galleryId) ?>">
                    <?php if ($imgs): ?>
                        <?php if (count($imgs) === 1): ?>
                            <?php $a = $imgs[0]; ?>
                            <div class="attachments-single">
                                <a class="att-img att-img-single js-lightbox"
                                   href="<?= h((string)$a['path']) ?>"
                                   data-gallery="<?= h($galleryId) ?>"
                                   target="_blank" rel="noopener">
                                    <img loading="lazy" decoding="async" src="<?= h((string)$a['path']) ?>" alt="">
                                </a>
                            </div>
                        <?php else: ?>
                            <div class="attachments-grid">
                                <?php foreach ($imgs as $a): ?>
                                    <a class="att-img js-lightbox"
                                       href="<?= h((string)$a['path']) ?>"
                                       data-gallery="<?= h($galleryId) ?>"
                                       target="_blank" rel="noopener">
                                        <img loading="lazy" decoding="async" src="<?= h((string)$a['path']) ?>" alt="">
                                    </a>
                                <?php endforeach; ?>
                            </div>
                        <?php endif; ?>
                    <?php endif; ?>

                    <?php foreach ($aud as $a): ?>
                        <div class="mt-2">
                            <audio controls preload="none" class="w-100">
                                <source src="<?= h((string)$a['path']) ?>" type="<?= h((string)$a['mime']) ?>">
                            </audio>
                        </div>
                    <?php endforeach; ?>

                    <?php foreach ($vid as $a): ?>
                        <div class="mt-2">
                            <video controls preload="metadata" class="w-100 rounded-3"
                                   playsinline webkit-playsinline
                                   disablepictureinpicture
                                   controlslist="nodownload noplaybackrate">
                                <source src="<?= h((string)$a['path']) ?>" type="<?= h((string)$a['mime']) ?>">
                            </video>
                        </div>
                    <?php endforeach; ?>

                    <?php if ($fil): ?>
                        <div class="mt-2 d-flex flex-column gap-1">
                            <?php foreach ($fil as $a): ?>
                                <a class="att-file" href="<?= h((string)$a['path']) ?>" target="_blank" rel="noopener">
                                    <?= h(t('download')) ?>: <?= h((string)$a['original_name']) ?>
                                </a>
                            <?php endforeach; ?>
                        </div>
                    <?php endif; ?>
                </div>
            <?php endif; ?>

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

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

                <?php if ($meId > 0): ?>
                    <button type="button" class="comment-reply-btn" data-reply-toggle="<?= $cid ?>">
                        <?= h(t('reply')) ?>
                    </button>
                <?php endif; ?>
            </div>

            <?php if ($meId > 0): ?>
                <div class="comment-reply-form d-none" id="reply-form-<?= $cid ?>">
                    <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="<?= $postId ?>">
                        <input type="hidden" name="parent_id" value="<?= $cid ?>">
                        <input type="hidden" name="back" value="<?= h(current_uri() . '#comment-' . $cid) ?>">

                        <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>

                            <div class="d-flex gap-2">
                                <button class="btn btn-sm btn-primary" type="submit"><?= h(t('send')) ?></button>
                                <button class="btn btn-sm btn-outline-secondary" type="button" data-reply-cancel="<?= $cid ?>"><?= h(t('cancel')) ?></button>
                            </div>
                        </div>
                    </form>
                </div>
            <?php endif; ?>

            <?php
            $repls = $repliesByParent[$cid] ?? [];
            if ($repls):
                ?>
                <div class="comment-replies mt-2">
                    <?php foreach ($repls as $r): ?>
                        <?php render_comment($r, $repliesByParent, $commentAttById, $previewByHash, $postId, $meId, $isAdmin, $T, true); ?>
                    <?php endforeach; ?>
                </div>
            <?php endif; ?>
        </div>
        <?php
    }
}