<?php
declare(strict_types=1);

/**
 * /functional/board/view.php
 * Перегляд оголошення
 */

require_once dirname(__DIR__, 2) . '/includes/start.php';
require_once __DIR__ . '/_lib.php';

$pdo = brd_db();
$me  = brd_me();

if (!brd_ready($pdo)) {
    http_response_code(500);
    echo 'Board module tables were not found. Run SQL migration first.';
    exit;
}

$adId = (int)($_GET['id'] ?? 0);
$ad = brd_load_ad($pdo, $adId);

if (!$ad || !brd_can_view_ad($ad, $me)) {
    http_response_code(404);
    exit('Ad not found.');
}

if ((string)($ad['status'] ?? '') === 'approved') {
    brd_record_view($pdo, $adId, $me);
    $ad = brd_load_ad($pdo, $adId) ?: $ad;
}

$images = brd_ad_images($pdo, $adId);
$isOwner = $me && (int)($me['id'] ?? 0) === (int)($ad['user_id'] ?? 0);
$displayName = brd_public_display_name($ad);
$title = (string)($ad['title'] ?? brd_t('Оголошення', 'Объявление', 'Ad'));
$meta_desc = mb_substr(trim(strip_tags((string)($ad['description'] ?? ''))), 0, 160);
$canonical = function_exists('abs_url') ? abs_url(brd_ad_url($adId)) : null;

require dirname(__DIR__, 2) . '/includes/header.php';
?>
<div class="container my-4">
    <style>
        .brd-lightbox-trigger {
            cursor: zoom-in;
        }
        .brd-lightbox-backdrop {
            position: fixed;
            inset: 0;
            background: rgba(0,0,0,.88);
            display: none;
            align-items: center;
            justify-content: center;
            padding: 24px;
            z-index: 99999;
        }
        .brd-lightbox-backdrop.is-open {
            display: flex;
        }
        .brd-lightbox-dialog {
            position: relative;
            max-width: min(96vw, 1400px);
            max-height: 92vh;
            display: flex;
            align-items: center;
            justify-content: center;
        }
        .brd-lightbox-image {
            display: block;
            max-width: 100%;
            max-height: 92vh;
            width: auto;
            height: auto;
            object-fit: contain;
            border-radius: 14px;
            box-shadow: 0 20px 60px rgba(0,0,0,.35);
            background: #111;
        }
        .brd-lightbox-close {
            position: absolute;
            top: -14px;
            right: -14px;
            width: 42px;
            height: 42px;
            border: 0;
            border-radius: 999px;
            background: #fff;
            color: #111;
            font-size: 28px;
            line-height: 1;
            cursor: pointer;
            box-shadow: 0 10px 25px rgba(0,0,0,.25);
        }
        .brd-lightbox-caption {
            position: fixed;
            left: 50%;
            bottom: 16px;
            transform: translateX(-50%);
            max-width: calc(100vw - 32px);
            padding: 8px 14px;
            border-radius: 999px;
            background: rgba(0,0,0,.55);
            color: #fff;
            font-size: 14px;
            text-align: center;
        }
        @media (max-width: 576px) {
            .brd-lightbox-backdrop {
                padding: 12px;
            }
            .brd-lightbox-close {
                top: 8px;
                right: 8px;
            }
        }
    </style>

    <div class="d-flex flex-wrap justify-content-between align-items-center gap-2 mb-3">
        <div>
            <div class="d-flex flex-wrap gap-2 align-items-center mb-1">
                <h1 class="h3 m-0"><?= brd_h((string)$ad['title']) ?></h1>
                <span class="badge bg-<?= brd_h(brd_status_badge_class((string)$ad['status'])) ?>">
                    <?= brd_h(brd_status_label((string)$ad['status'])) ?>
                </span>
                <?php if (trim((string)($ad['category_name'] ?? '')) !== ''): ?>
                    <span class="badge bg-light text-dark border"><?= brd_h((string)$ad['category_name']) ?></span>
                <?php endif; ?>
            </div>
            <div class="text-muted">
                <?= brd_h(trim((string)($ad['region_name'] ?? '') . ((string)($ad['city_name'] ?? '') !== '' ? ', ' . (string)$ad['city_name'] : ''))) ?>
            </div>
        </div>

        <div class="d-flex flex-wrap gap-2">
            <?php if ($isOwner): ?>
                <a class="btn btn-outline-primary" href="/functional/board/edit.php?id=<?= (int)$ad['id'] ?>">
                    <?= brd_h(brd_t('Редагувати', 'Редактировать', 'Edit')) ?>
                </a>
                <a class="btn btn-outline-secondary" href="/functional/board/my.php">
                    <?= brd_h(brd_t('Мої оголошення', 'Мои объявления', 'My ads')) ?>
                </a>
            <?php endif; ?>
            <a class="btn btn-outline-secondary" href="/board.php"><?= brd_h(brd_t('Назад до каталогу', 'Назад к каталогу', 'Back to catalog')) ?></a>
        </div>
    </div>

    <div class="row g-4">
        <div class="col-lg-8">
            <div class="card card-app overflow-hidden mb-3">
                <?php if (trim((string)($ad['main_image_path'] ?? '')) !== ''): ?>
                    <img
                        src="<?= brd_h((string)$ad['main_image_path']) ?>"
                        alt=""
                        class="img-fluid brd-lightbox-trigger"
                        data-board-lightbox="<?= brd_h((string)$ad['main_image_path']) ?>"
                        style="width:100%;max-height:540px;object-fit:contain;background:#f8f9fa;"
                    >
                <?php endif; ?>
            </div>

            <?php if ($images): ?>
                <div class="card card-app p-3 mb-3">
                    <div class="fw-semibold mb-3"><?= brd_h(brd_t('Додаткові фото', 'Дополнительные фото', 'Additional images')) ?></div>
                    <div class="row g-3">
                        <?php foreach ($images as $img): ?>
                            <div class="col-md-4">
                                <img
                                    src="<?= brd_h((string)$img['rel_path']) ?>"
                                    alt=""
                                    class="img-fluid rounded border brd-lightbox-trigger"
                                    data-board-lightbox="<?= brd_h((string)$img['rel_path']) ?>"
                                    style="width:100%;height:180px;object-fit:cover;"
                                >
                            </div>
                        <?php endforeach; ?>
                    </div>
                </div>
            <?php endif; ?>

            <div class="card card-app p-3 mb-3">
                <div class="d-flex flex-wrap gap-2 mb-3 align-items-center">
                    <span class="badge bg-success fs-6">
                        <?= brd_h(number_format((float)($ad['price_amount'] ?? 0), 2, '.', ' ') . ' ' . (string)($ad['currency_code'] ?? 'UAH')) ?>
                    </span>
                    <span class="text-muted small">
                        <?= brd_h(brd_t('Автор', 'Автор', 'Author')) ?>:
                        <a class="text-decoration-none" href="<?= brd_h(brd_profile_url((string)$ad['author_username'])) ?>">
                            <?= brd_h($displayName) ?>
                        </a>
                    </span>
                </div>

                <div style="white-space:pre-wrap;"><?= brd_h((string)($ad['description'] ?? '')) ?></div>
            </div>

            <?php if ($isOwner): ?>
                <div class="card card-app p-3">
                    <div class="fw-semibold mb-2"><?= brd_h(brd_t('Статистика оголошення', 'Статистика объявления', 'Ad statistics')) ?></div>
                    <div class="d-flex flex-wrap gap-4">
                        <div>
                            <div class="text-muted small"><?= brd_h(brd_t('Усього переглядів', 'Всего просмотров', 'Total views')) ?></div>
                            <div class="fs-4 fw-semibold"><?= (int)($ad['total_views'] ?? 0) ?></div>
                        </div>
                        <div>
                            <div class="text-muted small"><?= brd_h(brd_t('Унікальні перегляди', 'Уникальные просмотры', 'Unique views')) ?></div>
                            <div class="fs-4 fw-semibold"><?= (int)($ad['unique_views'] ?? 0) ?></div>
                        </div>
                    </div>
                </div>
            <?php endif; ?>
        </div>

        <div class="col-lg-4">
            <div class="card card-app p-3 mb-3">
                <div class="fw-semibold mb-3"><?= brd_h(brd_t('Контакти', 'Контакты', 'Contacts')) ?></div>

                <?php if (trim((string)($ad['contact_name'] ?? '')) !== ''): ?>
                    <div class="mb-2"><strong><?= brd_h(brd_t('Імʼя', 'Имя', 'Name')) ?>:</strong> <?= brd_h((string)$ad['contact_name']) ?></div>
                <?php endif; ?>

                <?php if (trim((string)($ad['contact_phone'] ?? '')) !== ''): ?>
                    <div class="mb-2"><strong><?= brd_h(brd_t('Телефон', 'Телефон', 'Phone')) ?>:</strong> <?= brd_h((string)$ad['contact_phone']) ?></div>
                <?php endif; ?>

                <?php if (trim((string)($ad['contact_email'] ?? '')) !== ''): ?>
                    <div class="mb-2"><strong>Email:</strong> <?= brd_h((string)$ad['contact_email']) ?></div>
                <?php endif; ?>

                <?php if (trim((string)($ad['contact_telegram'] ?? '')) !== ''): ?>
                    <div class="mb-3"><strong>Telegram:</strong> <?= brd_h((string)$ad['contact_telegram']) ?></div>
                <?php endif; ?>

                <?php if ($me && !$isOwner): ?>
                    <a class="btn btn-success" href="/messages/?u=<?= urlencode((string)$ad['author_username']) ?>">
                        ✉️ <?= brd_h(brd_t('Написати в приватні', 'Написать в личные', 'Write a private message')) ?>
                    </a>
                <?php elseif (!$me): ?>
                    <a class="btn btn-success" href="/login.php?to=<?= urlencode(brd_ad_url($adId)) ?>">
                        ✉️ <?= brd_h(brd_t('Увійти, щоб написати', 'Войти, чтобы написать', 'Log in to message')) ?>
                    </a>
                <?php endif; ?>
            </div>

            <?php if ((string)($ad['status'] ?? '') !== 'approved' && $isOwner): ?>
                <div class="card card-app p-3">
                    <div class="fw-semibold mb-2"><?= brd_h(brd_t('Стан публікації', 'Состояние публикации', 'Publication state')) ?></div>
                    <div class="mb-2">
                        <?= brd_h(brd_status_label((string)$ad['status'])) ?>
                    </div>
                    <?php if (trim((string)($ad['moderation_note'] ?? '')) !== ''): ?>
                        <div class="alert alert-danger mb-0">
                            <?= brd_h((string)$ad['moderation_note']) ?>
                        </div>
                    <?php endif; ?>
                </div>
            <?php endif; ?>
        </div>
    </div>
</div>

<div class="brd-lightbox-backdrop" id="brdImageLightbox" aria-hidden="true">
    <div class="brd-lightbox-dialog" role="dialog" aria-modal="true" aria-label="Image preview">
        <button type="button" class="brd-lightbox-close" id="brdImageLightboxClose" aria-label="Close">&times;</button>
        <img src="" alt="" class="brd-lightbox-image" id="brdImageLightboxImg">
    </div>
    <div class="brd-lightbox-caption"><?= brd_h(brd_t('Натисніть поза фото або Esc, щоб закрити', 'Нажмите вне фото или Esc, чтобы закрыть', 'Click outside image or press Esc to close')) ?></div>
</div>

<script>
(function () {
    const lightbox = document.getElementById('brdImageLightbox');
    const imageEl = document.getElementById('brdImageLightboxImg');
    const closeBtn = document.getElementById('brdImageLightboxClose');
    const triggers = document.querySelectorAll('[data-board-lightbox]');
    if (!lightbox || !imageEl || !closeBtn || !triggers.length) return;

    const body = document.body;
    let previousOverflow = '';

    function openLightbox(src) {
        if (!src) return;
        imageEl.src = src;
        lightbox.classList.add('is-open');
        lightbox.setAttribute('aria-hidden', 'false');
        previousOverflow = body.style.overflow || '';
        body.style.overflow = 'hidden';
    }

    function closeLightbox() {
        lightbox.classList.remove('is-open');
        lightbox.setAttribute('aria-hidden', 'true');
        imageEl.src = '';
        body.style.overflow = previousOverflow;
    }

    triggers.forEach(function (trigger) {
        trigger.addEventListener('click', function () {
            openLightbox(trigger.getAttribute('data-board-lightbox') || '');
        });
    });

    closeBtn.addEventListener('click', closeLightbox);

    lightbox.addEventListener('click', function (event) {
        if (event.target === lightbox) {
            closeLightbox();
        }
    });

    document.addEventListener('keydown', function (event) {
        if (event.key === 'Escape' && lightbox.classList.contains('is-open')) {
            closeLightbox();
        }
    });
})();
</script>
<?php require dirname(__DIR__, 2) . '/includes/footer.php'; ?>
