<?php
declare(strict_types=1);

/**
 * /functional/board/index.php
 * Публічний каталог дошки оголошень
 */

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

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

$settings = brd_load_settings($pdo);

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

if (($settings['board_enabled'] ?? '1') !== '1' && !brd_is_admin($me)) {
    http_response_code(404);
    echo 'Board module is disabled.';
    exit;
}

$viewerCountry = brd_detect_country_code($me, $settings);
$categories = brd_categories($pdo);
$regions = brd_regions($pdo, $viewerCountry);

$q = brd_trimmed($_GET['q'] ?? '');
$categoryId = (int)($_GET['category'] ?? 0);
$regionId = (int)($_GET['region_id'] ?? 0);
$city = brd_trimmed($_GET['city'] ?? '');
$page = max(1, (int)($_GET['page'] ?? 1));

$pagination = brd_pagination($page, (int)($settings['board_items_per_page'] ?? 12));

$where = ["a.status = 'approved'", "a.country_code = ?"];
$params = [$viewerCountry];

if ($q !== '') {
    $where[] = "(a.title LIKE ? OR a.description LIKE ?)";
    $like = '%' . $q . '%';
    $params[] = $like;
    $params[] = $like;
}

if ($categoryId > 0) {
    $where[] = 'a.category_id = ?';
    $params[] = $categoryId;
}

if ($regionId > 0) {
    $where[] = 'a.region_id = ?';
    $params[] = $regionId;
}

if ($city !== '') {
    $where[] = 'a.city_name LIKE ?';
    $params[] = '%' . $city . '%';
}

$whereSql = implode(' AND ', $where);

$countSql = "
    SELECT COUNT(*)
    FROM board_ads a
    WHERE {$whereSql}
";

$listSql = "
    SELECT
        a.id,
        a.title,
        a.price_amount,
        a.currency_code,
        a.city_name,
        a.region_name,
        a.main_image_path,
        a.published_at,
        a.created_at,
        u.username AS author_username,
        u.full_name AS author_full_name,
        c.slug AS category_slug,
        " . (brd_lang() === 'ru' ? 'c.name_ru' : (brd_lang() === 'en' ? 'c.name_en' : 'c.name_uk')) . " AS category_name
    FROM board_ads a
    INNER JOIN users u ON u.id = a.user_id
    LEFT JOIN board_categories c ON c.id = a.category_id
    WHERE {$whereSql}
    ORDER BY COALESCE(a.published_at, a.created_at) DESC, a.id DESC
    LIMIT {$pagination['offset']}, {$pagination['per_page']}
";

$total = 0;
$ads = [];

try {
    $stCount = $pdo->prepare($countSql);
    $stCount->execute($params);
    $total = (int)$stCount->fetchColumn();

    $stList = $pdo->prepare($listSql);
    $stList->execute($params);
    $ads = $stList->fetchAll(PDO::FETCH_ASSOC) ?: [];
} catch (Throwable $e) {
    $ads = [];
}

$totalPages = max(1, (int)ceil($total / $pagination['per_page']));

$title = brd_t('Дошка оголошень', 'Доска объявлений', 'Classifieds board');
$meta_desc = brd_t(
    'Каталог оголошень VMEREGI з фільтрами за категоріями, регіонами та містами.',
    'Каталог объявлений VMEREGI с фильтрами по категориям, регионам и городам.',
    'VMEREGI classifieds board with category, region and city filters.'
);
$canonical = function_exists('abs_url') ? abs_url('/board.php') : null;

require dirname(__DIR__, 2) . '/includes/header.php';
?>
<div class="container my-4">
    <div class="d-flex flex-wrap justify-content-between align-items-center gap-2 mb-3">
        <div>
            <h1 class="h3 mb-1"><?= brd_h($title) ?></h1>
            <div class="text-muted">
                <?= brd_h(brd_t(
                    'Ви бачите оголошення для країни: ',
                    'Вы видите объявления для страны: ',
                    'You are viewing ads for country: '
                ) . $viewerCountry) ?>
            </div>
        </div>

        <div class="d-flex flex-wrap gap-2">
            <?php if ($me): ?>
                <a class="btn btn-primary" href="/functional/board/create.php">
                    <?= brd_h(brd_t('Подати оголошення', 'Подать объявление', 'Post an ad')) ?>
                </a>
                <a class="btn btn-outline-secondary" href="/functional/board/my.php">
                    <?= brd_h(brd_t('Мої оголошення', 'Мои объявления', 'My ads')) ?>
                </a>
            <?php else: ?>
                <a class="btn btn-primary" href="/login.php?to=<?= urlencode('/functional/board/create.php') ?>">
                    <?= brd_h(brd_t('Увійти, щоб подати оголошення', 'Войти, чтобы подать объявление', 'Log in to post an ad')) ?>
                </a>
            <?php endif; ?>
        </div>
    </div>

    <div class="card card-app p-3 mb-4">
        <form method="get" action="/board.php" class="row g-3">
            <div class="col-lg-4">
                <label class="form-label"><?= brd_h(brd_t('Пошук', 'Поиск', 'Search')) ?></label>
                <input type="text" name="q" class="form-control" value="<?= brd_h($q) ?>" placeholder="<?= brd_h(brd_t('Заголовок або текст', 'Заголовок или текст', 'Title or text')) ?>">
            </div>

            <div class="col-lg-3">
                <label class="form-label"><?= brd_h(brd_t('Категорія', 'Категория', 'Category')) ?></label>
                <select name="category" class="form-select">
                    <option value="0"><?= brd_h(brd_t('Усі категорії', 'Все категории', 'All categories')) ?></option>
                    <?php foreach ($categories as $cat): ?>
                        <option value="<?= (int)$cat['id'] ?>" <?= ((int)$cat['id'] === $categoryId ? 'selected' : '') ?>>
                            <?= brd_h((string)$cat['name']) ?>
                        </option>
                    <?php endforeach; ?>
                </select>
            </div>

            <div class="col-lg-3">
                <label class="form-label"><?= brd_h(brd_t('Регіон', 'Регион', 'Region')) ?></label>
                <select name="region_id" class="form-select">
                    <option value="0"><?= brd_h(brd_t('Усі регіони', 'Все регионы', 'All regions')) ?></option>
                    <?php foreach ($regions as $region): ?>
                        <option value="<?= (int)$region['id'] ?>" <?= ((int)$region['id'] === $regionId ? 'selected' : '') ?>>
                            <?= brd_h((string)$region['name']) ?>
                        </option>
                    <?php endforeach; ?>
                </select>
            </div>

            <div class="col-lg-2">
                <label class="form-label"><?= brd_h(brd_t('Місто', 'Город', 'City')) ?></label>
                <input type="text" name="city" class="form-control" value="<?= brd_h($city) ?>">
            </div>

            <div class="col-12 d-flex flex-wrap gap-2">
                <button class="btn btn-primary"><?= brd_h(brd_t('Застосувати', 'Применить', 'Apply')) ?></button>
                <a class="btn btn-outline-secondary" href="/board.php"><?= brd_h(brd_t('Скинути', 'Сбросить', 'Reset')) ?></a>
            </div>
        </form>
    </div>

    <?php if (!$ads): ?>
        <div class="alert alert-light border">
            <?= brd_h(brd_t(
                'Оголошень поки немає або нічого не знайдено за вашими фільтрами.',
                'Объявлений пока нет или ничего не найдено по вашим фильтрам.',
                'No ads were found for your filters yet.'
            )) ?>
        </div>
    <?php else: ?>
        <div class="row g-3">
            <?php foreach ($ads as $ad): ?>
                <?php
                $displayName = trim((string)($ad['author_full_name'] ?? ''));
                if ($displayName === '') {
                    $displayName = (string)($ad['author_username'] ?? '');
                }
                $price = number_format((float)($ad['price_amount'] ?? 0), 2, '.', ' ');
                ?>
                <div class="col-md-6 col-xl-4">
                    <div class="card card-app h-100">
                        <?php if (trim((string)($ad['main_image_path'] ?? '')) !== ''): ?>
                            <a href="<?= brd_h(brd_ad_url((int)$ad['id'])) ?>" class="text-decoration-none">
                                <img src="<?= brd_h((string)$ad['main_image_path']) ?>" alt="" class="card-img-top" style="height:220px;object-fit:cover;">
                            </a>
                        <?php endif; ?>

                        <div class="card-body d-flex flex-column">
                            <div class="d-flex flex-wrap gap-2 mb-2">
                                <?php if (trim((string)($ad['category_name'] ?? '')) !== ''): ?>
                                    <span class="badge bg-light text-dark border"><?= brd_h((string)$ad['category_name']) ?></span>
                                <?php endif; ?>
                                <span class="badge bg-success"><?= brd_h($price . ' ' . (string)($ad['currency_code'] ?? 'UAH')) ?></span>
                            </div>

                            <div class="fw-semibold mb-2">
                                <a class="text-decoration-none" href="<?= brd_h(brd_ad_url((int)$ad['id'])) ?>">
                                    <?= brd_h((string)$ad['title']) ?>
                                </a>
                            </div>

                            <div class="text-muted small mb-2">
                                <?= brd_h(trim((string)($ad['region_name'] ?? '') . ($ad['city_name'] !== '' ? ', ' . $ad['city_name'] : ''))) ?>
                            </div>

                            <div class="text-muted small mt-auto">
                                <?= brd_h($displayName) ?>
                                ·
                                <?= brd_h(date('d.m.Y', strtotime((string)($ad['published_at'] ?? $ad['created_at'] ?? 'now')))) ?>
                            </div>
                        </div>
                    </div>
                </div>
            <?php endforeach; ?>
        </div>

        <?php if ($totalPages > 1): ?>
            <nav class="mt-4" aria-label="Board pagination">
                <ul class="pagination flex-wrap">
                    <?php
                    $baseQuery = $_GET;
                    for ($p = 1; $p <= $totalPages; $p++):
                        $baseQuery['page'] = $p;
                        $url = '/board.php?' . http_build_query($baseQuery);
                    ?>
                        <li class="page-item <?= ($p === $page ? 'active' : '') ?>">
                            <a class="page-link" href="<?= brd_h($url) ?>"><?= (int)$p ?></a>
                        </li>
                    <?php endfor; ?>
                </ul>
            </nav>
        <?php endif; ?>
    <?php endif; ?>
</div>
<?php require dirname(__DIR__, 2) . '/includes/footer.php'; ?>
